-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathbitvavo.py
More file actions
779 lines (679 loc) · 31 KB
/
bitvavo.py
File metadata and controls
779 lines (679 loc) · 31 KB
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
import requests
import time
import hmac
import hashlib
import json
import websocket
import threading
import datetime
debugging = False
def debugToConsole(message):
if(debugging):
print(str(datetime.datetime.now().time())[:-7] + " DEBUG: " + message)
def errorToConsole(message):
print(str(datetime.datetime.now().time())[:-7] + " ERROR: " + message)
def createSignature(timestamp, method, url, body, APISECRET):
string = str(timestamp) + method + '/v2' + url
if body is not None and len(body.keys()) > 0:
string += json.dumps(body, separators=(',',':'))
signature = hmac.new(APISECRET.encode('utf-8'), string.encode('utf-8'), hashlib.sha256).hexdigest()
return signature
def createPostfix(options):
options = _default(options, {})
params = []
for key in options:
params.append(key + '=' + str(options[key]))
postfix = '&'.join(params)
if(len(options) > 0):
postfix = '?' + postfix
return postfix
def _default(value, fallback):
return value if value is not None else fallback
def _epoch_millis(dt):
return int(dt.timestamp() * 1000)
def asksCompare(a, b):
if(a < b):
return True
return False
def bidsCompare(a, b):
if(a > b):
return True
return False
def sortAndInsert(book, update, compareFunc):
for updateEntry in update:
entrySet = False
for j in range(len(book)):
bookItem = book[j]
if compareFunc(float(updateEntry[0]), float(bookItem[0])):
book.insert(j, updateEntry)
entrySet = True
break
if float(updateEntry[0]) == float(bookItem[0]):
if float(updateEntry[1]) > 0.0:
book[j] = updateEntry
entrySet = True
break
else:
book.pop(j)
entrySet = True
break
if not entrySet:
book.append(updateEntry)
return book
def processLocalBook(ws, message):
if('action' in message):
if(message['action'] == 'getBook'):
market = message['response']['market']
ws.localBook[market]['bids'] = message['response']['bids']
ws.localBook[market]['asks'] = message['response']['asks']
ws.localBook[market]['nonce'] = message['response']['nonce']
ws.localBook[market]['market'] = market
elif('event' in message):
if(message['event'] == 'book'):
market = message['market']
if(message['nonce'] != ws.localBook[market]['nonce'] + 1):
ws.makeLocalBook(market, ws.callbacks['localBookUser'][market])
return
ws.localBook[market]['bids'] = sortAndInsert(ws.localBook[market]['bids'], message['bids'], bidsCompare)
ws.localBook[market]['asks'] = sortAndInsert(ws.localBook[market]['asks'], message['asks'], asksCompare)
ws.localBook[market]['nonce'] = message['nonce']
ws.callbacks['subscriptionBookUser'][market](ws.localBook[market])
class rateLimitThread (threading.Thread):
def __init__(self, reset, bitvavo):
self.timeToWait = reset
self.bitvavo = bitvavo
threading.Thread.__init__(self)
def waitForReset(self, waitTime):
time.sleep(waitTime)
if (time.time() < self.bitvavo.rateLimitReset):
self.bitvavo.rateLimitRemaining = 1000
debugToConsole('Ban should have been lifted, resetting rate limit to 1000.')
else:
timeToWait = (self.bitvavo.rateLimitReset / 1000) - time.time()
debugToConsole('Ban took longer than expected, sleeping again for ' + str(timeToWait) + ' seconds.')
self.waitForReset(timeToWait)
def run(self):
self.waitForReset(self.timeToWait)
class receiveThread (threading.Thread):
def __init__(self, ws, wsObject):
self.ws = ws
self.wsObject = wsObject
threading.Thread.__init__(self)
def run(self):
try:
while(self.wsObject.keepAlive):
self.ws.run_forever()
self.wsObject.reconnect = True
self.wsObject.authenticated = False
time.sleep(self.wsObject.reconnectTimer)
debugToConsole("we have just set reconnect to true and have waited for " + str(self.wsObject.reconnectTimer))
self.wsObject.reconnectTimer = self.wsObject.reconnectTimer * 2
except KeyboardInterrupt:
debugToConsole("We caught keyboard interrupt in the websocket thread.")
class Bitvavo:
def __init__(self, options = {}):
self.base = "https://api.bitvavo.com/v2"
self.wsUrl = "wss://ws.bitvavo.com/v2/"
self.ACCESSWINDOW = None
self.APIKEY = ''
self.APISECRET = ''
self.rateLimitRemaining = 1000
self.rateLimitReset = 0
self.timeout = None
global debugging
debugging = False
for key in options:
if key.lower() == "apikey":
self.APIKEY = options[key]
elif key.lower() == "apisecret":
self.APISECRET = options[key]
elif key.lower() == "accesswindow":
self.ACCESSWINDOW = options[key]
elif key.lower() == "debugging":
debugging = options[key]
elif key.lower() == "resturl":
self.base = options[key]
elif key.lower() == "wsurl":
self.wsUrl = options[key]
elif key.lower() == "timeout":
self.timeout = options[key]
if(self.ACCESSWINDOW == None):
self.ACCESSWINDOW = 10000
def getRemainingLimit(self):
return self.rateLimitRemaining
def updateRateLimit(self, response):
if 'errorCode' in response:
if (response['errorCode'] == 105):
self.rateLimitRemaining = 0
self.rateLimitReset = int(response['error'].split(' at ')[1].split('.')[0])
timeToWait = (self.rateLimitReset / 1000) - time.time()
if(not hasattr(self, 'rateLimitThread')):
self.rateLimitThread = rateLimitThread(timeToWait, self)
self.rateLimitThread.daemon = True
self.rateLimitThread.start()
# setTimeout(checkLimit, timeToWait)
if ('bitvavo-ratelimit-remaining' in response):
self.rateLimitRemaining = int(response['bitvavo-ratelimit-remaining'])
if ('bitvavo-ratelimit-resetat' in response):
self.rateLimitReset = int(response['bitvavo-ratelimit-resetat'])
timeToWait = (self.rateLimitReset / 1000) - time.time()
if(not hasattr(self, 'rateLimitThread')):
self.rateLimitThread = rateLimitThread(timeToWait, self)
self.rateLimitThread.daemon = True
self.rateLimitThread.start()
def publicRequest(self, url):
debugToConsole("REQUEST: " + url)
if(self.APIKEY != ''):
now = int(time.time() * 1000)
sig = createSignature(now, 'GET', url.replace(self.base, ''), None, self.APISECRET)
headers = {
'bitvavo-access-key': self.APIKEY,
'bitvavo-access-signature': sig,
'bitvavo-access-timestamp': str(now),
'bitvavo-access-window': str(self.ACCESSWINDOW)
}
r = requests.get(url, headers = headers, timeout = self.timeout)
else:
r = requests.get(url, timeout = self.timeout)
if('error' in r.json()):
self.updateRateLimit(r.json())
else:
self.updateRateLimit(r.headers)
return r.json()
def privateRequest(self, endpoint, postfix, body = None, method = 'GET'):
now = int(time.time() * 1000)
sig = createSignature(now, method, (endpoint + postfix), body, self.APISECRET)
url = self.base + endpoint + postfix
headers = {
'bitvavo-access-key': self.APIKEY,
'bitvavo-access-signature': sig,
'bitvavo-access-timestamp': str(now),
'bitvavo-access-window': str(self.ACCESSWINDOW),
}
debugToConsole("REQUEST: " + url)
r = requests.request(method, url, headers=headers, json=body, timeout=self.timeout)
if 'error' in r.json():
self.updateRateLimit(r.json())
else:
self.updateRateLimit(r.headers)
return r.json()
def time(self):
return self.publicRequest((self.base + '/time'))
# options: market
def markets(self, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/markets' + postfix))
# options: symbol
def assets(self, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/assets' + postfix))
# options: depth
def book(self, symbol, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/' + symbol + '/book' + postfix))
# options: limit, start, end, tradeIdFrom, tradeIdTo
def publicTrades(self, symbol, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/' + symbol + '/trades' + postfix))
# options: limit, start, end
def candles(self, symbol, interval, options=None, limit=None, start=None, end=None):
options = _default(options, {})
options['interval'] = interval
if limit is not None:
options['limit'] = limit
if start is not None:
options['start'] = _epoch_millis(start)
if end is not None:
options['end'] = _epoch_millis(end)
postfix = createPostfix(options)
return self.publicRequest((self.base + '/' + symbol + '/candles' + postfix))
# options: market
def tickerPrice(self, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/ticker/price' + postfix))
# options: market
def tickerBook(self, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/ticker/book' + postfix))
# options: market
def ticker24h(self, options=None):
postfix = createPostfix(options)
return self.publicRequest((self.base + '/ticker/24h' + postfix))
# optional body parameters: limit:(amount, price, postOnly), market:(amount, amountQuote, disableMarketProtection)
# stopLoss/takeProfit:(amount, amountQuote, disableMarketProtection, triggerType, triggerReference, triggerAmount)
# stopLossLimit/takeProfitLimit:(amount, price, postOnly, triggerType, triggerReference, triggerAmount)
# all orderTypes: timeInForce, selfTradePrevention, responseRequired, operatorId
def placeOrder(self, market, side, orderType, body):
body['market'] = market
body['side'] = side
body['orderType'] = orderType
return self.privateRequest('/order', '', body, 'POST')
def getOrder(self, market, orderId):
postfix = createPostfix({ 'market': market, 'orderId': orderId })
return self.privateRequest('/order', postfix, {}, 'GET')
# Optional parameters: limit:(amount, amountRemaining, price, timeInForce, selfTradePrevention, postOnly)
# untriggered stopLoss/takeProfit:(amount, amountQuote, disableMarketProtection, triggerType, triggerReference, triggerAmount)
# stopLossLimit/takeProfitLimit: (amount, price, postOnly, triggerType, triggerReference, triggerAmount)
# all orderTypes: operatorId
def updateOrder(self, market, orderId, body):
body['market'] = market
body['orderId'] = orderId
return self.privateRequest('/order', '', body, 'PUT')
def cancelOrder(self, market, orderId, operatorId=None):
params = {'market': market, 'orderId': orderId}
if operatorId is not None:
params['operatorId'] = operatorId
postfix = createPostfix(params)
return self.privateRequest('/order', postfix, {}, 'DELETE')
# options: limit, start, end, orderIdFrom, orderIdTo
def getOrders(self, market, options=None):
options = _default(options, {})
options['market'] = market
postfix = createPostfix(options)
return self.privateRequest('/orders', postfix, {}, 'GET')
# options: market
def cancelOrders(self, options=None):
postfix = createPostfix(options)
return self.privateRequest('/orders', postfix, {}, 'DELETE')
# options: market
def ordersOpen(self, options=None):
postfix = createPostfix(options)
return self.privateRequest('/ordersOpen', postfix, {}, 'GET')
# options: limit, start, end, tradeIdFrom, tradeIdTo
def trades(self, market, options=None):
options = _default(options, {})
options['market'] = market
postfix = createPostfix(options)
return self.privateRequest('/trades', postfix, {}, 'GET')
def account(self):
return self.privateRequest('/account', '', {}, 'GET')
def fees(self, market=None):
options = {}
if market is not None:
options['market'] = market
postfix = createPostfix(options)
return self.privateRequest('/account/fees', postfix, {}, 'GET')
# options: symbol
def balance(self, options=None):
postfix = createPostfix(options)
return self.privateRequest('/balance', postfix, {}, 'GET')
def depositAssets(self, symbol):
postfix = createPostfix({ 'symbol': symbol })
return self.privateRequest('/depositAssets', postfix, {}, 'GET')
# optional body parameters: paymentId, internal, addWithdrawalFee
def withdrawAssets(self, symbol, amount, address, body):
body['symbol'] = symbol
body['amount'] = amount
body['address'] = address
return self.privateRequest('/withdrawal', '', body, 'POST')
# options: symbol, limit, start, end
def depositHistory(self, options=None):
postfix = createPostfix(options)
return self.privateRequest('/depositHistory', postfix, {}, 'GET')
# options: symbol, limit, start, end
def withdrawalHistory(self, options=None):
postfix = createPostfix(options)
return self.privateRequest('/withdrawalHistory', postfix, {}, 'GET')
def newWebsocket(self):
return Bitvavo.websocket(self.APIKEY, self.APISECRET, self.ACCESSWINDOW, self.wsUrl, self)
class websocket:
def __init__(self, APIKEY, APISECRET, ACCESSWINDOW, WSURL, bitvavo):
self.APIKEY = APIKEY
self.APISECRET = APISECRET
self.ACCESSWINDOW = ACCESSWINDOW
self.wsUrl = WSURL
self.open = False
self.callbacks = {}
self.keepAlive = True
self.reconnect = False
self.reconnectTimer = 0.1
self.bitvavo = bitvavo
self.subscribe()
def subscribe(self):
websocket.enableTrace(False)
ws = websocket.WebSocketApp(self.wsUrl,
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close,
on_open = self.on_open)
self.ws = ws
self.receiveThread = receiveThread(ws, self)
self.receiveThread.daemon = True
self.receiveThread.start()
self.authenticated = False
self.keepBookCopy = False
self.localBook = {}
def closeSocket(self):
self.ws.close()
self.keepAlive = False
self.receiveThread.join()
def waitForSocket(self, ws, message, private):
if (not private and self.open) or (private and self.authenticated and self.open):
return
else:
time.sleep(0.1)
self.waitForSocket(ws, message, private)
def doSend(self, ws, message, private = False):
if private and self.APIKEY == '':
errorToConsole('You did not set the API key, but requested a private function.')
return
self.waitForSocket(ws, message, private)
ws.send(message)
debugToConsole('SENT: ' + message)
def on_message(self, ws, msg):
debugToConsole('RECEIVED: ' + msg)
msg = json.loads(msg)
callbacks = self.callbacks
if 'error' in msg:
if msg['errorCode'] == 105:
self.bitvavo.updateRateLimit(msg)
if 'error' in callbacks:
callbacks['error'](msg)
else:
errorToConsole(json.dumps(msg, indent=2))
if 'action' in msg:
if(msg['action'] == 'getTime'):
callbacks['time'](msg['response'])
elif(msg['action'] == 'getMarkets'):
callbacks['markets'](msg['response'])
elif(msg['action'] == 'getAssets'):
callbacks['assets'](msg['response'])
elif(msg['action'] == 'getTrades'):
callbacks['publicTrades'](msg['response'])
elif(msg['action'] == 'getCandles'):
callbacks['candles'](msg['response'])
elif(msg['action'] == 'getTicker24h'):
callbacks['ticker24h'](msg['response'])
elif(msg['action'] == 'getTickerPrice'):
callbacks['tickerPrice'](msg['response'])
elif(msg['action'] == 'getTickerBook'):
callbacks['tickerBook'](msg['response'])
elif(msg['action'] == 'privateCreateOrder'):
callbacks['placeOrder'](msg['response'])
elif(msg['action'] == 'privateUpdateOrder'):
callbacks['updateOrder'](msg['response'])
elif(msg['action'] == 'privateGetOrder'):
callbacks['getOrder'](msg['response'])
elif(msg['action'] == 'privateCancelOrder'):
callbacks['cancelOrder'](msg['response'])
elif(msg['action'] == 'privateGetOrders'):
callbacks['getOrders'](msg['response'])
elif(msg['action'] == 'privateGetOrdersOpen'):
callbacks['ordersOpen'](msg['response'])
elif(msg['action'] == 'privateGetTrades'):
callbacks['trades'](msg['response'])
elif(msg['action'] == 'privateGetAccount'):
callbacks['account'](msg['response'])
elif(msg['action'] == 'privateGetFees'):
callbacks['fees'](msg['response'])
elif(msg['action'] == 'privateGetBalance'):
callbacks['balance'](msg['response'])
elif(msg['action'] == 'privateDepositAssets'):
callbacks['depositAssets'](msg['response'])
elif(msg['action'] == 'privateWithdrawAssets'):
callbacks['withdrawAssets'](msg['response'])
elif(msg['action'] == 'privateGetDepositHistory'):
callbacks['depositHistory'](msg['response'])
elif(msg['action'] == 'privateGetWithdrawalHistory'):
callbacks['withdrawalHistory'](msg['response'])
elif(msg['action'] == 'privateCancelOrders'):
callbacks['cancelOrders'](msg['response'])
elif(msg['action'] == 'getBook'):
market = msg['response']['market']
if('book' in callbacks):
callbacks['book'](msg['response'])
if(self.keepBookCopy):
if(market in callbacks['subscriptionBook']):
callbacks['subscriptionBook'][market](ws, msg)
elif('event' in msg):
if(msg['event'] == 'authenticate'):
self.authenticated = True
debugToConsole('Authenticated Websocket.')
elif(msg['event'] == 'fill'):
market = msg['market']
callbacks['subscriptionAccount'][market](msg)
elif(msg['event'] == 'order'):
market = msg['market']
callbacks['subscriptionAccount'][market](msg)
elif(msg['event'] == 'ticker'):
market = msg['market']
callbacks['subscriptionTicker'][market](msg)
elif(msg['event'] == 'ticker24h'):
for entry in msg['data']:
callbacks['subscriptionTicker24h'][entry['market']](entry)
elif(msg['event'] == 'candle'):
market = msg['market']
interval = msg['interval']
callbacks['subscriptionCandles'][market][interval](msg)
elif(msg['event'] == 'book'):
market = msg['market']
if('subscriptionBookUpdate' in callbacks):
if(market in callbacks['subscriptionBookUpdate']):
callbacks['subscriptionBookUpdate'][market](msg)
if(self.keepBookCopy):
if(market in callbacks['subscriptionBook']):
callbacks['subscriptionBook'][market](ws, msg)
elif(msg['event'] == 'trade'):
market = msg['market']
if('subscriptionTrades' in callbacks):
callbacks['subscriptionTrades'][market](msg)
def on_error(self, ws, error):
if 'error' in self.callbacks:
self.callbacks['error'](error)
else:
errorToConsole(repr(error))
def on_close(self, ws, close_status_code=None, close_msg=None):
debugToConsole(f"Closed Websocket. code={close_status_code} reason={close_msg}")
def checkReconnect(self):
if('subscriptionTicker' in self.callbacks):
for market in self.callbacks['subscriptionTicker']:
self.subscriptionTicker(market, self.callbacks['subscriptionTicker'][market])
if('subscriptionTicker24h' in self.callbacks):
for market in self.callbacks['subscriptionTicker24h']:
self.subscriptionTicker(market, self.callbacks['subscriptionTicker24h'][market])
if('subscriptionAccount' in self.callbacks):
for market in self.callbacks['subscriptionAccount']:
self.subscriptionAccount(market, self.callbacks['subscriptionAccount'][market])
if('subscriptionCandles' in self.callbacks):
for market in self.callbacks['subscriptionCandles']:
for interval in self.callbacks['subscriptionCandles'][market]:
self.subscriptionCandles(market, interval, self.callbacks['subscriptionCandles'][market][interval])
if('subscriptionTrades' in self.callbacks):
for market in self.callbacks['subscriptionTrades']:
self.subscriptionTrades(market, self.callbacks['subscriptionTrades'][market])
if('subscriptionBookUpdate' in self.callbacks):
for market in self.callbacks['subscriptionBookUpdate']:
self.subscriptionBookUpdate(market, self.callbacks['subscriptionBookUpdate'][market])
if('subscriptionBookUser' in self.callbacks):
for market in self.callbacks['subscriptionBookUser']:
self.subscriptionBook(market, self.callbacks['subscriptionBookUser'][market])
def on_open(self, ws):
now = int(time.time()*1000)
self.open = True
self.reconnectTimer = 0.5
if self.APIKEY != '':
self.doSend(self.ws, json.dumps({ 'window':str(self.ACCESSWINDOW), 'action': 'authenticate', 'key': self.APIKEY, 'signature': createSignature(now, 'GET', '/websocket', {}, self.APISECRET), 'timestamp': now }))
if self.reconnect:
debugToConsole("we started reconnecting " + str(self.checkReconnect))
thread = threading.Thread(target = self.checkReconnect)
thread.start()
def setErrorCallback(self,callback):
self.callbacks['error'] = callback
def time(self, callback):
self.callbacks['time'] = callback
self.doSend(self.ws, json.dumps({ 'action': 'getTime' }))
# options: market
def markets(self, options, callback):
self.callbacks['markets'] = callback
options['action'] = 'getMarkets'
self.doSend(self.ws, json.dumps(options))
# options: symbol
def assets(self, options, callback):
self.callbacks['assets'] = callback
options['action'] = 'getAssets'
self.doSend(self.ws, json.dumps(options))
# options: depth
def book(self, market, options, callback):
self.callbacks['book'] = callback
options['market'] = market
options['action'] = 'getBook'
self.doSend(self.ws, json.dumps(options))
# options: limit, start, end, tradeIdFrom, tradeIdTo
def publicTrades(self, market, options, callback):
self.callbacks['publicTrades'] = callback
options['market'] = market
options['action'] = 'getTrades'
self.doSend(self.ws, json.dumps(options))
# options: limit
def candles(self, market, interval, options, callback):
self.callbacks['candles'] = callback
options['market'] = market
options['interval'] = interval
options['action'] = 'getCandles'
self.doSend(self.ws, json.dumps(options))
# options: market
def ticker24h(self, options, callback):
self.callbacks['ticker24h'] = callback
options['action'] = 'getTicker24h'
self.doSend(self.ws, json.dumps(options))
# options: market
def tickerPrice(self, options, callback):
self.callbacks['tickerPrice'] = callback
options['action'] = 'getTickerPrice'
self.doSend(self.ws, json.dumps(options))
# options: market
def tickerBook(self, options, callback):
self.callbacks['tickerBook'] = callback
options['action'] = 'getTickerBook'
self.doSend(self.ws, json.dumps(options))
# optional body parameters: limit:(amount, price, postOnly), market:(amount, amountQuote, disableMarketProtection)
# stopLoss/takeProfit:(amount, amountQuote, disableMarketProtection, triggerType, triggerReference, triggerAmount)
# stopLossLimit/takeProfitLimit:(amount, price, postOnly, triggerType, triggerReference, triggerAmount)
# all orderTypes: timeInForce, selfTradePrevention, responseRequired, operatorId
def placeOrder(self, market, side, orderType, body, callback):
self.callbacks['placeOrder'] = callback
body['market'] = market
body['side'] = side
body['orderType'] = orderType
body['action'] = 'privateCreateOrder'
self.doSend(self.ws, json.dumps(body), True)
def getOrder(self, market, orderId, callback):
self.callbacks['getOrder'] = callback
options = { 'action': 'privateGetOrder', 'market': market, 'orderId': orderId }
self.doSend(self.ws, json.dumps(options), True)
# Optional parameters: limit:(amount, amountRemaining, price, timeInForce, selfTradePrevention, postOnly)
# untriggered stopLoss/takeProfit:(amount, amountQuote, disableMarketProtection, triggerType, triggerReference, triggerAmount)
# stopLossLimit/takeProfitLimit: (amount, price, postOnly, triggerType, triggerReference, triggerAmount)
# all orderTypes: operatorId
def updateOrder(self, market, orderId, body, callback):
self.callbacks['updateOrder'] = callback
body['market'] = market
body['orderId'] = orderId
body['action'] = 'privateUpdateOrder'
self.doSend(self.ws, json.dumps(body), True)
def cancelOrder(self, market, orderId, callback, operatorId=None):
self.callbacks['cancelOrder'] = callback
options = { 'action': 'privateCancelOrder', 'market': market, 'orderId': orderId }
if operatorId is not None:
options['operatorId'] = operatorId
self.doSend(self.ws, json.dumps(options), True)
# options: limit, start, end, orderIdFrom, orderIdTo
def getOrders(self, market, options, callback):
self.callbacks['getOrders'] = callback
options['action'] = 'privateGetOrders'
options['market'] = market
self.doSend(self.ws, json.dumps(options), True)
# options: market
def cancelOrders(self, options, callback):
self.callbacks['cancelOrders'] = callback
options['action'] = 'privateCancelOrders'
self.doSend(self.ws, json.dumps(options), True)
# options: market
def ordersOpen(self, options, callback):
self.callbacks['ordersOpen'] = callback
options['action'] = 'privateGetOrdersOpen'
self.doSend(self.ws, json.dumps(options), True)
# options: limit, start, end, tradeIdFrom, tradeIdTo
def trades(self, market, options, callback):
self.callbacks['trades'] = callback
options['action'] = 'privateGetTrades'
options['market'] = market
self.doSend(self.ws, json.dumps(options), True)
def account(self, callback):
self.callbacks['account'] = callback
self.doSend(self.ws, json.dumps({ 'action': 'privateGetAccount' }), True)
def fees(self, market, callback=None):
if callable(market):
callback = market
market = None
self.callbacks['fees'] = callback
self.doSend(self.ws, json.dumps({ 'action': 'privateGetFees', 'market': market }), True)
# options: symbol
def balance(self, options, callback):
options['action'] = 'privateGetBalance'
self.callbacks['balance'] = callback
self.doSend(self.ws, json.dumps(options), True)
def depositAssets(self, symbol, callback):
self.callbacks['depositAssets'] = callback
self.doSend(self.ws, json.dumps({ 'action': 'privateDepositAssets', 'symbol': symbol }), True)
# optional body parameters: paymentId, internal, addWithdrawalFee
def withdrawAssets(self, symbol, amount, address, body, callback):
self.callbacks['withdrawAssets'] = callback
body['action'] = 'privateWithdrawAssets'
body['symbol'] = symbol
body['amount'] = amount
body['address'] = address
self.doSend(self.ws, json.dumps(body), True)
# options: symbol, limit, start, end
def depositHistory(self, options, callback):
self.callbacks['depositHistory'] = callback
options['action'] = 'privateGetDepositHistory'
self.doSend(self.ws, json.dumps(options), True)
# options: symbol, limit, start, end
def withdrawalHistory(self, options, callback):
self.callbacks['withdrawalHistory'] = callback
options['action'] = 'privateGetWithdrawalHistory'
self.doSend(self.ws, json.dumps(options), True)
def subscriptionTicker(self, market, callback):
if 'subscriptionTicker' not in self.callbacks:
self.callbacks['subscriptionTicker'] = {}
self.callbacks['subscriptionTicker'][market] = callback
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'ticker', 'markets': [market] }] }))
def subscriptionTicker24h(self, market, callback):
if 'subscriptionTicker24h' not in self.callbacks:
self.callbacks['subscriptionTicker24h'] = {}
self.callbacks['subscriptionTicker24h'][market] = callback
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'ticker24h', 'markets': [market] }] }))
def subscriptionAccount(self, market, callback):
if 'subscriptionAccount' not in self.callbacks:
self.callbacks['subscriptionAccount'] = {}
self.callbacks['subscriptionAccount'][market] = callback
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'account', 'markets': [market] }] }), True)
def subscriptionCandles(self, market, interval, callback):
if 'subscriptionCandles' not in self.callbacks:
self.callbacks['subscriptionCandles'] = {}
if market not in self.callbacks['subscriptionCandles']:
self.callbacks['subscriptionCandles'][market] = {}
self.callbacks['subscriptionCandles'][market][interval] = callback
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'candles', 'interval': [interval], 'markets': [market] }] }))
def subscriptionTrades(self, market, callback):
if 'subscriptionTrades' not in self.callbacks:
self.callbacks['subscriptionTrades'] = {}
self.callbacks['subscriptionTrades'][market] = callback
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'trades', 'markets': [market] }] }))
def subscriptionBookUpdate(self, market, callback):
if 'subscriptionBookUpdate' not in self.callbacks:
self.callbacks['subscriptionBookUpdate'] = {}
self.callbacks['subscriptionBookUpdate'][market] = callback
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'book', 'markets': [market] }] }))
def subscriptionBook(self, market, callback):
self.keepBookCopy = True
if 'subscriptionBookUser' not in self.callbacks:
self.callbacks['subscriptionBookUser'] = {}
self.callbacks['subscriptionBookUser'][market] = callback
if 'subscriptionBook' not in self.callbacks:
self.callbacks['subscriptionBook'] = {}
self.callbacks['subscriptionBook'][market] = processLocalBook
self.doSend(self.ws, json.dumps({ 'action': 'subscribe', 'channels': [{ 'name': 'book', 'markets': [market] }] }))
self.localBook[market] = {}
self.doSend(self.ws, json.dumps({ 'action': 'getBook', 'market': market }))