-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnicehash_api.py
executable file
·382 lines (337 loc) · 13 KB
/
nicehash_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python3
# Copyright 2020 Blade M. Doyle
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import uuid
import time
import json
import requests
import traceback
from datetime import datetime, timedelta
import hashlib
import hmac
import base64
## NiceHash settings - https://docs.nicehash.com/main/index.html
UPDATE_INTERVAL = timedelta(minutes = 10)
MAX_DECREASE = 0.0001
## --
class NiceHash():
def __init__(self, API_ID="", API_KEY="", ORG_ID="", logger=None):
self.API_ID = API_ID
self.API_KEY = API_KEY
self.ORG_ID = ORG_ID
self.mfd = {}
if logger is not None:
self.logger = logger
else:
import logging
self.logger = logging.getLogger("gnd")
def setAuth(self, nhid, nhkey, nhorg):
self.API_ID = nhid
self.API_KEY = nhkey
self.ORG_ID = nhorg
def call_nicehash_api(self, path, method, args=None, body=None):
url = "https://api2.nicehash.com"
zero_byte_field = "\x00"
timestamp = str(int(time.time() * 1000 ))
nonce = str(uuid.uuid4())
request_query_str = url + path
body_str = json.dumps(body)
req = "ts=" + str(timestamp)
if args is not None:
for arg, val in args.items():
req += "&{}={}".format(arg, val)
elif body is not None:
for arg, val in body.items():
req += "&{}={}".format(arg, val)
else:
raise Exception("Must specify either args or body")
request_query_str += "?" + req
secret_bytes = bytearray(self.API_KEY, 'ISO-8859-1')
message = self.API_ID + \
zero_byte_field + \
timestamp + \
zero_byte_field + \
nonce + \
zero_byte_field + \
zero_byte_field + \
self.ORG_ID + \
zero_byte_field + \
zero_byte_field + \
method + \
zero_byte_field + \
path + \
zero_byte_field + \
req
if body is not None:
message += \
zero_byte_field + \
body_str
message_bytes = bytearray(message, 'ISO-8859-1')
signature = hmac.new(secret_bytes, msg = message_bytes, digestmod = hashlib.sha256).hexdigest()
headers = {
'Content-type': 'application/json',
"X-Time": timestamp,
"X-Nonce": nonce,
"X-Organization-ID": self.ORG_ID,
}
if self.API_ID != "" and self.API_KEY != "":
headers["X-Auth"] = self.API_ID + ":" + signature
if method == "GET":
r = requests.get(
url=request_query_str,
headers=headers,
timeout=20,
)
elif method == "POST":
#print("xxx: {}".format(request_query_str))
#print("yyy: {}".format(body_str))
r = requests.post(
url=request_query_str,
headers=headers,
data=body_str,
timeout=20,
)
elif method == "DELETE":
#print("xxx: {}".format(request_query_str))
#print("yyy: {}".format(body_str))
r = requests.delete(
url=request_query_str,
headers=headers,
timeout=20,
)
else:
raise Exception("Unsupported method: {}".format(method))
if r.status_code >= 300 or r.status_code < 200:
error_msg = "Error calling {}. Code: {} Reason: {} content: {}".format(url, r.status_code, r.reason, r.content)
raise Exception(error_msg)
r_json = r.json()
if "error_id" in r_json:
message = r_json["errors"]["message"]
method = r_json["method"]
error_msg = "Error calling {}. Reason: {}".format(method, message)
raise Exception(error_msg)
#print("xxx {}".format(r_json))
return r_json
##
# Get Market Factor Data
def getMarketFactorData(self, algo):
# Its ok to cache this, it does not change
if algo in self.mfd:
return self.mfd[algo]
getAlgorithms_path = "/main/api/v2/mining/algorithms/"
getAlgorithms_args = {}
try:
result = self.call_nicehash_api(
path = getAlgorithms_path,
args = getAlgorithms_args,
method = "GET",
)
algorithms = result["miningAlgorithms"]
for a in algorithms:
if a["algorithm"] == algo:
self.mfd[algo] = a
return a
except Exception as e:
self.logger.error("failed getMarketFactorData(): {}".format(e))
raise
return None
##
# Get NiceHash orderbook for algo on market
def getOrderBook(self, market, algo):
getOrderBook_path = "/main/api/v2/hashpower/orderBook/"
getOrderBook_args = {
"algorithm": algo,
"page": "0",
"size": "1000",
}
try:
result = self.call_nicehash_api(
path = getOrderBook_path,
args = getOrderBook_args,
method = "GET",
)
orderbook = result["stats"][market]
except Exception as e:
self.logger.error("failed getOrderBook(): {}".format(e))
raise
return orderbook
# Get pool ID by name
def getPoolId(self, pool_name):
getPoolId_path = "/main/api/v2/pools"
getPoolId_args = {
"page": "0",
"size": "1000",
}
try:
result = self.call_nicehash_api(
path = getPoolId_path,
args = getPoolId_args,
method = "GET",
)
pools = result["list"]
except Exception as e:
self.logger.error("failed getPoolId(): {}".format(e))
raise
for pool in pools:
if pool["name"] == pool_name:
return pool["id"]
return None
def createOrder(self, algo, market, pool_id, price, speed, amount):
marketFactor = int(self.getMarketFactorData(algo)["marketFactor"])
displayMarketFactor = self.getMarketFactorData(algo)["displayMarketFactor"]
# Create an order
createOrder_path = "/main/api/v2/hashpower/order"
createOrder_body = {
"market": market,
"algorithm": algo,
"amount": amount,
"type": "STANDARD",
"poolId": pool_id,
"limit": "{:.2f}".format(float(speed)),
"price": "{:.4f}".format(float(price)),
"marketFactor": marketFactor,
"displayMarketFactor": displayMarketFactor.encode(),
}
self.logger.warn("createOrder_body: {}".format(createOrder_body))
try:
result = self.call_nicehash_api(
path = createOrder_path,
body = createOrder_body,
method = "POST",
)
order = result
self.logger.warn("order: {}".format(order))
except Exception as e:
self.logger.error("failed createOrder(): {}".format(e))
raise
return order
def getMyOrders(self, market, algo):
# Get existing orders
getMyOrders_path = "/main/api/v2/hashpower/myOrders/"
getMyOrders_args = {
"algorithm": algo,
"market": market,
"op": "LT",
"active": True,
"limit": 100,
}
try:
result = self.call_nicehash_api(
path = getMyOrders_path,
args = getMyOrders_args,
method = "GET",
)
myorders = result["list"]
except Exception as e:
self.logger.error("failed getMyOrders(): {}".format(e))
raise
return myorders
def getOrder(self, order_id):
# Get existing order by id
getOrder_path = "/main/api/v2/hashpower/order/{}/".format(order_id)
getOrder_args = {}
try:
result = self.call_nicehash_api(
path = getOrder_path,
args = getOrder_args,
method = "GET",
)
except Exception as e:
self.logger.error("failed getOrder(): {}".format(e))
raise
return result
def cancelOrder(self, order_id):
# Cancel an order
cancelOrder_path = "/main/api/v2/hashpower/order/{}".format(order_id)
cancelOrder_args = {}
try:
result = self.call_nicehash_api(
path = cancelOrder_path,
args = cancelOrder_args,
method = "DELETE",
)
except Exception as e:
self.logger.error("failed cancelOrder(): {}".format(e))
raise
return result
def updateOrder(self, algo, order_id, speed, price):
marketFactor = self.getMarketFactorData(algo)["marketFactor"]
displayMarketFactor = self.getMarketFactorData(algo)["displayMarketFactor"]
# Update an orders price and/or speed limit
increasePrice_path = "/main/api/v2/hashpower/order/{}/updatePriceAndLimit".format(order_id)
increasePrice_body = {
"marketFactor": marketFactor,
"displayMarketFactor": displayMarketFactor,
"limit": "{:.2f}".format(float(speed)),
"price": "{:.4f}".format(float(price)),
}
self.logger.warn("increasePrice_body: {}".format(increasePrice_body))
try:
result = self.call_nicehash_api(
path = increasePrice_path,
body = increasePrice_body,
method = "POST",
)
self.logger.warn("updated order: {}".format(result))
except Exception as e:
self.logger.error("failed updateOrder(): {}".format(e))
raise
return result
##
def getCurrentPrice(self, market, algo):
# Find the lowest price thats has miners working
orderbook = self.getOrderBook(market, algo)
prices = [o["price"] for o in orderbook["orders"] if int(o["rigsCount"]) > 0 and float(o["acceptedSpeed"]) > 0.00000005 and o["type"] == "STANDARD"]
prices = sorted(prices)
return float(prices[0])
def getCurrentSpeed(self, market, algo):
# Find the current Total Available NiceHash Speed
# aka How much hash nicehash is producing
orderbook = self.getOrderBook(market, algo)
speed = orderbook["totalSpeed"]
return float(speed)
def main():
# Some Tests
nh_api = NiceHash()
nh_api.setAuth(os.getenv("NICEHASH_API_ID"), os.getenv("NICEHASH_API_KEY"), os.getenv("NICEHASH_ORG_ID"))
p = nh_api.getCurrentPrice("EU", "GRINCUCKATOO32")
print("Current Price EU: {}".format(p))
p = nh_api.getCurrentPrice("USA", "GRINCUCKATOO32")
print("Current Price USA: {}\n\n".format(p))
s = nh_api.getCurrentSpeed("EU", "GRINCUCKATOO32")
print("Current Speed EU: {}".format(s))
s = nh_api.getCurrentSpeed("USA", "GRINCUCKATOO32")
print("Current Speed USA: {}\n\n".format(s))
o = nh_api.getMyOrders("EU", "GRINCUCKATOO32")
print("Current Orders EU: {}".format(o))
o = nh_api.getMyOrders("USA", "GRINCUCKATOO32")
print("Current Orders USA: {}\n\n".format(o))
poolid = nh_api.getPoolId("defender")
print("Pool id: {}\n\n".format(poolid))
# The following is commented out because it costs money to test
# o = nh_api.createOrder(algo = "GRINCUCKATOO32",
# market = "EU",
# pool_id = poolid,
# price = 0.1122,
# speed = 0.2,
# amount = 0.005,
# )
# o = nh_api.getOrder(o["id"])
# print("EU order details {}".format(o))
# updated_order = nh_api.updateOrder("GRINCUCKATOO32", o, 0.02 , 0.1122)
# print("Update Order Result: {}\n\n".format(updated_order))
# nh_api.cancelOrder(o)
if __name__ == "__main__":
main()