Skip to content

Commit 8ad1bb8

Browse files
author
nicehashdev
committed
Custom handlers
Added support for custom order handlers to manage max price and speed limit.
1 parent 34a1455 commit 8ad1bb8

File tree

10 files changed

+348
-8
lines changed

10 files changed

+348
-8
lines changed

bin/NiceHashBot_1.0.1.0.zip

213 KB
Binary file not shown.

src/HandlerExample/HandlerClass.cs

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using System.IO;
5+
using System.Net; // For generating HTTP requests and getting responses.
6+
using NiceHashBotLib; // Include this for Order class, which contains stats for our order.
7+
using Newtonsoft.Json; // For JSON parsing of remote APIs.
8+
9+
public class HandlerClass
10+
{
11+
/// <summary>
12+
/// This method is called every 0.5 seconds.
13+
/// </summary>
14+
/// <param name="OrderStats">Order stats - do not change any properties or call any methods. This is provided only as read-only object.</param>
15+
/// <param name="MaxPrice">Current maximal price. Change this, if you would like to change the price.</param>
16+
/// <param name="NewLimit">Current speed limit. Change this, if you would like to change the limit.</param>
17+
public static void HandleOrder(ref Order OrderStats, ref double MaxPrice, ref double NewLimit)
18+
{
19+
// Following line of code makes the rest of the code to run only once per minute.
20+
if ((++Tick % 120) != 0) return;
21+
22+
// Perform check, if order has been created at all. If not, stop executing the code.
23+
if (OrderStats == null) return;
24+
25+
// Retreive JSON data from API server. Replace URL with your own API request URL.
26+
string JSONData = GetHTTPResponseInJSON("http://www.coinwarz.com/v1/api/coininformation/?apikey=<API_KEY>&cointag=<COIN>");
27+
if (JSONData == null) return;
28+
29+
// Serialize returned JSON data.
30+
CoinwarzResponse Response;
31+
try
32+
{
33+
Response = JsonConvert.DeserializeObject<CoinwarzResponse>(JSONData);
34+
}
35+
catch
36+
{
37+
return;
38+
}
39+
40+
// Check if exchange rate is provided - at least one exchange must be included.
41+
if (Response.Data.ExchangeRates.Length == 0) return;
42+
double ExchangeRate = Response.Data.ExchangeRates[0].ToBTC;
43+
44+
// Calculate mining profitability in BTC per 1 TH of hashpower.
45+
double HT = Response.Data.Difficulty * (Math.Pow(2.0, 32) / (1000000000000.0));
46+
double CPD = Response.Data.BlockReward * 24.0 * 3600.0 / HT;
47+
double C = CPD * ExchangeRate;
48+
49+
// Subtract service fees.
50+
C -= 0.04 * C;
51+
52+
// Subtract minimal % profit we want to get.
53+
C -= 0.01 * C;
54+
55+
// Set new maximal price.
56+
MaxPrice = Math.Floor(C * 10000) / 10000;
57+
58+
// Example how to print some data on console...
59+
Console.WriteLine("Adjusting order #" + OrderStats.ID.ToString() + " maximal price to: " + MaxPrice.ToString("F4"));
60+
}
61+
62+
/// <summary>
63+
/// Data structure used for serializing JSON response from CoinWarz.
64+
/// It allows us to parse JSON with one line of code and easily access every data contained in JSON message.
65+
/// </summary>
66+
#pragma warning disable 0649
67+
class CoinwarzResponse
68+
{
69+
public bool Success;
70+
public string Message;
71+
72+
public class DataStruct
73+
{
74+
public string CoinName;
75+
public string CoinTag;
76+
public int BlockCount;
77+
public double Difficulty;
78+
public double BlockReward;
79+
public bool IsBlockExplorerOnline;
80+
public bool IsExchangeOnline;
81+
public string Algorithm;
82+
public class ExchangeRateStruct
83+
{
84+
public string Exchange;
85+
public double ToUSD;
86+
public double ToBTC;
87+
public double Volume;
88+
public double TimeStamp;
89+
}
90+
public ExchangeRateStruct[] ExchangeRates;
91+
public double BlockTimeInSeconds;
92+
public string HealthStatus;
93+
public string Message;
94+
}
95+
public DataStruct Data;
96+
}
97+
#pragma warning restore 0649
98+
99+
100+
/// <summary>
101+
/// Property used for measuring time.
102+
/// </summary>
103+
private static int Tick = -10;
104+
105+
106+
// Following methods do not need to be altered.
107+
#region PRIVATE_METHODS
108+
109+
/// <summary>
110+
/// Get HTTP JSON response for provided URL.
111+
/// </summary>
112+
/// <param name="URL">URL.</param>
113+
/// <returns>JSON data returned by webserver or null if error occured.</returns>
114+
private static string GetHTTPResponseInJSON(string URL)
115+
{
116+
try
117+
{
118+
HttpWebRequest WReq = (HttpWebRequest)WebRequest.Create(URL);
119+
WReq.Timeout = 60000;
120+
WebResponse WResp = WReq.GetResponse();
121+
Stream DataStream = WResp.GetResponseStream();
122+
DataStream.ReadTimeout = 60000;
123+
StreamReader SReader = new StreamReader(DataStream);
124+
string ResponseData = SReader.ReadToEnd();
125+
if (ResponseData[0] != '{')
126+
throw new Exception("Not JSON data.");
127+
128+
return ResponseData;
129+
}
130+
catch (Exception ex)
131+
{
132+
return null;
133+
}
134+
}
135+
136+
#endregion
137+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
6+
<ProductVersion>8.0.30703</ProductVersion>
7+
<SchemaVersion>2.0</SchemaVersion>
8+
<ProjectGuid>{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}</ProjectGuid>
9+
<OutputType>Library</OutputType>
10+
<AppDesignerFolder>Properties</AppDesignerFolder>
11+
<RootNamespace>HandlerExample</RootNamespace>
12+
<AssemblyName>HandlerExample</AssemblyName>
13+
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
14+
<FileAlignment>512</FileAlignment>
15+
<TargetFrameworkProfile />
16+
</PropertyGroup>
17+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
18+
<DebugSymbols>true</DebugSymbols>
19+
<DebugType>full</DebugType>
20+
<Optimize>false</Optimize>
21+
<OutputPath>bin\Debug\</OutputPath>
22+
<DefineConstants>DEBUG;TRACE</DefineConstants>
23+
<ErrorReport>prompt</ErrorReport>
24+
<WarningLevel>4</WarningLevel>
25+
</PropertyGroup>
26+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
27+
<DebugType>pdbonly</DebugType>
28+
<Optimize>true</Optimize>
29+
<OutputPath>bin\Release\</OutputPath>
30+
<DefineConstants>TRACE</DefineConstants>
31+
<ErrorReport>prompt</ErrorReport>
32+
<WarningLevel>4</WarningLevel>
33+
</PropertyGroup>
34+
<ItemGroup>
35+
<Reference Include="Newtonsoft.Json">
36+
<HintPath>..\NiceHashBotLib\Newtonsoft.Json.dll</HintPath>
37+
</Reference>
38+
<Reference Include="System" />
39+
<Reference Include="System.Data" />
40+
<Reference Include="System.Xml" />
41+
</ItemGroup>
42+
<ItemGroup>
43+
<Compile Include="HandlerClass.cs" />
44+
<Compile Include="Properties\AssemblyInfo.cs" />
45+
</ItemGroup>
46+
<ItemGroup>
47+
<ProjectReference Include="..\NiceHashBotLib\NiceHashBotLib.csproj">
48+
<Project>{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}</Project>
49+
<Name>NiceHashBotLib</Name>
50+
</ProjectReference>
51+
</ItemGroup>
52+
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
53+
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
54+
Other similar extension points exist, see Microsoft.Common.targets.
55+
<Target Name="BeforeBuild">
56+
</Target>
57+
<Target Name="AfterBuild">
58+
</Target>
59+
-->
60+
</Project>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// General Information about an assembly is controlled through the following
6+
// set of attributes. Change these attribute values to modify the information
7+
// associated with an assembly.
8+
[assembly: AssemblyTitle("HandlerExample")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("HandlerExample")]
13+
[assembly: AssemblyCopyright("Copyright © 2015")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// Setting ComVisible to false makes the types in this assembly not visible
18+
// to COM components. If you need to access a type in this assembly from
19+
// COM, set the ComVisible attribute to true on that type.
20+
[assembly: ComVisible(false)]
21+
22+
// The following GUID is for the ID of the typelib if this project is exposed to COM
23+
[assembly: Guid("720c3451-131b-445d-8627-deab30407713")]
24+
25+
// Version information for an assembly consists of the following four values:
26+
//
27+
// Major Version
28+
// Minor Version
29+
// Build Number
30+
// Revision
31+
//
32+
// You can specify all the values or you can default the Build and Revision Numbers
33+
// by using the '*' as shown below:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]

src/NHB.sln

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,14 @@
22
Microsoft Visual Studio Solution File, Format Version 11.00
33
# Visual Studio 2010
44
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NiceHashBot", "NiceHashBot\NiceHashBot.csproj", "{74BB3FF1-4FA4-4346-A254-873152EB9B6C}"
5+
ProjectSection(ProjectDependencies) = postProject
6+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276} = {7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}
7+
EndProjectSection
58
EndProject
69
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NiceHashBotLib", "NiceHashBotLib\NiceHashBotLib.csproj", "{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}"
710
EndProject
11+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HandlerExample", "HandlerExample\HandlerExample.csproj", "{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}"
12+
EndProject
813
Global
914
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1015
Debug|Any CPU = Debug|Any CPU
@@ -35,6 +40,16 @@ Global
3540
{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
3641
{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
3742
{B5B243E4-0497-42CB-AFBF-A4ED3B4343D6}.Release|x86.ActiveCfg = Release|Any CPU
43+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
44+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Any CPU.Build.0 = Debug|Any CPU
45+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
46+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
47+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Debug|x86.ActiveCfg = Debug|Any CPU
48+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Any CPU.ActiveCfg = Release|Any CPU
49+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Any CPU.Build.0 = Release|Any CPU
50+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
51+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|Mixed Platforms.Build.0 = Release|Any CPU
52+
{7C9EAB28-E50A-4E7B-9FF7-E964B60C5276}.Release|x86.ActiveCfg = Release|Any CPU
3853
EndGlobalSection
3954
GlobalSection(SolutionProperties) = preSolution
4055
HideSolutionNode = FALSE

src/NiceHashBot/FormMain.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ private void BalanceRefresh_Tick(object sender, EventArgs e)
5353

5454
private void TimerRefresh_Tick(object sender, EventArgs e)
5555
{
56+
if (!APIWrapper.ValidAuthorization) return;
57+
5658
OrderContainer[] Orders = OrderContainer.GetAll();
5759
int Selected = -1;
5860
if (listView1.SelectedIndices.Count > 0)

src/NiceHashBot/FormNewOrder.Designer.cs

Lines changed: 36 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/NiceHashBot/FormNewOrder.cs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
7979
else
8080
{
8181
linkLabel1.Text = "Hide advanced options";
82-
this.Size = new Size(this.Size.Width, 315);
82+
this.Size = new Size(this.Size.Width, 340);
8383
}
8484

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

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

112112
Close();
113113
}
114+
115+
private void button3_Click(object sender, EventArgs e)
116+
{
117+
OpenFileDialog OFD = new OpenFileDialog();
118+
OFD.Filter = "CSharp dynamic link library|*.dll";
119+
OFD.Multiselect = false;
120+
OFD.InitialDirectory = Application.StartupPath;
121+
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
122+
{
123+
textBox1.Text = OFD.FileName;
124+
}
125+
}
114126
}
115127
}

0 commit comments

Comments
 (0)