Giter Site home page Giter Site logo

rest-clients-demo's Introduction

rest-clients-demo

Examples by language

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.

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/

rest-clients-demo's People

Contributors

bl4z avatar dependabot[bot] avatar frstrtr avatar gingertrol avatar nushypool avatar overcookedpanda avatar shiggid avatar t4njast avatar xrado avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rest-clients-demo's Issues

[RPC][propose] get back count to next allowed price move-down

Hi.
Old nh rpc error message has a countdown:
"Price decrease possible after seconds: XXX"

New one doesn't have it. Please get it back like:
{"error_id":"bla","errors":[{"code":5061,"message":"Order price cannot be decreased yet, allowed once per 10 minutes","Price decrease possible after seconds":"XXX"}]}

run.sh not working, was not tested

Hello, the bash script "run.sh" is not working for me, I use POST and I get "Malformed request". For data I use '{"price":0.0058}' according to template in the script.

I think there is error in the script - the body parameter is -d and not -b as it is in the script now. Apparently noone tested it with POST. What is the correct format of body data for POST method please? Thank you

[QUESTION] How to set all power modes via api?

The Nicehash API allows settings power mode via POST to '/main/api/v2/mining/rigs/status2' to LOW, MEDIUM, or HIGH, which then shows up on the web interface as "Optimize", Lite, and Medium. It doesn't seem to accept any other obvious values, so I can't figure out how to use the API to set the power mode to High, Efficient, Efficient Low, Extreme, etc. Is there a different API call to use, or are there different power modes that are accepted to get the same results as with the web interface?

problem with api - javascript client withdraw / api.post

Would like to use the api to make withdrawals.

I am using the javascript client.

This is in my api.js

1st i call getTime and then try to call api.post()

