Repository navigation
Expand file tree
/
Copy pathcryptocom.py
More file actions
1324 lines (1224 loc) · 58.7 KB
/
Copy pathcryptocom.py
File metadata and controls
1324 lines (1224 loc) · 58.7 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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
import ccxt.async_support
from ccxt.async_support.base.ws.cache import ArrayCache, ArrayCacheBySymbolById, ArrayCacheBySymbolBySide, ArrayCacheByTimestamp
import hashlib
from ccxt.base.types import Balances, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, Trade
from ccxt.async_support.base.ws.client import Client
from typing import List
from typing import Any
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import NetworkError
from ccxt.base.errors import ChecksumError
class cryptocom(ccxt.async_support.cryptocom):
def describe(self):
return self.deep_extend(super(cryptocom, self).describe(), {
'has': {
'ws': True,
'watchBalance': True,
'watchTicker': True,
'watchTickers': True,
'watchBidsAsks': True,
'watchMyTrades': True,
'watchTrades': True,
'watchTradesForSymbols': True,
'watchOrderBook': True,
'watchOrderBookForSymbols': True,
'watchOrders': True,
'watchOHLCV': True,
'watchPositions': True,
'createOrderWs': True,
'cancelOrderWs': True,
'cancelAllOrders': True,
},
'urls': {
'api': {
'ws': {
'public': 'wss://stream.crypto.com/exchange/v1/market',
'private': 'wss://stream.crypto.com/exchange/v1/user',
},
},
'test': {
'public': 'wss://uat-stream.3ona.co/exchange/v1/market',
'private': 'wss://uat-stream.3ona.co/exchange/v1/user',
},
},
'options': {
'watchPositions': {
'fetchPositionsSnapshot': True, # or False
'awaitPositionsSnapshot': True, # whether to wait for the positions snapshot before providing updates
},
'watchOrderBook': {
'checksum': True,
},
},
'streaming': {
},
})
async def pong(self, client, message):
# {
# "id": 1587523073344,
# "method": "public/heartbeat",
# "code": 0
# }
try:
await client.send({'id': self.safe_integer(message, 'id'), 'method': 'public/respond-heartbeat'})
except Exception as e:
error = NetworkError(self.id + ' pong failed with error ' + self.json(e))
client.reset(error)
async def watch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
"""
watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#book-instrument_name
:param str symbol: unified symbol of the market to fetch the order book for
:param int [limit]: the maximum amount of order book entries to return
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.bookSubscriptionType]: The subscription type. Allowed values: SNAPSHOT full snapshot. This is the default if not specified. SNAPSHOT_AND_UPDATE delta updates
:param int [params.bookUpdateFrequency]: Book update interval in ms. Allowed values: 100 for snapshot subscription 10 for delta subscription
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
"""
return await self.watch_order_book_for_symbols([symbol], limit, params)
async def un_watch_order_book(self, symbol: str, params={}) -> Any:
"""
unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#book-instrument_name
:param str symbol: unified symbol of the market to fetch the order book for
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.bookSubscriptionType]: The subscription type. Allowed values: SNAPSHOT full snapshot. This is the default if not specified. SNAPSHOT_AND_UPDATE delta updates
:param int [params.bookUpdateFrequency]: Book update interval in ms. Allowed values: 100 for snapshot subscription 10 for delta subscription
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
"""
return await self.un_watch_order_book_for_symbols([symbol], params)
async def watch_order_book_for_symbols(self, symbols: List[str], limit: Int = None, params={}) -> OrderBook:
"""
watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#book-instrument_name
:param str[] symbols: unified array of symbols
:param int [limit]: the maximum amount of order book entries to return
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.bookSubscriptionType]: The subscription type. Allowed values: SNAPSHOT full snapshot. This is the default if not specified. SNAPSHOT_AND_UPDATE delta updates
:param int [params.bookUpdateFrequency]: Book update interval in ms. Allowed values: 100 for snapshot subscription 10 for delta subscription
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
"""
await self.load_markets()
symbols = self.market_symbols(symbols)
topics = []
messageHashes = []
if not limit:
limit = 50
topicParams = self.safe_value(params, 'params')
if topicParams is None:
params['params'] = {}
bookSubscriptionType = None
bookSubscriptionType2 = None
bookSubscriptionType, params = self.handle_option_and_params(params, 'watchOrderBook', 'bookSubscriptionType', 'SNAPSHOT_AND_UPDATE')
bookSubscriptionType2, params = self.handle_option_and_params(params, 'watchOrderBookForSymbols', 'bookSubscriptionType', bookSubscriptionType)
params['params']['bookSubscriptionType'] = bookSubscriptionType2
bookUpdateFrequency = None
bookUpdateFrequency2 = None
bookUpdateFrequency, params = self.handle_option_and_params(params, 'watchOrderBook', 'bookUpdateFrequency')
bookUpdateFrequency2, params = self.handle_option_and_params(params, 'watchOrderBookForSymbols', 'bookUpdateFrequency', bookUpdateFrequency)
if bookUpdateFrequency2 is not None:
params['params']['bookSubscriptionType'] = bookUpdateFrequency2
for i in range(0, len(symbols)):
symbol = symbols[i]
market = self.market(symbol)
currentTopic = 'book' + '.' + market['id'] + '.' + str(limit)
messageHash = 'orderbook:' + market['symbol']
messageHashes.append(messageHash)
topics.append(currentTopic)
orderbook = await self.watch_public_multiple(messageHashes, topics, params)
return orderbook.limit()
async def un_watch_order_book_for_symbols(self, symbols: List[str], params={}) -> OrderBook:
"""
unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#book-instrument_name
:param str[] symbols: unified array of symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.limit]: orderbook limit, default is 50
:param str [params.bookSubscriptionType]: The subscription type. Allowed values: SNAPSHOT full snapshot. This is the default if not specified. SNAPSHOT_AND_UPDATE delta updates
:param int [params.bookUpdateFrequency]: Book update interval in ms. Allowed values: 100 for snapshot subscription 10 for delta subscription
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
"""
await self.load_markets()
symbols = self.market_symbols(symbols)
topics = []
subMessageHashes = []
messageHashes = []
limit = self.safe_integer(params, 'limit', 50)
topicParams = self.safe_value(params, 'params')
if topicParams is None:
params['params'] = {}
bookSubscriptionType = None
bookSubscriptionType2 = None
bookSubscriptionType, params = self.handle_option_and_params(params, 'watchOrderBook', 'bookSubscriptionType', 'SNAPSHOT_AND_UPDATE')
bookSubscriptionType2, params = self.handle_option_and_params(params, 'watchOrderBookForSymbols', 'bookSubscriptionType', bookSubscriptionType)
params['params']['bookSubscriptionType'] = bookSubscriptionType2
bookUpdateFrequency = None
bookUpdateFrequency2 = None
bookUpdateFrequency, params = self.handle_option_and_params(params, 'watchOrderBook', 'bookUpdateFrequency')
bookUpdateFrequency2, params = self.handle_option_and_params(params, 'watchOrderBookForSymbols', 'bookUpdateFrequency', bookUpdateFrequency)
if bookUpdateFrequency2 is not None:
params['params']['bookSubscriptionType'] = bookUpdateFrequency2
for i in range(0, len(symbols)):
symbol = symbols[i]
market = self.market(symbol)
currentTopic = 'book' + '.' + market['id'] + '.' + str(limit)
messageHash = 'orderbook:' + market['symbol']
subMessageHashes.append(messageHash)
messageHashes.append('unsubscribe:' + messageHash)
topics.append(currentTopic)
return await self.un_watch_public_multiple('orderbook', symbols, messageHashes, subMessageHashes, topics, params)
def handle_delta(self, bookside, delta):
price = self.safe_float(delta, 0)
amount = self.safe_float(delta, 1)
count = self.safe_integer(delta, 2)
bookside.storeArray([price, amount, count])
def handle_deltas(self, bookside, deltas):
for i in range(0, len(deltas)):
self.handle_delta(bookside, deltas[i])
def handle_order_book(self, client: Client, message):
#
# snapshot
# {
# "instrument_name":"LTC_USDT",
# "subscription":"book.LTC_USDT.150",
# "channel":"book",
# "depth":150,
# "data": [
# {
# "bids": [
# [122.21, 0.74041, 4]
# ],
# "asks": [
# [122.29, 0.00002, 1]
# ]
# "t": 1648123943803,
# "s":754560122
# }
# ]
# }
# update
# {
# "instrument_name":"BTC_USDT",
# "subscription":"book.BTC_USDT.50",
# "channel":"book.update",
# "depth":50,
# "data":[
# {
# "update":{
# "asks":[
# [
# "43755.46",
# "0.10000",
# "1"
# ],
# ...
# ],
# "bids":[
# [
# "43737.46",
# "0.14096",
# "1"
# ],
# ...
# ]
# },
# "t":1704484068898,
# "tt":1704484068892,
# "u":78795598253024,
# "pu":78795598162080,
# "cs":-781431132
# }
# ]
# }
#
marketId = self.safe_string(message, 'instrument_name')
market = self.safe_market(marketId)
symbol = market['symbol']
data = self.safe_value(message, 'data')
data = self.safe_value(data, 0)
timestamp = self.safe_integer(data, 't')
if not (symbol in self.orderbooks):
limit = self.safe_integer(message, 'depth')
self.orderbooks[symbol] = self.counted_order_book({}, limit)
orderbook = self.orderbooks[symbol]
channel = self.safe_string(message, 'channel')
nonce = self.safe_integer_2(data, 'u', 's')
books = data
if channel == 'book': # snapshot
orderbook.reset({})
orderbook['symbol'] = symbol
orderbook['timestamp'] = timestamp
orderbook['datetime'] = self.iso8601(timestamp)
orderbook['nonce'] = nonce
else:
books = self.safe_value(data, 'update', {})
previousNonce = self.safe_integer(data, 'pu')
currentNonce = orderbook['nonce']
if currentNonce != previousNonce:
checksum = self.handle_option('watchOrderBook', 'checksum', True)
if checksum:
raise ChecksumError(self.id + ' ' + self.orderbook_checksum_message(symbol))
self.handle_deltas(orderbook['asks'], self.safe_value(books, 'asks', []))
self.handle_deltas(orderbook['bids'], self.safe_value(books, 'bids', []))
orderbook['nonce'] = nonce
self.orderbooks[symbol] = orderbook
messageHash = 'orderbook:' + symbol
client.resolve(orderbook, messageHash)
async def watch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
"""
get the list of most recent trades for a particular symbol
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#trade-instrument_name
:param str symbol: unified symbol of the market to fetch trades for
:param int [since]: timestamp in ms of the earliest trade to fetch
:param int [limit]: the maximum amount of trades to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
"""
return await self.watch_trades_for_symbols([symbol], since, limit, params)
async def un_watch_trades(self, symbol: str, params={}) -> List[Trade]:
"""
get the list of most recent trades for a particular symbol
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#trade-instrument_name
:param str symbol: unified symbol of the market to fetch trades for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
"""
return await self.un_watch_trades_for_symbols([symbol], params)
async def watch_trades_for_symbols(self, symbols: List[str], since: Int = None, limit: Int = None, params={}) -> List[Trade]:
"""
get the list of most recent trades for a particular symbol
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#trade-instrument_name
:param str[] symbols: unified symbol of the market to fetch trades for
:param int [since]: timestamp in ms of the earliest trade to fetch
:param int [limit]: the maximum amount of trades to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
"""
await self.load_markets()
symbols = self.market_symbols(symbols)
topics = []
for i in range(0, len(symbols)):
symbol = symbols[i]
market = self.market(symbol)
currentTopic = 'trade' + '.' + market['id']
topics.append(currentTopic)
trades = await self.watch_public_multiple(topics, topics, params)
if self.newUpdates:
first = self.safe_value(trades, 0)
tradeSymbol = self.safe_string(first, 'symbol')
limit = trades.getLimit(tradeSymbol, limit)
return self.filter_by_since_limit(trades, since, limit, 'timestamp', True)
async def un_watch_trades_for_symbols(self, symbols: List[str], params={}) -> Any:
"""
get the list of most recent trades for a particular symbol
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#trade-instrument_name
:param str[] [symbols]: list of unified market symbols to unwatch trades for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
"""
await self.load_markets()
symbols = self.market_symbols(symbols)
topics = []
messageHashes = []
for i in range(0, len(symbols)):
symbol = symbols[i]
market = self.market(symbol)
currentTopic = 'trade' + '.' + market['id']
messageHashes.append('unsubscribe:trades:' + market['symbol'])
topics.append(currentTopic)
return await self.un_watch_public_multiple('trades', symbols, messageHashes, topics, topics, params)
def handle_trades(self, client: Client, message):
#
# {
# "code": 0,
# "method": "subscribe",
# "result": {
# "instrument_name": "BTC_USDT",
# "subscription": "trade.BTC_USDT",
# "channel": "trade",
# "data": [
# {
# "dataTime":1648122434405,
# "d":"2358394540212355488",
# "s":"SELL",
# "p":42980.85,
# "q":0.002325,
# "t":1648122434404,
# "i":"BTC_USDT"
# }
# (...)
# ]
# }
#
channel = self.safe_string(message, 'channel')
marketId = self.safe_string(message, 'instrument_name')
symbolSpecificMessageHash = self.safe_string(message, 'subscription')
market = self.safe_market(marketId)
symbol = market['symbol']
stored = self.safe_value(self.trades, symbol)
if stored is None:
limit = self.safe_integer(self.options, 'tradesLimit', 1000)
stored = ArrayCache(limit)
self.trades[symbol] = stored
data = self.safe_value(message, 'data', [])
dataLength = len(data)
if dataLength == 0:
return
parsedTrades = self.parse_trades(data, market)
for j in range(0, len(parsedTrades)):
stored.append(parsedTrades[j])
channelReplaced = channel.replace('.' + marketId, '')
client.resolve(stored, symbolSpecificMessageHash)
client.resolve(stored, channelReplaced)
async def watch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
"""
watches information on multiple trades made by the user
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#user-trade-instrument_name
:param str symbol: unified market symbol of the market trades were made in
:param int [since]: the earliest time in ms to fetch trades for
:param int [limit]: the maximum number of trade structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
"""
await self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
symbol = market['symbol']
messageHash = 'user.trade'
messageHash = (messageHash + '.' + market['id']) if (market is not None) else messageHash
trades = await self.watch_private_subscribe(messageHash, params)
if self.newUpdates:
limit = trades.getLimit(symbol, limit)
return self.filter_by_symbol_since_limit(trades, symbol, since, limit, True)
async def watch_ticker(self, symbol: str, params={}) -> Ticker:
"""
watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#ticker-instrument_name
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
"""
await self.load_markets()
market = self.market(symbol)
messageHash = 'ticker' + '.' + market['id']
return await self.watch_public(messageHash, params)
async def un_watch_ticker(self, symbol: str, params={}) -> Any:
"""
unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#ticker-instrument_name
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
"""
await self.load_markets()
market = self.market(symbol)
subMessageHash = 'ticker' + '.' + market['id']
messageHash = 'unsubscribe:ticker:' + market['symbol']
return await self.un_watch_public_multiple('ticker', [market['symbol']], [messageHash], [subMessageHash], [subMessageHash], params)
async def watch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
"""
watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#ticker-instrument_name
:param str[] symbols: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
"""
await self.load_markets()
symbols = self.market_symbols(symbols, None, False)
messageHashes = []
marketIds = self.market_ids(symbols)
for i in range(0, len(marketIds)):
marketId = marketIds[i]
messageHashes.append('ticker.' + marketId)
url = self.urls['api']['ws']['public']
id = self.nonce()
request: dict = {
'method': 'subscribe',
'params': {
'channels': messageHashes,
},
'nonce': id,
}
ticker = await self.watch_multiple(url, messageHashes, self.extend(request, params), messageHashes)
if self.newUpdates:
result: dict = {}
result[ticker['symbol']] = ticker
return result
return self.filter_by_array(self.tickers, 'symbol', symbols)
async def un_watch_tickers(self, symbols: Strings = None, params={}) -> Any:
"""
unWatches a price ticker
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#ticker-instrument_name
:param str[] symbols: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
"""
await self.load_markets()
symbols = self.market_symbols(symbols, None, False)
messageHashes = []
subMessageHashes = []
marketIds = self.market_ids(symbols)
for i in range(0, len(marketIds)):
marketId = marketIds[i]
symbol = symbols[i]
subMessageHashes.append('ticker.' + marketId)
messageHashes.append('unsubscribe:ticker:' + symbol)
return await self.un_watch_public_multiple('ticker', symbols, messageHashes, subMessageHashes, subMessageHashes, params)
def handle_ticker(self, client: Client, message):
#
# {
# "instrument_name": "ETHUSD-PERP",
# "subscription": "ticker.ETHUSD-PERP",
# "channel": "ticker",
# "data": [
# {
# "h": "2400.20",
# "l": "2277.10",
# "a": "2335.25",
# "c": "-0.0022",
# "b": "2335.10",
# "bs": "5.4000",
# "k": "2335.16",
# "ks": "1.9970",
# "i": "ETHUSD-PERP",
# "v": "1305697.6462",
# "vv": "3058704939.17",
# "oi": "161646.3614",
# "t": 1726069647560
# }
# ]
# }
#
self.handle_bid_ask(client, message)
messageHash = self.safe_string(message, 'subscription')
marketId = self.safe_string(message, 'instrument_name')
market = self.safe_market(marketId)
data = self.safe_value(message, 'data', [])
for i in range(0, len(data)):
ticker = data[i]
parsed = self.parse_ws_ticker(ticker, market)
symbol = parsed['symbol']
self.tickers[symbol] = parsed
client.resolve(parsed, messageHash)
def parse_ws_ticker(self, ticker: dict, market: Market = None) -> Ticker:
#
# {
# "h": "2400.20",
# "l": "2277.10",
# "a": "2335.25",
# "c": "-0.0022",
# "b": "2335.10",
# "bs": "5.4000",
# "k": "2335.16",
# "ks": "1.9970",
# "i": "ETHUSD-PERP",
# "v": "1305697.6462",
# "vv": "3058704939.17",
# "oi": "161646.3614",
# "t": 1726069647560
# }
#
timestamp = self.safe_integer(ticker, 't')
marketId = self.safe_string(ticker, 'i')
market = self.safe_market(marketId, market, '_')
quote = self.safe_string(market, 'quote')
last = self.safe_string(ticker, 'a')
return self.safe_ticker({
'symbol': market['symbol'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_number(ticker, 'h'),
'low': self.safe_number(ticker, 'l'),
'bid': self.safe_number(ticker, 'b'),
'bidVolume': self.safe_number(ticker, 'bs'),
'ask': self.safe_number(ticker, 'k'),
'askVolume': self.safe_number(ticker, 'ks'),
'vwap': None,
'open': None,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': self.safe_string(ticker, 'c'),
'average': None,
'baseVolume': self.safe_string(ticker, 'v'),
'quoteVolume': self.safe_string(ticker, 'vv') if (quote == 'USD') else None,
'info': ticker,
}, market)
async def watch_bids_asks(self, symbols: Strings = None, params={}) -> Tickers:
"""
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#ticker-instrument_name
watches best bid & ask for symbols
:param str[] symbols: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
"""
await self.load_markets()
symbols = self.market_symbols(symbols, None, False)
messageHashes = []
topics = []
marketIds = self.market_ids(symbols)
for i in range(0, len(marketIds)):
marketId = marketIds[i]
messageHashes.append('bidask.' + symbols[i])
topics.append('ticker.' + marketId)
url = self.urls['api']['ws']['public']
id = self.nonce()
request: dict = {
'method': 'subscribe',
'params': {
'channels': topics,
},
'nonce': id,
}
newTickers = await self.watch_multiple(url, messageHashes, self.extend(request, params), messageHashes)
if self.newUpdates:
tickers: dict = {}
tickers[newTickers['symbol']] = newTickers
return tickers
return self.filter_by_array(self.bidsasks, 'symbol', symbols)
def handle_bid_ask(self, client: Client, message):
data = self.safe_list(message, 'data', [])
ticker = self.safe_dict(data, 0, {})
parsedTicker = self.parse_ws_bid_ask(ticker)
symbol = parsedTicker['symbol']
self.bidsasks[symbol] = parsedTicker
messageHash = 'bidask.' + symbol
client.resolve(parsedTicker, messageHash)
def parse_ws_bid_ask(self, ticker, market=None):
marketId = self.safe_string(ticker, 'i')
market = self.safe_market(marketId, market)
symbol = self.safe_string(market, 'symbol')
timestamp = self.safe_integer(ticker, 't')
return self.safe_ticker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'ask': self.safe_string(ticker, 'k'),
'askVolume': self.safe_string(ticker, 'ks'),
'bid': self.safe_string(ticker, 'b'),
'bidVolume': self.safe_string(ticker, 'bs'),
'info': ticker,
}, market)
async def watch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
"""
watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#candlestick-time_frame-instrument_name
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int [since]: timestamp in ms of the earliest candle to fetch
:param int [limit]: the maximum amount of candles to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int[][]: A list of candles ordered, open, high, low, close, volume
"""
await self.load_markets()
market = self.market(symbol)
symbol = market['symbol']
interval = self.safe_string(self.timeframes, timeframe, timeframe)
messageHash = 'candlestick' + '.' + interval + '.' + market['id']
ohlcv = await self.watch_public(messageHash, params)
if self.newUpdates:
limit = ohlcv.getLimit(symbol, limit)
return self.filter_by_since_limit(ohlcv, since, limit, 0, True)
async def un_watch_ohlcv(self, symbol: str, timeframe='1m', params={}) -> Any:
"""
unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#candlestick-time_frame-instrument_name
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int[][]: A list of candles ordered, open, high, low, close, volume
"""
await self.load_markets()
market = self.market(symbol)
symbol = market['symbol']
interval = self.safe_string(self.timeframes, timeframe, timeframe)
subMessageHash = 'candlestick' + '.' + interval + '.' + market['id']
messageHash = 'unsubscribe:ohlcv:' + market['symbol'] + ':' + timeframe
subExtend = {
'symbolsAndTimeframes': [[market['symbol'], timeframe]],
}
return await self.un_watch_public_multiple('ohlcv', [market['symbol']], [messageHash], [subMessageHash], [subMessageHash], params, subExtend)
def handle_ohlcv(self, client: Client, message):
#
# {
# "instrument_name": "BTC_USDT",
# "subscription": "candlestick.1m.BTC_USDT",
# "channel": "candlestick",
# "depth": 300,
# "interval": "1m",
# "data": [[Object]]
# }
#
messageHash = self.safe_string(message, 'subscription')
marketId = self.safe_string(message, 'instrument_name')
market = self.safe_market(marketId)
symbol = market['symbol']
interval = self.safe_string(message, 'interval')
timeframe = self.find_timeframe(interval)
self.ohlcvs[symbol] = self.safe_value(self.ohlcvs, symbol, {})
stored = self.safe_value(self.ohlcvs[symbol], timeframe)
if stored is None:
limit = self.safe_integer(self.options, 'OHLCVLimit', 1000)
stored = ArrayCacheByTimestamp(limit)
self.ohlcvs[symbol][timeframe] = stored
data = self.safe_value(message, 'data')
for i in range(0, len(data)):
tick = data[i]
parsed = self.parse_ohlcv(tick, market)
stored.append(parsed)
client.resolve(stored, messageHash)
async def watch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
"""
watches information on multiple orders made by the user
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#user-order-instrument_name
:param str symbol: unified market symbol of the market orders were made in
:param int [since]: the earliest time in ms to fetch orders for
:param int [limit]: the maximum number of order structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
"""
await self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
symbol = market['symbol']
messageHash = 'user.order'
messageHash = (messageHash + '.' + market['id']) if (market is not None) else messageHash
orders = await self.watch_private_subscribe(messageHash, params)
if self.newUpdates:
limit = orders.getLimit(symbol, limit)
return self.filter_by_symbol_since_limit(orders, symbol, since, limit, True)
def handle_orders(self, client: Client, message, subscription=None):
#
# {
# "method": "subscribe",
# "result": {
# "instrument_name": "ETH_CRO",
# "subscription": "user.order.ETH_CRO",
# "channel": "user.order",
# "data": [
# {
# "status": "ACTIVE",
# "side": "BUY",
# "price": 1,
# "quantity": 1,
# "order_id": "366455245775097673",
# "client_oid": "my_order_0002",
# "create_time": 1588758017375,
# "update_time": 1588758017411,
# "type": "LIMIT",
# "instrument_name": "ETH_CRO",
# "cumulative_quantity": 0,
# "cumulative_value": 0,
# "avg_price": 0,
# "fee_currency": "CRO",
# "time_in_force":"GOOD_TILL_CANCEL"
# }
# ],
# "channel": "user.order.ETH_CRO"
# }
# }
#
channel = self.safe_string(message, 'channel')
symbolSpecificMessageHash = self.safe_string(message, 'subscription')
orders = self.safe_value(message, 'data', [])
ordersLength = len(orders)
if ordersLength > 0:
if self.orders is None:
limit = self.safe_integer(self.options, 'ordersLimit', 1000)
self.orders = ArrayCacheBySymbolById(limit)
stored = self.orders
parsed = self.parse_orders(orders)
for i in range(0, len(parsed)):
stored.append(parsed[i])
client.resolve(stored, symbolSpecificMessageHash)
# non-symbol specific
client.resolve(stored, channel) # channel might have a symbol-specific suffix
client.resolve(stored, 'user.order')
async def watch_positions(self, symbols: Strings = None, since: Int = None, limit: Int = None, params={}) -> List[Position]:
"""
watch all open positions
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#user-position_balance
:param str[] [symbols]: list of unified market symbols to watch positions for
:param int [since]: the earliest time in ms to fetch positions for
:param int [limit]: the maximum number of positions to retrieve
:param dict params: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
"""
await self.load_markets()
await self.authenticate()
url = self.urls['api']['ws']['private']
id = self.nonce()
request: dict = {
'method': 'subscribe',
'params': {
'channels': ['user.position_balance'],
},
'nonce': id,
}
messageHash = 'positions'
symbols = self.market_symbols(symbols)
if not self.is_empty(symbols):
messageHash = '::' + ','.join(symbols)
client = self.client(url)
self.set_positions_cache(client, symbols)
fetchPositionsSnapshot = self.handle_option('watchPositions', 'fetchPositionsSnapshot', True)
awaitPositionsSnapshot = self.handle_option('watchPositions', 'awaitPositionsSnapshot', True)
if fetchPositionsSnapshot and awaitPositionsSnapshot and self.positions is None:
snapshot = await client.future('fetchPositionsSnapshot')
return self.filter_by_symbols_since_limit(snapshot, symbols, since, limit, True)
newPositions = await self.watch(url, messageHash, self.extend(request, params))
if self.newUpdates:
return newPositions
return self.filter_by_symbols_since_limit(self.positions, symbols, since, limit, True)
def set_positions_cache(self, client: Client, type, symbols: Strings = None):
fetchPositionsSnapshot = self.handle_option('watchPositions', 'fetchPositionsSnapshot', False)
if fetchPositionsSnapshot:
messageHash = 'fetchPositionsSnapshot'
if not (messageHash in client.futures):
client.future(messageHash)
self.spawn(self.load_positions_snapshot, client, messageHash)
else:
self.positions = ArrayCacheBySymbolBySide()
async def load_positions_snapshot(self, client, messageHash):
positions = await self.fetch_positions()
self.positions = ArrayCacheBySymbolBySide()
cache = self.positions
for i in range(0, len(positions)):
position = positions[i]
contracts = self.safe_number(position, 'contracts', 0)
if contracts > 0:
cache.append(position)
# don't remove the future from the .futures cache
future = client.futures[messageHash]
future.resolve(cache)
client.resolve(cache, 'positions')
def handle_positions(self, client, message):
#
# {
# "subscription": "user.position_balance",
# "channel": "user.position_balance",
# "data": [{
# "balances": [{
# "instrument_name": "USD",
# "quantity": "8.9979961950886",
# "update_timestamp_ms": 1695598760597,
# }],
# "positions": [{
# "account_id": "96a0edb1-afb5-4c7c-af89-5cb610319e2c",
# "instrument_name": "LTCUSD-PERP",
# "type": "PERPETUAL_SWAP",
# "quantity": "1.8",
# "cost": "114.766",
# "open_position_pnl": "-0.0216206",
# "session_pnl": "0.00962994",
# "update_timestamp_ms": 1695598760597,
# "open_pos_cost": "114.766",
# }],
# }],
# }
#
# each account is connected to a different endpoint
# and has exactly one subscriptionhash which is the account type
data = self.safe_value(message, 'data', [])
firstData = self.safe_value(data, 0, {})
rawPositions = self.safe_value(firstData, 'positions', [])
if self.positions is None:
self.positions = ArrayCacheBySymbolBySide()
cache = self.positions
newPositions = []
for i in range(0, len(rawPositions)):
rawPosition = rawPositions[i]
position = self.parse_position(rawPosition)
newPositions.append(position)
cache.append(position)
messageHashes = self.find_message_hashes(client, 'positions::')
for i in range(0, len(messageHashes)):
messageHash = messageHashes[i]
parts = messageHash.split('::')
symbolsString = parts[1]
symbols = symbolsString.split(',')
positions = self.filter_by_array(newPositions, 'symbol', symbols, False)
if not self.is_empty(positions):
client.resolve(positions, messageHash)
client.resolve(newPositions, 'positions')
async def watch_balance(self, params={}) -> Balances:
"""
watch balance and get the amount of funds available for trading or funds locked in orders
https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#user-balance
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
"""
messageHash = 'user.balance'
return await self.watch_private_subscribe(messageHash, params)
def handle_balance(self, client: Client, message):
#
# {
# "id": 1,
# "method": "subscribe",
# "code": 0,
# "result": {
# "subscription": "user.balance",
# "channel": "user.balance",
# "data": [
# {
# "total_available_balance": "5.84684368",
# "total_margin_balance": "5.84684368",
# "total_initial_margin": "0",
# "total_maintenance_margin": "0",
# "total_position_cost": "0",
# "total_cash_balance": "6.44412101",
# "total_collateral_value": "5.846843685",
# "total_session_unrealized_pnl": "0",
# "instrument_name": "USD",
# "total_session_realized_pnl": "0",
# "position_balances": [
# {
# "quantity": "0.0002119875",
# "reserved_qty": "0",
# "collateral_weight": "0.9",
# "collateral_amount": "5.37549592",
# "market_value": "5.97277325",
# "max_withdrawal_balance": "0.00021198",
# "instrument_name": "BTC",
# "hourly_interest_rate": "0"
# },
# ],
# "total_effective_leverage": "0",
# "position_limit": "3000000",
# "used_position_limit": "0",
# "total_borrow": "0",
# "margin_score": "0",
# "is_liquidating": False,
# "has_risk": False,
# "terminatable": True
# }
# ]
# }
# }
#
messageHash = self.safe_string(message, 'subscription')
data = self.safe_value(message, 'data', [])
positionBalances = self.safe_value(data[0], 'position_balances', [])
self.balance['info'] = data
for i in range(0, len(positionBalances)):
balance = positionBalances[i]
currencyId = self.safe_string(balance, 'instrument_name')
code = self.safe_currency_code(currencyId)
account = self.account()
account['total'] = self.safe_string(balance, 'quantity')
account['used'] = self.safe_string(balance, 'reserved_qty')
self.balance[code] = account
self.balance = self.safe_balance(self.balance)
client.resolve(self.balance, messageHash)
messageHashRequest = self.safe_string(message, 'id')
client.resolve(self.balance, messageHashRequest)
async def create_order_ws(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> Order: