Skip to content

Commit

Permalink
Custom handlers
Browse files Browse the repository at this point in the history
Added support for custom order handlers to manage max price and speed
limit.
  • Loading branch information
nicehashdev committed Feb 6, 2015
1 parent 34a1455 commit 8ad1bb8
Show file tree
Hide file tree
Showing 10 changed files with 348 additions and 8 deletions.
Binary file added bin/NiceHashBot_1.0.1.0.zip
Binary file not shown.
137 changes: 137 additions & 0 deletions src/HandlerExample/HandlerClass.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net; // For generating HTTP requests and getting responses.
using NiceHashBotLib; // Include this for Order class, which contains stats for our order.
using Newtonsoft.Json; // For JSON parsing of remote APIs.

public class HandlerClass
{
/// <summary>
/// This method is called every 0.5 seconds.
/// </summary>
/// <param name="OrderStats">Order stats - do not change any properties or call any methods. This is provided only as read-only object.</param>
/// <param name="MaxPrice">Current maximal price. Change this, if you would like to change the price.</param>
/// <param name="NewLimit">Current speed limit. Change this, if you would like to change the limit.</param>
public static void HandleOrder(ref Order OrderStats, ref double MaxPrice, ref double NewLimit)
{
// Following line of code makes the rest of the code to run only once per minute.
if ((++Tick % 120) != 0) return;

// Perform check, if order has been created at all. If not, stop executing the code.
if (OrderStats == null) return;

// Retreive JSON data from API server. Replace URL with your own API request URL.
string JSONData = GetHTTPResponseInJSON("http://www.coinwarz.com/v1/api/coininformation/?apikey=<API_KEY>&cointag=<COIN>");
if (JSONData == null) return;

// Serialize returned JSON data.
CoinwarzResponse Response;
try
{
Response = JsonConvert.DeserializeObject<CoinwarzResponse>(JSONData);
}
catch
{
return;
}

// Check if exchange rate is provided - at least one exchange must be included.
if (Response.Data.ExchangeRates.Length == 0) return;
double ExchangeRate = Response.Data.ExchangeRates[0].ToBTC;

// Calculate mining profitability in BTC per 1 TH of hashpower.
double HT = Response.Data.Difficulty * (Math.Pow(2.0, 32) / (1000000000000.0));
double CPD = Response.Data.BlockReward * 24.0 * 3600.0 / HT;
double C = CPD * ExchangeRate;

// Subtract service fees.
C -= 0.04 * C;

// Subtract minimal % profit we want to get.
C -= 0.01 * C;

// Set new maximal price.
MaxPrice = Math.Floor(C * 10000) / 10000;

// Example how to print some data on console...
Console.WriteLine("Adjusting order #" + OrderStats.ID.ToString() + " maximal price to: " + MaxPrice.ToString("F4"));
}

/// <summary>
/// Data structure used for serializing JSON response from CoinWarz.
/// It allows us to parse JSON with one line of code and easily access every data contained in JSON message.
/// </summary>
#pragma warning disable 0649
class CoinwarzResponse
{
public bool Success;
public string Message;

public class DataStruct
{
public string CoinName;
public string CoinTag;
public int BlockCount;
public double Difficulty;
public double BlockReward;
public bool IsBlockExplorerOnline;
public bool IsExchangeOnline;
public string Algorithm;
public class ExchangeRateStruct
{
public string Exchange;
public double ToUSD;
public double ToBTC;
public double Volume;
public double TimeStamp;
}
public ExchangeRateStruct[] ExchangeRates;
public double BlockTimeInSeconds;
public string HealthStatus;
public string Message;
}
public DataStruct Data;
}
#pragma warning restore 0649


/// <summary>
/// Property used for measuring time.
/// </summary>
private static int Tick = -10;


// Following methods do not need to be altered.
#region PRIVATE_METHODS

/// <summary>
/// Get HTTP JSON response for provided URL.
/// </summary>
/// <param name="URL">URL.</param>
/// <returns>JSON data returned by webserver or null if error occured.</returns>
private static string GetHTTPResponseInJSON(string URL)
{
try
{
HttpWebRequest WReq = (HttpWebRequest)WebRequest.Create(URL);
WReq.Timeout = 60000;
WebResponse WResp = WReq.GetResponse();
Stream DataStream = WResp.GetResponseStream();
DataStream.ReadTimeout = 60000;
StreamReader SReader = new StreamReader(DataStream);
string ResponseData = SReader.ReadToEnd();
if (ResponseData[0] != '{')
throw new Exception("Not JSON data.");

return ResponseData;
}
catch (Exception ex)
{
return null;
}
}

#endregion
}
60 changes: 60 additions & 0 deletions src/HandlerExample/HandlerExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HandlerExample</RootNamespace>
<AssemblyName>HandlerExample</AssemblyName>
<TargetFrameworkVersion>v2.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="Newtonsoft.Json">
<HintPath>..\NiceHashBotLib\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="HandlerClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NiceHashBotLib\NiceHashBotLib.csproj">
<Project>{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}</Project>
<Name>NiceHashBotLib</Name>
</ProjectReference>
</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>
36 changes: 36 additions & 0 deletions src/HandlerExample/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -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("HandlerExample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HandlerExample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("720c3451-131b-445d-8627-deab30407713")]

// 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")]
15 changes: 15 additions & 0 deletions src/NHB.sln
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NiceHashBot", "NiceHashBot\NiceHashBot.csproj", "{74BB3FF1-4FA4-4346-A254-873152EB9B6C}"
ProjectSection(ProjectDependencies) = postProject
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276} = {7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NiceHashBotLib", "NiceHashBotLib\NiceHashBotLib.csproj", "{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HandlerExample", "HandlerExample\HandlerExample.csproj", "{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -35,6 +40,16 @@ Global
{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}.Release|x86.ActiveCfg = Release|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|x86.ActiveCfg = Debug|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Any CPU.Build.0 = Release|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
2 changes: 2 additions & 0 deletions src/NiceHashBot/FormMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ private void BalanceRefresh_Tick(object sender, EventArgs e)

private void TimerRefresh_Tick(object sender, EventArgs e)
{
if (!APIWrapper.ValidAuthorization) return;

OrderContainer[] Orders = OrderContainer.GetAll();
int Selected = -1;
if (listView1.SelectedIndices.Count > 0)
Expand Down
37 changes: 36 additions & 1 deletion src/NiceHashBot/FormNewOrder.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 14 additions & 2 deletions src/NiceHashBot/FormNewOrder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
else
{
linkLabel1.Text = "Hide advanced options";
this.Size = new Size(this.Size.Width, 315);
this.Size = new Size(this.Size.Width, 340);
}

AdvancedOptionsShown = !AdvancedOptionsShown;
Expand All @@ -102,7 +102,7 @@ private void button2_Click(object sender, EventArgs e)

if (AdvancedOptionsShown)
{
OrderContainer.Add(comboBox1.SelectedIndex, comboBox2.SelectedIndex, MaxPrice, Limit, Pools[comboBox3.SelectedIndex], OrderID, StartPrice, StartAmount);
OrderContainer.Add(comboBox1.SelectedIndex, comboBox2.SelectedIndex, MaxPrice, Limit, Pools[comboBox3.SelectedIndex], OrderID, StartPrice, StartAmount, textBox1.Text);
}
else
{
Expand All @@ -111,5 +111,17 @@ private void button2_Click(object sender, EventArgs e)

Close();
}

private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "CSharp dynamic link library|*.dll";
OFD.Multiselect = false;
OFD.InitialDirectory = Application.StartupPath;
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox1.Text = OFD.FileName;
}
}
}
}
Loading

0 comments on commit 8ad1bb8

Please sign in to comment.