-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huobi.py
530 lines (429 loc) · 15 KB
/
Huobi.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
import datetime
import hashlib
import hmac
import json
import urllib
import urllib.parse
import urllib.request
import requests
class Client(object):
# API 请求地址
MARKET_URL = "https://api.huobi.pro"
TRADE_URL = "https://api.huobi.pro"
def __init__(self, api_key, api_secret):
self.ACCESS_KEY = api_key
self.SECRET_KEY = api_secret
if(api_key != ''):
accounts = self.get_accounts()
self.ACCOUNT_ID = accounts['data'][0]['id']
def _http_get_request(self, url, params, add_to_headers=None):
headers = {
"Content-type": "application/x-www-form-urlencoded",
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
}
if add_to_headers:
headers.update(add_to_headers)
postdata = urllib.parse.urlencode(params)
try:
response = requests.get(url, postdata, headers=headers, timeout=5)
if response.status_code == 200:
return response.json()
else:
return
except BaseException as e:
print("httpGet failed, detail is:%s,%s" %(response.text,e))
return
def _http_post_request(self, url, params, add_to_headers=None):
headers = {
"Accept": "application/json",
'Content-Type': 'application/json'
}
if add_to_headers:
headers.update(add_to_headers)
postdata = json.dumps(params)
try:
response = requests.post(url, postdata, headers=headers, timeout=10)
if response.status_code == 200:
return response.json()
else:
return
except BaseException as e:
print("httpPost failed, detail is:%s,%s" %(response.text,e))
return
def _api_key_get(self, params, request_path):
method = 'GET'
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
params.update({'AccessKeyId': self.ACCESS_KEY,
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'Timestamp': timestamp})
host_url = self.TRADE_URL
host_name = urllib.parse.urlparse(host_url).hostname
host_name = host_name.lower()
params['Signature'] = self._createSign(params, method, host_name, request_path, self.SECRET_KEY)
url = host_url + request_path
return self._http_get_request(url, params)
def _api_key_post(self, params, request_path):
method = 'POST'
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
params_to_sign = {'AccessKeyId': self.ACCESS_KEY,
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'Timestamp': timestamp}
host_url = self.TRADE_URL
host_name = urllib.parse.urlparse(host_url).hostname
host_name = host_name.lower()
params_to_sign['Signature'] = self._createSign(params_to_sign, method, host_name, request_path, self.SECRET_KEY)
url = host_url + request_path + '?' + urllib.parse.urlencode(params_to_sign)
return self._http_post_request(url, params)
def _createSign(self, pParams, method, host_url, request_path, secret_key):
sorted_params = sorted(pParams.items(), key=lambda d: d[0], reverse=False)
encode_params = urllib.parse.urlencode(sorted_params)
payload = [method, host_url, request_path, encode_params]
payload = '\n'.join(payload)
payload = payload.encode(encoding='UTF8')
secret_key = secret_key.encode(encoding='UTF8')
digest = hmac.new(secret_key, payload, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(digest)
signature = signature.decode()
return signature
'''
Market data API
'''
# 获取KLine
def get_kline(self, symbol, period, size=150):
"""
:param symbol
:param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
:param size: 可选值: [1,2000]
:return:
"""
params = {'symbol': symbol,
'period': period,
'size': size}
url = self.MARKET_URL + '/market/history/kline'
return self._http_get_request(url, params)
# 获取marketdepth
def get_depth(self, symbol, type):
"""
:param symbol
:param type: 可选值:{ percent10, step0, step1, step2, step3, step4, step5 }
:return:
"""
params = {'symbol': symbol,
'type': type}
url = self.MARKET_URL + '/market/depth'
return self._http_get_request(url, params)
# 获取tradedetail
def get_trade(self, symbol):
"""
:param symbol
:return:
"""
params = {'symbol': symbol}
url = self.MARKET_URL + '/market/trade'
return self._http_get_request(url, params)
# 获取merge ticker
def get_ticker(self, symbol):
"""
:param symbol:
:return:
"""
params = {'symbol': symbol}
url = self.MARKET_URL + '/market/detail/merged'
return self._http_get_request(url, params)
# 获取 Market Detail 24小时成交量数据
def get_detail(self, symbol):
"""
:param symbol
:return:
"""
params = {'symbol': symbol}
url = self.MARKET_URL + '/market/detail'
return self._http_get_request(url, params)
# 获取 支持的交易对
def get_symbols(self, long_polling=None):
"""
"""
params = {}
if long_polling:
params['long-polling'] = long_polling
path = '/v1/common/symbols'
return self._api_key_get(params, path)
'''
Trade/Account API
'''
def get_accounts(self):
"""
:return:
"""
path = "/v1/account/accounts"
params = {}
return self._api_key_get(params, path)
# 获取当前账户资产
def get_balance(self, acct_id=None):
"""
:param acct_id
:return:
"""
if not acct_id:
accounts = self.get_accounts()
acct_id = accounts['data'][0]['id'];
url = "/v1/account/accounts/{0}/balance".format(acct_id)
params = {"account-id": acct_id}
return self._api_key_get(params, url)
# 下单
# 创建并执行订单
def send_order(self, amount, source, symbol, _type, price=0):
"""
:param amount:
:param source: 如果使用借贷资产交易,请在下单接口,请求参数source中填写'margin-api'
:param symbol:
:param _type: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param price:
:return:
"""
try:
accounts = self.get_accounts()
acct_id = accounts['data'][0]['id']
except BaseException as e:
print ('get acct_id error.%s' % e)
acct_id = self.ACCOUNT_ID
params = {"account-id": acct_id,
"amount": amount,
"symbol": symbol,
"type": _type,
"source": source}
if price:
params["price"] = price
url = '/v1/order/orders/place'
return self._api_key_post(params, url)
# 撤销订单
def cancel_order(self, order_id):
"""
:param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}/submitcancel".format(order_id)
return self._api_key_post(params, url)
# 查询某个订单
def order_info(self, order_id):
"""
:param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}".format(order_id)
return self._api_key_get(params, url)
# 查询某个订单的成交明细
def order_matchresults(self, order_id):
"""
:param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}/matchresults".format(order_id)
return self._api_key_get(params, url)
# 查询当前委托、历史委托
def orders_list(self, symbol, states, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
"""
:param symbol:
:param states: 可选值 {pre-submitted 准备提交, submitted 已提交, partial-filled 部分成交, partial-canceled 部分成交撤销, filled 完全成交, canceled 已撤销}
:param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param start_date:
:param end_date:
:param _from:
:param direct: 可选值{prev 向前,next 向后}
:param size:
:return:
"""
params = {'symbol': symbol,
'states': states}
if types:
params[types] = types
if start_date:
params['start-date'] = start_date
if end_date:
params['end-date'] = end_date
if _from:
params['from'] = _from
if direct:
params['direct'] = direct
if size:
params['size'] = size
url = '/v1/order/orders'
return self._api_key_get(params, url)
# 查询当前成交、历史成交
def orders_matchresults(self, symbol, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
"""
:param symbol:
:param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param start_date:
:param end_date:
:param _from:
:param direct: 可选值{prev 向前,next 向后}
:param size:
:return:
"""
params = {'symbol': symbol}
if types:
params[types] = types
if start_date:
params['start-date'] = start_date
if end_date:
params['end-date'] = end_date
if _from:
params['from'] = _from
if direct:
params['direct'] = direct
if size:
params['size'] = size
url = '/v1/order/matchresults'
return self._api_key_get(params, url)
# 申请提现虚拟币
def withdraw(self, address, amount, currency, fee=0, addr_tag=""):
"""
:param address_id:
:param amount:
:param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种)
:param fee:
:param addr-tag:
:return: {
"status": "ok",
"data": 700
}
"""
params = {'address': address,
'amount': amount,
"currency": currency,
"fee": fee,
"addr-tag": addr_tag}
url = '/v1/dw/withdraw/api/create'
return self._api_key_post(params, url)
# 申请取消提现虚拟币
def cancel_withdraw(self, address_id):
"""
:param address_id:
:return: {
"status": "ok",
"data": 700
}
"""
params = {}
url = '/v1/dw/withdraw-virtual/{0}/cancel'.format(address_id)
return self._api_key_post(params, url)
'''
借贷API
'''
# 创建并执行借贷订单
def send_margin_order(self, amount, source, symbol, _type, price=0):
"""
:param amount:
:param source: 'margin-api'
:param symbol:
:param _type: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param price:
:return:
"""
try:
accounts = self.get_accounts()
acct_id = accounts['data'][0]['id']
except BaseException as e:
print ('get acct_id error.%s' % e)
acct_id = self.ACCOUNT_ID
params = {"account-id": acct_id,
"amount": amount,
"symbol": symbol,
"type": _type,
"source": 'margin-api'}
if price:
params["price"] = price
url = '/v1/order/orders/place'
return self._api_key_post(params, url)
# 现货账户划入至借贷账户
def exchange_to_margin(self, symbol, currency, amount):
"""
:param amount:
:param currency:
:param symbol:
:return:
"""
params = {"symbol": symbol,
"currency": currency,
"amount": amount}
url = "/v1/dw/transfer-in/margin"
return self._api_key_post(params, url)
# 借贷账户划出至现货账户
def margin_to_exchange(self, symbol, currency, amount):
"""
:param amount:
:param currency:
:param symbol:
:return:
"""
params = {"symbol": symbol,
"currency": currency,
"amount": amount}
url = "/v1/dw/transfer-out/margin"
return self._api_key_post(params, url)
# 申请借贷
def get_margin(self, symbol, currency, amount):
"""
:param amount:
:param currency:
:param symbol:
:return:
"""
params = {"symbol": symbol,
"currency": currency,
"amount": amount}
url = "/v1/margin/orders"
return self._api_key_post(params, url)
# 归还借贷
def repay_margin(self, order_id, amount):
"""
:param order_id:
:param amount:
:return:
"""
params = {"order-id": order_id,
"amount": amount}
url = "/v1/margin/orders/{0}/repay".format(order_id)
return self._api_key_post(params, url)
# 借贷订单
def loan_orders(self, symbol, currency, start_date="", end_date="", start="", direct="", size=""):
"""
:param symbol:
:param currency:
:param direct: prev 向前,next 向后
:return:
"""
params = {"symbol": symbol,
"currency": currency}
if start_date:
params["start-date"] = start_date
if end_date:
params["end-date"] = end_date
if start:
params["from"] = start
if direct and direct in ["prev", "next"]:
params["direct"] = direct
if size:
params["size"] = size
url = "/v1/margin/loan-orders"
return self._api_key_get(params, url)
# 借贷账户详情,支持查询单个币种
def margin_balance(self, symbol):
"""
:param symbol:
:return:
"""
params = {}
url = "/v1/margin/accounts/balance"
if symbol:
params['symbol'] = symbol
return self._api_key_get(params, url)