Skip to content

Commit

Permalink
Merge commit 'b40b87876523f8b79a71ead7d6edee8d3cb055dc' as 'nuxhash/n…
Browse files Browse the repository at this point in the history
…hrest'
  • Loading branch information
YoRyan committed Oct 12, 2019
2 parents e654ebe + b40b878 commit d29c573
Show file tree
Hide file tree
Showing 29 changed files with 2,440 additions and 0 deletions.
2 changes: 2 additions & 0 deletions nuxhash/nhrest/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea
javascript/node_modules
21 changes: 21 additions & 0 deletions nuxhash/nhrest/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# rest-clients-demo

### TEST environment

Generate Api key and Secret for test platform on:

https://test.nicehash.com (User / Settings / API Keys)
Organization ID is displayed just above "+ Create new API key" button.

Use https://api-test.nicehash.com for API domain.

The entire platform runs on testnet. This means that you don’t have to use your own funds to test the platform. This is the opportunity to familiarize yourself with the new system, place hash-power orders and try trading without spending any real money.

![](https://raw.githubusercontent.com/nicehash/rest-clients-demo/master/generate_key.gif)

### PRODUCTION environment

To use production just generate key the same way on https://www.nicehash.com and use https://api2.nicehash.com for API domain.

### API docs
Can be found here: https://docs.nicehash.com/
17 changes: 17 additions & 0 deletions nuxhash/nhrest/bash/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Instructions

Get python client

wget https://raw.githubusercontent.com/nicehash/rest-clients-demo/master/python/nicehash.py

Install dependencies

pip install requests

Enter API key/secret/org in to the bash script

./run.sh

For more options see

python nicehash.py -h
13 changes: 13 additions & 0 deletions nuxhash/nhrest/bash/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/bin/bash
# Configuration
ORG="---"
KEY="---"
SEC="---"
#API="https://api2.nicehash.com" #prod env
API="https://api-test.nicehash.com" # test env

# Command
NHCLIENT="python nicehash.py -b $API -o $ORG -k $KEY -s $SEC"

# Run method
eval "$NHCLIENT -m GET -p '/main/api/v2/accounting/accounts'"; # -b '{json}'
25 changes: 25 additions & 0 deletions nuxhash/nhrest/c#/connect/connect.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29021.104
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "connect", "connect\connect.csproj", "{25EF6083-E791-4BAD-A0C0-462A1A1220E3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{25EF6083-E791-4BAD-A0C0-462A1A1220E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{25EF6083-E791-4BAD-A0C0-462A1A1220E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{25EF6083-E791-4BAD-A0C0-462A1A1220E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{25EF6083-E791-4BAD-A0C0-462A1A1220E3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A8EDF606-C147-427F-B08D-FECCD44EC071}
EndGlobalSection
EndGlobal
174 changes: 174 additions & 0 deletions nuxhash/nhrest/c#/connect/connect/Api.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace connect
{
class Api
{
private string urlRoot;
private string orgId;
private string apiKey;
private string apiSecret;

public Api(string urlRoot, string orgId, string apiKey, string apiSecret)
{
this.urlRoot = urlRoot;
this.orgId = orgId;
this.apiKey = apiKey;
this.apiSecret = apiSecret;
}

private static string HashBySegments(string key, string apiKey, string time, string nonce, string orgId, string method, string encodedPath, string query, string bodyStr)
{
List<string> segments = new List<string>();
segments.Add(apiKey);
segments.Add(time);
segments.Add(nonce);
segments.Add(null);
segments.Add(orgId);
segments.Add(null);
segments.Add(method);
segments.Add(encodedPath == null ? null : encodedPath);
segments.Add(query == null ? null : query);

if (bodyStr != null && bodyStr.Length > 0) {
segments.Add(bodyStr);
}
return Api.CalcHMACSHA256Hash(Api.JoinSegments(segments), key);
}
private static string getPath(string url)
{
var arrSplit = url.Split('?');
return arrSplit[0];
}
private static string getQuery(string url) {
var arrSplit = url.Split('?');

if (arrSplit.Length == 1)
{
return null;
}
else
{
return arrSplit[1];
}
}

private static string JoinSegments(List<string> segments) {
var sb = new System.Text.StringBuilder();
bool first = true;
foreach (var segment in segments) {
if (!first)
{
sb.Append("\x00");
}
else
{
first = false;
}

if (segment != null)
{
sb.Append(segment);
}
}
//Console.WriteLine("["+sb.ToString()+"]");
return sb.ToString();
}

private static string CalcHMACSHA256Hash(string plaintext, string salt)
{
string result = "";
var enc = Encoding.Default;
byte[]
baText2BeHashed = enc.GetBytes(plaintext),
baSalt = enc.GetBytes(salt);
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(baSalt);
byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
return result;
}

public string get(string url)
{
return this.get(url, false, null);
}

public string get(string url, bool auth, string time)
{
var client = new RestSharp.RestClient(this.urlRoot);
var request = new RestSharp.RestRequest(url);

if (auth)
{
string nonce = Guid.NewGuid().ToString();
string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "GET", getPath(url), getQuery(url), null);

request.AddHeader("X-Time", time);
request.AddHeader("X-Nonce", nonce);
request.AddHeader("X-Auth", this.apiKey + ":" + digest);
request.AddHeader("X-Organization-Id", this.orgId);
}

var response = client.Execute(request, RestSharp.Method.GET);
var content = response.Content;
return content;
}

public string post(string url, string payload, string time, bool requestId)
{
var client = new RestSharp.RestClient(this.urlRoot);
var request = new RestSharp.RestRequest(url);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-type", "application/json");

string nonce = Guid.NewGuid().ToString();
string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "POST", getPath(url), getQuery(url), payload);

if (payload !=null)
{
request.AddJsonBody(payload);
}

request.AddHeader("X-Time", time);
request.AddHeader("X-Nonce", nonce);
request.AddHeader("X-Auth", this.apiKey + ":" + digest);
request.AddHeader("X-Organization-Id", this.orgId);

if (requestId)
{
request.AddHeader("X-Request-Id", Guid.NewGuid().ToString());
}

var response = client.Execute(request, RestSharp.Method.POST);
var content = response.Content;
return content;
}

public string delete(string url, string time, bool requestId)
{
var client = new RestSharp.RestClient(this.urlRoot);
var request = new RestSharp.RestRequest(url);

string nonce = Guid.NewGuid().ToString();
string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "DELETE", getPath(url), getQuery(url), null);

request.AddHeader("X-Time", time);
request.AddHeader("X-Nonce", nonce);
request.AddHeader("X-Auth", this.apiKey + ":" + digest);
request.AddHeader("X-Organization-Id", this.orgId);

if (requestId)
{
request.AddHeader("X-Request-Id", Guid.NewGuid().ToString());
}

var response = client.Execute(request, RestSharp.Method.DELETE);
var content = response.Content;
return content;
}
}
}
6 changes: 6 additions & 0 deletions nuxhash/nhrest/c#/connect/connect/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
38 changes: 38 additions & 0 deletions nuxhash/nhrest/c#/connect/connect/Connect.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace connect
{
class Connect
{
static void Main(string[] args)
{
Console.WriteLine("running HashPowerOrder");
new Hpo();
Console.WriteLine("\n\nrunning Exchange");
new Exch();
Console.ReadLine();
}
}

public class ServerTime
{
public string serverTime { get; set; }
}
public class Pool
{
public string id { get; set; }
}
public class Order
{
public string id { get; set; }
}
public class OrderBooks
{
public List<double[]> sell { get; set; }
public List<double[]> buy { get; set; }
}
}
84 changes: 84 additions & 0 deletions nuxhash/nhrest/c#/connect/connect/Exch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace connect
{
class Exch
{
private static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

private static string URL_ROOT = "https://api-test.nicehash.com"; //use https://api2.nicehash.com for production
private static string ORG_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
private static string API_KEY = "ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj";
private static string API_SECRET = "kkkkkkkk-llll-mmmm-nnnn-oooooooooooooooooooo-pppp-qqqq-rrrr-ssssssssssss";

private static string CURRENCY_SELL = "TBTC"; //user BTC for production
private static string CURRENCY_BUY = "TLTC"; //use LTC for production

public Exch()
{
var config = new NLog.Config.LoggingConfiguration();
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
NLog.LogManager.Configuration = config;

Api api = new Api(URL_ROOT, ORG_ID, API_KEY, API_SECRET);

//get server time
string timeResponse = api.get("/api/v2/time");
ServerTime serverTimeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerTime>(timeResponse);
string time = serverTimeObject.serverTime;
Logger.Info("server time: {}", time);

//get algo settings
string exchResponse = api.get("/exchange/api/v2/info/status");
Console.WriteLine("[[["+exchResponse+"]]]");
DataTable exchArray = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(exchResponse);

DataRow mySettings = null;
foreach (DataRow symbol in exchArray.Rows)
{
if (symbol["baseAsset"].Equals(CURRENCY_BUY))
{
mySettings = symbol;
}
}
Logger.Info("exchange settings: {}", mySettings["currency"]);

//get balance
string accountsResponse = api.get("/main/api/v2/accounting/accounts", true, time);
DataTable accountsArray = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(accountsResponse);

DataRow myBalace = null;
foreach (DataRow account in accountsArray.Rows)
{
if (account["currency"].Equals(CURRENCY_SELL))
{
myBalace = account;
}
}
Logger.Info("balance: {} {}", myBalace["balance"], CURRENCY_SELL);

//get order book
string orderBookResponse = api.get("/exchange/api/v2/orderbook?market=" + CURRENCY_BUY + CURRENCY_SELL + "&limit=100", true, time);
OrderBooks orderBooks = Newtonsoft.Json.JsonConvert.DeserializeObject<OrderBooks>(orderBookResponse);
Logger.Info("cheapest offer price: {} supply: {}", orderBooks.sell[0][0], orderBooks.sell[0][1]);

double qty = 0.1 * 2;
string sQty = qty.ToString("0.00000000", System.Globalization.CultureInfo.InvariantCulture);
string sPrice = orderBooks.sell[0][0].ToString("0.00000000", System.Globalization.CultureInfo.InvariantCulture);

//buy with limit order
string url = "/exchange/api/v2/order?market=" + CURRENCY_BUY + CURRENCY_SELL + "&side=buy&type=limit&quantity=" + sQty + "&price=" + sPrice;
Logger.Info("order url: {}", url);
string orderCreateResponse = api.post(url, null, time, true);
Logger.Info("order create: {}", orderCreateResponse);
}
}

}
Loading

0 comments on commit d29c573

Please sign in to comment.