-
Notifications
You must be signed in to change notification settings - Fork 12
/
zapi.py
559 lines (521 loc) · 18.6 KB
/
zapi.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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import hashlib
import struct
import sha
import time
import requests
suc_codes = ["1000"]
DEBUG = True
errcode = {
"1000": "success",
"1001": "normal error",
"1002": "internal error",
"1003": "verify not passed",
"1004": "fund security password locked",
"1005": "fund security password not right",
"1006": "real-name authentication verifying or not passed",
"1009": "current api not in service",
"2001": "RMB not sufficient",
"2002": "BTC not sufficient",
"2003": "LTC not sufficient",
"2005": "ETH not sufficient",
"2006": "ETC not sufficient",
"2007": "BTS not sufficient",
"2009": "balance not sufficient",
"3001": "order not found",
"3002": "invalid amount of money",
"3003": "invalid count",
"3004": "user not exists",
"3005": "illegal argument",
"3006": "IP error",
"3007": "time expired",
"3008": "trade history not found",
"4001": "API locked or not opened",
"4002": "requests too frequently"
}
ORDER_TYPE_BUY = 1
ORDER_TYPE_SELL = 0
ORDER_STATUS_CANCELED = 1
ORDER_STATUS_DONE = 2
ORDER_STATUS_WAITING = 3
TPL_MARKETS = 'http://api.zb.com/data/v1/markets'
TPL_MARKET = 'http://api.zb.com/data/v1/ticker?market={MARKET}'
TPL_DEPTH = 'http://api.zb.com/data/v1/ticker?market={MARKET}&size={SIZE}'
TPL_TRADES = 'http://api.zb.com/data/v1/trades?market={MARKET}'
TPL_KLINE = 'http://api.zb.com/data/v1/kline?market={MARKET}'
URL_ORDER = 'https://trade.zb.com/api/order'
URL_CANCEL_ORDER = 'https://trade.zb.com/api/cancelOrder'
URL_GET_ORDER = 'https://trade.zb.com/api/getOrder'
URL_GET_ORDERS = 'https://trade.zb.com/api/getOrders'
URL_GET_ORDERS_NEW = 'https://trade.zb.com/api/getOrdersNew'
URL_GET_ORDERS_IGNORE_TRADE_TYPE = 'https://trade.zb.com/api/getOrdersIgnoreTradeType'
URL_GET_UNFINISHED_ORDERS_IGNORE_TRADE_TYPE = 'https://trade.zb.com/api/getUnfinishedOrdersIgnoreTradeType'
URL_GET_ACCOUNT_INFO = 'https://trade.zb.com/api/getAccountInfo'
URL_GET_USER_ADDRESS = 'https://trade.zb.com/api/getUserAddress'
URL_GET_WITHDRAW_ADDRESS = 'https://trade.zb.com/api/getWithdrawAddress'
URL_GET_WITHDRAW_RECORD = 'https://trade.zb.com/api/getWithdrawRecord'
URL_GET_CHARGE_RECORD = 'https://trade.zb.com/api/getChargeRecord'
URL_WITHDRAW = 'https://trade.zb.com/api/withdraw'
class ZApi:
def __init__(self, access_key, secret_key):
"""
opened markets and status, format:
{
"btc_usdt": {
"amountScale": 4,
"priceScale": 2
},
"ltc_usdt": {
"amountScale": 3,
"priceScale": 2
}
...
}
"""
self._access_key_ = access_key
self._secret_key_ = secret_key
self._markets_ = self.markets()
if len(self._markets_) < 1:
raise Exception("Get markets status failed")
def get(self, url):
while True:
try:
r = requests.get(url)
except Exception:
time.sleep(0.5)
continue
if r.status_code != 200:
time.sleep(0.5)
continue
return r.json()
def check_market_code(self, market):
if not market:
return False
if market not in self._markets_:
return False
else:
return True
def markets(self):
"""
markets data, result format:
{
"btc_usdt": {
"amountScale": 4,
"priceScale": 2
},
"ltc_usdt": {
"amountScale": 3,
"priceScale": 2
}
...
}
:return: result data of markets
"""
url = TPL_MARKETS
return self.get(url)
def ticker(self, market):
"""
ticker data, result format:
{
"ticker": {
"vol": "40.463",
"last": "0.899999",
"sell": "0.5",
"buy": "0.225",
"high": "0.899999",
"low": "0.081"
},
"date": "1507875747359"
}
:param market: market code string
:return: ticker result
"""
url = TPL_MARKET.format(MARKET=market)
return self.get(url)
def depth(self, market, size):
"""
depth data of specific market, result format:
{
"asks": [
[
83.28,
11.8
]...
],
"bids": [
[
81.91,
3.65
]...
],
"timestamp" : timestamp
}
:param market: market code string
:param size: depth size
:return: result depth data
"""
url = TPL_DEPTH.format(MARKET=market, SIZE=str(size))
return self.get(url)
def trades(self, market):
"""
trade history, result format:
[
{
"amount": 0.541,
"date": 1472711925,
"price": 81.87,
"tid": 16497097,
"trade_type": "ask",
"type": "sell"
}...
]
:return: trade history data
"""
url = TPL_TRADES.format(MARKET=market)
return self.get(url)
def kline(self, market):
"""
kline data, result format:
{
"data": [
[
1472107500000,
3840.46,
3843.56,
3839.58,
3843.3,
492.456
]...
],
"moneyType": "btc",
"symbol": "ltc"
}
:param market: market code
:return: kline data
"""
url = TPL_KLINE.format(MARKET=market)
return self.get(url)
def order(self, market, type, amount, price):
"""
order api, result format:
{
"code": "1000",
"message": "***",
"id": "20131228361867"
}
:param market: currency
:param type: ORDER_TYPE_BUY or ORDER_TYPE_SELL
:param amount: order amount
:param price: order price
:return: order result
"""
params = 'accesskey=%s&amount=%s¤cy=%s&method=order&price=%s&tradeType=%s' % (self._access_key_, amount, market, price, type)
return self.call_api(url=URL_ORDER, params=params)
def cancel_order(self, market, order_id):
"""
cancel an order, result format:
{
"code": "1000",
"message": "***"
}
:param market: currency
:param order_id: order id
:return: result
"""
params = 'accesskey=%s¤cy=%s&id=%s&method=cancelOrder' % (self._access_key_, market, order_id)
return self.call_api(url=URL_CANCEL_ORDER, params=params)
def get_order(self, market, order_id):
"""
get order detail, result format:
{
"currency": "btc",
"id": "20150928158614292",
"price": 1560,
"status": 3,
"total_amount": 0.1,
"trade_amount": 0,
"trade_price" : 6000,
"trade_date": 1443410396717,
"trade_money": 0,
"type": 0,
}
:param market: currency
:param order_id: order id
:return: result
"""
params = 'accesskey=%s¤cy=%s&id=%s&method=getOrder' % (self._access_key_, market, order_id)
return self.call_api(url=URL_GET_ORDER, params=params)
def get_orders(self, market, page, type):
"""
get multiple orders, result format:
[
{
"currency": "btc",
"id": "20150928158614292",
"price": 1560,
"status": 3,
"total_amount": 0.1,
"trade_amount": 0,
"trade_price" : 6000,
"trade_date": 1443410396717,
"trade_money": 0,
"type": 0
}...
]
:param market: currency
:param page: page index
:param type: order type
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getOrders&pageIndex=%s&tradeType=%s' % (self._access_key_, market, page, type)
return self.call_api(url=URL_GET_ORDERS, params=params)
def get_orders_new(self, market, page_index, page_size, type):
"""
get multiple orders, result format same as get_orders
:param market: currency
:param page_index: page index
:param page_size: page size
:param type: order type
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getOrdersNew&pageIndex=%s&pageSize=%s&tradeType=%s' % (self._access_key_, market, page_index, page_size, type)
return self.call_api(url=URL_GET_ORDERS_NEW, params=params)
def get_orders_ignore_tader_type(self, market, page_index, page_size):
"""
get multiple orders ignore type, result format same as get_orders
:param market: currency
:param page_index: page index
:param page_size: page size
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getOrdersIgnoreTradeType&pageIndex=%s&pageSize=%s' % (self._access_key_, market, page_index, page_size)
return self.call_api(url=URL_GET_ORDERS_IGNORE_TRADE_TYPE, params=params)
def get_unfinished_orders_ignore_trade_type(self, market, page_index, page_size):
"""
get multiple unfinished orders ignore type, result format same as get_orders
:param market: currency
:param page_index: page index
:param page_size: page size
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=%s&pageSize=%s' % (self._access_key_, market, page_index, page_size)
return self.call_api(url=URL_GET_UNFINISHED_ORDERS_IGNORE_TRADE_TYPE, params=params)
def get_account_info(self):
"""
get account information, result format:
{
"result": {
"coins": [
{
"freez": "0.00000000",
"enName": "BTC",
"unitDecimal": 8,
"cnName": "BTC",
"unitTag": "*",
"available": "0.00000000",
"key": "btc"
},
{
"freez": "0.00000000",
"enName": "LTC",
"unitDecimal": 8,
"cnName": "LTC",
"unitTag": "*",
"available": "0.00000000",
"key": "ltc"
},
...
],
"base": {
"username": "134150***",
"trade_password_enabled": true,
"auth_google_enabled": false,
"auth_mobile_enabled": true
}
}
}
:return: result
"""
params = 'accesskey=%s&method=getAccountInfo' % self._access_key_
return self.call_api(url=URL_GET_ACCOUNT_INFO, params=params)
def get_user_address(self, currency):
"""
get user address, result format:
{
"code": 1000,
"message": {
"des": "success",
"isSuc": true,
"datas": {
"key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
}
}
}
:param currency: currency
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getUserAddress' % (self._access_key_, currency)
return self.call_api(url=URL_GET_USER_ADDRESS, params=params)
def get_withdraw_address(self, currency):
"""
get withdraw address, result format:
{
"code": 1000,
"message": {
"des": "success",
"isSuc": true,
"datas": {
"key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
}
}
}
:param currency: currency
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getWithdrawAddress' % (self._access_key_, currency)
return self.call_api(url=URL_GET_WITHDRAW_ADDRESS, params=params)
def get_withdraw_record(self, currency, page_index, page_size):
"""
get withdraw record, result format:
{
"code": 1000,
"message": {
"des": "success",
"isSuc": true,
"datas": {
"list": [
{
"amount": 0.01,
"fees": 0.001,
"id": 2016042556231,
"manageTime": 1461579340000,
"status": 3,
"submitTime": 1461579288000,
"toAddress": "14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp"
}...
],
"pageIndex": 1,
"pageSize": 10,
"totalCount": 4,
"totalPage": 1
}
}
}
:param currency:
:param page_index:
:param page_size:
:return:
"""
params = 'accesskey=%s¤cy=%s&method=getWithdrawRecord&pageIndex=%s&pageSize=%s' % (self._access_key_, currency, page_index, page_size)
return self.call_api(url=URL_GET_WITHDRAW_RECORD, params=params)
def get_charge_record(self, currency, page_index, page_size):
"""
get charge record, result format:
{
"code": 1000,
"message": {
"des": "success",
"isSuc": true,
"datas": {
"list": [
{
"address": "1FKN1DZqCm8HaTujDioRL2Aezdh7Qj7xxx",
"amount": "1.00000000",
"confirmTimes": 1,
"currency": "BTC",
"description": "***",
"hash": "7ce842de187c379abafadd64a5fe66c5c61c8a21fb04edff9532234a1dae6xxx",
"id": 558,
"itransfer": 1,
"status": 2,
"submit_time": "2016-12-07 18:51:57"
}...
],
"pageIndex": 1,
"pageSize": 10,
"total": 8
}
}
}
:param currency: currency
:param page_index: page index
:param page_size: page size
:return: result
"""
params = 'accesskey=%s¤cy=%s&method=getChargeRecord&pageIndex=%s&pageSize=%s' % (self._access_key_, currency, page_index, page_size)
return self.call_api(url=URL_GET_CHARGE_RECORD, params=params)
def withdraw(self, currency, amount, fees, itransfer, addr, pwd):
"""
withdraw coins, result format:
{
"code": 1000,
"message": "success",
"id": "***"
}
:param currency: currency
:param amount: amount
:param fees: fees
:param itransfer: itransfer
:param addr: receive address
:param pwd: safe password of current account
:return: result
"""
params = 'accesskey=%s&amount=%s¤cy=%s&fees=%s&itransfer=%s&method=withdraw&receiveAddr=%s&safePwd=%s' % (self._access_key, amount, currency, fees, itransfer, addr, pwd)
return self.call_api(url=URL_WITHDRAW, params=params)
def call_api(self, url, params=''):
full_url = url
if params:
sha_secret = self.digest(self._secret_key_)
sign = self.hmac_sign(params, sha_secret)
req_time = int(round(time.time() * 1000))
params += '&sign=%s&reqTime=%d' % (sign, req_time)
full_url += '?' + params
result = {}
while True:
try:
r = requests.get(full_url, timeout=2)
except Exception:
time.sleep(0.5)
continue
if r.status_code != 200:
time.sleep(0.5)
continue
else:
result = r.json()
break
return result
@staticmethod
def fill(value, lenght, fill_byte):
if len(value) >= lenght:
return value
else:
fill_size = lenght - len(value)
return value + chr(fill_byte) * fill_size
@staticmethod
def xor(s, value):
slist = list(s)
for index in xrange(len(slist)):
slist[index] = chr(ord(slist[index]) ^ value)
return "".join(slist)
def hmac_sign(self, arg_value, arg_key):
keyb = struct.pack("%ds" % len(arg_key), arg_key)
value = struct.pack("%ds" % len(arg_value), arg_value)
k_ipad = self.xor(keyb, 0x36)
k_opad = self.xor(keyb, 0x5c)
k_ipad = self.fill(k_ipad, 64, 54)
k_opad = self.fill(k_opad, 64, 92)
m = hashlib.md5()
m.update(k_ipad)
m.update(value)
dg = m.digest()
m = hashlib.md5()
m.update(k_opad)
subStr = dg[0:16]
m.update(subStr)
dg = m.hexdigest()
return dg
def digest(self, arg_value):
value = struct.pack("%ds" % len(arg_value), arg_value)
h = sha.new()
h.update(value)
dg = h.hexdigest()
return dg