async function nicehashpost(url, body) {
    try {
        await api.getTime();

        const res = await api.post(url, body);
        return res;
    } catch (error) {
        console.error('Error in nicehashpost:', error);
        throw error;
    }

This is the context of the call using POST to withdraw

async function withdrawFunds(amount) {
    if (amount < threshold) {
        console.error("Withdrawal amount too low. Must be at least ${threshold}")
        return
    }
    formattedAmount = amount.toFixed(8)
    response = await nicehashpost('/main/api/v2/accounting/withdrawal', {
        body:{"currency":"BTC","amount":formattedAmount,"withdrawalAddressId":"identifier-number","walletType":"BLOCKCHAIN"}
        })
    console.log(response);
    return response;
}

Not sure why I am getting this response:

{
  error_id: 'some-error-id-number',
  errors: [ { code: 2000, message: 'Invalid session (1009)' } ]
} 

Any help would be appreciated.

use case

it's not a bug, but a support request, is there a guide to take that data and put it on an influx db? until recently I used this https://github.com/tg44/nicehash-exporter very simple and useful tool, but now with the change in the API response the data is no longer readable correctly

Working PHP API Code?

Hello everyone. I have tested all codes here. But I don't get any good working code. Can anybody share with us the working PHP code here?
Best programming to everybody
Note: I want only to get balance and mining information (estimated daily rewards etc.)

Problem with parameters, malformed request

Hello, some time ago you have sucessfuly resolved my problem with malformed request for order change - you hepled to set correct parameters syntax.

Now I want to POST order create, but I am getting Malformed request again. The syntax should be correct, I used it from previsous working order update. I think the problem can be displayPriceFactor and priceFactor, because NiceHash documentation is extremely vague. Can you help please?

python3 /home/janbenes/nicehash.py -b https://api2.nicehash.com -o <key> -k <key> -s <secret> -m POST -p "/main/api/v2/hashpower/order" -d '{"market":"EU","algorithm":"SHA256ASICBOOST","amount":"0.011","poolId":"ANTpool","type":"STANDARD","marketFactor":"1000000000000000.00000000","displayMarketFactor":"PH","limit":"0.1","price":"0.0053","displayPriceFactor":"BTC","priceFactor":"1"}'

Unexpected error: 400: Bad Request: b'{"error_id":"99037110-3632-4ec7-9ed5-02f6d90635d5","errors":[{"code":60,"message":"Malformed request"}]}'

Java Sample Code - Invalid Session - Error Code 2000 Response

Hello, I don't think the java sample code is correct. After resolving the JsonObject exception, I used the same key, secret, and org id values that I was getting a response for on the Nicehash API website. With those same values, the java sample code returns:

`INFO: Accounts Object: {"error_id":"36b23e04-77a7-49e6-880a-df693eb15786","errors":[{"code":2000,"message":"Invalid session"}]}

Im thinking the sha256 and all the signing is wrong.

Invalid Session in the bash

Hello.
I'm trying to figure out api and implement bash on Linux. But it doesn’t work out.

set -x 

rand_str2(){
    echo $(od -x /dev/urandom | head -1 | awk '{OFS="-"; print $2$3,$4,$5,$6,$7$8$9}')
}

get_server_time(){
    echo $(curl -s 'https://api-test.nicehash.com/api/v2/time'|sed s/[^0-9]//g)
}

get_time(){
    date +%s
}

get_HASH256(){
    local str=''
    str+=$1         #key
    str+='\x00'
    str+=$2         #time
    str+='\x00'
    str+=$3         #x-nonce
    str+='\x00'
    str+='\x00'
    str+=$4         #x-org-id
    str+='\x00'
    str+='\x00'
    str+=$5         #method
    str+='\x00'
    str+=$6         #path
    if [ ! -z "$7" -a "$7" != " " ];then
        str+='\x00'
        str+=$7     #query
    fi
    echo -ne "$str" | openssl dgst -hmac "$8" -sha256 | awk '{print $2}'
}

url_root='https://api-test.nicehash.com'
time=$(get_server_time)

x_nonce=$(rand_str2) # generate uuid random string
key='ac09bbab-1f7a-4893-8a96-50c5417b0726'
secret='e9634354-d781-4e9a-85b1-10ea0b5b83cbe3cc1a4a-d65f-4417-bc61-2440dcd6951c'
org_id='d6396a75-595c-473e-be0b-b94d87c6f750'
#path='/main/api/v2/accounting/accounts'
path='/main/api/v2/trades'
method='GET'
query=''

signature=$(get_HASH256 "$key" "$time" "$x_nonce" "$org_id" "$method" "$path" "$query" "$secret")

url=$url_root$path

h1="X-Time: $time"
h2="X-Nonce: $x_nonce"
h3="X-Organization-Id: $org_id"
h4="X-Auth: $key:$signature"
h5="Accept: application/json"
h6="Content-Type: application/json; charset=utf-8"

curl -s -H "$h1" -H "$h2" -H "$h3" -H "$h4" -H "$h5" -H "$h6" $url

Result:
{"error_id":"79dda1fa-eab1-4e00-8fb9-ed6e81c0ec2a","errors":[{"code":2000,"message":"Invalid Session"}]}

PS sorry for my bad English.

API calls returning improper JSON with Python example.

It appears when using the nicehash.py example that the json data is being returning using single quotes instead of double quotes which then fails to parse as proper json.

As a work around, I've used string replace and parse with jq, but it would be idea of the API returned properly formatted JSON. Is this an issue within nicehash.py or server side?

Please provide PHP example

Always get "errors":[{"code":2000,"message":"Invalid Session"}]

I am guessing I did not set up my sign data properly.
My OrgID matches what's in my account and the API info is set up under my Org.

Please help

PHP CODE

define('NH_API_KEY', 'XXXX' );
define('NH_API_SEC', 'XXXX' );
define('NH_ORGID',    'da41b3bc-3d0b-4226-b7ea-aee73f94a518' );
$UTCtime 		= UTC_Get_Millis();
$OrgID 			= NH_ORGID;
$Nonce			= GEN_UUIDv4();
$Method   	= 'GET';
$Path				= "/main/api/v2/mining/info";
$Query			= "";
$SigData 		= NH_API_KEY."\x00{$UTCtime}\x00{$Nonce}\x00\x00{$OrgID}\x00\x00{$Method}\x00{$Path}\x00{$Query}";
$Signature 	= hash_hmac('sha256', $SigData, NH_API_SEC );

$RequestID = GEN_UUIDv4();

$Headers = array(
	"X-Time: {$UTCtime}",
	"X-Nonce: {$Nonce}",
	"X-Organization-Id: {$OrgID}",
	"X-Request-Id: {$RequestID}",
	"X-Auth: ".NH_API_KEY.":{$Signature}",
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api2.nicehash.com{$Path}/" );
curl_setopt($curl, CURLOPT_HTTPHEADER, $Headers );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curl);
if(!$result){
	die("Connection Failure");
}
curl_close($curl);
echo $result;

Java Sample Returning JsonSyntaxException

Exception in thread "main" com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonArray but was com.google.gson.JsonObject
at com.google.gson.internal.bind.TypeAdapters$35$1.read(TypeAdapters.java:897)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at Exch.(Exch.java:56)
at Exch.main(Exch.java:26)

I made sure my Organization Id, API key, and API secret were all correct by using this: https://www.nicehash.com/docs/rest and inputting the same values and getting a 200 response code.

I'm also using the production api2 for the URL_ROOT, Ran Exch.java and getting the exception above.

Lazarus client, Indy package for HTTP requests

I'm constantly receiving error 2000
{"error_id":"42b8c1a3-5911-499f-8dd6-5835d0f26163","errors":[{"code":2000,"message":"Invalid session"}]}

I did examples for sign that i found here, my hash is 100% ok, for both situations GET and PUT. I'd added all needed Headers, but, i'm still stuck with that error.
And, requests get 401 error when i'm not add username and password, When i add login credential connection is established but error 2000 appears. I did not found nothing in api docs about login and password neither your examples have. What i'm doing wrong, pls give me a hand!
Thank you!

body for POST request malformed

Hello, following command line is not working, probably because the body parameter with POST request is not properly formatted, but according to documentation it should work. GET requests work, but not POST:

nicehash -b https://api2.nicehash.com -o key -k key -s secret -m POST -p "/main/api/v2/hashpower/order/some_order/updatePriceAndLimit" -d {\"price\":0.0050,\"limit\":0.9,\"displayMarketFactor\":\"GH\",\"marketFactor\":1000000000}

Error getting profitability info

Hello, I am using the python client.

I added this in the public api class, and used the example body in the official document.

def get_profitability(self, speeds):
    hashrate_data = {"speeds": {"SCRYPT": 50, "SHA256":20}}
    return self.request('POST', '/main/api/v2/public/profcalc/profitability/', '', hashrate_data)

However, every time I run my code, I get this error
Exception: 415: Unsupported Media Type: b'{"error_id":"f4d268dd-91a0-403b-8e7e-3dbd6d8a55fd","errors":[{"code":140,"message":"Unsupported media type"}]}'

Any advices will be helpful!
Thank you

API key generation doesn't work

Since Nicehash on new platform closed all addresses to get help (just no information, how to get help), I have to write here: creation of ne API keys doesn't work (FF 68.01, Chrome 77.038, ... )

I've got API key creation failed, that's all. Fresh new account on new version of platform, tried different accounts.

So your rest API doesn't work too :)

NHOS POST Malformed request 60 with /main/api/v2/mining/rigs/status2

Hi, GET API examples work fine, keep getting a malformed request with POST. Is anyone able to tell me what this error code is related too?

python3 nicehash.py -b https://api2.nicehash.com -o orgid -k key -s secret -m POST -p /main/api/v2/mining/rigs/status2 -d '{"rigId": "rigidhere", "deviceId": "2-4", "action": "STOP"}'

Unexpected error: 400: Bad Request: b'{"error_id":"b8220586-b6b5-4cf6-a793-aaf8fde97432","errors":[{"code":60,"message":"Malformed request"}]}'

My rig is running NHOS

Invalid Session code 2000 in Python

I want to call the following url using python, but I get an error.
What should I fix?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid, hmac, hashlib, requests, json
urlroot = 'https://api2.nicehash.com'
xtime = str(json.loads(requests.get('https://api2.nicehash.com/api/v2/time').text)['serverTime'])
xnonce = str(uuid.uuid4())
xorid = 'MY_ORG_ID'
apikey = 'MY_KEY'
mthd = 'GET'
pth = '/main/api/v2/mining/rigs'
qry = 'size=100&page=0'
scrt = 'MY_SECRET'
inpt = '{}\00{}\00{}\00\00{}\00\00{}\00{}\00{}'.format(apikey, xtime, xnonce, xorid, mthd, pth, qry)
sig = hmac.new(inpt.encode(), scrt.encode(), hashlib.sha256).hexdigest()
xauth = '{}:{}'.format(apikey, sig)
r = requests.get('{}{}?{}'.format(urlroot, pth, qry), headers={'X-Time': xtime, 'X-Nonce': xnonce, 'X-Organization-Id': xorid, 'X-Request-Id': xnonce, 'X-Auth': xauth})
data = json.loads(r.text)
print(data)

{'error_id': '64ee9c9f-6612-405b-9dd8-1b7bcb304e1b', 'errors': [{'code': 2000, 'message': 'Invalid Session'}]}

get account insufficient permissions

So I tried to use this specific endpoint, and can't seem to be able to get the info.

I have been using some other rig functions as well, marked as private, so I don't think that would be the issue.

Any chance it's my 2-factor auth causing these issues?

If so, any way to bypass it or validate it?

Invalid Session

Any more info on why a request is getting code:2000 Invalid Session error? Signing is correct in X-Auth.

Error 2000 Invalid session

import nicehash

host = 'https://api2.nicehash.com/'
organisation_id = 'id'
key = 'key'
secret = 'secret'

private_api = nicehash.private_api(host, organisation_id, key, secret)

my_accounts = private_api.get_accounts_for_currency('BTC')
print(my_accounts)

error:

Exception: 401: Unauthorized: b'{"error_id":"e7e06815-4aa6-41d6-a9a7-423f8063cdf8","errors":[{"code":2000,"message":"Invalid session"}]}'

Any ideas on implementing for R?

Hi all,

I'm a newbie and the only language I know a little of is R.

I've managed to get a number of other APIs working under R using syntax like this:

  # Account Stats
  response <- httr::GET( 
    url = "https://API_URL_GOES_HERE", 
  )

I think I've got the gist of the syntax for R, but I'm having problems with hashing the Secret Key.

My API key / secret works with the "Try it out" link here.

But I get the usual invalid / 2000 error when passing my hashed secret key via the API.

Here's my code:

Here's how I'm trying to generate the hashed secret key:

input <- paste0(APIKey," ", XTime," ", XNonce," "," ", OrgID," ", " ", "GET"," ", "/main/api/v2/accounting/accounts2", " ")
# Needs hashed?
APISecret <- hmac(input, "My_Secret_Key", "sha256")
XAuth <- paste0(APIKey, ":", APISecret)

And here's my API call:

# Account Stats
response<- httr::GET( 
  url = "https://api2.nicehash.com/main/api/v2/accounting/accounts2", 
  httr::add_headers(
    `X-Time` = XTime,
    `X-Nonce` = XNonce,
    `X-Organization-Id` = OrgID,
    #`X-Request-Id` = XNonce,
    `X-Auth`= XAuth,
    `Content-Type` = "application/json; charset=utf-8"
  )
)

My thoughts are:

  1. input is not correctly formatted
  2. hmac() isn't generating what NiceHash expects
  3. My GET() isn't structured quite right

Any ideas?

Invalid Session - WITHDRAWAL

when I try to withdraw with the api
curl /main/api/v2/accounting/withdrawal2/{currency}/{id}

i have the following answer:
{"error_id":"87e68fc4-b67d-468e-b570-ddae003ba9db","errors":[{"code":2000,"message":"Invalid session"}]}

is this because i have 2FA enabled? if yes is there any way to request with the 2fa code?

Malformed request

Hello,

I'm getting the following error:
,"errors":[{"code":60,"message":"Malformed request"}]
When I'm trying to call "/main/api/v2/hashpower/myOrders/" on the production environment.

I'm using the examples from this repo with this exact file : https://github.com/nicehash/rest-clients-demo/blob/master/javascript/api.js

apiKey, apiSecret and organisation id are 100% correct. I checked them several times.

What this error might mean ?
Thanks

nicehash.py wrong path to the endpoint

nicehash.py
(

def get_curencies(self):
)

def get_curencies(self):
    return self.request('GET', '/api/v2/enum/currencies/', '', None)

Exception: 404: Not Found

get_curencies method missed second 'r' in 'curencies' by design?

this also leads to

(

my_btc_account = private_api.get_accounts_for_currency(currencies['currencies'][0]['currency'])
)
my_btc_account = private_api.get_accounts_for_currency(currencies['currencies'][0]['currency'])

generate

NameError: name 'currencies' is not defined

Java example with time rage

Hello.
I'm not able to figure out how to make Java example to work with URL:
https://api2.nicehash.com/main/api/v2/mining/rigs/stats/algo/
Do you have any example of call with time rage?

C# API sample broken

Is the C# api sample meant to be working? I'm getting the 2000 invalid session error that others have complained about but I'm using the published api class in the C# demo.

HMAC Signature Calculation

Hi, I'm reading this example overhere https://docs.nicehash.com/main/index.html
Input for signing:
4ebd366d-76f4-4400-a3b6-e51515d054d6 ⊠ 1543597115712 ⊠ 9675d0f8-1325-484b-9594-c9d6d3268890 ⊠ ⊠ da41b3bc-3d0b-4226-b7ea-aee73f94a518 ⊠ ⊠ GET ⊠ /main/api/v2/hashpower/orderBook ⊠ algorithm=X16R&page=0&size=100

Signature is generated via HMAC-SHA256 (input, API_SECRET): 21e6a16f6eb34ac476d59f969f548b47fffe3fea318d9c99e77fc710d2fed798
Then I try to re-create the signature with this tool https://www.freeformatter.com/hmac-generator.html#ad-output, by using the same input & secret, but I can't reproduce it no matter what, can anyone please guide me how to correctly create the HMAC SHA256 signature ? Thank you in advance.

C# sample app

Hi, I have tried to use the C# demo app, found it a bit hard to understand and it uses .NET Framework instead of .NET.

I have built a Console application that takes in stats, start-rig and stop-rig so we can control our rigs and see some stats.
https://github.com/jernejk/NiceHash

It also has the implementation in a separate project, so everyone can build their own solution and extend the implementation.
The next example will include Elgato Stream Deck, so we can more easily turn off the miner before starting to game.

JavaScript getting invaild session when posting

I got code 140 when posting to https://api2.nicehash.com/main/api/v2/mining/rigs/status2

and this is my request code:

var rawUrl = 'https://api2.nicehash.com/main/api/v2/mining/rigs/status2';
var url = require('url');
var link = url.parse(rawUrl);
var path = "/main/api/v2/mining/rigs/status2";
var requestBody =
{
	"rigId": "...",
	"action": "START"
};

// ...

var hmac = forge.hmac.create();
hmac.start('sha256', niceHashAPISecret);
var utcTimeUnix = (Math.floor(new Date().getTime())).toString();
var randomUUID = require('uuid').v4();
hmac.update(`${niceHashAPIKey}\0${utcTimeUnix}\0${randomUUID}\0\0${niceHashOrgID}\0\0POST\0${path}\0\0${JSON.stringify(requestBody)}`);
var hashText = hmac.digest().toHex();

// ...

const https = require("https");
var options =
{
	method: 'POST',
	hostname: link.hostname,
	port: null,
	path: link.path,
	headers:
	{
		'X-Time': utcTimeUnix,
		'X-Nonce': randomUUID,
		'X-Organization-Id': niceHashOrgID,
		'X-Request-Id': randomUUID + "_RID",
		'X-Auth': niceHashAPIKey + ":" + hashText,
		'X-User-Agent': 'NHNodeClient'
	},
	json: true
};

// ...

var req = https.request(options, res => {...});
req.write(JSON.stringify(requestBody));
req.end();









INVALID SESSION VBA

I am using the following code for hashpowerEarnings results from API In Excel with VBA, but it shows an INVALID SESSION error

Private strURL, strQuery, apiKey, apiSecret, urlSignature, OrgID, nTime, nNonce, xAuth As String

Sub getAPIData()
  Dim endpoint As String
  Dim encodedURLLink As String
  Dim urlroot As String
  Dim pth As String
  Dim spaceS As String
  
  
  urlroot = "https://api2.nicehash.com"
  pth = "/main/api/v2/accounting/hashpowerEarnings/BTC"
  apiKey = "XXXX"
  apiSecret = "XXXX"
  OrgID = "XXXX"
  
  nTime = nichhashTime
  nNonce = generateNonce
  
  endpoint = apiKey + nTime + nNonce + OrgID + "GET" + pth
  strURL = urlroot & pth
  
  xAuth = apiKey & ":" & HexHash(endpoint, apiSecret, "SHA256")
  Debug.Print GetHttpResponse()
End Sub

Function GetHttpResponse() As String
Dim objHTTP: Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
With objHTTP
    .Open "GET", strURL, False
    .setrequestheader "X-Time", Str(nTime)
    .setrequestheader "X-Nonce", nNonce
    .setrequestheader "X-Organization-Id", OrgID
    .setrequestheader "X-Request-Id", generateNonce
    .setrequestheader "X-Auth", xAuth
    .send
    GetHttpResponse = .responseText
End With
Set objHTTP = Nothing
End Function

Function nichhashTime() As String
Dim strTime As String
Dim xhr1: Set xhr1 = CreateObject("WinHttp.WinHttpRequest.5.1")
With xhr1
    .Open "GET", "https://api2.nicehash.com/api/v2/time"
    .send
    .waitForResponse
    strTime = .responseText
End With
nichhashTime = Mid(strTime, 15, 13)
End Function

API reply is following-
{"error_id":"dc7a58bc-805c-4fc7-990d-2741dd6d5269","errors":[{"code":2000,"message":"Invalid `session"}]}

/main/api/v2/mining/rig/stats/algo maximum range

Hello, it looks like /main/api/v2/mining/rig/stats/algo is limited to the last 7 days even if afterTimestamp goes further back than that.
Is there a way to obtain longer timeseries of stats for individual rigs?

TypeScript version of api.js (+ solution with node-fetch)

It'd be great to have TS version of Api.js.

Here's my stab at it:

import CryptoJS from "crypto-js";
import fetch from "node-fetch";
import { parse, stringify } from "qs";

function createNonce() {
  let s = "";
  const length = 32;
  do {
    s += Math.random().toString(36).slice(2);
  } while (s.length < length);
  s = s.slice(0, Math.max(0, length));
  return s;
}

const getAuthHeader = (
  apiKey: string,
  apiSecret: string,
  time: string,
  nonce: string,
  organizationId = "",
  request: {
    method: string;
    path: string;
    query: Record<string, unknown> | string;
    body: unknown;
  },
) => {
  const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, apiSecret);

  hmac.update(apiKey);
  hmac.update("\0");
  hmac.update(time);
  hmac.update("\0");
  hmac.update(nonce);
  hmac.update("\0");
  hmac.update("\0");
  if (organizationId) hmac.update(organizationId);
  hmac.update("\0");
  hmac.update("\0");
  hmac.update(request.method);
  hmac.update("\0");
  hmac.update(request.path);
  hmac.update("\0");
  if (request.query)
    hmac.update(
      typeof request.query === "string"
        ? request.query
        : stringify(request.query),
    );
  if (request.body) {
    hmac.update("\0");
    hmac.update(
      typeof request.body === "string"
        ? request.body
        : JSON.stringify(request.body),
    );
  }

  return apiKey + ":" + hmac.finalize().toString(CryptoJS.enc.Hex);
};

