refactor: create CoinProfitabilityLibrary

new library to facilitate CLI version
This commit is contained in:
2013-05-30 14:37:30 -07:00
parent 71f7ffa281
commit 6d17e41264
8 changed files with 450 additions and 238 deletions

View File

@@ -2,6 +2,11 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Express 2012 for Windows Desktop
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoinProfitability", "CoinProfitability\CoinProfitability.csproj", "{583376E1-A666-4199-8ACE-7B7CBC734C56}"
ProjectSection(ProjectDependencies) = postProject
{F496F99C-A09D-40A0-BC87-5662893FCBB3} = {F496F99C-A09D-40A0-BC87-5662893FCBB3}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoinProfitabilityLibrary", "CoinProfitabilityLibrary\CoinProfitabilityLibrary.csproj", "{F496F99C-A09D-40A0-BC87-5662893FCBB3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -13,6 +18,10 @@ Global
{583376E1-A666-4199-8ACE-7B7CBC734C56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{583376E1-A666-4199-8ACE-7B7CBC734C56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{583376E1-A666-4199-8ACE-7B7CBC734C56}.Release|Any CPU.Build.0 = Release|Any CPU
{F496F99C-A09D-40A0-BC87-5662893FCBB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F496F99C-A09D-40A0-BC87-5662893FCBB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F496F99C-A09D-40A0-BC87-5662893FCBB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F496F99C-A09D-40A0-BC87-5662893FCBB3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -50,12 +50,14 @@
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="CoinProfitabilityLibrary">
<HintPath>..\CoinProfitabilityLibrary\bin\Release\CoinProfitabilityLibrary.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Numerics" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>

View File

@@ -2,10 +2,7 @@
using System.Collections.Generic;
using System.Windows.Forms;
using System.Numerics;
using System.Net;
using Microsoft.Win32;
using System.IO;
using System.Web.Script.Serialization;
using ScottAlfter.CoinProfitabilityLibrary;
// Coin Profitability Calculator
//
@@ -33,212 +30,9 @@ namespace CoinProfitability
{
public partial class Form1 : Form
{
// exchange rate wrapper
// this reads in registry settings
private decimal GetExchangeRate(string exchange, string abbrev)
{
switch (exchange)
{
case "Bter":
return GetExchangeRateJSON("https://bter.com/api/1/ticker/"+abbrev.ToLower()+"_btc", "buy");
case "Cryptsy":
return GetExchangeRateCryptsy(abbrev.ToUpper());
default:
throw new ArgumentException(exchange + " exchange not supported");
}
}
// scrape HTML to get exchange data from Cryptsy
private decimal GetExchangeRateCryptsy(string abbrev)
{
WebClient wc = new WebClient();
string page = wc.DownloadString("https://www.cryptsy.com/");
foreach (string line in page.Split(new char[] { '\n' }))
if (line.Contains(abbrev + "/BTC") && line.Contains("leftmarketinfo"))
{
string link = line.Substring(line.IndexOf("href") + 6);
link = link.Substring(0, link.IndexOf("\""));
link = "https://www.cryptsy.com"+link.Replace("/markets/view", "/orders/ajaxbuyorderslist");
string data = wc.DownloadString(link);
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(data);
return Convert.ToDecimal(table["aaData"][0][0]);
}
return 0;
}
// parse JSON data returned by exchange to select desired rate
private decimal GetExchangeRateJSON(string url, string item)
{
WebClient wc = new WebClient();
string data = wc.DownloadString(url);
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(data);
return Convert.ToDecimal(table[item]);
}
// wrapper to get current block reward
private decimal GetReward(string chain_type, string url_prefix, string chain_name)
{
switch (chain_type)
{
case "Abe":
return GetRewardAbe(url_prefix, chain_name);
case "BlockEx":
return GetRewardBlockEx(url_prefix);
case "Tyrion":
return GetRewardTyrion(url_prefix, chain_name);
default:
throw new ArgumentException("Block explorer type \"" + chain_type + "\" unknown");
}
}
// wrapper to get current difficulty
private double GetDifficulty(string chain_type, string url_prefix, string chain_name)
{
switch (chain_type)
{
case "Abe":
case "Tyrion": // similar enough to Abe
double difficulty = -1;
try { difficulty = GetDifficultyAbe(url_prefix, chain_name); }
catch { }
if (difficulty == -1)
{
try { difficulty = GetDifficultyAbeAlt(url_prefix, chain_name); }
catch { }
}
if (difficulty != -1)
return difficulty;
else
throw new InvalidDataException("Can't get difficulty from " + url_prefix);
case "BlockEx":
return GetDifficultyBlockEx(url_prefix);
default:
throw new ArgumentException("Block explorer type \"" + chain_type + "\" unknown");
}
}
// workaround for explorer.litecoin.net's outdated Abe installation:
// get difficulty from most recent block
private double GetDifficultyAbeAlt(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
int blockcount = Convert.ToInt32(wc.DownloadString(url_prefix + "/chain/" + chain_name + "/q/getblockcount"));
string blockinfo = wc.DownloadString(url_prefix + "/search?q=" + blockcount.ToString());
double difficulty = 0;
foreach (string line in blockinfo.Split(new char[] { '\n' }))
if (line.Contains("Difficulty") && !line.Contains("Cumulative"))
difficulty = Convert.ToDouble(line.Split(new char[] { ' ' })[1]);
return difficulty;
}
// get block reward from most recent block on a Tyrion blockchain explorer
private decimal GetRewardTyrion(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
string homepage=wc.DownloadString(url_prefix + "/chain/" + chain_name);
string link = "";
foreach (string line in homepage.Split(new char[] { '\n' }))
if (line.Contains("<tr>") && !line.Contains("<table"))
{
string[] fields = line.Split(new string[] { "<td>", "</td>", "<tr>", "</tr>" }, StringSplitOptions.RemoveEmptyEntries);
link = fields[0].Substring(11);
link = url_prefix + link.Substring(0, link.IndexOf("\""));
break;
}
string blockinfo = wc.DownloadString(link);
int tx_index = 0;
decimal reward = 0;
foreach (string line in blockinfo.Split(new char[] { '\n' }))
if (line.Contains("<tr>") && !line.Contains("<table"))
{
string[] fields = line.Split(new string[] { "<td>", "</td>", "<tr>", "</tr>" }, StringSplitOptions.RemoveEmptyEntries);
if (tx_index == 0)
{
reward = Convert.ToDecimal(fields[3].Split(new char[] { ' ' })[1]);
if (fields[3].Contains("+"))
break;
}
else
reward -= Convert.ToDecimal(fields[1]);
tx_index++;
}
return reward * (decimal)100000000;
}
// get block reward from most recent block on an Abe blockchain explorer
private decimal GetRewardAbe(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
int blockcount = Convert.ToInt32(wc.DownloadString(url_prefix + "/chain/" + chain_name + "/q/getblockcount"));
string blockinfo = wc.DownloadString(url_prefix + "/search?q=" + blockcount.ToString());
int tx_index = 0;
decimal reward = 0;
foreach (string line in blockinfo.Split(new char[] { '\n' }))
if (line.Contains("<tr>") && !line.Contains("<table>"))
{
string[] fields = line.Split(new string[] { "<td>", "</td>", "<tr>", "</tr>" }, StringSplitOptions.RemoveEmptyEntries);
if (tx_index == 0)
{
reward = Convert.ToDecimal(fields[3].Split(new char[] { ' ' })[1]);
if (fields[3].Contains("+"))
break;
}
else
reward -= Convert.ToDecimal(fields[1]);
tx_index++;
}
return reward * (decimal)100000000;
}
// get difficulty (only works with newer Abe servers)
private double GetDifficultyAbe(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
return Convert.ToDouble(wc.DownloadString(url_prefix + "/chain/" + chain_name + "/q/getdifficulty"));
}
// get block reward from a blockexplorer.com-compatible server
private decimal GetRewardBlockEx(string url_prefix)
{
WebClient wc = new WebClient();
return Convert.ToDecimal(wc.DownloadString(url_prefix+"/q/bcperblock"));
}
// get difficulty from a blockexplorer.com-compatible server
private double GetDifficultyBlockEx(string url_prefix)
{
WebClient wc = new WebClient();
return Convert.ToDouble(wc.DownloadString(url_prefix+"/q/getdifficulty"));
}
// registry settings are read into these
private struct CoinInfo
{
public string ExplorerBaseURL;
public string ExplorerChain;
public string ExplorerType;
public string DefaultHashRateUnit;
//public string ExchangeURL;
//public string ExchangeJSONKey;
public string Exchange;
public string Abbreviation;
public string DefaultHashRate;
}
SortedDictionary<string, CoinInfo> coins = new SortedDictionary<string, CoinInfo>();
RegistrySettings rs = new RegistrySettings();
// drop-down lists are populated with these
@@ -324,30 +118,8 @@ namespace CoinProfitability
cbHashrateUnit.Items.Add(new Item("H/s", "1"));
cbHashrateUnit.SelectedIndex = 1;
// read registry settings
try
{
using (RegistryKey rkcu = Registry.CurrentUser)
using (RegistryKey rkSettings = rkcu.OpenSubKey("Software\\Scott Alfter\\CoinProfitability"))
{
foreach (string i in rkSettings.GetSubKeyNames())
{
RegistryKey k = rkSettings.OpenSubKey(i);
CoinInfo t = new CoinInfo();
t.ExplorerBaseURL = (string)k.GetValue("ExplorerBaseURL");
t.ExplorerType = (string)k.GetValue("ExplorerType");
t.ExplorerChain = (string)k.GetValue("ExplorerChain");
t.DefaultHashRateUnit = (string)k.GetValue("DefaultHashRateUnit");
t.Exchange = (string)k.GetValue("Exchange");
t.Abbreviation = (string)k.GetValue("Abbreviation");
t.DefaultHashRate = (string)k.GetValue("DefaultHashRate");
coins.Add(i, t);
cbCoinType.Items.Add(i);
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
foreach (string i in rs.GetCoinTypes())
cbCoinType.Items.Add(i);
}
private void cbInterval_SelectedIndexChanged(object sender, EventArgs e)
@@ -371,15 +143,17 @@ namespace CoinProfitability
private void cbCoinType_SelectedIndexChanged(object sender, EventArgs e)
{
ExchangeInformation ei = new ExchangeInformation();
CoinInformation ci = new CoinInformation();
lblUpdating.Visible = true;
this.Refresh();
string szCoinType=cbCoinType.Items[cbCoinType.SelectedIndex].ToString();
CoinInfo i = coins[szCoinType];
CoinInfo i = rs.Coins[szCoinType];
lblAbbrev.Text = lblRewardCurrency.Text = i.Abbreviation;
lblExchangeRateCurrency.Text = "BTC/" + i.Abbreviation;
try { tbDifficulty.Text = GetDifficulty(i.ExplorerType, i.ExplorerBaseURL, i.ExplorerChain).ToString(); }
try { tbDifficulty.Text = ci.GetDifficulty(i.ExplorerType, i.ExplorerBaseURL, i.ExplorerChain).ToString(); }
catch { tbDifficulty.Text = "Unavailable"; }
try { tbReward.Text = (GetReward(i.ExplorerType, i.ExplorerBaseURL, i.ExplorerChain) / (decimal)100000000).ToString(); }
try { tbReward.Text = (ci.GetReward(i.ExplorerType, i.ExplorerBaseURL, i.ExplorerChain) / (decimal)100000000).ToString(); }
catch { tbReward.Text = "Unavailable"; }
for (int c = 0; c < cbHashrateUnit.Items.Count; c++)
if (((Item)cbHashrateUnit.Items[c]).Name == i.DefaultHashRateUnit)
@@ -387,7 +161,7 @@ namespace CoinProfitability
try
{
if (i.Exchange != null)
tbExchangeRate.Text = GetExchangeRate(i.Exchange, i.Abbreviation).ToString();
tbExchangeRate.Text = ei.GetExchangeRate(i.Exchange, i.Abbreviation).ToString();
else
tbExchangeRate.Text = "";
}

View File

@@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
// Coin Profitability Calculator
//
// Copyright © 2013 Scott Alfter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ScottAlfter.CoinProfitabilityLibrary
{
public class CoinInformation
{
// wrapper to get current block reward
public decimal GetReward(string chain_type, string url_prefix, string chain_name)
{
switch (chain_type)
{
case "Abe":
return GetRewardAbe(url_prefix, chain_name);
case "BlockEx":
return GetRewardBlockEx(url_prefix);
case "Tyrion":
return GetRewardTyrion(url_prefix, chain_name);
default:
throw new ArgumentException("Block explorer type \"" + chain_type + "\" unknown");
}
}
// get block reward from most recent block on a Tyrion blockchain explorer
private decimal GetRewardTyrion(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
string homepage = wc.DownloadString(url_prefix + "/chain/" + chain_name);
string link = "";
foreach (string line in homepage.Split(new char[] { '\n' }))
if (line.Contains("<tr>") && !line.Contains("<table"))
{
string[] fields = line.Split(new string[] { "<td>", "</td>", "<tr>", "</tr>" }, StringSplitOptions.RemoveEmptyEntries);
link = fields[0].Substring(11);
link = url_prefix + link.Substring(0, link.IndexOf("\""));
break;
}
string blockinfo = wc.DownloadString(link);
int tx_index = 0;
decimal reward = 0;
foreach (string line in blockinfo.Split(new char[] { '\n' }))
if (line.Contains("<tr>") && !line.Contains("<table"))
{
string[] fields = line.Split(new string[] { "<td>", "</td>", "<tr>", "</tr>" }, StringSplitOptions.RemoveEmptyEntries);
if (tx_index == 0)
{
reward = Convert.ToDecimal(fields[3].Split(new char[] { ' ' })[1]);
if (fields[3].Contains("+"))
break;
}
else
reward -= Convert.ToDecimal(fields[1]);
tx_index++;
}
return reward * (decimal)100000000;
}
// get block reward from most recent block on an Abe blockchain explorer
private decimal GetRewardAbe(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
int blockcount = Convert.ToInt32(wc.DownloadString(url_prefix + "/chain/" + chain_name + "/q/getblockcount"));
string blockinfo = wc.DownloadString(url_prefix + "/search?q=" + blockcount.ToString());
int tx_index = 0;
decimal reward = 0;
foreach (string line in blockinfo.Split(new char[] { '\n' }))
if (line.Contains("<tr>") && !line.Contains("<table>"))
{
string[] fields = line.Split(new string[] { "<td>", "</td>", "<tr>", "</tr>" }, StringSplitOptions.RemoveEmptyEntries);
if (tx_index == 0)
{
reward = Convert.ToDecimal(fields[3].Split(new char[] { ' ' })[1]);
if (fields[3].Contains("+"))
break;
}
else
reward -= Convert.ToDecimal(fields[1]);
tx_index++;
}
return reward * (decimal)100000000;
}
// get block reward from a blockexplorer.com-compatible server
private decimal GetRewardBlockEx(string url_prefix)
{
WebClient wc = new WebClient();
return Convert.ToDecimal(wc.DownloadString(url_prefix + "/q/bcperblock"));
}
// wrapper to get current difficulty
public double GetDifficulty(string chain_type, string url_prefix, string chain_name)
{
switch (chain_type)
{
case "Abe":
case "Tyrion": // similar enough to Abe
double difficulty = -1;
try { difficulty = GetDifficultyAbe(url_prefix, chain_name); }
catch { }
if (difficulty == -1)
{
try { difficulty = GetDifficultyAbeAlt(url_prefix, chain_name); }
catch { }
}
if (difficulty != -1)
return difficulty;
else
throw new InvalidDataException("Can't get difficulty from " + url_prefix);
case "BlockEx":
return GetDifficultyBlockEx(url_prefix);
default:
throw new ArgumentException("Block explorer type \"" + chain_type + "\" unknown");
}
}
// get difficulty (only works with newer Abe servers)
private double GetDifficultyAbe(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
return Convert.ToDouble(wc.DownloadString(url_prefix + "/chain/" + chain_name + "/q/getdifficulty"));
}
// workaround for explorer.litecoin.net's outdated Abe installation:
// get difficulty from most recent block
private double GetDifficultyAbeAlt(string url_prefix, string chain_name)
{
WebClient wc = new WebClient();
int blockcount = Convert.ToInt32(wc.DownloadString(url_prefix + "/chain/" + chain_name + "/q/getblockcount"));
string blockinfo = wc.DownloadString(url_prefix + "/search?q=" + blockcount.ToString());
double difficulty = 0;
foreach (string line in blockinfo.Split(new char[] { '\n' }))
if (line.Contains("Difficulty") && !line.Contains("Cumulative"))
difficulty = Convert.ToDouble(line.Split(new char[] { ' ' })[1]);
return difficulty;
}
// get difficulty from a blockexplorer.com-compatible server
private double GetDifficultyBlockEx(string url_prefix)
{
WebClient wc = new WebClient();
return Convert.ToDouble(wc.DownloadString(url_prefix + "/q/getdifficulty"));
}
}
}

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{F496F99C-A09D-40A0-BC87-5662893FCBB3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CoinProfitabilityLibrary</RootNamespace>
<AssemblyName>CoinProfitabilityLibrary</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CoinInformation.cs" />
<Compile Include="ExchangeInformation.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RegistrySettings.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Net;
// Coin Profitability Calculator
//
// Copyright © 2013 Scott Alfter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ScottAlfter.CoinProfitabilityLibrary
{
public class ExchangeInformation
{
// exchange rate wrapper
public decimal GetExchangeRate(string exchange, string abbrev)
{
switch (exchange)
{
case "Bter":
return GetExchangeRateJSON("https://bter.com/api/1/ticker/" + abbrev.ToLower() + "_btc", "buy");
case "Cryptsy":
return GetExchangeRateCryptsy(abbrev.ToUpper());
default:
throw new ArgumentException(exchange + " exchange not supported");
}
}
// scrape HTML to get exchange data from Cryptsy
private decimal GetExchangeRateCryptsy(string abbrev)
{
WebClient wc = new WebClient();
string page = wc.DownloadString("https://www.cryptsy.com/");
foreach (string line in page.Split(new char[] { '\n' }))
if (line.Contains(abbrev + "/BTC") && line.Contains("leftmarketinfo"))
{
string link = line.Substring(line.IndexOf("href") + 6);
link = link.Substring(0, link.IndexOf("\""));
link = "https://www.cryptsy.com" + link.Replace("/markets/view", "/orders/ajaxbuyorderslist");
string data = wc.DownloadString(link);
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(data);
return Convert.ToDecimal(table["aaData"][0][0]);
}
return 0;
}
// parse JSON data returned by exchange to select desired rate
private decimal GetExchangeRateJSON(string url, string item)
{
WebClient wc = new WebClient();
string data = wc.DownloadString(url);
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(data);
return Convert.ToDecimal(table[item]);
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CoinProfitabilityLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("CoinProfitabilityLibrary")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d588c3ff-e94a-4215-a4c3-56926202712c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using Microsoft.Win32;
// Coin Profitability Calculator
//
// Copyright © 2013 Scott Alfter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ScottAlfter.CoinProfitabilityLibrary
{
public struct CoinInfo
{
public string ExplorerBaseURL;
public string ExplorerChain;
public string ExplorerType;
public string DefaultHashRateUnit;
public string Exchange;
public string Abbreviation;
public string DefaultHashRate;
}
public class RegistrySettings
{
// registry settings are read into these
public SortedDictionary<string, CoinInfo> Coins=new SortedDictionary<string,CoinInfo>();
public RegistrySettings()
{
try
{
using (RegistryKey rkcu = Registry.CurrentUser)
using (RegistryKey rkSettings = rkcu.OpenSubKey("Software\\Scott Alfter\\CoinProfitability"))
{
foreach (string i in rkSettings.GetSubKeyNames())
{
RegistryKey k = rkSettings.OpenSubKey(i);
CoinInfo t = new CoinInfo();
t.ExplorerBaseURL = (string)k.GetValue("ExplorerBaseURL");
t.ExplorerType = (string)k.GetValue("ExplorerType");
t.ExplorerChain = (string)k.GetValue("ExplorerChain");
t.DefaultHashRateUnit = (string)k.GetValue("DefaultHashRateUnit");
t.Exchange = (string)k.GetValue("Exchange");
t.Abbreviation = (string)k.GetValue("Abbreviation");
t.DefaultHashRate = (string)k.GetValue("DefaultHashRate");
Coins.Add(i, t);
}
}
}
catch { }
}
public List<string> GetCoinTypes()
{
List<string> rtnval=new List<string>();
foreach (string i in Coins.Keys)
rtnval.Add(i);
return rtnval;
}
}
}