ccxt 4.3.70__py2.py3-none-any.whl → 4.3.71__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. ccxt/__init__.py +3 -1
  2. ccxt/abstract/paradex.py +40 -0
  3. ccxt/async_support/__init__.py +3 -1
  4. ccxt/async_support/base/exchange.py +1 -1
  5. ccxt/async_support/paradex.py +1966 -0
  6. ccxt/async_support/woo.py +4 -2
  7. ccxt/base/exchange.py +58 -1
  8. ccxt/paradex.py +1966 -0
  9. ccxt/pro/__init__.py +3 -1
  10. ccxt/pro/bequant.py +4 -0
  11. ccxt/pro/paradex.py +340 -0
  12. ccxt/static_dependencies/__init__.py +1 -1
  13. ccxt/static_dependencies/lark/__init__.py +38 -0
  14. ccxt/static_dependencies/lark/__pyinstaller/__init__.py +6 -0
  15. ccxt/static_dependencies/lark/__pyinstaller/hook-lark.py +14 -0
  16. ccxt/static_dependencies/lark/ast_utils.py +59 -0
  17. ccxt/static_dependencies/lark/common.py +86 -0
  18. ccxt/static_dependencies/lark/exceptions.py +292 -0
  19. ccxt/static_dependencies/lark/grammar.py +130 -0
  20. ccxt/static_dependencies/lark/grammars/__init__.py +0 -0
  21. ccxt/static_dependencies/lark/indenter.py +143 -0
  22. ccxt/static_dependencies/lark/lark.py +658 -0
  23. ccxt/static_dependencies/lark/lexer.py +678 -0
  24. ccxt/static_dependencies/lark/load_grammar.py +1428 -0
  25. ccxt/static_dependencies/lark/parse_tree_builder.py +391 -0
  26. ccxt/static_dependencies/lark/parser_frontends.py +257 -0
  27. ccxt/static_dependencies/lark/parsers/__init__.py +0 -0
  28. ccxt/static_dependencies/lark/parsers/cyk.py +340 -0
  29. ccxt/static_dependencies/lark/parsers/earley.py +314 -0
  30. ccxt/static_dependencies/lark/parsers/earley_common.py +42 -0
  31. ccxt/static_dependencies/lark/parsers/earley_forest.py +801 -0
  32. ccxt/static_dependencies/lark/parsers/grammar_analysis.py +203 -0
  33. ccxt/static_dependencies/lark/parsers/lalr_analysis.py +332 -0
  34. ccxt/static_dependencies/lark/parsers/lalr_interactive_parser.py +158 -0
  35. ccxt/static_dependencies/lark/parsers/lalr_parser.py +122 -0
  36. ccxt/static_dependencies/lark/parsers/lalr_parser_state.py +110 -0
  37. ccxt/static_dependencies/lark/parsers/xearley.py +165 -0
  38. ccxt/static_dependencies/lark/py.typed +0 -0
  39. ccxt/static_dependencies/lark/reconstruct.py +107 -0
  40. ccxt/static_dependencies/lark/tools/__init__.py +70 -0
  41. ccxt/static_dependencies/lark/tools/nearley.py +202 -0
  42. ccxt/static_dependencies/lark/tools/serialize.py +32 -0
  43. ccxt/static_dependencies/lark/tools/standalone.py +196 -0
  44. ccxt/static_dependencies/lark/tree.py +267 -0
  45. ccxt/static_dependencies/lark/tree_matcher.py +186 -0
  46. ccxt/static_dependencies/lark/tree_templates.py +180 -0
  47. ccxt/static_dependencies/lark/utils.py +343 -0
  48. ccxt/static_dependencies/lark/visitors.py +596 -0
  49. ccxt/static_dependencies/marshmallow/__init__.py +81 -0
  50. ccxt/static_dependencies/marshmallow/base.py +65 -0
  51. ccxt/static_dependencies/marshmallow/class_registry.py +94 -0
  52. ccxt/static_dependencies/marshmallow/decorators.py +231 -0
  53. ccxt/static_dependencies/marshmallow/error_store.py +60 -0
  54. ccxt/static_dependencies/marshmallow/exceptions.py +71 -0
  55. ccxt/static_dependencies/marshmallow/fields.py +2114 -0
  56. ccxt/static_dependencies/marshmallow/orderedset.py +89 -0
  57. ccxt/static_dependencies/marshmallow/py.typed +0 -0
  58. ccxt/static_dependencies/marshmallow/schema.py +1228 -0
  59. ccxt/static_dependencies/marshmallow/types.py +12 -0
  60. ccxt/static_dependencies/marshmallow/utils.py +378 -0
  61. ccxt/static_dependencies/marshmallow/validate.py +678 -0
  62. ccxt/static_dependencies/marshmallow/warnings.py +2 -0
  63. ccxt/static_dependencies/marshmallow_dataclass/__init__.py +1047 -0
  64. ccxt/static_dependencies/marshmallow_dataclass/collection_field.py +51 -0
  65. ccxt/static_dependencies/marshmallow_dataclass/lazy_class_attribute.py +45 -0
  66. ccxt/static_dependencies/marshmallow_dataclass/mypy.py +71 -0
  67. ccxt/static_dependencies/marshmallow_dataclass/py.typed +0 -0
  68. ccxt/static_dependencies/marshmallow_dataclass/typing.py +14 -0
  69. ccxt/static_dependencies/marshmallow_dataclass/union_field.py +82 -0
  70. ccxt/static_dependencies/marshmallow_oneofschema/__init__.py +1 -0
  71. ccxt/static_dependencies/marshmallow_oneofschema/one_of_schema.py +193 -0
  72. ccxt/static_dependencies/marshmallow_oneofschema/py.typed +0 -0
  73. ccxt/static_dependencies/starknet/__init__.py +0 -0
  74. ccxt/static_dependencies/starknet/cairo/__init__.py +0 -0
  75. ccxt/static_dependencies/starknet/cairo/data_types.py +123 -0
  76. ccxt/static_dependencies/starknet/cairo/deprecated_parse/__init__.py +0 -0
  77. ccxt/static_dependencies/starknet/cairo/deprecated_parse/cairo_types.py +77 -0
  78. ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser.py +46 -0
  79. ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser_transformer.py +138 -0
  80. ccxt/static_dependencies/starknet/cairo/felt.py +64 -0
  81. ccxt/static_dependencies/starknet/cairo/type_parser.py +121 -0
  82. ccxt/static_dependencies/starknet/cairo/v1/__init__.py +0 -0
  83. ccxt/static_dependencies/starknet/cairo/v1/type_parser.py +59 -0
  84. ccxt/static_dependencies/starknet/cairo/v2/__init__.py +0 -0
  85. ccxt/static_dependencies/starknet/cairo/v2/type_parser.py +77 -0
  86. ccxt/static_dependencies/starknet/ccxt_utils.py +7 -0
  87. ccxt/static_dependencies/starknet/common.py +15 -0
  88. ccxt/static_dependencies/starknet/constants.py +39 -0
  89. ccxt/static_dependencies/starknet/hash/__init__.py +0 -0
  90. ccxt/static_dependencies/starknet/hash/address.py +79 -0
  91. ccxt/static_dependencies/starknet/hash/compiled_class_hash_objects.py +111 -0
  92. ccxt/static_dependencies/starknet/hash/selector.py +16 -0
  93. ccxt/static_dependencies/starknet/hash/storage.py +12 -0
  94. ccxt/static_dependencies/starknet/hash/utils.py +78 -0
  95. ccxt/static_dependencies/starknet/serialization/__init__.py +24 -0
  96. ccxt/static_dependencies/starknet/serialization/_calldata_reader.py +40 -0
  97. ccxt/static_dependencies/starknet/serialization/_context.py +142 -0
  98. ccxt/static_dependencies/starknet/serialization/data_serializers/__init__.py +10 -0
  99. ccxt/static_dependencies/starknet/serialization/data_serializers/_common.py +82 -0
  100. ccxt/static_dependencies/starknet/serialization/data_serializers/array_serializer.py +43 -0
  101. ccxt/static_dependencies/starknet/serialization/data_serializers/bool_serializer.py +37 -0
  102. ccxt/static_dependencies/starknet/serialization/data_serializers/byte_array_serializer.py +66 -0
  103. ccxt/static_dependencies/starknet/serialization/data_serializers/cairo_data_serializer.py +71 -0
  104. ccxt/static_dependencies/starknet/serialization/data_serializers/enum_serializer.py +71 -0
  105. ccxt/static_dependencies/starknet/serialization/data_serializers/felt_serializer.py +50 -0
  106. ccxt/static_dependencies/starknet/serialization/data_serializers/named_tuple_serializer.py +58 -0
  107. ccxt/static_dependencies/starknet/serialization/data_serializers/option_serializer.py +43 -0
  108. ccxt/static_dependencies/starknet/serialization/data_serializers/output_serializer.py +40 -0
  109. ccxt/static_dependencies/starknet/serialization/data_serializers/payload_serializer.py +72 -0
  110. ccxt/static_dependencies/starknet/serialization/data_serializers/struct_serializer.py +36 -0
  111. ccxt/static_dependencies/starknet/serialization/data_serializers/tuple_serializer.py +36 -0
  112. ccxt/static_dependencies/starknet/serialization/data_serializers/uint256_serializer.py +76 -0
  113. ccxt/static_dependencies/starknet/serialization/data_serializers/uint_serializer.py +100 -0
  114. ccxt/static_dependencies/starknet/serialization/data_serializers/unit_serializer.py +32 -0
  115. ccxt/static_dependencies/starknet/serialization/errors.py +10 -0
  116. ccxt/static_dependencies/starknet/serialization/factory.py +229 -0
  117. ccxt/static_dependencies/starknet/serialization/function_serialization_adapter.py +110 -0
  118. ccxt/static_dependencies/starknet/serialization/tuple_dataclass.py +59 -0
  119. ccxt/static_dependencies/starknet/utils/__init__.py +0 -0
  120. ccxt/static_dependencies/starknet/utils/constructor_args_translator.py +86 -0
  121. ccxt/static_dependencies/starknet/utils/iterable.py +13 -0
  122. ccxt/static_dependencies/starknet/utils/schema.py +13 -0
  123. ccxt/static_dependencies/starknet/utils/typed_data.py +182 -0
  124. ccxt/static_dependencies/sympy/__init__.py +0 -0
  125. ccxt/static_dependencies/sympy/external/__init__.py +0 -0
  126. ccxt/static_dependencies/sympy/external/gmpy.py +345 -0
  127. ccxt/static_dependencies/sympy/external/importtools.py +187 -0
  128. ccxt/static_dependencies/sympy/external/ntheory.py +637 -0
  129. ccxt/static_dependencies/sympy/external/pythonmpq.py +341 -0
  130. ccxt/static_dependencies/typing_extensions/__init__.py +0 -0
  131. ccxt/static_dependencies/typing_extensions/typing_extensions.py +3839 -0
  132. ccxt/static_dependencies/typing_inspect/__init__.py +0 -0
  133. ccxt/static_dependencies/typing_inspect/typing_inspect.py +851 -0
  134. ccxt/test/tests_async.py +43 -1
  135. ccxt/test/tests_sync.py +43 -1
  136. ccxt/woo.py +4 -2
  137. {ccxt-4.3.70.dist-info → ccxt-4.3.71.dist-info}/METADATA +7 -6
  138. {ccxt-4.3.70.dist-info → ccxt-4.3.71.dist-info}/RECORD +141 -16
  139. {ccxt-4.3.70.dist-info → ccxt-4.3.71.dist-info}/LICENSE.txt +0 -0
  140. {ccxt-4.3.70.dist-info → ccxt-4.3.71.dist-info}/WHEEL +0 -0
  141. {ccxt-4.3.70.dist-info → ccxt-4.3.71.dist-info}/top_level.txt +0 -0