export default class Api {
  private readonly locale: string;
  private readonly host: string;
  private readonly key: string;
  private readonly secret: string;
  private readonly org: string;
  private localTimeDiff?: number;

  constructor({
    locale,
    apiHost,
    apiKey,
    apiSecret,
    orgId,
  }: {
    locale?: string;
    apiHost: string;
    apiKey: string;
    apiSecret: string;
    orgId: string;
  }) {
    this.locale = locale || "en";
    this.host = apiHost;
    this.key = apiKey;
    this.secret = apiSecret;
    this.org = orgId;

    this.getTime();
  }

  async getTime() {
    const response = (await (
      await fetch(this.host + "/api/v2/time")
    ).json()) as { serverTime: number };
    this.localTimeDiff = response.serverTime - Date.now();
    return response;
  }

  private async apiCall(
    method: "GET" | "POST" | "PUT" | "DELETE",
    path: string,
    options?: {
      query: Record<string, unknown>;
      body?: unknown;
      time?: number;
    },
  ) {
    let query = {},
      body,
      time;
    if (options) ({ query, body, time } = options);

    if (this.localTimeDiff === undefined) {
      throw new Error("Get server time first .getTime()");
    }

    // query in path
    const [pathOnly, pathQuery] = path.split("?");
    if (pathQuery) query = { ...parse(pathQuery), ...query };

    const nonce = createNonce();
    const timestamp = (time || Date.now() + this.localTimeDiff).toString();

    return (
      await fetch(`${this.host}${pathOnly}?${stringify(query)}`, {
        method: method,
        headers: {
          "X-Request-Id": nonce,
          "X-User-Agent": "NHNodeClient",
          "X-Time": timestamp,
          "X-Nonce": nonce,
          "X-User-Lang": this.locale,
          "X-Organization-Id": this.org,
          "X-Auth": getAuthHeader(
            this.key,
            this.secret,
            timestamp,
            nonce,
            this.org,
            {
              method,
              path: pathOnly,
              query,
              body,
            },
          ),
        },
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        body: body as any,
      })
    ).json();
  }

