-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
exchange.py
3695 lines (3333 loc) · 156 KB
/
exchange.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
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 -*-
"""Base exchange class"""
# -----------------------------------------------------------------------------
__version__ = '2.4.79'
# -----------------------------------------------------------------------------
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import NetworkError
from ccxt.base.errors import NotSupported
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import RequestTimeout
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import NullResponse
from ccxt.base.errors import RateLimitExceeded
# -----------------------------------------------------------------------------
from ccxt.base.decimal_to_precision import decimal_to_precision
from ccxt.base.decimal_to_precision import DECIMAL_PLACES, TICK_SIZE, NO_PADDING, TRUNCATE, ROUND, ROUND_UP, ROUND_DOWN
from ccxt.base.decimal_to_precision import number_to_string
from ccxt.base.precise import Precise
# -----------------------------------------------------------------------------
# rsa jwt signing
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key
# -----------------------------------------------------------------------------
# ecdsa signing
from ccxt.static_dependencies import ecdsa
from ccxt.static_dependencies import keccak
# eddsa signing
try:
import axolotl_curve25519 as eddsa
except ImportError:
eddsa = None
# -----------------------------------------------------------------------------
__all__ = [
'Exchange',
]
# -----------------------------------------------------------------------------
import types
import logging
import base64
import binascii
import calendar
import collections
import datetime
from email.utils import parsedate
import functools
import gzip
import hashlib
import hmac
import io
import json
import math
import random
from numbers import Number
import re
from requests import Session
from requests.utils import default_user_agent
from requests.exceptions import HTTPError, Timeout, TooManyRedirects, RequestException, ConnectionError as requestsConnectionError
# import socket
from ssl import SSLError
# import sys
import time
import uuid
import zlib
from decimal import Decimal
from time import mktime
from wsgiref.handlers import format_date_time
import urllib.parse as _urlencode
# -----------------------------------------------------------------------------
class Exchange(object):
"""Base exchange class"""
id = None
name = None
version = None
certified = False # if certified by the CCXT dev team
pro = False # if it is integrated with CCXT Pro for WebSocket support
alias = False # whether this exchange is an alias to another exchange
# rate limiter settings
enableRateLimit = True
rateLimit = 2000 # milliseconds = seconds * 1000
timeout = 10000 # milliseconds = seconds * 1000
asyncio_loop = None
aiohttp_proxy = None
aiohttp_trust_env = False
requests_trust_env = False
session = None # Session () by default
verify = True # SSL verification
validateServerSsl = True
validateClientSsl = False
logger = None # logging.getLogger(__name__) by default
userAgent = None
userAgents = {
'chrome': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
'chrome39': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
'chrome100': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
}
verbose = False
markets = None
symbols = None
codes = None
timeframes = None
fees = {
'trading': {
'percentage': True, # subclasses should rarely have to redefine this
},
'funding': {
'withdraw': {},
'deposit': {},
},
}
loaded_fees = {
'trading': {
'percentage': True,
},
'funding': {
'withdraw': {},
'deposit': {},
},
}
ids = None
urls = None
api = None
parseJsonResponse = True
proxy = ''
origin = '*' # CORS origin
proxies = None
hostname = None # in case of inaccessibility of the "main" domain
apiKey = ''
secret = ''
password = ''
uid = ''
privateKey = '' # a "0x"-prefixed hexstring private key for a wallet
walletAddress = '' # the wallet address "0x"-prefixed hexstring
token = '' # reserved for HTTP auth in some cases
twofa = None
markets_by_id = None
currencies_by_id = None
precision = None
exceptions = None
limits = {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': None,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
}
httpExceptions = {
'422': ExchangeError,
'418': DDoSProtection,
'429': RateLimitExceeded,
'404': ExchangeNotAvailable,
'409': ExchangeNotAvailable,
'410': ExchangeNotAvailable,
'451': ExchangeNotAvailable,
'500': ExchangeNotAvailable,
'501': ExchangeNotAvailable,
'502': ExchangeNotAvailable,
'520': ExchangeNotAvailable,
'521': ExchangeNotAvailable,
'522': ExchangeNotAvailable,
'525': ExchangeNotAvailable,
'526': ExchangeNotAvailable,
'400': ExchangeNotAvailable,
'403': ExchangeNotAvailable,
'405': ExchangeNotAvailable,
'503': ExchangeNotAvailable,
'530': ExchangeNotAvailable,
'408': RequestTimeout,
'504': RequestTimeout,
'401': AuthenticationError,
'407': AuthenticationError,
'511': AuthenticationError,
}
headers = None
balance = None
orderbooks = None
orders = None
myTrades = None
trades = None
transactions = None
ohlcvs = None
tickers = None
base_currencies = None
quote_currencies = None
currencies = None
options = None # Python does not allow to define properties in run-time with setattr
accounts = None
positions = None
status = {
'status': 'ok',
'updated': None,
'eta': None,
'url': None,
}
requiredCredentials = {
'apiKey': True,
'secret': True,
'uid': False,
'login': False,
'password': False,
'twofa': False, # 2-factor authentication (one-time password key)
'privateKey': False, # a "0x"-prefixed hexstring private key for a wallet
'walletAddress': False, # the wallet address "0x"-prefixed hexstring
'token': False, # reserved for HTTP auth in some cases
}
# API method metainfo
has = {
'publicAPI': True,
'privateAPI': True,
'CORS': None,
'spot': None,
'margin': None,
'swap': None,
'future': None,
'option': None,
'addMargin': None,
'cancelAllOrders': None,
'cancelOrder': True,
'cancelOrders': None,
'createDepositAddress': None,
'createLimitOrder': True,
'createMarketOrder': True,
'createOrder': True,
'createPostOnlyOrder': None,
'createReduceOnlyOrder': None,
'createStopOrder': None,
'createStopLimitOrder': None,
'createStopMarketOrder': None,
'editOrder': 'emulated',
'fetchAccounts': None,
'fetchBalance': True,
'fetchBidsAsks': None,
'fetchBorrowInterest': None,
'fetchBorrowRate': None,
'fetchBorrowRateHistory': None,
'fetchBorrowRatesPerSymbol': None,
'fetchBorrowRates': None,
'fetchCanceledOrders': None,
'fetchClosedOrder': None,
'fetchClosedOrders': None,
'fetchCurrencies': 'emulated',
'fetchDeposit': None,
'fetchDepositAddress': None,
'fetchDepositAddresses': None,
'fetchDepositAddressesByNetwork': None,
'fetchDeposits': None,
'fetchFundingFee': None,
'fetchFundingFees': None,
'fetchFundingHistory': None,
'fetchFundingRate': None,
'fetchFundingRateHistory': None,
'fetchFundingRates': None,
'fetchIndexOHLCV': None,
'fetchL2OrderBook': True,
'fetchLedger': None,
'fetchLedgerEntry': None,
'fetchLeverageTiers': None,
'fetchMarketLeverageTiers': None,
'fetchMarkets': True,
'fetchMarkOHLCV': None,
'fetchMyTrades': None,
'fetchOHLCV': 'emulated',
'fetchOpenOrder': None,
'fetchOpenOrders': None,
'fetchOrder': None,
'fetchOrderBook': True,
'fetchOrderBooks': None,
'fetchOrders': None,
'fetchOrderTrades': None,
'fetchPermissions': None,
'fetchPosition': None,
'fetchPositions': None,
'fetchPositionsRisk': None,
'fetchPremiumIndexOHLCV': None,
'fetchStatus': 'emulated',
'fetchTicker': True,
'fetchTickers': None,
'fetchTime': None,
'fetchTrades': True,
'fetchTradingFee': None,
'fetchTradingFees': None,
'fetchTradingLimits': None,
'fetchTransactions': None,
'fetchTransfers': None,
'fetchWithdrawal': None,
'fetchWithdrawals': None,
'reduceMargin': None,
'setLeverage': None,
'setMargin': None,
'setMarginMode': None,
'setPositionMode': None,
'signIn': None,
'transfer': None,
'withdraw': None,
}
precisionMode = DECIMAL_PLACES
paddingMode = NO_PADDING
minFundingAddressLength = 1 # used in check_address
substituteCommonCurrencyCodes = True
quoteJsonNumbers = True
number = float # or str (a pointer to a class)
handleContentTypeApplicationZip = False
# whether fees should be summed by currency code
reduceFees = True
lastRestRequestTimestamp = 0
lastRestPollTimestamp = 0
restRequestQueue = None
restPollerLoopIsRunning = False
rateLimitTokens = 16
rateLimitMaxTokens = 16
rateLimitUpdateTime = 0
enableLastHttpResponse = True
enableLastJsonResponse = True
enableLastResponseHeaders = True
last_http_response = None
last_json_response = None
last_response_headers = None
requiresEddsa = False
base58_encoder = None
base58_decoder = None
# no lower case l or upper case I, O
base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
commonCurrencies = {
'XBT': 'BTC',
'BCC': 'BCH',
'BCHABC': 'BCH',
'BCHSV': 'BSV',
}
synchronous = True
def __init__(self, config={}):
self.precision = dict() if self.precision is None else self.precision
self.limits = dict() if self.limits is None else self.limits
self.exceptions = dict() if self.exceptions is None else self.exceptions
self.headers = dict() if self.headers is None else self.headers
self.balance = dict() if self.balance is None else self.balance
self.orderbooks = dict() if self.orderbooks is None else self.orderbooks
self.tickers = dict() if self.tickers is None else self.tickers
self.trades = dict() if self.trades is None else self.trades
self.transactions = dict() if self.transactions is None else self.transactions
self.positions = dict() if self.positions is None else self.positions
self.ohlcvs = dict() if self.ohlcvs is None else self.ohlcvs
self.currencies = dict() if self.currencies is None else self.currencies
self.options = self.get_default_options() if self.options is None else self.options # Python does not allow to define properties in run-time with setattr
self.decimal_to_precision = decimal_to_precision
self.number_to_string = number_to_string
# version = '.'.join(map(str, sys.version_info[:3]))
# self.userAgent = {
# 'User-Agent': 'ccxt/' + __version__ + ' (+https://github.com/ccxt/ccxt) Python/' + version
# }
self.origin = self.uuid()
self.userAgent = default_user_agent()
settings = self.deep_extend(self.describe(), config)
for key in settings:
if hasattr(self, key) and isinstance(getattr(self, key), dict):
setattr(self, key, self.deep_extend(getattr(self, key), settings[key]))
else:
setattr(self, key, settings[key])
if self.api:
self.define_rest_api(self.api, 'request')
if self.markets:
self.set_markets(self.markets)
# convert all properties from underscore notation foo_bar to camelcase notation fooBar
cls = type(self)
for name in dir(self):
if name[0] != '_' and name[-1] != '_' and '_' in name:
parts = name.split('_')
# fetch_ohlcv → fetchOHLCV (not fetchOhlcv!)
exceptions = {'ohlcv': 'OHLCV', 'le': 'LE', 'be': 'BE'}
camelcase = parts[0] + ''.join(exceptions.get(i, self.capitalize(i)) for i in parts[1:])
attr = getattr(self, name)
if isinstance(attr, types.MethodType):
setattr(cls, camelcase, getattr(cls, name))
else:
setattr(self, camelcase, attr)
self.tokenBucket = self.extend({
'refillRate': 1.0 / self.rateLimit if self.rateLimit > 0 else float('inf'),
'delay': 0.001,
'capacity': 1.0,
'defaultCost': 1.0,
}, getattr(self, 'tokenBucket', {}))
if not self.session and self.synchronous:
self.session = Session()
self.session.trust_env = self.requests_trust_env
self.logger = self.logger if self.logger else logging.getLogger(__name__)
def __del__(self):
if self.session:
try:
self.session.close()
except Exception as e:
pass
def __repr__(self):
return 'ccxt.' + ('async_support.' if self.asyncio_loop else '') + self.id + '()'
def __str__(self):
return self.name
def describe(self):
return {}
def set_sandbox_mode(self, enabled):
if enabled:
if 'test' in self.urls:
self.urls['apiBackup'] = self.urls['api']
self.urls['api'] = self.urls['test']
else:
raise NotSupported(self.id + ' does not have a sandbox URL')
elif 'apiBackup' in self.urls:
self.urls['api'] = self.urls['apiBackup']
del self.urls['apiBackup']
def define_rest_api_endpoint(self, method_name, uppercase_method, lowercase_method, camelcase_method, path, paths, config={}):
cls = type(self)
entry = getattr(cls, method_name) # returns a function (instead of a bound method)
delimiters = re.compile('[^a-zA-Z0-9]')
split_path = delimiters.split(path)
lowercase_path = [x.strip().lower() for x in split_path]
camelcase_suffix = ''.join([Exchange.capitalize(x) for x in split_path])
underscore_suffix = '_'.join([x for x in lowercase_path if len(x)])
camelcase_prefix = ''
underscore_prefix = ''
if len(paths):
camelcase_prefix = paths[0]
underscore_prefix = paths[0]
if len(paths) > 1:
camelcase_prefix += ''.join([Exchange.capitalize(x) for x in paths[1:]])
underscore_prefix += '_' + '_'.join([x.strip() for p in paths[1:] for x in delimiters.split(p)])
api_argument = paths
else:
api_argument = paths[0]
camelcase = camelcase_prefix + camelcase_method + Exchange.capitalize(camelcase_suffix)
underscore = underscore_prefix + '_' + lowercase_method + '_' + underscore_suffix.lower()
def partialer():
outer_kwargs = {'path': path, 'api': api_argument, 'method': uppercase_method, 'config': config}
@functools.wraps(entry)
def inner(_self, params=None, context=None):
"""
Inner is called when a generated method (publicGetX) is called.
_self is a reference to self created by function.__get__(exchange, type(exchange))
https://en.wikipedia.org/wiki/Closure_(computer_programming) equivalent to functools.partial
"""
inner_kwargs = dict(outer_kwargs) # avoid mutation
if params is not None:
inner_kwargs['params'] = params
if context is not None:
inner_kwargs['context'] = params
return entry(_self, **inner_kwargs)
return inner
to_bind = partialer()
setattr(cls, camelcase, to_bind)
setattr(cls, underscore, to_bind)
def define_rest_api(self, api, method_name, paths=[]):
for key, value in api.items():
uppercase_method = key.upper()
lowercase_method = key.lower()
camelcase_method = lowercase_method.capitalize()
if isinstance(value, list):
for path in value:
self.define_rest_api_endpoint(method_name, uppercase_method, lowercase_method, camelcase_method, path, paths)
# the options HTTP method conflicts with the 'options' API url path
# elif re.search(r'^(?:get|post|put|delete|options|head|patch)$', key, re.IGNORECASE) is not None:
elif re.search(r'^(?:get|post|put|delete|head|patch)$', key, re.IGNORECASE) is not None:
for [endpoint, config] in value.items():
path = endpoint.strip()
if isinstance(config, dict):
self.define_rest_api_endpoint(method_name, uppercase_method, lowercase_method, camelcase_method, path, paths, config)
elif isinstance(config, Number):
self.define_rest_api_endpoint(method_name, uppercase_method, lowercase_method, camelcase_method, path, paths, {'cost': config})
else:
raise NotSupported(self.id + ' define_rest_api() API format not supported, API leafs must strings, objects or numbers')
else:
self.define_rest_api(value, method_name, paths + [key])
def throttle(self, cost=None):
now = float(self.milliseconds())
elapsed = now - self.lastRestRequestTimestamp
cost = 1 if cost is None else cost
sleep_time = self.rateLimit * cost
if elapsed < sleep_time:
delay = sleep_time - elapsed
time.sleep(delay / 1000.0)
@staticmethod
def gzip_deflate(response, text):
encoding = response.info().get('Content-Encoding')
if encoding in ('gzip', 'x-gzip', 'deflate'):
if encoding == 'deflate':
return zlib.decompress(text, -zlib.MAX_WBITS)
else:
return gzip.GzipFile('', 'rb', 9, io.BytesIO(text)).read()
return text
def prepare_request_headers(self, headers=None):
headers = headers or {}
if self.session:
headers.update(self.session.headers)
headers.update(self.headers)
if self.userAgent:
if type(self.userAgent) is str:
headers.update({'User-Agent': self.userAgent})
elif (type(self.userAgent) is dict) and ('User-Agent' in self.userAgent):
headers.update(self.userAgent)
if self.proxy:
headers.update({'Origin': self.origin})
headers.update({'Accept-Encoding': 'gzip, deflate'})
return self.set_headers(headers)
def log(self, *args):
print(*args)
def on_rest_response(self, code, reason, url, method, response_headers, response_body, request_headers, request_body):
return response_body.strip()
def on_json_response(self, response_body):
if self.quoteJsonNumbers:
return json.loads(response_body, parse_float=str, parse_int=str)
else:
return json.loads(response_body)
def fetch(self, url, method='GET', headers=None, body=None):
"""Perform a HTTP request and return decoded JSON data"""
request_headers = self.prepare_request_headers(headers)
url = self.proxy + url
if self.verbose:
self.log("\nfetch Request:", self.id, method, url, "RequestHeaders:", request_headers, "RequestBody:", body)
self.logger.debug("%s %s, Request: %s %s", method, url, request_headers, body)
request_body = body
if body:
body = body.encode()
self.session.cookies.clear()
http_response = None
http_status_code = None
http_status_text = None
json_response = None
try:
response = self.session.request(
method,
url,
data=body,
headers=request_headers,
timeout=int(self.timeout / 1000),
proxies=self.proxies,
verify=self.verify and self.validateServerSsl
)
# does not try to detect encoding
response.encoding = 'utf-8'
headers = response.headers
http_status_code = response.status_code
http_status_text = response.reason
http_response = self.on_rest_response(http_status_code, http_status_text, url, method, headers, response.text, request_headers, request_body)
json_response = self.parse_json(http_response)
# FIXME remove last_x_responses from subclasses
if self.enableLastHttpResponse:
self.last_http_response = http_response
if self.enableLastJsonResponse:
self.last_json_response = json_response
if self.enableLastResponseHeaders:
self.last_response_headers = headers
if self.verbose:
self.log("\nfetch Response:", self.id, method, url, http_status_code, "ResponseHeaders:", headers, "ResponseBody:", http_response)
self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response)
response.raise_for_status()
except Timeout as e:
details = ' '.join([self.id, method, url])
raise RequestTimeout(details) from e
except TooManyRedirects as e:
details = ' '.join([self.id, method, url])
raise ExchangeError(details) from e
except SSLError as e:
details = ' '.join([self.id, method, url])
raise ExchangeError(details) from e
except HTTPError as e:
details = ' '.join([self.id, method, url])
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
if not skip_further_error_handling:
self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response)
raise ExchangeError(details) from e
except requestsConnectionError as e:
error_string = str(e)
details = ' '.join([self.id, method, url])
if 'Read timed out' in error_string:
raise RequestTimeout(details) from e
else:
raise NetworkError(details) from e
except ConnectionResetError as e:
error_string = str(e)
details = ' '.join([self.id, method, url])
raise NetworkError(details) from e
except RequestException as e: # base exception class
error_string = str(e)
details = ' '.join([self.id, method, url])
if any(x in error_string for x in ['ECONNRESET', 'Connection aborted.', 'Connection broken:']):
raise NetworkError(details) from e
else:
raise ExchangeError(details) from e
self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
if json_response is not None:
return json_response
elif self.is_text_response(headers):
return http_response
else:
return response.content
def parse_json(self, http_response):
try:
if Exchange.is_json_encoded_object(http_response):
return self.on_json_response(http_response)
except ValueError: # superclass of JsonDecodeError (python2)
pass
def is_text_response(self, headers):
# https://github.com/ccxt/ccxt/issues/5302
content_type = headers.get('Content-Type', '')
return content_type.startswith('application/json') or content_type.startswith('text/')
@staticmethod
def key_exists(dictionary, key):
if dictionary is None or key is None:
return False
if isinstance(dictionary, list):
if isinstance(key, int) and 0 <= key and key < len(dictionary):
return dictionary[key] is not None
else:
return False
if key in dictionary:
return dictionary[key] is not None and dictionary[key] != ''
return False
@staticmethod
def safe_float(dictionary, key, default_value=None):
value = default_value
try:
if Exchange.key_exists(dictionary, key):
value = float(dictionary[key])
except ValueError as e:
value = default_value
return value
@staticmethod
def safe_string(dictionary, key, default_value=None):
return str(dictionary[key]) if Exchange.key_exists(dictionary, key) else default_value
@staticmethod
def safe_string_lower(dictionary, key, default_value=None):
if Exchange.key_exists(dictionary, key):
return str(dictionary[key]).lower()
else:
return default_value.lower() if default_value is not None else default_value
@staticmethod
def safe_string_upper(dictionary, key, default_value=None):
if Exchange.key_exists(dictionary, key):
return str(dictionary[key]).upper()
else:
return default_value.upper() if default_value is not None else default_value
@staticmethod
def safe_integer(dictionary, key, default_value=None):
if not Exchange.key_exists(dictionary, key):
return default_value
value = dictionary[key]
try:
# needed to avoid breaking on "100.0"
# https://stackoverflow.com/questions/1094717/convert-a-string-to-integer-with-decimal-in-python#1094721
return int(float(value))
except ValueError:
return default_value
except TypeError:
return default_value
@staticmethod
def safe_integer_product(dictionary, key, factor, default_value=None):
if not Exchange.key_exists(dictionary, key):
return default_value
value = dictionary[key]
if isinstance(value, Number):
return int(value * factor)
elif isinstance(value, str):
try:
return int(float(value) * factor)
except ValueError:
pass
return default_value
@staticmethod
def safe_timestamp(dictionary, key, default_value=None):
return Exchange.safe_integer_product(dictionary, key, 1000, default_value)
@staticmethod
def safe_value(dictionary, key, default_value=None):
return dictionary[key] if Exchange.key_exists(dictionary, key) else default_value
# we're not using safe_floats with a list argument as we're trying to save some cycles here
# we're not using safe_float_3 either because those cases are too rare to deserve their own optimization
@staticmethod
def safe_float_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_either(Exchange.safe_float, dictionary, key1, key2, default_value)
@staticmethod
def safe_string_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_either(Exchange.safe_string, dictionary, key1, key2, default_value)
@staticmethod
def safe_string_lower_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_either(Exchange.safe_string_lower, dictionary, key1, key2, default_value)
@staticmethod
def safe_string_upper_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_either(Exchange.safe_string_upper, dictionary, key1, key2, default_value)
@staticmethod
def safe_integer_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_either(Exchange.safe_integer, dictionary, key1, key2, default_value)
@staticmethod
def safe_integer_product_2(dictionary, key1, key2, factor, default_value=None):
value = Exchange.safe_integer_product(dictionary, key1, factor)
return value if value is not None else Exchange.safe_integer_product(dictionary, key2, factor, default_value)
@staticmethod
def safe_timestamp_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_integer_product_2(dictionary, key1, key2, 1000, default_value)
@staticmethod
def safe_value_2(dictionary, key1, key2, default_value=None):
return Exchange.safe_either(Exchange.safe_value, dictionary, key1, key2, default_value)
# safe_method_n methods family
@staticmethod
def safe_float_n(dictionary, key_list, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
if value is None:
return default_value
try:
value = float(value)
except ValueError as e:
value = default_value
return value
@staticmethod
def safe_string_n(dictionary, key_list, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
return str(value) if value is not None else default_value
@staticmethod
def safe_string_lower_n(dictionary, key_list, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
if value is not None:
return str(value).lower()
elif default_value is None:
return default_value
else:
return default_value.lower()
@staticmethod
def safe_string_upper_n(dictionary, key_list, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
if value is not None:
return str(value).upper()
elif default_value is None:
return default_value
else:
return default_value.upper()
@staticmethod
def safe_integer_n(dictionary, key_list, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
if value is None:
return default_value
try:
# needed to avoid breaking on "100.0"
# https://stackoverflow.com/questions/1094717/convert-a-string-to-integer-with-decimal-in-python#1094721
return int(float(value))
except ValueError:
return default_value
except TypeError:
return default_value
@staticmethod
def safe_integer_product_n(dictionary, key_list, factor, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
if value is None:
return default_value
if isinstance(value, Number):
return int(value * factor)
elif isinstance(value, str):
try:
return int(float(value) * factor)
except ValueError:
pass
return default_value
@staticmethod
def safe_timestamp_n(dictionary, key_list, default_value=None):
return Exchange.safe_integer_product_n(dictionary, key_list, 1000, default_value)
@staticmethod
def safe_value_n(dictionary, key_list, default_value=None):
value = Exchange.get_object_value_from_key_list(dictionary, key_list)
return value if value is not None else default_value
@staticmethod
def get_object_value_from_key_list(dictionary, key_list):
filtered_list = list(filter(lambda el: el in dictionary and dictionary[el] != '' and dictionary[el] is not None, key_list))
if (len(filtered_list) == 0):
return None
return dictionary[filtered_list[0]]
@staticmethod
def safe_either(method, dictionary, key1, key2, default_value=None):
"""A helper-wrapper for the safe_value_2() family."""
value = method(dictionary, key1)
return value if value is not None else method(dictionary, key2, default_value)
@staticmethod
def truncate(num, precision=0):
"""Deprecated, use decimal_to_precision instead"""
if precision > 0:
decimal_precision = math.pow(10, precision)
return math.trunc(num * decimal_precision) / decimal_precision
return int(Exchange.truncate_to_string(num, precision))
@staticmethod
def truncate_to_string(num, precision=0):
"""Deprecated, todo: remove references from subclasses"""
if precision > 0:
parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.')
decimal_digits = parts[1][:precision].rstrip('0')
decimal_digits = decimal_digits if len(decimal_digits) else '0'
return parts[0] + '.' + decimal_digits
return ('%d' % num)
@staticmethod
def uuid22(length=22):
return format(random.getrandbits(length * 4), 'x')
@staticmethod
def uuid16(length=16):
return format(random.getrandbits(length * 4), 'x')
@staticmethod
def uuid():
return str(uuid.uuid4())
@staticmethod
def uuidv1():
return str(uuid.uuid1()).replace('-', '')
@staticmethod
def capitalize(string): # first character only, rest characters unchanged
# the native pythonic .capitalize() method lowercases all other characters
# which is an unwanted behaviour, therefore we use this custom implementation
# check it yourself: print('foobar'.capitalize(), 'fooBar'.capitalize())
if len(string) > 1:
return "%s%s" % (string[0].upper(), string[1:])
return string.upper()
@staticmethod
def strip(string):
return string.strip()
@staticmethod
def keysort(dictionary):
return collections.OrderedDict(sorted(dictionary.items(), key=lambda t: t[0]))
@staticmethod
def extend(*args):
if args is not None:
result = None
if type(args[0]) is collections.OrderedDict:
result = collections.OrderedDict()
else:
result = {}
for arg in args:
result.update(arg)
return result
return {}
@staticmethod
def deep_extend(*args):
result = None
for arg in args:
if isinstance(arg, dict):
if not isinstance(result, dict):
result = {}
for key in arg:
result[key] = Exchange.deep_extend(result[key] if key in result else None, arg[key])
else:
result = arg
return result
@staticmethod
def filter_by(array, key, value=None):
array = Exchange.to_array(array)
return list(filter(lambda x: x[key] == value, array))
@staticmethod
def filterBy(array, key, value=None):
return Exchange.filter_by(array, key, value)
@staticmethod
def group_by(array, key):
result = {}
array = Exchange.to_array(array)
array = [entry for entry in array if (key in entry) and (entry[key] is not None)]
for entry in array:
if entry[key] not in result:
result[entry[key]] = []
result[entry[key]].append(entry)
return result
@staticmethod
def groupBy(array, key):
return Exchange.group_by(array, key)
@staticmethod
def index_by(array, key):
result = {}
if type(array) is dict:
array = Exchange.keysort(array).values()
is_int_key = isinstance(key, int)
for element in array:
if ((is_int_key and (key < len(element))) or (key in element)) and (element[key] is not None):
k = element[key]
result[k] = element
return result
@staticmethod
def sort_by(array, key, descending=False):
return sorted(array, key=lambda k: k[key] if k[key] is not None else "", reverse=descending)