ccxt/paradex.py ADDED
@@ -0,0 +1,1966 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
4
+ # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
5
+
6
+ from ccxt.base.exchange import Exchange
7
+ from ccxt.abstract.paradex import ImplicitAPI
8
+ from ccxt.base.types import Balances, Currency, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, Transaction
9
+ from typing import List
10
+ from ccxt.base.errors import ExchangeError
11
+ from ccxt.base.errors import AuthenticationError
12
+ from ccxt.base.errors import PermissionDenied
13
+ from ccxt.base.errors import ArgumentsRequired
14
+ from ccxt.base.errors import BadRequest
15
+ from ccxt.base.errors import OperationRejected
16
+ from ccxt.base.errors import InvalidOrder
17
+ from ccxt.base.decimal_to_precision import TICK_SIZE
18
+ from ccxt.base.precise import Precise
19
+
20
+
21
+ class paradex(Exchange, ImplicitAPI):
22
+
23
+ def describe(self):
24
+ return self.deep_extend(super(paradex, self).describe(), {
25
+ 'id': 'paradex',
26
+ 'name': 'Paradex',
27
+ 'countries': [],
28
+ 'version': 'v1',
29
+ 'rateLimit': 50,
30
+ 'certified': False,
31
+ 'pro': True,
32
+ 'dex': True,
33
+ 'has': {
34
+ 'CORS': None,
35
+ 'spot': False,
36
+ 'margin': False,
37
+ 'swap': True,
38
+ 'future': False,
39
+ 'option': False,
40
+ 'addMargin': False,
41
+ 'borrowCrossMargin': False,
42
+ 'borrowIsolatedMargin': False,
43
+ 'cancelAllOrders': True,
44
+ 'cancelAllOrdersAfter': False,
45
+ 'cancelOrder': False,
46
+ 'cancelOrders': False,
47
+ 'cancelOrdersForSymbols': False,
48
+ 'closeAllPositions': False,
49
+ 'closePosition': False,
50
+ 'createMarketBuyOrderWithCost': False,
51
+ 'createMarketOrderWithCost': False,
52
+ 'createMarketSellOrderWithCost': False,
53
+ 'createOrder': True,
54
+ 'createOrders': False,
55
+ 'createReduceOnlyOrder': False,
56
+ 'editOrder': False,
57
+ 'fetchAccounts': False,
58
+ 'fetchBalance': True,
59
+ 'fetchBorrowInterest': False,
60
+ 'fetchBorrowRateHistories': False,
61
+ 'fetchBorrowRateHistory': False,
62
+ 'fetchCanceledOrders': False,
63
+ 'fetchClosedOrders': False,
64
+ 'fetchCrossBorrowRate': False,
65
+ 'fetchCrossBorrowRates': False,
66
+ 'fetchCurrencies': False,
67
+ 'fetchDepositAddress': False,
68
+ 'fetchDepositAddresses': False,
69
+ 'fetchDeposits': True,
70
+ 'fetchDepositWithdrawFee': False,
71
+ 'fetchDepositWithdrawFees': False,
72
+ 'fetchFundingHistory': False,
73
+ 'fetchFundingRate': False,
74
+ 'fetchFundingRateHistory': False,
75
+ 'fetchFundingRates': False,
76
+ 'fetchIndexOHLCV': False,
77
+ 'fetchIsolatedBorrowRate': False,
78
+ 'fetchIsolatedBorrowRates': False,
79
+ 'fetchLedger': False,
80
+ 'fetchLeverage': False,
81
+ 'fetchLeverageTiers': False,
82
+ 'fetchLiquidations': True,
83
+ 'fetchMarginMode': None,
84
+ 'fetchMarketLeverageTiers': False,
85
+ 'fetchMarkets': True,
86
+ 'fetchMarkOHLCV': False,
87
+ 'fetchMyLiquidations': False,
88
+ 'fetchMyTrades': True,
89
+ 'fetchOHLCV': True,
90
+ 'fetchOpenInterest': True,
91
+ 'fetchOpenInterestHistory': False,
92
+ 'fetchOpenOrders': True,
93
+ 'fetchOrder': True,
94
+ 'fetchOrderBook': True,
95
+ 'fetchOrders': True,
96
+ 'fetchOrderTrades': False,
97
+ 'fetchPosition': True,
98
+ 'fetchPositionMode': False,
99
+ 'fetchPositions': True,
100
+ 'fetchPositionsRisk': False,
101
+ 'fetchPremiumIndexOHLCV': False,
102
+ 'fetchStatus': True,
103
+ 'fetchTicker': True,
104
+ 'fetchTickers': True,
105
+ 'fetchTime': True,
106
+ 'fetchTrades': True,
107
+ 'fetchTradingFee': False,
108
+ 'fetchTradingFees': False,
109
+ 'fetchTransfer': False,
110
+ 'fetchTransfers': False,
111
+ 'fetchWithdrawal': False,
112
+ 'fetchWithdrawals': True,
113
+ 'reduceMargin': False,
114
+ 'repayCrossMargin': False,
115
+ 'repayIsolatedMargin': False,
116
+ 'sandbox': True,
117
+ 'setLeverage': False,
118
+ 'setMarginMode': False,
119
+ 'setPositionMode': False,
120
+ 'transfer': False,
121
+ 'withdraw': False,
122
+ },
123
+ 'timeframes': {
124
+ '1m': 1,
125
+ '3m': 3,
126
+ '5m': 5,
127
+ '15m': 15,
128
+ '30m': 30,
129
+ '1h': 60,
130
+ },
131
+ 'hostname': 'paradex.trade',
132
+ 'urls': {
133
+ 'logo': 'https://github.com/user-attachments/assets/5dadc09a-74ba-466a-a8f2-3f55c7e4654a',
134
+ 'api': {
135
+ 'v1': 'https://api.prod.{hostname}/v1',
136
+ },
137
+ 'test': {
138
+ 'v1': 'https://api.testnet.{hostname}/v1',
139
+ },
140
+ 'www': 'https://www.paradex.trade/',
141
+ 'doc': 'https://docs.api.testnet.paradex.trade/',
142
+ 'fees': 'https://docs.paradex.trade/getting-started/trading-fees',
143
+ 'referral': 'https://app.paradex.trade/r/ccxt24',
144
+ },
145
+ 'api': {
146
+ 'public': {
147
+ 'get': {
148
+ 'bbo/{market}': 1,
149
+ 'funding/data': 1,
150
+ 'markets': 1,
151
+ 'markets/klines': 1,
152
+ 'markets/summary': 1,
153
+ 'orderbook/{market}': 1,
154
+ 'insurance': 1,
155
+ 'referrals/config': 1,
156
+ 'system/config': 1,
157
+ 'system/state': 1,
158
+ 'system/time': 1,
159
+ 'trades': 1,
160
+ },
161
+ },
162
+ 'private': {
163
+ 'get': {
164
+ 'account': 1,
165
+ 'account/profile': 1,
166
+ 'balance': 1,
167
+ 'fills': 1,
168
+ 'funding/payments': 1,
169
+ 'positions': 1,
170
+ 'tradebusts': 1,
171
+ 'transactions': 1,
172
+ 'liquidations': 1,
173
+ 'orders': 1,
174
+ 'orders-history': 1,
175
+ 'orders/by_client_id/{client_id}': 1,
176
+ 'orders/{order_id}': 1,
177
+ 'points_data/{market}/{program}': 1,
178
+ 'referrals/summary': 1,
179
+ 'transfers': 1,
180
+ },
181
+ 'post': {
182
+ 'account/profile/referral_code': 1,
183
+ 'account/profile/username': 1,
184
+ 'auth': 1,
185
+ 'onboarding': 1,
186
+ 'orders': 1,
187
+ },
188
+ 'delete': {
189
+ 'orders': 1,
190
+ 'orders/by_client_id/{client_id}': 1,
191
+ 'orders/{order_id}': 1,
192
+ },
193
+ },
194
+ },
195
+ 'fees': {
196
+ 'swap': {
197
+ 'taker': self.parse_number('0.0002'),
198
+ 'maker': self.parse_number('0.0002'),
199
+ },
200
+ 'spot': {
201
+ 'taker': self.parse_number('0.0002'),
202
+ 'maker': self.parse_number('0.0002'),
203
+ },
204
+ },
205
+ 'requiredCredentials': {
206
+ 'apiKey': False,
207
+ 'secret': False,
208
+ 'walletAddress': True,
209
+ 'privateKey': True,
210
+ },
211
+ 'exceptions': {
212
+ 'exact': {
213
+ 'VALIDATION_ERROR': AuthenticationError,
214
+ 'BINDING_ERROR': OperationRejected,
215
+ 'INTERNAL_ERROR': ExchangeError,
216
+ 'NOT_FOUND': BadRequest,
217
+ 'SERVICE_UNAVAILABLE': ExchangeError,
218
+ 'INVALID_REQUEST_PARAMETER': BadRequest,
219
+ 'ORDER_ID_NOT_FOUND': InvalidOrder,
220
+ 'ORDER_IS_CLOSED': InvalidOrder,
221
+ 'ORDER_IS_NOT_OPEN_YET': InvalidOrder,
222
+ 'CLIENT_ORDER_ID_NOT_FOUND': InvalidOrder,
223
+ 'DUPLICATED_CLIENT_ID': InvalidOrder,
224
+ 'INVALID_PRICE_PRECISION': OperationRejected,
225
+ 'INVALID_SYMBOL': OperationRejected,
226
+ 'INVALID_TOKEN': OperationRejected,
227
+ 'INVALID_ETHEREUM_ADDRESS': OperationRejected,
228
+ 'INVALID_ETHEREUM_SIGNATURE': OperationRejected,
229
+ 'INVALID_STARKNET_ADDRESS': OperationRejected,
230
+ 'INVALID_STARKNET_SIGNATURE': OperationRejected,
231
+ 'STARKNET_SIGNATURE_VERIFICATION_FAILED': AuthenticationError,
232
+ 'BAD_STARKNET_REQUEST': BadRequest,
233
+ 'ETHEREUM_SIGNER_MISMATCH': BadRequest,
234
+ 'ETHEREUM_HASH_MISMATCH': BadRequest,
235
+ 'NOT_ONBOARDED': BadRequest,
236
+ 'INVALID_TIMESTAMP': BadRequest,
237
+ 'INVALID_SIGNATURE_EXPIRATION': AuthenticationError,
238
+ 'ACCOUNT_NOT_FOUND': AuthenticationError,
239
+ 'INVALID_ORDER_SIGNATURE': AuthenticationError,
240
+ 'PUBLIC_KEY_INVALID': BadRequest,
241
+ 'UNAUTHORIZED_ETHEREUM_ADDRESS': BadRequest,
242
+ 'ETHEREUM_ADDRESS_ALREADY_ONBOARDED': BadRequest,
243
+ 'MARKET_NOT_FOUND': BadRequest,
244
+ 'ALLOWLIST_ENTRY_NOT_FOUND': BadRequest,
245
+ 'USERNAME_IN_USE': AuthenticationError,
246
+ 'GEO_IP_BLOCK': PermissionDenied,
247
+ 'ETHEREUM_ADDRESS_BLOCKED': PermissionDenied,
248
+ 'PROGRAM_NOT_FOUND': BadRequest,
249
+ 'INVALID_DASHBOARD': OperationRejected,
250
+ 'MARKET_NOT_OPEN': BadRequest,
251
+ 'INVALID_REFERRAL_CODE': OperationRejected,
252
+ 'PARENT_ADDRESS_ALREADY_ONBOARDED': BadRequest,
253
+ 'INVALID_PARENT_ACCOUNT': OperationRejected,
254
+ 'INVALID_VAULT_OPERATOR_CHAIN': OperationRejected,
255
+ 'VAULT_OPERATOR_ALREADY_ONBOARDED': OperationRejected,
256
+ 'VAULT_NAME_IN_USE': OperationRejected,
257
+ 'BATCH_SIZE_OUT_OF_RANGE': OperationRejected,
258
+ 'ISOLATED_MARKET_ACCOUNT_MISMATCH': OperationRejected,
259
+ 'POINTS_SUMMARY_NOT_FOUND': OperationRejected,
260
+ '-32700': BadRequest, # Parse error
261
+ '-32600': BadRequest, # Invalid request
262
+ '-32601': BadRequest, # Method not found
263
+ '-32602': BadRequest, # Invalid parameterss
264
+ '-32603': ExchangeError, # Internal error
265
+ '100': BadRequest, # Method error
266
+ '40110': AuthenticationError, # Malformed Bearer Token
267
+ '40111': AuthenticationError, # Invalid Bearer Token
268
+ '40112': PermissionDenied, # Geo IP blocked
269
+ },
270
+ 'broad': {
271
+ },
272
+ },
273
+ 'precisionMode': TICK_SIZE,
274
+ 'commonCurrencies': {
275
+ },
276
+ 'options': {
277
+ 'broker': 'CCXT',
278
+ },
279
+ })
280
+
281
+ def fetch_time(self, params={}):
282
+ """
283
+ fetches the current integer timestamp in milliseconds from the exchange server
284
+ :see: https://docs.api.testnet.paradex.trade/#get-system-time-unix-milliseconds
285
+ :param dict [params]: extra parameters specific to the exchange API endpoint
286
+ :returns int: the current integer timestamp in milliseconds from the exchange server
287
+ """
288
+ response = self.publicGetSystemTime(params)
289
+ #
290
+ # {
291
+ # "server_time": "1681493415023"
292
+ # }
293
+ #
294
+ return self.safe_integer(response, 'server_time')
295
+
296
+ def fetch_status(self, params={}):
297
+ """
298
+ the latest known information on the availability of the exchange API
299
+ :see: https://docs.api.testnet.paradex.trade/#get-system-state
300
+ :param dict [params]: extra parameters specific to the exchange API endpoint
301
+ :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
302
+ """
303
+ response = self.publicGetSystemState(params)
304
+ #
305
+ # {
306
+ # "status": "ok"
307
+ # }
308
+ #
309
+ status = self.safe_string(response, 'status')
310
+ return {
311
+ 'status': 'ok' if (status == 'ok') else 'maintenance',
312
+ 'updated': None,
313
+ 'eta': None,
314
+ 'url': None,
315
+ 'info': response,
316
+ }
317
+
318
+ def fetch_markets(self, params={}) -> List[Market]:
319
+ """
320
+ retrieves data on all markets for bitget
321
+ :see: https://docs.api.testnet.paradex.trade/#list-available-markets
322
+ :param dict [params]: extra parameters specific to the exchange API endpoint
323
+ :returns dict[]: an array of objects representing market data
324
+ """
325
+ response = self.publicGetMarkets(params)
326
+ #
327
+ # {
328
+ # "results": [
329
+ # {
330
+ # "symbol": "BODEN-USD-PERP",
331
+ # "base_currency": "BODEN",
332
+ # "quote_currency": "USD",
333
+ # "settlement_currency": "USDC",
334
+ # "order_size_increment": "1",
335
+ # "price_tick_size": "0.00001",
336
+ # "min_notional": "200",
337
+ # "open_at": 1717065600000,
338
+ # "expiry_at": 0,
339
+ # "asset_kind": "PERP",
340
+ # "position_limit": "2000000",
341
+ # "price_bands_width": "0.2",
342
+ # "max_open_orders": 50,
343
+ # "max_funding_rate": "0.05",
344
+ # "delta1_cross_margin_params": {
345
+ # "imf_base": "0.2",
346
+ # "imf_shift": "180000",
347
+ # "imf_factor": "0.00071",
348
+ # "mmf_factor": "0.5"
349
+ # },
350
+ # "price_feed_id": "9LScEHse1ioZt2rUuhwiN6bmYnqpMqvZkQJDNUpxVHN5",
351
+ # "oracle_ewma_factor": "0.14999987905913592",
352
+ # "max_order_size": "520000",
353
+ # "max_funding_rate_change": "0.0005",
354
+ # "max_tob_spread": "0.2"
355
+ # }
356
+ # ]
357
+ # }
358
+ #
359
+ data = self.safe_list(response, 'results')
360
+ return self.parse_markets(data)
361
+
362
+ def parse_market(self, market: dict) -> Market:
363
+ #
364
+ # {
365
+ # "symbol": "BODEN-USD-PERP",
366
+ # "base_currency": "BODEN",
367
+ # "quote_currency": "USD",
368
+ # "settlement_currency": "USDC",
369
+ # "order_size_increment": "1",
370
+ # "price_tick_size": "0.00001",
371
+ # "min_notional": "200",
372
+ # "open_at": 1717065600000,
373
+ # "expiry_at": 0,
374
+ # "asset_kind": "PERP",
375
+ # "position_limit": "2000000",
376
+ # "price_bands_width": "0.2",
377
+ # "max_open_orders": 50,
378
+ # "max_funding_rate": "0.05",
379
+ # "delta1_cross_margin_params": {
380
+ # "imf_base": "0.2",
381
+ # "imf_shift": "180000",
382
+ # "imf_factor": "0.00071",
383
+ # "mmf_factor": "0.5"
384
+ # },
385
+ # "price_feed_id": "9LScEHse1ioZt2rUuhwiN6bmYnqpMqvZkQJDNUpxVHN5",
386
+ # "oracle_ewma_factor": "0.14999987905913592",
387
+ # "max_order_size": "520000",
388
+ # "max_funding_rate_change": "0.0005",
389
+ # "max_tob_spread": "0.2"
390
+ # }
391
+ #
392
+ marketId = self.safe_string(market, 'symbol')
393
+ quoteId = self.safe_string(market, 'quote_currency')
394
+ baseId = self.safe_string(market, 'base_currency')
395
+ quote = self.safe_currency_code(quoteId)
396
+ base = self.safe_currency_code(baseId)
397
+ settleId = self.safe_string(market, 'settlement_currency')
398
+ settle = self.safe_currency_code(settleId)
399
+ symbol = base + '/' + quote + ':' + settle
400
+ expiry = self.safe_integer(market, 'expiry_at')
401
+ takerFee = self.parse_number('0.0003')
402
+ makerFee = self.parse_number('-0.00005')
403
+ return self.safe_market_structure({
404
+ 'id': marketId,
405
+ 'symbol': symbol,
406
+ 'base': base,
407
+ 'quote': quote,
408
+ 'settle': settle,
409
+ 'baseId': baseId,
410
+ 'quoteId': quoteId,
411
+ 'settleId': settleId,
412
+ 'type': 'swap',
413
+ 'spot': False,
414
+ 'margin': None,
415
+ 'swap': True,
416
+ 'future': False,
417
+ 'option': False,
418
+ 'active': self.safe_bool(market, 'enableTrading'),
419
+ 'contract': True,
420
+ 'linear': True,
421
+ 'inverse': None,
422
+ 'taker': takerFee,
423
+ 'maker': makerFee,
424
+ 'contractSize': self.parse_number('1'),
425
+ 'expiry': None if (expiry == 0) else expiry,
426
+ 'expiryDatetime': None if (expiry == 0) else self.iso8601(expiry),
427
+ 'strike': None,
428
+ 'optionType': None,
429
+ 'precision': {
430
+ 'amount': self.safe_number(market, 'order_size_increment'),
431
+ 'price': self.safe_number(market, 'price_tick_size'),
432
+ },
433
+ 'limits': {
434
+ 'leverage': {
435
+ 'min': None,
436
+ 'max': None,
437
+ },
438
+ 'amount': {
439
+ 'min': None,
440
+ 'max': self.safe_number(market, 'max_order_size'),
441
+ },
442
+ 'price': {
443
+ 'min': None,
444
+ 'max': None,
445
+ },
446
+ 'cost': {
447
+ 'min': self.safe_number(market, 'min_notional'),
448
+ 'max': None,
449
+ },
450
+ },
451
+ 'created': None,
452
+ 'info': market,
453
+ })
454
+
455
+ def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
456
+ """
457
+ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
458
+ :see: https://docs.api.testnet.paradex.trade/#ohlcv-for-a-symbol
459
+ :param str symbol: unified symbol of the market to fetch OHLCV data for
460
+ :param str timeframe: the length of time each candle represents
461
+ :param int [since]: timestamp in ms of the earliest candle to fetch
462
+ :param int [limit]: the maximum amount of candles to fetch
463
+ :param dict [params]: extra parameters specific to the exchange API endpoint
464
+ :param int [params.until]: timestamp in ms of the latest candle to fetch
465
+ :returns int[][]: A list of candles ordered, open, high, low, close, volume
466
+ """
467
+ self.load_markets()
468
+ market = self.market(symbol)
469
+ request: dict = {
470
+ 'resolution': self.safe_string(self.timeframes, timeframe, timeframe),
471
+ 'symbol': market['id'],
472
+ }
473
+ now = self.milliseconds()
474
+ duration = self.parse_timeframe(timeframe)
475
+ until = self.safe_integer_2(params, 'until', 'till', now)
476
+ params = self.omit(params, ['until', 'till'])
477
+ if since is not None:
478
+ request['start_at'] = since
479
+ if limit is not None:
480
+ request['end_at'] = self.sum(since, duration * (limit + 1) * 1000) - 1
481
+ else:
482
+ request['end_at'] = until
483
+ else:
484
+ request['end_at'] = until
485
+ if limit is not None:
486
+ request['start_at'] = until - duration * (limit + 1) * 1000 + 1
487
+ else:
488
+ request['start_at'] = until - duration * 101 * 1000 + 1
489
+ response = self.publicGetMarketsKlines(self.extend(request, params))
490
+ #
491
+ # {
492
+ # "results": [
493
+ # [
494
+ # 1720071900000,
495
+ # 58961.3,
496
+ # 58961.3,
497
+ # 58961.3,
498
+ # 58961.3,
499
+ # 1591
500
+ # ]
501
+ # ]
502
+ # }
503
+ #
504
+ data = self.safe_list(response, 'results', [])
505
+ return self.parse_ohlcvs(data, market, timeframe, since, limit)
506
+
507
+ def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
508
+ #
509
+ # [
510
+ # 1720071900000,
511
+ # 58961.3,
512
+ # 58961.3,
513
+ # 58961.3,
514
+ # 58961.3,
515
+ # 1591
516
+ # ]
517
+ #
518
+ return [
519
+ self.safe_integer(ohlcv, 0),
520
+ self.safe_number(ohlcv, 1),
521
+ self.safe_number(ohlcv, 2),
522
+ self.safe_number(ohlcv, 3),
523
+ self.safe_number(ohlcv, 4),
524
+ self.safe_number(ohlcv, 5),
525
+ ]
526
+
527
+ def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
528
+ """
529
+ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
530
+ :see: https://docs.api.testnet.paradex.trade/#list-available-markets-summary
531
+ :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
532
+ :param dict [params]: extra parameters specific to the exchange API endpoint
533
+ :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
534
+ """
535
+ self.load_markets()
536
+ symbols = self.market_symbols(symbols)
537
+ request: dict = {}
538
+ if symbols is not None:
539
+ if isinstance(symbols, list):
540
+ request['market'] = self.market_id(symbols[0])
541
+ else:
542
+ request['market'] = self.market_id(symbols)
543
+ else:
544
+ request['market'] = 'ALL'
545
+ response = self.publicGetMarketsSummary(self.extend(request, params))
546
+ #
547
+ # {
548
+ # "results": [
549
+ # {
550
+ # "symbol": "BTC-USD-PERP",
551
+ # "oracle_price": "68465.17449906",
552
+ # "mark_price": "68465.17449906",
553
+ # "last_traded_price": "68495.1",
554
+ # "bid": "68477.6",
555
+ # "ask": "69578.2",
556
+ # "volume_24h": "5815541.397939004",
557
+ # "total_volume": "584031465.525259686",
558
+ # "created_at": 1718170156580,
559
+ # "underlying_price": "67367.37268422",
560
+ # "open_interest": "162.272",
561
+ # "funding_rate": "0.01629574927887",
562
+ # "price_change_rate_24h": "0.009032"
563
+ # }
564
+ # ]
565
+ # }
566
+ #
567
+ data = self.safe_list(response, 'results', [])
568
+ return self.parse_tickers(data, symbols)
569
+
570
+ def fetch_ticker(self, symbol: str, params={}) -> Ticker:
571
+ """
572
+ fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
573
+ :see: https://docs.api.testnet.paradex.trade/#list-available-markets-summary
574
+ :param str symbol: unified symbol of the market to fetch the ticker for
575
+ :param dict [params]: extra parameters specific to the exchange API endpoint
576
+ :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
577
+ """
578
+ self.load_markets()
579
+ market = self.market(symbol)
580
+ request: dict = {
581
+ 'market': market['id'],
582
+ }
583
+ response = self.publicGetMarketsSummary(self.extend(request, params))
584
+ #
585
+ # {
586
+ # "results": [
587
+ # {
588
+ # "symbol": "BTC-USD-PERP",
589
+ # "oracle_price": "68465.17449906",
590
+ # "mark_price": "68465.17449906",
591
+ # "last_traded_price": "68495.1",
592
+ # "bid": "68477.6",
593
+ # "ask": "69578.2",
594
+ # "volume_24h": "5815541.397939004",
595
+ # "total_volume": "584031465.525259686",
596
+ # "created_at": 1718170156580,
597
+ # "underlying_price": "67367.37268422",
598
+ # "open_interest": "162.272",
599
+ # "funding_rate": "0.01629574927887",
600
+ # "price_change_rate_24h": "0.009032"
601
+ # }
602
+ # ]
603
+ # }
604
+ #
605
+ data = self.safe_list(response, 'results', [])
606
+ ticker = self.safe_dict(data, 0, {})
607
+ return self.parse_ticker(ticker, market)
608
+
609
+ def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
610
+ #
611
+ # {
612
+ # "symbol": "BTC-USD-PERP",
613
+ # "oracle_price": "68465.17449906",
614
+ # "mark_price": "68465.17449906",
615
+ # "last_traded_price": "68495.1",
616
+ # "bid": "68477.6",
617
+ # "ask": "69578.2",
618
+ # "volume_24h": "5815541.397939004",
619
+ # "total_volume": "584031465.525259686",
620
+ # "created_at": 1718170156580,
621
+ # "underlying_price": "67367.37268422",
622
+ # "open_interest": "162.272",
623
+ # "funding_rate": "0.01629574927887",
624
+ # "price_change_rate_24h": "0.009032"
625
+ # }
626
+ #
627
+ percentage = self.safe_string(ticker, 'price_change_rate_24h')
628
+ if percentage is not None:
629
+ percentage = Precise.string_mul(percentage, '100')
630
+ last = self.safe_string(ticker, 'last_traded_price')
631
+ marketId = self.safe_string(ticker, 'symbol')
632
+ market = self.safe_market(marketId, market)
633
+ symbol = market['symbol']
634
+ timestamp = self.safe_integer(ticker, 'created_at')
635
+ return self.safe_ticker({
636
+ 'symbol': symbol,
637
+ 'timestamp': timestamp,
638
+ 'datetime': self.iso8601(timestamp),
639
+ 'high': None,
640
+ 'low': None,
641
+ 'bid': self.safe_string(ticker, 'bid'),
642
+ 'bidVolume': None,
643
+ 'ask': self.safe_string(ticker, 'sdk'),
644
+ 'askVolume': None,
645
+ 'vwap': None,
646
+ 'open': None,
647
+ 'close': last,
648
+ 'last': last,
649
+ 'previousClose': None,
650
+ 'change': None,
651
+ 'percentage': percentage,
652
+ 'average': None,
653
+ 'baseVolume': None,
654
+ 'quoteVolume': self.safe_string(ticker, 'volume_24h'),
655
+ 'info': ticker,
656
+ }, market)
657
+
658
+ def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
659
+ """
660
+ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
661
+ :see: https://docs.api.testnet.paradex.trade/#get-market-orderbook
662
+ :param str symbol: unified symbol of the market to fetch the order book for
663
+ :param int [limit]: the maximum amount of order book entries to return
664
+ :param dict [params]: extra parameters specific to the exchange API endpoint
665
+ :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
666
+ """
667
+ self.load_markets()
668
+ market = self.market(symbol)
669
+ request: dict = {'market': market['id']}
670
+ response = self.publicGetOrderbookMarket(self.extend(request, params))
671
+ #
672
+ # {
673
+ # "market": "BTC-USD-PERP",
674
+ # "seq_no": 14115975,
675
+ # "last_updated_at": 1718172538340,
676
+ # "asks": [
677
+ # [
678
+ # "69578.2",
679
+ # "3.019"
680
+ # ]
681
+ # ],
682
+ # "bids": [
683
+ # [
684
+ # "68477.6",
685
+ # "0.1"
686
+ # ]
687
+ # ]
688
+ # }
689
+ #
690
+ if limit is not None:
691
+ request['depth'] = limit
692
+ timestamp = self.safe_integer(response, 'last_updated_at')
693
+ orderbook = self.parse_order_book(response, market['symbol'], timestamp)
694
+ orderbook['nonce'] = self.safe_integer(response, 'seq_no')
695
+ return orderbook
696
+
697
+ def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
698
+ """
699
+ get the list of most recent trades for a particular symbol
700
+ :see: https://docs.api.testnet.paradex.trade/#trade-tape
701
+ :param str symbol: unified symbol of the market to fetch trades for
702
+ :param int [since]: timestamp in ms of the earliest trade to fetch
703
+ :param int [limit]: the maximum amount of trades to fetch
704
+ :param dict [params]: extra parameters specific to the exchange API endpoint
705
+ :param int [params.until]: the latest time in ms to fetch trades for
706
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times
707
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
708
+ """
709
+ self.load_markets()
710
+ paginate = False
711
+ paginate, params = self.handle_option_and_params(params, 'fetchTrades', 'paginate')
712
+ if paginate:
713
+ return self.fetch_paginated_call_cursor('fetchTrades', symbol, since, limit, params, 'next', 'cursor', None, 100)
714
+ market = self.market(symbol)
715
+ request: dict = {
716
+ 'market': market['id'],
717
+ }
718
+ if limit is not None:
719
+ request['page_size'] = limit
720
+ if since is not None:
721
+ request['start_at'] = since
722
+ request, params = self.handle_until_option('end_at', request, params)
723
+ response = self.publicGetTrades(self.extend(request, params))
724
+ #
725
+ # {
726
+ # "next": "...",
727
+ # "prev": "...",
728
+ # "results": [
729
+ # {
730
+ # "id": "1718154353750201703989430001",
731
+ # "market": "BTC-USD-PERP",
732
+ # "side": "BUY",
733
+ # "size": "0.026",
734
+ # "price": "69578.2",
735
+ # "created_at": 1718154353750,
736
+ # "trade_type": "FILL"
737
+ # }
738
+ # ]
739
+ # }
740
+ #
741
+ trades = self.safe_list(response, 'results', [])
742
+ for i in range(0, len(trades)):
743
+ trades[i]['next'] = self.safe_string(response, 'next')
744
+ return self.parse_trades(trades, market, since, limit)
745
+
746
+ def parse_trade(self, trade: dict, market: Market = None) -> Trade:
747
+ #
748
+ # fetchTrades(public)
749
+ #
750
+ # {
751
+ # "id": "1718154353750201703989430001",
752
+ # "market": "BTC-USD-PERP",
753
+ # "side": "BUY",
754
+ # "size": "0.026",
755
+ # "price": "69578.2",
756
+ # "created_at": 1718154353750,
757
+ # "trade_type": "FILL"
758
+ # }
759
+ #
760
+ # fetchMyTrades(private)
761
+ #
762
+ # {
763
+ # "id": "1718947571560201703986670001",
764
+ # "side": "BUY",
765
+ # "liquidity": "TAKER",
766
+ # "market": "BTC-USD-PERP",
767
+ # "order_id": "1718947571540201703992340000",
768
+ # "price": "64852.9",
769
+ # "size": "0.01",
770
+ # "fee": "0.1945587",
771
+ # "fee_currency": "USDC",
772
+ # "created_at": 1718947571569,
773
+ # "remaining_size": "0",
774
+ # "client_id": "",
775
+ # "fill_type": "FILL"
776
+ # }
777
+ #
778
+ marketId = self.safe_string(trade, 'market')
779
+ market = self.safe_market(marketId, market)
780
+ id = self.safe_string(trade, 'id')
781
+ timestamp = self.safe_integer(trade, 'created_at')
782
+ priceString = self.safe_string(trade, 'price')
783
+ amountString = self.safe_string(trade, 'size')
784
+ side = self.safe_string_lower(trade, 'side')
785
+ liability = self.safe_string_lower(trade, 'liquidity', 'taker')
786
+ isTaker = liability == 'taker'
787
+ takerOrMaker = 'taker' if (isTaker) else 'maker'
788
+ currencyId = self.safe_string(trade, 'fee_currency')
789
+ code = self.safe_currency_code(currencyId)
790
+ return self.safe_trade({
791
+ 'info': trade,
792
+ 'id': id,
793
+ 'order': self.safe_string(trade, 'order_id'),
794
+ 'timestamp': timestamp,
795
+ 'datetime': self.iso8601(timestamp),
796
+ 'symbol': market['symbol'],
797
+ 'type': None,
798
+ 'takerOrMaker': takerOrMaker,
799
+ 'side': side,
800
+ 'price': priceString,
801
+ 'amount': amountString,
802
+ 'cost': None,
803
+ 'fee': {
804
+ 'cost': self.safe_string(trade, 'fee'),
805
+ 'currency': code,
806
+ 'rate': None,
807
+ },
808
+ }, market)
809
+
810
+ def fetch_open_interest(self, symbol: str, params={}):
811
+ """
812
+ retrieves the open interest of a contract trading pair
813
+ :see: https://docs.api.testnet.paradex.trade/#list-available-markets-summary
814
+ :param str symbol: unified CCXT market symbol
815
+ :param dict [params]: exchange specific parameters
816
+ :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
817
+ """
818
+ self.load_markets()
819
+ market = self.market(symbol)
820
+ if not market['contract']:
821
+ raise BadRequest(self.id + ' fetchOpenInterest() supports contract markets only')
822
+ request: dict = {
823
+ 'market': market['id'],
824
+ }
825
+ response = self.publicGetMarketsSummary(self.extend(request, params))
826
+ #
827
+ # {
828
+ # "results": [
829
+ # {
830
+ # "symbol": "BTC-USD-PERP",
831
+ # "oracle_price": "68465.17449906",
832
+ # "mark_price": "68465.17449906",
833
+ # "last_traded_price": "68495.1",
834
+ # "bid": "68477.6",
835
+ # "ask": "69578.2",
836
+ # "volume_24h": "5815541.397939004",
837
+ # "total_volume": "584031465.525259686",
838
+ # "created_at": 1718170156580,
839
+ # "underlying_price": "67367.37268422",
840
+ # "open_interest": "162.272",
841
+ # "funding_rate": "0.01629574927887",
842
+ # "price_change_rate_24h": "0.009032"
843
+ # }
844
+ # ]
845
+ # }
846
+ #
847
+ data = self.safe_list(response, 'results', [])
848
+ interest = self.safe_dict(data, 0, {})
849
+ return self.parse_open_interest(interest, market)
850
+
851
+ def parse_open_interest(self, interest, market: Market = None):
852
+ #
853
+ # {
854
+ # "symbol": "BTC-USD-PERP",
855
+ # "oracle_price": "68465.17449906",
856
+ # "mark_price": "68465.17449906",
857
+ # "last_traded_price": "68495.1",
858
+ # "bid": "68477.6",
859
+ # "ask": "69578.2",
860
+ # "volume_24h": "5815541.397939004",
861
+ # "total_volume": "584031465.525259686",
862
+ # "created_at": 1718170156580,
863
+ # "underlying_price": "67367.37268422",
864
+ # "open_interest": "162.272",
865
+ # "funding_rate": "0.01629574927887",
866
+ # "price_change_rate_24h": "0.009032"
867
+ # }
868
+ #
869
+ timestamp = self.safe_integer(interest, 'created_at')
870
+ marketId = self.safe_string(interest, 'symbol')
871
+ market = self.safe_market(marketId, market)
872
+ symbol = market['symbol']
873
+ return self.safe_open_interest({
874
+ 'symbol': symbol,
875
+ 'openInterestAmount': self.safe_string(interest, 'open_interest'),
876
+ 'openInterestValue': None,
877
+ 'timestamp': timestamp,
878
+ 'datetime': self.iso8601(timestamp),
879
+ 'info': interest,
880
+ }, market)
881
+
882
+ def hash_message(self, message):
883
+ return '0x' + self.hash(message, 'keccak', 'hex')
884
+
885
+ def sign_hash(self, hash, privateKey):
886
+ signature = self.ecdsa(hash[-64:], privateKey[-64:], 'secp256k1', None)
887
+ r = signature['r']
888
+ s = signature['s']
889
+ v = self.int_to_base16(self.sum(27, signature['v']))
890
+ return '0x' + r.rjust(64, '0') + s.rjust(64, '0') + v
891
+
892
+ def sign_message(self, message, privateKey):
893
+ return self.sign_hash(self.hash_message(message), privateKey[-64:])
894
+
895
+ def get_system_config(self):
896
+ cachedConfig: dict = self.safe_dict(self.options, 'systemConfig')
897
+ if cachedConfig is not None:
898
+ return cachedConfig
899
+ response = self.publicGetSystemConfig()
900
+ #
901
+ # {
902
+ # "starknet_gateway_url": "https://potc-testnet-sepolia.starknet.io",
903
+ # "starknet_fullnode_rpc_url": "https://pathfinder.api.testnet.paradex.trade/rpc/v0_7",
904
+ # "starknet_chain_id": "PRIVATE_SN_POTC_SEPOLIA",
905
+ # "block_explorer_url": "https://voyager.testnet.paradex.trade/",
906
+ # "paraclear_address": "0x286003f7c7bfc3f94e8f0af48b48302e7aee2fb13c23b141479ba00832ef2c6",
907
+ # "paraclear_decimals": 8,
908
+ # "paraclear_account_proxy_hash": "0x3530cc4759d78042f1b543bf797f5f3d647cde0388c33734cf91b7f7b9314a9",
909
+ # "paraclear_account_hash": "0x41cb0280ebadaa75f996d8d92c6f265f6d040bb3ba442e5f86a554f1765244e",
910
+ # "oracle_address": "0x2c6a867917ef858d6b193a0ff9e62b46d0dc760366920d631715d58baeaca1f",
911
+ # "bridged_tokens": [
912
+ # {
913
+ # "name": "TEST USDC",
914
+ # "symbol": "USDC",
915
+ # "decimals": 6,
916
+ # "l1_token_address": "0x29A873159D5e14AcBd63913D4A7E2df04570c666",
917
+ # "l1_bridge_address": "0x8586e05adc0C35aa11609023d4Ae6075Cb813b4C",
918
+ # "l2_token_address": "0x6f373b346561036d98ea10fb3e60d2f459c872b1933b50b21fe6ef4fda3b75e",
919
+ # "l2_bridge_address": "0x46e9237f5408b5f899e72125dd69bd55485a287aaf24663d3ebe00d237fc7ef"
920
+ # }
921
+ # ],
922
+ # "l1_core_contract_address": "0x582CC5d9b509391232cd544cDF9da036e55833Af",
923
+ # "l1_operator_address": "0x11bACdFbBcd3Febe5e8CEAa75E0Ef6444d9B45FB",
924
+ # "l1_chain_id": "11155111",
925
+ # "liquidation_fee": "0.2"
926
+ # }
927
+ #
928
+ self.options['systemConfig'] = response
929
+ return response
930
+
931
+ def prepare_paradex_domain(self, l1=False):
932
+ systemConfig = self.get_system_config()
933
+ if l1 is True:
934
+ return {
935
+ 'name': 'Paradex',
936
+ 'chainId': systemConfig['l1_chain_id'],
937
+ 'version': '1',
938
+ }
939
+ return {
940
+ 'name': 'Paradex',
941
+ 'chainId': systemConfig['starknet_chain_id'],
942
+ 'version': 1,
943
+ }
944
+
945
+ def retrieve_account(self):
946
+ self.check_required_credentials()
947
+ cachedAccount: dict = self.safe_dict(self.options, 'paradexAccount')
948
+ if cachedAccount is not None:
949
+ return cachedAccount
950
+ systemConfig = self.get_system_config()
951
+ domain = self.prepare_paradex_domain(True)
952
+ messageTypes = {
953
+ 'Constant': [
954
+ {'name': 'action', 'type': 'string'},
955
+ ],
956
+ }
957
+ message = {
958
+ 'action': 'STARK Key',
959
+ }
960
+ msg = self.eth_encode_structured_data(domain, messageTypes, message)
961
+ signature = self.sign_message(msg, self.privateKey)
962
+ account = self.retrieve_stark_account(
963
+ signature,
964
+ systemConfig['paraclear_account_hash'],
965
+ systemConfig['paraclear_account_proxy_hash']
966
+ )
967
+ self.options['paradexAccount'] = account
968
+ return account
969
+
970
+ def onboarding(self, params={}):
971
+ account = self.retrieve_account()
972
+ req = {
973
+ 'action': 'Onboarding',
974
+ }
975
+ domain = self.prepare_paradex_domain()
976
+ messageTypes = {
977
+ 'Constant': [
978
+ {'name': 'action', 'type': 'felt'},
979
+ ],
980
+ }
981
+ msg = self.starknet_encode_structured_data(domain, messageTypes, req, account['address'])
982
+ signature = self.starknet_sign(msg, account['privateKey'])
983
+ params['signature'] = signature
984
+ params['account'] = account['address']
985
+ params['public_key'] = account['publicKey']
986
+ response = self.privatePostOnboarding(params)
987
+ return response
988
+
989
+ def authenticate_rest(self, params={}):
990
+ cachedToken = self.safe_string(self.options, 'authToken')
991
+ if cachedToken is not None:
992
+ return cachedToken
993
+ account = self.retrieve_account()
994
+ now = self.nonce()
995
+ req = {
996
+ 'method': 'POST',
997
+ 'path': '/v1/auth',
998
+ 'body': '',
999
+ 'timestamp': now,
1000
+ 'expiration': now + 86400 * 7,
1001
+ }
1002
+ domain = self.prepare_paradex_domain()
1003
+ messageTypes = {
1004
+ 'Request': [
1005
+ {'name': 'method', 'type': 'felt'},
1006
+ {'name': 'path', 'type': 'felt'},
1007
+ {'name': 'body', 'type': 'felt'},
1008
+ {'name': 'timestamp', 'type': 'felt'},
1009
+ {'name': 'expiration', 'type': 'felt'},
1010
+ ],
1011
+ }
1012
+ msg = self.starknet_encode_structured_data(domain, messageTypes, req, account['address'])
1013
+ signature = self.starknet_sign(msg, account['privateKey'])
1014
+ params['signature'] = signature
1015
+ params['account'] = account['address']
1016
+ params['timestamp'] = req['timestamp']
1017
+ params['expiration'] = req['expiration']
1018
+ response = self.privatePostAuth(params)
1019
+ #
1020
+ # {
1021
+ # jwt_token: "ooooccxtooootoooootheoooomoonooooo"
1022
+ # }
1023
+ #
1024
+ token = self.safe_string(response, 'jwt_token')
1025
+ self.options['authToken'] = token
1026
+ return token
1027
+
1028
+ def parse_order(self, order: dict, market: Market = None) -> Order:
1029
+ #
1030
+ # {
1031
+ # "account": "0x4638e3041366aa71720be63e32e53e1223316c7f0d56f7aa617542ed1e7512x",
1032
+ # "avg_fill_price": "26000",
1033
+ # "client_id": "x1234",
1034
+ # "cancel_reason": "NOT_ENOUGH_MARGIN",
1035
+ # "created_at": 1681493746016,
1036
+ # "flags": [
1037
+ # "REDUCE_ONLY"
1038
+ # ],
1039
+ # "id": "123456",
1040
+ # "instruction": "GTC",
1041
+ # "last_updated_at": 1681493746016,
1042
+ # "market": "BTC-USD-PERP",
1043
+ # "price": "26000",
1044
+ # "published_at": 1681493746016,
1045
+ # "received_at": 1681493746016,
1046
+ # "remaining_size": "0",
1047
+ # "seq_no": 1681471234972000000,
1048
+ # "side": "BUY",
1049
+ # "size": "0.05",
1050
+ # "status": "NEW",
1051
+ # "stp": "EXPIRE_MAKER",
1052
+ # "timestamp": 1681493746016,
1053
+ # "trigger_price": "26000",
1054
+ # "type": "MARKET"
1055
+ # }
1056
+ #
1057
+ timestamp = self.safe_integer(order, 'created_at')
1058
+ orderId = self.safe_string(order, 'id')
1059
+ clientOrderId = self.omit_zero(self.safe_string(order, 'client_id'))
1060
+ marketId = self.safe_string(order, 'market')
1061
+ market = self.safe_market(marketId, market)
1062
+ symbol = market['symbol']
1063
+ price = self.safe_string(order, 'price')
1064
+ amount = self.safe_string(order, 'size')
1065
+ orderType = self.safe_string(order, 'type')
1066
+ status = self.safe_string(order, 'status')
1067
+ side = self.safe_string_lower(order, 'side')
1068
+ average = self.omit_zero(self.safe_string(order, 'avg_fill_price'))
1069
+ remaining = self.omit_zero(self.safe_string(order, 'remaining_size'))
1070
+ stopPrice = self.safe_string(order, 'trigger_price')
1071
+ lastUpdateTimestamp = self.safe_integer(order, 'last_updated_at')
1072
+ return self.safe_order({
1073
+ 'id': orderId,
1074
+ 'clientOrderId': clientOrderId,
1075
+ 'timestamp': timestamp,
1076
+ 'datetime': self.iso8601(timestamp),
1077
+ 'lastTradeTimestamp': None,
1078
+ 'lastUpdateTimestamp': lastUpdateTimestamp,
1079
+ 'status': self.parse_order_status(status),
1080
+ 'symbol': symbol,
1081
+ 'type': self.parse_order_type(orderType),
1082
+ 'timeInForce': self.parse_time_in_force(self.safe_string(order, 'instrunction')),
1083
+ 'postOnly': None,
1084
+ 'reduceOnly': None,
1085
+ 'side': side,
1086
+ 'price': price,
1087
+ 'stopPrice': stopPrice,
1088
+ 'triggerPrice': stopPrice,
1089
+ 'takeProfitPrice': None,
1090
+ 'stopLossPrice': None,
1091
+ 'average': average,
1092
+ 'amount': amount,
1093
+ 'filled': None,
1094
+ 'remaining': remaining,
1095
+ 'cost': None,
1096
+ 'trades': None,
1097
+ 'fee': {
1098
+ 'cost': None,
1099
+ 'currency': None,
1100
+ },
1101
+ 'info': order,
1102
+ }, market)
1103
+
1104
+ def parse_time_in_force(self, timeInForce: Str):
1105
+ timeInForces: dict = {
1106
+ 'IOC': 'IOC',
1107
+ 'GTC': 'GTC',
1108
+ 'POST_ONLY': 'PO',
1109
+ }
1110
+ return self.safe_string(timeInForces, timeInForce, None)
1111
+
1112
+ def parse_order_status(self, status: Str):
1113
+ if status is not None:
1114
+ statuses: dict = {
1115
+ 'NEW': 'open',
1116
+ 'UNTRIGGERED': 'open',
1117
+ 'OPEN': 'open',
1118
+ 'CLOSED': 'closed',
1119
+ }
1120
+ return self.safe_string(statuses, status, status)
1121
+ return status
1122
+
1123
+ def parse_order_type(self, type: Str):
1124
+ types: dict = {
1125
+ 'LIMIT': 'limit',
1126
+ 'MARKET': 'market',
1127
+ 'STOP_LIMIT': 'limit',
1128
+ 'STOP_MARKET': 'market',
1129
+ }
1130
+ return self.safe_string_lower(types, type, type)
1131
+
1132
+ def convert_short_string(self, str: str):
1133
+ # TODO: add stringToBase16 in exchange
1134
+ return '0x' + self.binary_to_base16(self.base64_to_binary(self.string_to_base64(str)))
1135
+
1136
+ def scale_number(self, num: str):
1137
+ return Precise.string_mul(num, '100000000')
1138
+
1139
+ def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
1140
+ """
1141
+ create a trade order
1142
+ :see: https://docs.api.prod.paradex.trade/#create-order
1143
+ :param str symbol: unified symbol of the market to create an order in
1144
+ :param str type: 'market' or 'limit'
1145
+ :param str side: 'buy' or 'sell'
1146
+ :param float amount: how much of currency you want to trade in units of base currency
1147
+ :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
1148
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1149
+ :param float [params.stopPrice]: The price a trigger order is triggered at
1150
+ :param float [params.triggerPrice]: The price a trigger order is triggered at
1151
+ :param str [params.timeInForce]: "GTC", "IOC", or "POST_ONLY"
1152
+ :param bool [params.postOnly]: True or False
1153
+ :param bool [params.reduceOnly]: Ensures that the executed order does not flip the opened position.
1154
+ :param str [params.clientOrderId]: a unique id for the order
1155
+ :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1156
+ """
1157
+ self.authenticate_rest()
1158
+ self.load_markets()
1159
+ market = self.market(symbol)
1160
+ reduceOnly = self.safe_bool_2(params, 'reduceOnly', 'reduce_only')
1161
+ orderType = type.upper()
1162
+ orderSide = side.upper()
1163
+ request: dict = {
1164
+ 'market': market['id'],
1165
+ 'side': orderSide,
1166
+ 'type': orderType, # LIMIT/MARKET/STOP_LIMIT/STOP_MARKET
1167
+ 'size': self.amount_to_precision(symbol, amount),
1168
+ }
1169
+ stopPrice = self.safe_string_2(params, 'triggerPrice', 'stopPrice')
1170
+ isMarket = orderType == 'MARKET'
1171
+ timeInForce = self.safe_string_upper(params, 'timeInForce')
1172
+ postOnly = self.is_post_only(isMarket, None, params)
1173
+ if not isMarket:
1174
+ if postOnly:
1175
+ request['instruction'] = 'POST_ONLY'
1176
+ elif timeInForce == 'ioc':
1177
+ request['instruction'] = 'IOC'
1178
+ if reduceOnly:
1179
+ request['flags'] = [
1180
+ 'REDUCE_ONLY',
1181
+ ]
1182
+ if price is not None:
1183
+ request['price'] = self.price_to_precision(symbol, price)
1184
+ clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1185
+ if clientOrderId is not None:
1186
+ request['client_id'] = clientOrderId
1187
+ if stopPrice is not None:
1188
+ if isMarket:
1189
+ request['type'] = 'STOP_MARKET'
1190
+ else:
1191
+ request['type'] = 'STOP_LIMIT'
1192
+ request['trigger_price'] = self.price_to_precision(symbol, stopPrice)
1193
+ params = self.omit(params, ['reduceOnly', 'reduce_only', 'clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice'])
1194
+ account = self.retrieve_account()
1195
+ now = self.nonce()
1196
+ orderReq = {
1197
+ 'timestamp': now * 1000,
1198
+ 'market': self.convert_short_string(request['market']),
1199
+ 'side': '1' if (orderSide == 'BUY') else '2',
1200
+ 'orderType': self.convert_short_string(request['type']),
1201
+ 'size': self.scale_number(request['size']),
1202
+ 'price': '0' if (isMarket) else self.scale_number(request['price']),
1203
+ }
1204
+ domain = self.prepare_paradex_domain()
1205
+ messageTypes = {
1206
+ 'Order': [
1207
+ {'name': 'timestamp', 'type': 'felt'},
1208
+ {'name': 'market', 'type': 'felt'},
1209
+ {'name': 'side', 'type': 'felt'},
1210
+ {'name': 'orderType', 'type': 'felt'},
1211
+ {'name': 'size', 'type': 'felt'},
1212
+ {'name': 'price', 'type': 'felt'},
1213
+ ],
1214
+ }
1215
+ msg = self.starknet_encode_structured_data(domain, messageTypes, orderReq, account['address'])
1216
+ signature = self.starknet_sign(msg, account['privateKey'])
1217
+ request['signature'] = signature
1218
+ request['signature_timestamp'] = orderReq['timestamp']
1219
+ response = self.privatePostOrders(self.extend(request, params))
1220
+ #
1221
+ # {
1222
+ # "account": "0x4638e3041366aa71720be63e32e53e1223316c7f0d56f7aa617542ed1e7512x",
1223
+ # "avg_fill_price": "26000",
1224
+ # "cancel_reason": "NOT_ENOUGH_MARGIN",
1225
+ # "client_id": "x1234",
1226
+ # "created_at": 1681493746016,
1227
+ # "flags": [
1228
+ # "REDUCE_ONLY"
1229
+ # ],
1230
+ # "id": "123456",
1231
+ # "instruction": "GTC",
1232
+ # "last_updated_at": 1681493746016,
1233
+ # "market": "BTC-USD-PERP",
1234
+ # "price": "26000",
1235
+ # "published_at": 1681493746016,
1236
+ # "received_at": 1681493746016,
1237
+ # "remaining_size": "0",
1238
+ # "seq_no": 1681471234972000000,
1239
+ # "side": "BUY",
1240
+ # "size": "0.05",
1241
+ # "status": "NEW",
1242
+ # "stp": "EXPIRE_MAKER",
1243
+ # "timestamp": 1681493746016,
1244
+ # "trigger_price": "26000",
1245
+ # "type": "MARKET"
1246
+ # }
1247
+ #
1248
+ order = self.parse_order(response, market)
1249
+ return order
1250
+
1251
+ def cancel_order(self, id: str, symbol: Str = None, params={}):
1252
+ """
1253
+ cancels an open order
1254
+ :see: https://docs.api.prod.paradex.trade/#cancel-order
1255
+ :see: https://docs.api.prod.paradex.trade/#cancel-open-order-by-client-order-id
1256
+ :param str id: order id
1257
+ :param str symbol: unified symbol of the market the order was made in
1258
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1259
+ :param str [params.clientOrderId]: a unique id for the order
1260
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1261
+ """
1262
+ self.authenticate_rest()
1263
+ self.load_markets()
1264
+ request: dict = {}
1265
+ clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1266
+ response = None
1267
+ if clientOrderId is not None:
1268
+ request['client_id'] = clientOrderId
1269
+ response = self.privateDeleteOrdersByClientIdClientId(self.extend(request, params))
1270
+ else:
1271
+ request['order_id'] = id
1272
+ response = self.privateDeleteOrdersOrderId(self.extend(request, params))
1273
+ #
1274
+ # if success, no response...
1275
+ #
1276
+ return self.parse_order(response)
1277
+
1278
+ def cancel_all_orders(self, symbol: Str = None, params={}):
1279
+ """
1280
+ cancel all open orders in a market
1281
+ :see: https://docs.api.prod.paradex.trade/#cancel-all-open-orders
1282
+ :param str symbol: unified market symbol of the market to cancel orders in
1283
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1284
+ :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1285
+ """
1286
+ if symbol is None:
1287
+ raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a symbol argument')
1288
+ self.authenticate_rest()
1289
+ self.load_markets()
1290
+ market = self.market(symbol)
1291
+ request: dict = {
1292
+ 'market': market['id'],
1293
+ }
1294
+ response = self.privateDeleteOrders(self.extend(request, params))
1295
+ #
1296
+ # if success, no response...
1297
+ #
1298
+ return response
1299
+
1300
+ def fetch_order(self, id: str, symbol: Str = None, params={}):
1301
+ """
1302
+ fetches information on an order made by the user
1303
+ :see: https://docs.api.prod.paradex.trade/#get-order
1304
+ :see: https://docs.api.prod.paradex.trade/#get-order-by-client-id
1305
+ :param str id: the order id
1306
+ :param str symbol: unified symbol of the market the order was made in
1307
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1308
+ :param str [params.clientOrderId]: a unique id for the order
1309
+ :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
1310
+ """
1311
+ self.authenticate_rest()
1312
+ self.load_markets()
1313
+ request: dict = {}
1314
+ clientOrderId = self.safe_string_n(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1315
+ params = self.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id'])
1316
+ response = None
1317
+ if clientOrderId is not None:
1318
+ request['client_id'] = clientOrderId
1319
+ response = self.privateGetOrdersByClientIdClientId(self.extend(request, params))
1320
+ else:
1321
+ request['order_id'] = id
1322
+ response = self.privateGetOrdersOrderId(self.extend(request, params))
1323
+ #
1324
+ # {
1325
+ # "id": "1718941725080201704028870000",
1326
+ # "account": "0x49ddd7a564c978f6e4089ff8355b56a42b7e2d48ba282cb5aad60f04bea0ec3",
1327
+ # "market": "BTC-USD-PERP",
1328
+ # "side": "SELL",
1329
+ # "type": "LIMIT",
1330
+ # "size": "10.153",
1331
+ # "remaining_size": "10.153",
1332
+ # "price": "70784.5",
1333
+ # "status": "CLOSED",
1334
+ # "created_at": 1718941725082,
1335
+ # "last_updated_at": 1718958002991,
1336
+ # "timestamp": 1718941724678,
1337
+ # "cancel_reason": "USER_CANCELED",
1338
+ # "client_id": "",
1339
+ # "seq_no": 1718958002991595738,
1340
+ # "instruction": "GTC",
1341
+ # "avg_fill_price": "",
1342
+ # "stp": "EXPIRE_TAKER",
1343
+ # "received_at": 1718958510959,
1344
+ # "published_at": 1718958510960,
1345
+ # "flags": [],
1346
+ # "trigger_price": "0"
1347
+ # }
1348
+ #
1349
+ return self.parse_order(response)
1350
+
1351
+ def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1352
+ """
1353
+ fetches information on multiple orders made by the user
1354
+ :see: https://docs.api.prod.paradex.trade/#get-orders
1355
+ :param str symbol: unified market symbol of the market orders were made in
1356
+ :param int [since]: the earliest time in ms to fetch orders for
1357
+ :param int [limit]: the maximum number of order structures to retrieve
1358
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1359
+ :param str [params.side]: 'buy' or 'sell'
1360
+ :param boolean [params.paginate]: set to True if you want to fetch orders with pagination
1361
+ :param int params['until']: timestamp in ms of the latest order to fetch
1362
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1363
+ """
1364
+ self.authenticate_rest()
1365
+ self.load_markets()
1366
+ paginate = False
1367
+ paginate, params = self.handle_option_and_params(params, 'fetchOrders', 'paginate')
1368
+ if paginate:
1369
+ return self.fetch_paginated_call_cursor('fetchOrders', symbol, since, limit, params, 'next', 'cursor', None, 50)
1370
+ request: dict = {}
1371
+ market: Market = None
1372
+ if symbol is not None:
1373
+ market = self.market(symbol)
1374
+ request['market'] = market['id']
1375
+ if since is not None:
1376
+ request['start_at'] = since
1377
+ if limit is not None:
1378
+ request['page_size'] = limit
1379
+ request, params = self.handle_until_option('end_at', request, params)
1380
+ response = self.privateGetOrdersHistory(self.extend(request, params))
1381
+ #
1382
+ # {
1383
+ # "next": "eyJmaWx0ZXIiMsIm1hcmtlciI6eyJtYXJrZXIiOiIxNjc1NjUwMDE3NDMxMTAxNjk5N=",
1384
+ # "prev": "eyJmaWx0ZXIiOnsiTGltaXQiOjkwfSwidGltZSI6MTY4MTY3OTgzNzk3MTMwOTk1MywibWFya2VyIjp7Im1zMjExMD==",
1385
+ # "results": [
1386
+ # {
1387
+ # "account": "0x4638e3041366aa71720be63e32e53e1223316c7f0d56f7aa617542ed1e7512x",
1388
+ # "avg_fill_price": "26000",
1389
+ # "cancel_reason": "NOT_ENOUGH_MARGIN",
1390
+ # "client_id": "x1234",
1391
+ # "created_at": 1681493746016,
1392
+ # "flags": [
1393
+ # "REDUCE_ONLY"
1394
+ # ],
1395
+ # "id": "123456",
1396
+ # "instruction": "GTC",
1397
+ # "last_updated_at": 1681493746016,
1398
+ # "market": "BTC-USD-PERP",
1399
+ # "price": "26000",
1400
+ # "published_at": 1681493746016,
1401
+ # "received_at": 1681493746016,
1402
+ # "remaining_size": "0",
1403
+ # "seq_no": 1681471234972000000,
1404
+ # "side": "BUY",
1405
+ # "size": "0.05",
1406
+ # "status": "NEW",
1407
+ # "stp": "EXPIRE_MAKER",
1408
+ # "timestamp": 1681493746016,
1409
+ # "trigger_price": "26000",
1410
+ # "type": "MARKET"
1411
+ # }
1412
+ # ]
1413
+ # }
1414
+ #
1415
+ orders = self.safe_list(response, 'results', [])
1416
+ paginationCursor = self.safe_string(response, 'next')
1417
+ ordersLength = len(orders)
1418
+ if (paginationCursor is not None) and (ordersLength > 0):
1419
+ first = orders[0]
1420
+ first['next'] = paginationCursor
1421
+ orders[0] = first
1422
+ return self.parse_orders(orders, market, since, limit)
1423
+
1424
+ def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
1425
+ """
1426
+ fetches information on multiple orders made by the user
1427
+ :see: https://docs.api.prod.paradex.trade/#paradex-rest-api-orders
1428
+ :param str symbol: unified market symbol of the market orders were made in
1429
+ :param int [since]: the earliest time in ms to fetch orders for
1430
+ :param int [limit]: the maximum number of order structures to retrieve
1431
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1432
+ :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
1433
+ """
1434
+ self.authenticate_rest()
1435
+ self.load_markets()
1436
+ request: dict = {}
1437
+ market: Market = None
1438
+ if symbol is not None:
1439
+ market = self.market(symbol)
1440
+ request['market'] = market['id']
1441
+ response = self.privateGetOrders(self.extend(request, params))
1442
+ #
1443
+ # {
1444
+ # "results": [
1445
+ # {
1446
+ # "account": "0x4638e3041366aa71720be63e32e53e1223316c7f0d56f7aa617542ed1e7512x",
1447
+ # "avg_fill_price": "26000",
1448
+ # "client_id": "x1234",
1449
+ # "cancel_reason": "NOT_ENOUGH_MARGIN",
1450
+ # "created_at": 1681493746016,
1451
+ # "flags": [
1452
+ # "REDUCE_ONLY"
1453
+ # ],
1454
+ # "id": "123456",
1455
+ # "instruction": "GTC",
1456
+ # "last_updated_at": 1681493746016,
1457
+ # "market": "BTC-USD-PERP",
1458
+ # "price": "26000",
1459
+ # "published_at": 1681493746016,
1460
+ # "received_at": 1681493746016,
1461
+ # "remaining_size": "0",
1462
+ # "seq_no": 1681471234972000000,
1463
+ # "side": "BUY",
1464
+ # "size": "0.05",
1465
+ # "status": "NEW",
1466
+ # "stp": "EXPIRE_MAKER",
1467
+ # "timestamp": 1681493746016,
1468
+ # "trigger_price": "26000",
1469
+ # "type": "MARKET"
1470
+ # }
1471
+ # ]
1472
+ # }
1473
+ #
1474
+ orders = self.safe_list(response, 'results', [])
1475
+ return self.parse_orders(orders, market, since, limit)
1476
+
1477
+ def fetch_balance(self, params={}) -> Balances:
1478
+ """
1479
+ query for balance and get the amount of funds available for trading or funds locked in orders
1480
+ :see: https://docs.api.prod.paradex.trade/#list-balances
1481
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1482
+ :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
1483
+ """
1484
+ self.authenticate_rest()
1485
+ self.load_markets()
1486
+ response = self.privateGetBalance()
1487
+ #
1488
+ # {
1489
+ # "results": [
1490
+ # {
1491
+ # "token": "USDC",
1492
+ # "size": "99980.2382266290601",
1493
+ # "last_updated_at": 1718529757240
1494
+ # }
1495
+ # ]
1496
+ # }
1497
+ #
1498
+ data = self.safe_list(response, 'results', [])
1499
+ return self.parse_balance(data)
1500
+
1501
+ def parse_balance(self, response) -> Balances:
1502
+ result: dict = {'info': response}
1503
+ for i in range(0, len(response)):
1504
+ balance = self.safe_dict(response, i, {})
1505
+ currencyId = self.safe_string(balance, 'token')
1506
+ code = self.safe_currency_code(currencyId)
1507
+ account = self.account()
1508
+ account['total'] = self.safe_string(balance, 'size')
1509
+ result[code] = account
1510
+ return self.safe_balance(result)
1511
+
1512
+ def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
1513
+ """
1514
+ fetch all trades made by the user
1515
+ :see: https://docs.api.prod.paradex.trade/#list-fills
1516
+ :param str symbol: unified market symbol
1517
+ :param int [since]: the earliest time in ms to fetch trades for
1518
+ :param int [limit]: the maximum number of trades structures to retrieve
1519
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1520
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1521
+ :param int [params.until]: the latest time in ms to fetch entries for
1522
+ :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
1523
+ """
1524
+ self.authenticate_rest()
1525
+ self.load_markets()
1526
+ paginate = False
1527
+ paginate, params = self.handle_option_and_params(params, 'fetchMyTrades', 'paginate')
1528
+ if paginate:
1529
+ return self.fetch_paginated_call_cursor('fetchMyTrades', symbol, since, limit, params, 'next', 'cursor', None, 100)
1530
+ request: dict = {}
1531
+ market: Market = None
1532
+ if symbol is not None:
1533
+ market = self.market(symbol)
1534
+ request['market'] = market['id']
1535
+ if limit is not None:
1536
+ request['page_size'] = limit
1537
+ if since is not None:
1538
+ request['start_at'] = since
1539
+ request, params = self.handle_until_option('end_at', request, params)
1540
+ response = self.privateGetFills(self.extend(request, params))
1541
+ #
1542
+ # {
1543
+ # "next": null,
1544
+ # "prev": null,
1545
+ # "results": [
1546
+ # {
1547
+ # "id": "1718947571560201703986670001",
1548
+ # "side": "BUY",
1549
+ # "liquidity": "TAKER",
1550
+ # "market": "BTC-USD-PERP",
1551
+ # "order_id": "1718947571540201703992340000",
1552
+ # "price": "64852.9",
1553
+ # "size": "0.01",
1554
+ # "fee": "0.1945587",
1555
+ # "fee_currency": "USDC",
1556
+ # "created_at": 1718947571569,
1557
+ # "remaining_size": "0",
1558
+ # "client_id": "",
1559
+ # "fill_type": "FILL"
1560
+ # }
1561
+ # ]
1562
+ # }
1563
+ #
1564
+ trades = self.safe_list(response, 'results', [])
1565
+ for i in range(0, len(trades)):
1566
+ trades[i]['next'] = self.safe_string(response, 'next')
1567
+ return self.parse_trades(trades, market, since, limit)
1568
+
1569
+ def fetch_position(self, symbol: str, params={}):
1570
+ """
1571
+ fetch data on an open position
1572
+ :see: https://docs.api.prod.paradex.trade/#list-open-positions
1573
+ :param str symbol: unified market symbol of the market the position is held in
1574
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1575
+ :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
1576
+ """
1577
+ self.authenticate_rest()
1578
+ self.load_markets()
1579
+ market = self.market(symbol)
1580
+ positions = self.fetch_positions([market['symbol']], params)
1581
+ return self.safe_dict(positions, 0, {})
1582
+
1583
+ def fetch_positions(self, symbols: Strings = None, params={}):
1584
+ """
1585
+ fetch all open positions
1586
+ :see: https://docs.api.prod.paradex.trade/#list-open-positions
1587
+ :param str[] [symbols]: list of unified market symbols
1588
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1589
+ :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
1590
+ """
1591
+ self.authenticate_rest()
1592
+ self.load_markets()
1593
+ symbols = self.market_symbols(symbols)
1594
+ response = self.privateGetPositions()
1595
+ #
1596
+ # {
1597
+ # "results": [
1598
+ # {
1599
+ # "id": "0x49ddd7a564c978f6e4089ff8355b56a42b7e2d48ba282cb5aad60f04bea0ec3-BTC-USD-PERP",
1600
+ # "market": "BTC-USD-PERP",
1601
+ # "status": "OPEN",
1602
+ # "side": "LONG",
1603
+ # "size": "0.01",
1604
+ # "average_entry_price": "64839.96053748",
1605
+ # "average_entry_price_usd": "64852.9",
1606
+ # "realized_pnl": "0",
1607
+ # "unrealized_pnl": "-2.39677214",
1608
+ # "unrealized_funding_pnl": "-0.11214013",
1609
+ # "cost": "648.39960537",
1610
+ # "cost_usd": "648.529",
1611
+ # "cached_funding_index": "35202.1002351",
1612
+ # "last_updated_at": 1718950074249,
1613
+ # "last_fill_id": "1718947571560201703986670001",
1614
+ # "seq_no": 1718950074249176253,
1615
+ # "liquidation_price": ""
1616
+ # }
1617
+ # ]
1618
+ # }
1619
+ #
1620
+ data = self.safe_list(response, 'results', [])
1621
+ return self.parse_positions(data, symbols)
1622
+
1623
+ def parse_position(self, position: dict, market: Market = None):
1624
+ #
1625
+ # {
1626
+ # "id": "0x49ddd7a564c978f6e4089ff8355b56a42b7e2d48ba282cb5aad60f04bea0ec3-BTC-USD-PERP",
1627
+ # "market": "BTC-USD-PERP",
1628
+ # "status": "OPEN",
1629
+ # "side": "LONG",
1630
+ # "size": "0.01",
1631
+ # "average_entry_price": "64839.96053748",
1632
+ # "average_entry_price_usd": "64852.9",
1633
+ # "realized_pnl": "0",
1634
+ # "unrealized_pnl": "-2.39677214",
1635
+ # "unrealized_funding_pnl": "-0.11214013",
1636
+ # "cost": "648.39960537",
1637
+ # "cost_usd": "648.529",
1638
+ # "cached_funding_index": "35202.1002351",
1639
+ # "last_updated_at": 1718950074249,
1640
+ # "last_fill_id": "1718947571560201703986670001",
1641
+ # "seq_no": 1718950074249176253,
1642
+ # "liquidation_price": ""
1643
+ # }
1644
+ #
1645
+ marketId = self.safe_string(position, 'market')
1646
+ market = self.safe_market(marketId, market)
1647
+ symbol = market['symbol']
1648
+ side = self.safe_string_lower(position, 'side')
1649
+ quantity = self.safe_string(position, 'size')
1650
+ if side != 'long':
1651
+ quantity = Precise.string_mul('-1', quantity)
1652
+ timestamp = self.safe_integer(position, 'time')
1653
+ return self.safe_position({
1654
+ 'info': position,
1655
+ 'id': self.safe_string(position, 'id'),
1656
+ 'symbol': symbol,
1657
+ 'entryPrice': self.safe_string(position, 'average_entry_price'),
1658
+ 'markPrice': None,
1659
+ 'notional': None,
1660
+ 'collateral': self.safe_string(position, 'cost'),
1661
+ 'unrealizedPnl': self.safe_string(position, 'unrealized_pnl'),
1662
+ 'side': side,
1663
+ 'contracts': self.parse_number(quantity),
1664
+ 'contractSize': None,
1665
+ 'timestamp': timestamp,
1666
+ 'datetime': self.iso8601(timestamp),
1667
+ 'hedged': None,
1668
+ 'maintenanceMargin': None,
1669
+ 'maintenanceMarginPercentage': None,
1670
+ 'initialMargin': None,
1671
+ 'initialMarginPercentage': None,
1672
+ 'leverage': None,
1673
+ 'liquidationPrice': None,
1674
+ 'marginRatio': None,
1675
+ 'marginMode': None,
1676
+ 'percentage': None,
1677
+ })
1678
+
1679
+ def fetch_liquidations(self, symbol: str, since: Int = None, limit: Int = None, params={}):
1680
+ """
1681
+ retrieves the public liquidations of a trading pair
1682
+ :see: https://docs.api.prod.paradex.trade/#list-liquidations
1683
+ :param str symbol: unified CCXT market symbol
1684
+ :param int [since]: the earliest time in ms to fetch liquidations for
1685
+ :param int [limit]: the maximum number of liquidation structures to retrieve
1686
+ :param dict [params]: exchange specific parameters for the huobi api endpoint
1687
+ :param int [params.until]: timestamp in ms of the latest liquidation
1688
+ :returns dict: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
1689
+ """
1690
+ self.authenticate_rest()
1691
+ request: dict = {}
1692
+ if since is not None:
1693
+ request['from'] = since
1694
+ else:
1695
+ request['from'] = 1
1696
+ market = self.market(symbol)
1697
+ request, params = self.handle_until_option('to', request, params)
1698
+ response = self.privateGetLiquidations(self.extend(request, params))
1699
+ #
1700
+ # {
1701
+ # "results": [
1702
+ # {
1703
+ # "created_at": 1697213130097,
1704
+ # "id": "0x123456789"
1705
+ # }
1706
+ # ]
1707
+ # }
1708
+ #
1709
+ data = self.safe_list(response, 'results', [])
1710
+ return self.parse_liquidations(data, market, since, limit)
1711
+
1712
+ def parse_liquidation(self, liquidation, market: Market = None):
1713
+ #
1714
+ # {
1715
+ # "created_at": 1697213130097,
1716
+ # "id": "0x123456789"
1717
+ # }
1718
+ #
1719
+ timestamp = self.safe_integer(liquidation, 'created_at')
1720
+ return self.safe_liquidation({
1721
+ 'info': liquidation,
1722
+ 'symbol': None,
1723
+ 'contracts': None,
1724
+ 'contractSize': None,
1725
+ 'price': None,
1726
+ 'baseValue': None,
1727
+ 'quoteValue': None,
1728
+ 'timestamp': timestamp,
1729
+ 'datetime': self.iso8601(timestamp),
1730
+ })
1731
+
1732
+ def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
1733
+ """
1734
+ fetch all deposits made to an account
1735
+ :see: https://docs.api.prod.paradex.trade/#paradex-rest-api-transfers
1736
+ :param str code: unified currency code
1737
+ :param int [since]: the earliest time in ms to fetch deposits for
1738
+ :param int [limit]: the maximum number of deposits structures to retrieve
1739
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1740
+ :param int [params.until]: the latest time in ms to fetch entries for
1741
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1742
+ :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
1743
+ """
1744
+ self.authenticate_rest()
1745
+ self.load_markets()
1746
+ paginate = False
1747
+ paginate, params = self.handle_option_and_params(params, 'fetchDeposits', 'paginate')
1748
+ if paginate:
1749
+ return self.fetch_paginated_call_cursor('fetchDeposits', code, since, limit, params, 'next', 'cursor', None, 100)
1750
+ request: dict = {}
1751
+ if limit is not None:
1752
+ request['page_size'] = limit
1753
+ if since is not None:
1754
+ request['start_at'] = since
1755
+ request, params = self.handle_until_option('end_at', request, params)
1756
+ response = self.privateGetTransfers(self.extend(request, params))
1757
+ #
1758
+ # {
1759
+ # "next": null,
1760
+ # "prev": null,
1761
+ # "results": [
1762
+ # {
1763
+ # "id": "1718940471200201703989430000",
1764
+ # "account": "0x49ddd7a564c978f6e4089ff8355b56a42b7e2d48ba282cb5aad60f04bea0ec3",
1765
+ # "kind": "DEPOSIT",
1766
+ # "status": "COMPLETED",
1767
+ # "amount": "100000",
1768
+ # "token": "USDC",
1769
+ # "created_at": 1718940471208,
1770
+ # "last_updated_at": 1718941455546,
1771
+ # "txn_hash": "0x73a415ca558a97bbdcd1c43e52b45f1e0486a0a84b3bb4958035ad6c59cb866",
1772
+ # "external_txn_hash": "",
1773
+ # "socialized_loss_factor": ""
1774
+ # }
1775
+ # ]
1776
+ # }
1777
+ #
1778
+ rows = self.safe_list(response, 'results', [])
1779
+ deposits = []
1780
+ for i in range(0, len(rows)):
1781
+ row = rows[i]
1782
+ if row['kind'] == 'DEPOSIT':
1783
+ deposits.append(row)
1784
+ return self.parse_transactions(deposits, None, since, limit)
1785
+
1786
+ def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]:
1787
+ """
1788
+ fetch all withdrawals made from an account
1789
+ :see: https://docs.api.prod.paradex.trade/#paradex-rest-api-transfers
1790
+ :param str code: unified currency code
1791
+ :param int [since]: the earliest time in ms to fetch withdrawals for
1792
+ :param int [limit]: the maximum number of withdrawals structures to retrieve
1793
+ :param dict [params]: extra parameters specific to the exchange API endpoint
1794
+ :param int [params.until]: the latest time in ms to fetch withdrawals for
1795
+ :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1796
+ :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
1797
+ """
1798
+ self.authenticate_rest()
1799
+ self.load_markets()
1800
+ paginate = False
1801
+ paginate, params = self.handle_option_and_params(params, 'fetchWithdrawals', 'paginate')
1802
+ if paginate:
1803
+ return self.fetch_paginated_call_cursor('fetchWithdrawals', code, since, limit, params, 'next', 'cursor', None, 100)
1804
+ request: dict = {}
1805
+ if limit is not None:
1806
+ request['page_size'] = limit
1807
+ if since is not None:
1808
+ request['start_at'] = since
1809
+ request, params = self.handle_until_option('end_at', request, params)
1810
+ response = self.privateGetTransfers(self.extend(request, params))
1811
+ #
1812
+ # {
1813
+ # "next": null,
1814
+ # "prev": null,
1815
+ # "results": [
1816
+ # {
1817
+ # "id": "1718940471200201703989430000",
1818
+ # "account": "0x49ddd7a564c978f6e4089ff8355b56a42b7e2d48ba282cb5aad60f04bea0ec3",
1819
+ # "kind": "DEPOSIT",
1820
+ # "status": "COMPLETED",
1821
+ # "amount": "100000",
1822
+ # "token": "USDC",
1823
+ # "created_at": 1718940471208,
1824
+ # "last_updated_at": 1718941455546,
1825
+ # "txn_hash": "0x73a415ca558a97bbdcd1c43e52b45f1e0486a0a84b3bb4958035ad6c59cb866",
1826
+ # "external_txn_hash": "",
1827
+ # "socialized_loss_factor": ""
1828
+ # }
1829
+ # ]
1830
+ # }
1831
+ #
1832
+ rows = self.safe_list(response, 'results', [])
1833
+ deposits = []
1834
+ for i in range(0, len(rows)):
1835
+ row = rows[i]
1836
+ if row['kind'] == 'WITHDRAWAL':
1837
+ deposits.append(row)
1838
+ return self.parse_transactions(deposits, None, since, limit)
1839
+
1840
+ def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction:
1841
+ #
1842
+ # fetchDeposits & fetchWithdrawals
1843
+ #
1844
+ # {
1845
+ # "id": "1718940471200201703989430000",
1846
+ # "account": "0x49ddd7a564c978f6e4089ff8355b56a42b7e2d48ba282cb5aad60f04bea0ec3",
1847
+ # "kind": "DEPOSIT",
1848
+ # "status": "COMPLETED",
1849
+ # "amount": "100000",
1850
+ # "token": "USDC",
1851
+ # "created_at": 1718940471208,
1852
+ # "last_updated_at": 1718941455546,
1853
+ # "txn_hash": "0x73a415ca558a97bbdcd1c43e52b45f1e0486a0a84b3bb4958035ad6c59cb866",
1854
+ # "external_txn_hash": "",
1855
+ # "socialized_loss_factor": ""
1856
+ # }
1857
+ #
1858
+ id = self.safe_string(transaction, 'id')
1859
+ address = self.safe_string(transaction, 'account')
1860
+ txid = self.safe_string(transaction, 'txn_hash')
1861
+ currencyId = self.safe_string(transaction, 'token')
1862
+ code = self.safe_currency_code(currencyId, currency)
1863
+ timestamp = self.safe_integer(transaction, 'created_at')
1864
+ updated = self.safe_integer(transaction, 'last_updated_at')
1865
+ type = self.safe_string(transaction, 'kind')
1866
+ type = 'deposit' if (type == 'DEPOSIT') else 'withdrawal'
1867
+ status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
1868
+ amount = self.safe_number(transaction, 'amount')
1869
+ return {
1870
+ 'info': transaction,
1871
+ 'id': id,
1872
+ 'txid': txid,
1873
+ 'timestamp': timestamp,
1874
+ 'datetime': self.iso8601(timestamp),
1875
+ 'network': None,
1876
+ 'address': address,
1877
+ 'addressTo': address,
1878
+ 'addressFrom': None,
1879
+ 'tag': None,
1880
+ 'tagTo': None,
1881
+ 'tagFrom': None,
1882
+ 'type': type,
1883
+ 'amount': amount,
1884
+ 'currency': code,
1885
+ 'status': status,
1886
+ 'updated': updated,
1887
+ 'internal': None,
1888
+ 'comment': None,
1889
+ 'fee': None,
1890
+ }
1891
+
1892
+ def parse_transaction_status(self, status: Str):
1893
+ statuses: dict = {
1894
+ 'PENDING': 'pending',
1895
+ 'AVAILABLE': 'pending',
1896
+ 'COMPLETED': 'ok',
1897
+ 'FAILED': 'failed',
1898
+ }
1899
+ return self.safe_string(statuses, status, status)
1900
+
1901
+ def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
1902
+ url = self.implode_hostname(self.urls['api'][self.version]) + '/' + self.implode_params(path, params)
1903
+ query = self.omit(params, self.extract_params(path))
1904
+ if api == 'public':
1905
+ if query:
1906
+ url += '?' + self.urlencode(query)
1907
+ elif api == 'private':
1908
+ self.check_required_credentials()
1909
+ headers = {
1910
+ 'Accept': 'application/json',
1911
+ 'PARADEX-PARTNER': self.safe_string(self.options, 'broker', 'CCXT'),
1912
+ }
1913
+ # TODO: optimize
1914
+ if path == 'auth':
1915
+ headers['PARADEX-STARKNET-ACCOUNT'] = query['account']
1916
+ headers['PARADEX-STARKNET-SIGNATURE'] = query['signature']
1917
+ headers['PARADEX-TIMESTAMP'] = str(query['timestamp'])
1918
+ headers['PARADEX-SIGNATURE-EXPIRATION'] = str(query['expiration'])
1919
+ elif path == 'onboarding':
1920
+ headers['PARADEX-ETHEREUM-ACCOUNT'] = self.walletAddress
1921
+ headers['PARADEX-STARKNET-ACCOUNT'] = query['account']
1922
+ headers['PARADEX-STARKNET-SIGNATURE'] = query['signature']
1923
+ headers['PARADEX-TIMESTAMP'] = str(self.nonce())
1924
+ headers['Content-Type'] = 'application/json'
1925
+ body = self.json({
1926
+ 'public_key': query['public_key'],
1927
+ })
1928
+ else:
1929
+ token = self.options['authToken']
1930
+ headers['Authorization'] = 'Bearer ' + token
1931
+ if method == 'POST':
1932
+ headers['Content-Type'] = 'application/json'
1933
+ body = self.json(query)
1934
+ else:
1935
+ url = url + '?' + self.urlencode(query)
1936
+ # headers = {
1937
+ # 'Accept': 'application/json',
1938
+ # 'Authorization': 'Bearer ' + self.apiKey,
1939
+ # }
1940
+ # if method == 'POST':
1941
+ # body = self.json(query)
1942
+ # headers['Content-Type'] = 'application/json'
1943
+ # else:
1944
+ # if query:
1945
+ # url += '?' + self.urlencode(query)
1946
+ # }
1947
+ # }
1948
+ return {'url': url, 'method': method, 'body': body, 'headers': headers}
1949
+
1950
+ def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
1951
+ if not response:
1952
+ return None # fallback to default error handler
1953
+ #
1954
+ # {
1955
+ # "data": null,
1956
+ # "error": "NOT_ONBOARDED",
1957
+ # "message": "User has never called /onboarding endpoint"
1958
+ # }
1959
+ #
1960
+ errorCode = self.safe_string(response, 'error')
1961
+ if errorCode is not None:
1962
+ feedback = self.id + ' ' + body
1963
+ self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
1964
+ self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
1965
+ raise ExchangeError(feedback) # unknown message
1966
+ return None