  get(
    path: string,
    options?: {
      query: Record<string, unknown>;
      body?: unknown;
      time?: number;
    },
  ) {
    return this.apiCall("GET", path, options);
  }

  post(
    path: string,
    options?: {
      query: Record<string, unknown>;
      body?: unknown;
      time?: number;
    },
  ) {
    return this.apiCall("POST", path, options);
  }

  put(
    path: string,
    options?: {
      query: Record<string, unknown>;
      body?: unknown;
      time?: number;
    },
  ) {
    return this.apiCall("PUT", path, options);
  }

  delete(
    path: string,
    options?: {
      query: Record<string, unknown>;
      body?: unknown;
      time?: number;
    },
  ) {
    return this.apiCall("DELETE", path, options);
  }
}

Then I use it like so:

await api.getTime(); // get server time - required
const { totalBalance } = (await api.get(
  "/main/api/v2/accounting/account2/BTC",
)) as { totalBalance: number }; // get balance settings
console.log(`NiceHash total balance: ${totalBalance} BTC`);

Exchange Order API

I've been trying to call the Exhange Order API but unluckily I can't succeed. I don't know what is the problem with the code below. I can get the Wallet balance and the Server time but not on POSTING new Order..

`<?
echo '

';
$url_root = "https://api2.nicehash.com";
$org_id = "";
$api_key = "";
$api_secret = "";

//get current time
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, $url_root."/api/v2/time");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);

$time = json_decode($result, true)['serverTime'];
echo "server time: ".$time."\n";


$nonce     = uniqid();
$path      = "/exchange/api/v2/order";
//$qs        = "market=BTCUSDC&side=SELL&type=LIMIT&quantity=.00012&price=35000&secQuantity=.00012";
$qs ="";

$postbody  = json_encode(array(
	"market"=>"BTCUSDC",
	"side"=>"SELL",
	"type"=>"LIMIT",
	"quantity"=>0.00012,
	"price"=>35000,
	"minSecQuantity"=>'',
	"secQuantity"=>0.00012,
	"minQuantity"=>''
	)
);

print_r($postbody);
$postlen   = strlen($postbody);

//$signature = $api_key."\x00".$time."\x00".$nonce."\x00"."\x00".$org_id."\x00"."\x00"."POST"."\x00".$path."\x00".$qs;
//$signature = $api_key."\x00".$time."\x00".$nonce."\x00"."\x00".$org_id."\x00"."\x00"."POST"."\x00".$path."\x00".$qs."\x00".$postbody;
$signature = $api_key."\x00".$time."\x00".$nonce."\x00"."\x00".$org_id."\x00"."\x00"."POST"."\x00".$path."\x00".$postbody;
$signhash  = hash_hmac('sha256', $signature, $api_secret);


//$postlen   = strlen($qs);

//echo $postlen .' <br>';

$headers = array(
	"X-Time: {$time}",
	"X-Nonce: {$nonce}",
	"X-Organization-Id: {$org_id}",
	"X-Request-Id: {$nonce}",
	"X-Auth: {$api_key}:{$signhash}",
	"Content-Length: {$postlen}",
);
echo ' <br>headers: <br>';
print_r ($headers);

$curl = curl_init($url_root.$path);
//curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postbody); 


//curl_setopt($curl, CURLOPT_URL, $url_root.$path.'?'.$qs);
//curl_setopt($curl, CURLOPT_URL, $url_root.$path);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);

if(curl_errno($curl)){
    echo 'Err : ' . curl_error($curl) .'<br>';
}
print_r($result);

curl_close($curl);
//if(!$result){echo "Connection Failure";}


//print_r($result);

$info = json_decode($result, true);
echo '<br>info: <br>';
print_r($info);


echo '-- END -- <br>';

?>`

Income Projections

I've been looking through the API documentation and I can find no reference to income projections (a feature of the old api).

On the NiceHash website, it is easy to find the income projections (https://www.nicehash.com/my/mining/stats).

Is this functionality available in the v2 API? If not, will it be in the future? I found this information very useful in the v1 API.

Getting error code 10 on withdrawl

Withdrawl endpoint seems to be broken, somehow? Atfirst started getting "unsupported media type" and as soon as I added the accept & contenttype headers for a json request im now getting:

{
error_id: '8b31ab1d-351e-4cbe-a60d-cc872de5af85',
errors: [
{
code: 10,
message: 'An error occurred while fulfilling the request'
}
]
}

Generic Server Error on creating FIXED order

Hello some time ago I debugged here parameters for STANDARD order in Issue #46 . I now try to create FIXED order. In parameters I replaced STANDARD type with FIXED, but that did not work and returns

Unexpected error: 500: Internal Server Error: b'{"error_id":"ab668244-7212-405e-a6d1-2f7b6bf757ed","errors":[{"code":2999,"message":"Generic Server Error"}]}'

Parameters are:
python3 /home/janbenes/nicehash.py -b https://api2.nicehash.com -o dorg-key1 -k a-key-5 -s 3-secret-e -m POST -p "/main/api/v2/hashpower/order" -d '{"market":"EU","algorithm":"SHA256ASICBOOST","amount":"0.001","poolId":"125c3400-e602-4ae1-953c-402298533158","type":"FIXED","marketFactor":"1000000000000000.00000000","displayMarketFactor":"PH","limit":"500","price":"0.0051","displayPriceFactor":"PH","priceFactor":"1000000000000000.00000000"}'

Enable CORS support

I am unable to use the NiceHash API from a web app, specifically Flutter Web. From an Android device works fine.

The error message I get isn't very helpful ("XMLHttpRequest error"), but almost every GitHub issue or Stack Overflow post I could find says that the server side needs to enable CORS support:
https://stackoverflow.com/a/60891897/9915119
flutter/flutter#57421 (comment)
https://stackoverflow.com/a/71369372/9915119
https://enable-cors.org/server.html

Seems like this would need to get fixed from your end but also doesn't seem that hard to change.

Insomnia

Looking to get the API work with Insomnia but I dont know which value goes where. Like are the API key go as a header or what?

Thank you

Withdrawal API not work

I can't make a withdrawal request by API it keep showing error code 10 with message "An error occurred while fulfilling the request"

invalid session #3

having issues signing POST request. specifically "Create Order"....what should the message body look like? I can replicate example given in issue #2 just not with actual order data. signed Get requests are working fine.....not sure what I'm missing. thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.