ccxt 4.5.44 → 4.5.45

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 (81) hide show
  1. package/README.md +9 -12
  2. package/dist/ccxt.browser.min.js +3 -3
  3. package/dist/cjs/ccxt.js +1 -12
  4. package/dist/cjs/src/abstract/kucoinfutures.js +1 -1
  5. package/dist/cjs/src/base/Exchange.js +36 -3
  6. package/dist/cjs/src/base/functions/encode.js +2 -2
  7. package/dist/cjs/src/base/functions/generic.js +8 -2
  8. package/dist/cjs/src/bitrue.js +1 -1
  9. package/dist/cjs/src/bitteam.js +1 -1
  10. package/dist/cjs/src/btcbox.js +1 -1
  11. package/dist/cjs/src/cex.js +1 -0
  12. package/dist/cjs/src/gate.js +227 -168
  13. package/dist/cjs/src/grvt.js +3 -2
  14. package/dist/cjs/src/hyperliquid.js +16 -5
  15. package/dist/cjs/src/kraken.js +2 -2
  16. package/dist/cjs/src/krakenfutures.js +1 -5
  17. package/dist/cjs/src/kucoin.js +4729 -970
  18. package/dist/cjs/src/kucoinfutures.js +14 -3434
  19. package/dist/cjs/src/lbank.js +1 -1
  20. package/dist/cjs/src/poloniex.js +1 -1
  21. package/dist/cjs/src/pro/gate.js +37 -1
  22. package/dist/cjs/src/pro/kucoin.js +819 -178
  23. package/dist/cjs/src/pro/kucoinfutures.js +95 -1261
  24. package/dist/cjs/src/pro/mexc.js +10 -5
  25. package/dist/cjs/src/pro/okx.js +84 -39
  26. package/js/ccxt.d.ts +2 -14
  27. package/js/ccxt.js +2 -10
  28. package/js/src/abstract/kucoin.d.ts +46 -3
  29. package/js/src/abstract/kucoinfutures.d.ts +27 -12
  30. package/js/src/base/Exchange.d.ts +12 -1
  31. package/js/src/base/Exchange.js +36 -3
  32. package/js/src/base/functions/encode.js +2 -2
  33. package/js/src/base/functions/generic.js +9 -3
  34. package/js/src/bitrue.js +1 -1
  35. package/js/src/bitteam.js +1 -1
  36. package/js/src/btcbox.js +1 -1
  37. package/js/src/cex.js +2 -1
  38. package/js/src/gate.d.ts +125 -119
  39. package/js/src/gate.js +227 -168
  40. package/js/src/grvt.js +3 -2
  41. package/js/src/hyperliquid.d.ts +3 -1
  42. package/js/src/hyperliquid.js +16 -5
  43. package/js/src/kraken.js +2 -2
  44. package/js/src/krakenfutures.js +1 -5
  45. package/js/src/kucoin.d.ts +696 -100
  46. package/js/src/kucoin.js +4730 -971
  47. package/js/src/kucoinfutures.d.ts +4 -522
  48. package/js/src/kucoinfutures.js +14 -3434
  49. package/js/src/lbank.js +1 -1
  50. package/js/src/poloniex.js +1 -1
  51. package/js/src/pro/gate.d.ts +30 -1
  52. package/js/src/pro/gate.js +37 -1
  53. package/js/src/pro/kucoin.d.ts +70 -30
  54. package/js/src/pro/kucoin.js +821 -180
  55. package/js/src/pro/kucoinfutures.d.ts +17 -195
  56. package/js/src/pro/kucoinfutures.js +96 -1262
  57. package/js/src/pro/mexc.js +10 -5
  58. package/js/src/pro/okx.d.ts +1 -0
  59. package/js/src/pro/okx.js +84 -39
  60. package/package.json +1 -1
  61. package/dist/cjs/src/abstract/alp.js +0 -11
  62. package/dist/cjs/src/abstract/defx.js +0 -11
  63. package/dist/cjs/src/abstract/timex.js +0 -11
  64. package/dist/cjs/src/alp.js +0 -1059
  65. package/dist/cjs/src/defx.js +0 -2142
  66. package/dist/cjs/src/pro/defx.js +0 -866
  67. package/dist/cjs/src/timex.js +0 -1793
  68. package/js/src/abstract/alp.d.ts +0 -21
  69. package/js/src/abstract/alp.js +0 -5
  70. package/js/src/abstract/defx.d.ts +0 -72
  71. package/js/src/abstract/defx.js +0 -5
  72. package/js/src/abstract/timex.d.ts +0 -65
  73. package/js/src/abstract/timex.js +0 -5
  74. package/js/src/alp.d.ts +0 -209
  75. package/js/src/alp.js +0 -1052
  76. package/js/src/defx.d.ts +0 -348
  77. package/js/src/defx.js +0 -2135
  78. package/js/src/pro/defx.d.ts +0 -236
  79. package/js/src/pro/defx.js +0 -859
  80. package/js/src/timex.d.ts +0 -247
  81. package/js/src/timex.js +0 -1786
package/js/src/defx.js DELETED
@@ -1,2135 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- import Exchange from './abstract/defx.js';
3
- import { Precise } from './base/Precise.js';
4
- import { TICK_SIZE } from './base/functions/number.js';
5
- import { sha256 } from './static_dependencies/noble-hashes/sha256.js';
6
- import { NotSupported, ArgumentsRequired, BadRequest, AuthenticationError, InvalidOrder, ExchangeError } from './base/errors.js';
7
- // ---------------------------------------------------------------------------
8
- /**
9
- * @class defx
10
- * @augments Exchange
11
- */
12
- export default class defx extends Exchange {
13
- describe() {
14
- return this.deepExtend(super.describe(), {
15
- 'id': 'defx',
16
- 'name': 'Defx X',
17
- // 'countries': [ '' ],
18
- 'rateLimit': 100,
19
- 'version': 'v1',
20
- 'certified': false,
21
- 'pro': false,
22
- 'hostname': 'defx.com',
23
- 'dex': true,
24
- 'has': {
25
- 'CORS': undefined,
26
- 'spot': false,
27
- 'margin': false,
28
- 'swap': true,
29
- 'future': false,
30
- 'option': false,
31
- 'addMargin': true,
32
- 'cancelAllOrders': true,
33
- 'cancelAllOrdersAfter': false,
34
- 'cancelOrder': true,
35
- 'cancelWithdraw': false,
36
- 'closeAllPositions': true,
37
- 'closePosition': true,
38
- 'createConvertTrade': false,
39
- 'createDepositAddress': false,
40
- 'createMarketBuyOrderWithCost': false,
41
- 'createMarketOrder': false,
42
- 'createMarketOrderWithCost': false,
43
- 'createMarketSellOrderWithCost': false,
44
- 'createOrder': true,
45
- 'createOrderWithTakeProfitAndStopLoss': true,
46
- 'createReduceOnlyOrder': true,
47
- 'createStopLimitOrder': false,
48
- 'createStopLossOrder': false,
49
- 'createStopMarketOrder': false,
50
- 'createStopOrder': false,
51
- 'createTakeProfitOrder': true,
52
- 'createTrailingAmountOrder': false,
53
- 'createTrailingPercentOrder': false,
54
- 'createTriggerOrder': true,
55
- 'fetchAccounts': false,
56
- 'fetchBalance': true,
57
- 'fetchCanceledOrders': true,
58
- 'fetchClosedOrder': false,
59
- 'fetchClosedOrders': true,
60
- 'fetchConvertCurrencies': false,
61
- 'fetchConvertQuote': false,
62
- 'fetchConvertTrade': false,
63
- 'fetchConvertTradeHistory': false,
64
- 'fetchCurrencies': false,
65
- 'fetchDepositAddress': false,
66
- 'fetchDepositAddresses': false,
67
- 'fetchDepositAddressesByNetwork': false,
68
- 'fetchDeposits': false,
69
- 'fetchDepositsWithdrawals': false,
70
- 'fetchFundingHistory': false,
71
- 'fetchFundingInterval': false,
72
- 'fetchFundingIntervals': false,
73
- 'fetchFundingRate': true,
74
- 'fetchFundingRateHistory': false,
75
- 'fetchFundingRates': false,
76
- 'fetchIndexOHLCV': false,
77
- 'fetchLedger': true,
78
- 'fetchLeverage': false,
79
- 'fetchMarginAdjustmentHistory': false,
80
- 'fetchMarginMode': false,
81
- 'fetchMarkets': true,
82
- 'fetchMarkOHLCV': false,
83
- 'fetchMarkPrice': false,
84
- 'fetchMarkPrices': false,
85
- 'fetchMyTrades': true,
86
- 'fetchOHLCV': true,
87
- 'fetchOpenInterestHistory': false,
88
- 'fetchOpenOrder': false,
89
- 'fetchOpenOrders': true,
90
- 'fetchOrder': true,
91
- 'fetchOrderBook': true,
92
- 'fetchOrders': true,
93
- 'fetchOrderTrades': false,
94
- 'fetchPosition': true,
95
- 'fetchPositionHistory': false,
96
- 'fetchPositionMode': false,
97
- 'fetchPositions': true,
98
- 'fetchPositionsHistory': false,
99
- 'fetchPremiumIndexOHLCV': false,
100
- 'fetchStatus': true,
101
- 'fetchTicker': true,
102
- 'fetchTickers': true,
103
- 'fetchTime': true,
104
- 'fetchTrades': true,
105
- 'fetchTradingFee': false,
106
- 'fetchTradingFees': false,
107
- 'fetchTransactions': false,
108
- 'fetchTransfers': false,
109
- 'fetchWithdrawals': false,
110
- 'reduceMargin': false,
111
- 'sandbox': true,
112
- 'setLeverage': true,
113
- 'setMargin': false,
114
- 'setPositionMode': false,
115
- 'transfer': false,
116
- 'withdraw': true,
117
- },
118
- 'timeframes': {
119
- '1m': '1m',
120
- '3m': '3m',
121
- '5m': '5m',
122
- '15m': '15m',
123
- '30m': '30m',
124
- '1h': '1h',
125
- '2h': '2h',
126
- '4h': '4h',
127
- '12h': '12h',
128
- '1d': '1d',
129
- '1w': '1w',
130
- '1M': '1M',
131
- },
132
- 'urls': {
133
- 'logo': 'https://github.com/user-attachments/assets/4e92bace-d7a9-45ea-92be-122168dc87e4',
134
- 'api': {
135
- 'public': 'https://api.{hostname}',
136
- 'private': 'https://api.{hostname}',
137
- },
138
- 'test': {
139
- 'public': 'https://api.testnet.{hostname}',
140
- 'private': 'https://api.testnet.{hostname}',
141
- },
142
- 'www': 'https://defx.com/home',
143
- 'doc': [
144
- 'https://docs.defx.com/docs',
145
- 'https://api-docs.defx.com/',
146
- ],
147
- 'fees': [
148
- '',
149
- ],
150
- 'referral': {
151
- 'url': 'https://app.defx.com/join/6I2CZ7',
152
- },
153
- },
154
- 'api': {
155
- 'v1': {
156
- 'public': {
157
- 'get': {
158
- 'healthcheck/ping': 1,
159
- 'symbols/{symbol}/ohlc': 1,
160
- 'symbols/{symbol}/trades': 1,
161
- 'symbols/{symbol}/prices': 1,
162
- 'symbols/{symbol}/ticker/24hr': 1,
163
- 'symbols/{symbol}/depth/{level}/{slab}': 1,
164
- 'ticker/24HrAgg': 1,
165
- 'c/markets': 1,
166
- 'c/markets/metadata': 1,
167
- 'analytics/market/stats/newUsers': 1,
168
- 'analytics/market/stats/tvl': 1,
169
- 'analytics/market/stats/volumeByInstrument': 1,
170
- 'analytics/market/stats/liquidation': 1,
171
- 'analytics/market/stats/totalVolume': 1,
172
- 'analytics/market/stats/openInterest': 1,
173
- 'analytics/market/stats/totalTrades': 1,
174
- 'analytics/market/stats/basis': 1,
175
- 'analytics/market/stats/insuranceFund': 1,
176
- 'analytics/market/stats/longAndShortRatio': 1,
177
- 'analytics/market/stats/fundingRate': 1,
178
- 'analytics/market/overview': 1,
179
- 'explorer/search': 1,
180
- 'explorer/transactions': 1,
181
- 'explorer/blocks': 1,
182
- },
183
- },
184
- 'private': {
185
- 'get': {
186
- 'api/order/{orderId}': 1,
187
- 'api/orders': 1,
188
- 'api/orders/oco/{parentOrderId}': 1,
189
- 'api/trades': 1,
190
- 'api/position/active': 1,
191
- 'api/users/metadata/leverage': 1,
192
- 'api/users/metadata/feeMultiplier': 1,
193
- 'api/users/metadata/slippage': 1,
194
- 'api/users/referral': 1,
195
- 'api/users/apikeys': 1,
196
- 'connection-signature-message/evm': 1,
197
- 'api/users/profile/wallets': 1,
198
- 'api/notifications': 1,
199
- 'api/wallet/balance': 1,
200
- 'api/wallet/transactions': 1,
201
- 'api/analytics/user/overview': 1,
202
- 'api/analytics/user/pnl': 1,
203
- 'api/analytics/points/overview': 1,
204
- 'api/analytics/points/history': 1,
205
- },
206
- 'post': {
207
- 'api/order': 1,
208
- 'api/position/oco': 1,
209
- 'api/users/socket/listenKeys': 1,
210
- 'api/users/metadata/leverage': 1,
211
- 'api/users/metadata/feeMultiplier': 1,
212
- 'api/users/metadata/slippage': 1,
213
- 'api/users/referral/recordReferralSignup': 1,
214
- 'api/users/apikeys': 1,
215
- 'api/users/profile/wallets': 1,
216
- 'api/transfers/withdrawal': 1,
217
- 'api/transfers/bridge/withdrawal': 1,
218
- },
219
- 'put': {
220
- 'api/position/updatePositionMargin': 1,
221
- 'api/users/socket/listenKeys/{listenKey}': 1,
222
- 'api/users/apikeys/{accessKey}/status': 1,
223
- 'api/users/referral': 1,
224
- },
225
- 'patch': {
226
- 'api/users/apikeys/{accessKey}': 1,
227
- },
228
- 'delete': {
229
- 'api/orders/allOpen': 1,
230
- 'api/order/{orderId}': 1,
231
- 'api/position/{positionId}': 1,
232
- 'api/position/all': 1,
233
- 'api/users/socket/listenKeys/{listenKey}': 1,
234
- 'api/users/apikeys/{accessKey}': 1,
235
- },
236
- },
237
- },
238
- },
239
- 'fees': {
240
- 'trading': {
241
- 'tierBased': true,
242
- 'percentage': true,
243
- 'maker': this.parseNumber('0.0002'),
244
- 'taker': this.parseNumber('0.0005'),
245
- },
246
- },
247
- 'options': {
248
- 'sandboxMode': false,
249
- },
250
- 'features': {
251
- 'spot': undefined,
252
- 'forDerivatives': {
253
- 'sandbox': true,
254
- 'createOrder': {
255
- 'marginMode': false,
256
- 'triggerPrice': true,
257
- // todo implement
258
- 'triggerPriceType': {
259
- 'last': true,
260
- 'mark': true,
261
- 'index': false,
262
- },
263
- 'triggerDirection': false,
264
- 'stopLossPrice': false,
265
- 'takeProfitPrice': false,
266
- 'attachedStopLossTakeProfit': undefined,
267
- 'timeInForce': {
268
- 'IOC': true,
269
- 'FOK': true,
270
- 'PO': true,
271
- 'GTD': false,
272
- },
273
- 'hedged': false,
274
- 'selfTradePrevention': false,
275
- 'trailing': false,
276
- 'iceberg': false,
277
- 'leverage': false,
278
- 'marketBuyByCost': false,
279
- 'marketBuyRequiresPrice': false,
280
- },
281
- 'createOrders': undefined,
282
- 'fetchMyTrades': {
283
- 'marginMode': false,
284
- 'limit': 1000,
285
- 'daysBack': undefined,
286
- 'untilDays': undefined,
287
- 'symbolRequired': false,
288
- },
289
- 'fetchOrder': {
290
- 'marginMode': false,
291
- 'trigger': false,
292
- 'trailing': false,
293
- 'symbolRequired': false,
294
- },
295
- 'fetchOpenOrders': {
296
- 'marginMode': true,
297
- 'limit': 100,
298
- 'trigger': false,
299
- 'trailing': false,
300
- 'symbolRequired': false,
301
- },
302
- 'fetchOrders': {
303
- 'marginMode': false,
304
- 'limit': 500,
305
- 'daysBack': 100000,
306
- 'untilDays': 100000,
307
- 'trigger': false,
308
- 'trailing': false,
309
- 'symbolRequired': false,
310
- },
311
- 'fetchClosedOrders': {
312
- 'marginMode': false,
313
- 'limit': 500,
314
- 'daysBack': 100000,
315
- 'daysBackCanceled': 1,
316
- 'untilDays': 100000,
317
- 'trigger': false,
318
- 'trailing': false,
319
- 'symbolRequired': false,
320
- },
321
- 'fetchOHLCV': {
322
- 'limit': 1000,
323
- },
324
- },
325
- 'swap': {
326
- 'linear': {
327
- 'extends': 'forDerivatives',
328
- },
329
- 'inverse': undefined,
330
- },
331
- 'future': {
332
- 'linear': undefined,
333
- 'inverse': undefined,
334
- },
335
- },
336
- 'commonCurrencies': {},
337
- 'exceptions': {
338
- 'exact': {
339
- '404': BadRequest,
340
- 'missing_auth_signature': AuthenticationError,
341
- 'leverage_higher_than_capped_leverage': BadRequest,
342
- 'order_rejected': InvalidOrder,
343
- 'invalid_order_id': InvalidOrder,
344
- 'filter_lotsize_maxqty': InvalidOrder,
345
- 'filter_notional_min': InvalidOrder,
346
- 'failed_index_price_up_multiplier_filter': InvalidOrder,
347
- 'no_open_orders': InvalidOrder,
348
- 'active_position_not_found': InvalidOrder,
349
- 'position_inactive': InvalidOrder,
350
- 'invalid_position_id': InvalidOrder,
351
- 'Internal server error': ExchangeError, // {"msg":"Internal server error","code":"internal_server_error"}
352
- },
353
- 'broad': {
354
- 'Bad Request': BadRequest, // {"errorMessage":"Bad Request","data":[{"param":"symbol","message":"\"symbol\" must be one of [ETH_USDC, BTC_USDC, BNB_USDC, SOL_USDC, DOGE_USDC, TON_USDC, AVAX_USDC, WIF_USDC, KPEPE_USDC, KSHIB_USDC, KBONK_USDC, MOODENG_USDC, POPCAT_USDC, MOTHER_USDC]"}]}
355
- },
356
- },
357
- 'precisionMode': TICK_SIZE,
358
- });
359
- }
360
- /**
361
- * @method
362
- * @name defx#fetchStatus
363
- * @description the latest known information on the availability of the exchange API
364
- * @see https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6
365
- * @param {object} [params] extra parameters specific to the exchange API endpoint
366
- * @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
367
- */
368
- async fetchStatus(params = {}) {
369
- const response = await this.v1PublicGetHealthcheckPing(params);
370
- //
371
- // {
372
- // "success": true,
373
- // "t": 1709705048323,
374
- // "v": "0.0.7",
375
- // "msg": "A programmer’s wife tells him, “While you’re at the grocery store, buy some eggs.” He never comes back."
376
- // }
377
- //
378
- let status = undefined;
379
- const success = this.safeBool(response, 'success');
380
- if (success) {
381
- status = 'ok';
382
- }
383
- else {
384
- status = 'error';
385
- }
386
- return {
387
- 'status': status,
388
- 'updated': undefined,
389
- 'eta': undefined,
390
- 'url': undefined,
391
- 'info': response,
392
- };
393
- }
394
- /**
395
- * @method
396
- * @name defx#fetchTime
397
- * @description fetches the current integer timestamp in milliseconds from the exchange server
398
- * @see https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6
399
- * @param {object} [params] extra parameters specific to the exchange API endpoint
400
- * @returns {int} the current integer timestamp in milliseconds from the exchange server
401
- */
402
- async fetchTime(params = {}) {
403
- const response = await this.v1PublicGetHealthcheckPing(params);
404
- //
405
- // {
406
- // "success": true,
407
- // "t": 1709705048323,
408
- // "v": "0.0.7",
409
- // "msg": "A programmer’s wife tells him, “While you’re at the grocery store, buy some eggs.” He never comes back."
410
- // }
411
- //
412
- return this.safeInteger(response, 't');
413
- }
414
- /**
415
- * @method
416
- * @name defx#fetchMarkets
417
- * @description retrieves data on all markets for defx
418
- * @see https://api-docs.defx.com/#73cce0c8-f842-4891-9145-01bb6d61324d
419
- * @see https://api-docs.defx.com/#24fd4e5b-840e-451e-99e0-7fea47c7f371
420
- * @param {object} [params] extra parameters specific to the exchange API endpoint
421
- * @returns {object[]} an array of objects representing market data
422
- */
423
- async fetchMarkets(params = {}) {
424
- const request = {
425
- 'type': 'perps',
426
- };
427
- const promises = [
428
- this.v1PublicGetCMarkets(this.extend(request, params)),
429
- this.v1PublicGetCMarketsMetadata(this.extend(request, params)),
430
- ];
431
- const responses = await Promise.all(promises);
432
- //
433
- // {
434
- // "data": [
435
- // {
436
- // "market": "DOGE_USDC",
437
- // "candleWindows": [
438
- // "1m",
439
- // "3m",
440
- // "5m",
441
- // "15m",
442
- // "30m",
443
- // "1h",
444
- // "2h",
445
- // "4h",
446
- // "12h",
447
- // "1d",
448
- // "1w",
449
- // "1M"
450
- // ],
451
- // "depthSlabs": [
452
- // "0.00001",
453
- // "0.00005",
454
- // "0.0001",
455
- // "0.001",
456
- // "0.01"
457
- // ],
458
- // "filters": [
459
- // {
460
- // "filterType": "LOT_SIZE",
461
- // "minQty": "1.00000",
462
- // "maxQty": "1500000.00000",
463
- // "stepSize": "1.00000"
464
- // },
465
- // {
466
- // "filterType": "MARKET_LOT_SIZE",
467
- // "minQty": "1.00000",
468
- // "maxQty": "750000.00000",
469
- // "stepSize": "1.00000"
470
- // },
471
- // {
472
- // "filterType": "PRICE_FILTER",
473
- // "minPrice": "0.00244000",
474
- // "maxPrice": "30.00000000",
475
- // "tickSize": "0.00001"
476
- // },
477
- // {
478
- // "filterType": "NOTIONAL",
479
- // "minNotional": "100.00000000"
480
- // },
481
- // {
482
- // "filterType": "PERCENT_PRICE_BY_SIDE",
483
- // "bidMultiplierUp": "1.5",
484
- // "bidMultiplierDown": "0.5",
485
- // "askMultiplierUp": "1.5",
486
- // "askMultiplierDown": "0.5"
487
- // },
488
- // {
489
- // "filterType": "INDEX_PRICE_FILTER",
490
- // "multiplierUp": "1.3",
491
- // "multiplierDown": "0.7"
492
- // }
493
- // ],
494
- // "cappedLeverage": "25",
495
- // "maintenanceMarginTiers": [
496
- // {
497
- // "tier": "1",
498
- // "minMaintenanceMargin": "0",
499
- // "maxMaintenanceMargin": "2500",
500
- // "leverage": "25"
501
- // },
502
- // {
503
- // "tier": "2",
504
- // "minMaintenanceMargin": "2500",
505
- // "maxMaintenanceMargin": "12500",
506
- // "leverage": "20"
507
- // },
508
- // {
509
- // "tier": "3",
510
- // "minMaintenanceMargin": "12500",
511
- // "maxMaintenanceMargin": "25000",
512
- // "leverage": "15"
513
- // },
514
- // {
515
- // "tier": "4",
516
- // "minMaintenanceMargin": "25000",
517
- // "maxMaintenanceMargin": "50000",
518
- // "leverage": "10"
519
- // },
520
- // {
521
- // "tier": "5",
522
- // "minMaintenanceMargin": "50000",
523
- // "maxMaintenanceMargin": "75000",
524
- // "leverage": "8"
525
- // },
526
- // {
527
- // "tier": "6",
528
- // "minMaintenanceMargin": "75000",
529
- // "maxMaintenanceMargin": "125000",
530
- // "leverage": "7"
531
- // },
532
- // {
533
- // "tier": "7",
534
- // "minMaintenanceMargin": "125000",
535
- // "maxMaintenanceMargin": "187500",
536
- // "leverage": "5"
537
- // },
538
- // {
539
- // "tier": "8",
540
- // "minMaintenanceMargin": "187500",
541
- // "maxMaintenanceMargin": "250000",
542
- // "leverage": "3"
543
- // },
544
- // {
545
- // "tier": "9",
546
- // "minMaintenanceMargin": "250000",
547
- // "maxMaintenanceMargin": "375000",
548
- // "leverage": "2"
549
- // },
550
- // {
551
- // "tier": "10",
552
- // "minMaintenanceMargin": "375000",
553
- // "maxMaintenanceMargin": "500000",
554
- // "leverage": "1"
555
- // }
556
- // ],
557
- // "fees": {
558
- // "maker": "0.08",
559
- // "taker": "0.1"
560
- // }
561
- // },
562
- // ]
563
- // }
564
- //
565
- const activeMarkets = this.safeList(responses[0], 'data');
566
- const activeMarketsByType = this.indexBy(activeMarkets, 'market');
567
- const marketMetadatas = this.safeList(responses[1], 'data');
568
- for (let i = 0; i < marketMetadatas.length; i++) {
569
- const marketId = marketMetadatas[i]['market'];
570
- let status = undefined;
571
- if (marketId in activeMarketsByType) {
572
- status = activeMarketsByType[marketId]['status'];
573
- }
574
- marketMetadatas[i]['status'] = status;
575
- }
576
- return this.parseMarkets(marketMetadatas);
577
- }
578
- parseMarket(market) {
579
- const marketId = this.safeString(market, 'market');
580
- const parts = marketId.split('_');
581
- const baseId = this.safeString(parts, 0);
582
- const quoteId = this.safeString(parts, 1);
583
- const base = this.safeCurrencyCode(baseId);
584
- const quote = this.safeCurrencyCode(quoteId);
585
- const symbol = base + '/' + quote + ':' + quote;
586
- const filters = this.safeList(market, 'filters', []);
587
- const fees = this.safeDict(market, 'fees', {});
588
- const filtersByType = this.indexBy(filters, 'filterType');
589
- const priceFilter = this.safeDict(filtersByType, 'PRICE_FILTER', {});
590
- const lotFilter = this.safeDict(filtersByType, 'LOT_SIZE', {});
591
- const marketLotFilter = this.safeDict(filtersByType, 'MARKET_LOT_SIZE', {});
592
- const notionalFilter = this.safeDict(filtersByType, 'NOTIONAL', {});
593
- return {
594
- 'id': marketId,
595
- 'symbol': symbol,
596
- 'base': base,
597
- 'quote': quote,
598
- 'settle': quote,
599
- 'baseId': baseId,
600
- 'quoteId': quoteId,
601
- 'settleId': quoteId,
602
- 'type': 'swap',
603
- 'spot': false,
604
- 'margin': false,
605
- 'swap': true,
606
- 'future': false,
607
- 'option': false,
608
- 'active': this.safeString(market, 'status', '') === 'active',
609
- 'contract': true,
610
- 'linear': true,
611
- 'inverse': false,
612
- 'taker': this.safeNumber(fees, 'taker'),
613
- 'maker': this.safeNumber(fees, 'maker'),
614
- 'contractSize': this.parseNumber('1'),
615
- 'expiry': undefined,
616
- 'expiryDatetime': undefined,
617
- 'strike': undefined,
618
- 'optionType': undefined,
619
- 'precision': {
620
- 'amount': this.safeNumber(lotFilter, 'stepSize'),
621
- 'price': this.safeNumber(priceFilter, 'tickSize'),
622
- },
623
- 'limits': {
624
- 'leverage': {
625
- 'min': undefined,
626
- 'max': this.safeNumber(market, 'cappedLeverage'),
627
- },
628
- 'amount': {
629
- 'min': this.safeNumber(lotFilter, 'minQty'),
630
- 'max': this.safeNumber(lotFilter, 'maxQty'),
631
- },
632
- 'price': {
633
- 'min': this.safeNumber(priceFilter, 'minPrice'),
634
- 'max': this.safeNumber(priceFilter, 'maxPrice'),
635
- },
636
- 'cost': {
637
- 'min': this.safeNumber(notionalFilter, 'minNotional'),
638
- 'max': undefined,
639
- },
640
- 'market': {
641
- 'min': this.safeNumber(marketLotFilter, 'minQty'),
642
- 'max': this.safeNumber(marketLotFilter, 'maxQty'),
643
- },
644
- },
645
- 'created': undefined,
646
- 'info': market,
647
- };
648
- }
649
- /**
650
- * @method
651
- * @name defx#fetchTicker
652
- * @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
653
- * @see https://api-docs.defx.com/#fe6f81d0-2f3a-4eee-976f-c8fc8f4c5d56
654
- * @param {string} symbol unified symbol of the market to fetch the ticker for
655
- * @param {object} [params] extra parameters specific to the exchange API endpoint
656
- * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
657
- */
658
- async fetchTicker(symbol, params = {}) {
659
- await this.loadMarkets();
660
- const market = this.market(symbol);
661
- const request = {
662
- 'symbol': market['id'],
663
- };
664
- const response = await this.v1PublicGetSymbolsSymbolTicker24hr(this.extend(request, params));
665
- //
666
- // {
667
- // "symbol": "BTC_USDC",
668
- // "priceChange": "0",
669
- // "priceChangePercent": "0",
670
- // "weightedAvgPrice": "0",
671
- // "lastPrice": "2.00",
672
- // "lastQty": "10.000",
673
- // "bestBidPrice": "1646.00",
674
- // "bestBidQty": "10.000",
675
- // "bestAskPrice": "1646.00",
676
- // "bestAskQty": "10.000",
677
- // "openPrice": "0.00",
678
- // "highPrice": "0.00",
679
- // "lowPrice": "0.00",
680
- // "volume": "0.000",
681
- // "quoteVolume": "0.00",
682
- // "openTime": 1700142658697,
683
- // "closeTime": 1700142658697,
684
- // "openInterestBase": "1.000",
685
- // "openInterestQuote": "0.43112300"
686
- // }
687
- //
688
- return this.parseTicker(response, market);
689
- }
690
- /**
691
- * @method
692
- * @name defx#fetchTickers
693
- * @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
694
- * @see https://api-docs.defx.com/#8c61cfbd-40d9-410e-b014-f5b36eba51d1
695
- * @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
696
- * @param {object} [params] extra parameters specific to the exchange API endpoint
697
- * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
698
- */
699
- async fetchTickers(symbols = undefined, params = {}) {
700
- await this.loadMarkets();
701
- let market = undefined;
702
- if (symbols !== undefined) {
703
- symbols = this.marketSymbols(symbols);
704
- const firstSymbol = this.safeString(symbols, 0);
705
- if (firstSymbol !== undefined) {
706
- market = this.market(firstSymbol);
707
- }
708
- }
709
- let type = undefined;
710
- [type, params] = this.handleMarketTypeAndParams('fetchTickers', market, params);
711
- if (type === 'spot') {
712
- throw new NotSupported(this.id + ' fetchTickers() is not supported for ' + type + ' markets');
713
- }
714
- const response = await this.v1PublicGetTicker24HrAgg(params);
715
- //
716
- // {
717
- // "ETH_USDC": {
718
- // "priceChange": "0",
719
- // "priceChangePercent": "0",
720
- // "openPrice": "1646.15",
721
- // "highPrice": "1646.15",
722
- // "lowPrice": "1646.15",
723
- // "lastPrice": "1646.15",
724
- // "quoteVolume": "13.17",
725
- // "volume": "0.008",
726
- // "markPrice": "1645.15"
727
- // }
728
- // }
729
- //
730
- return this.parseTickers(response, symbols);
731
- }
732
- parseTicker(ticker, market = undefined) {
733
- //
734
- // fetchTicker
735
- //
736
- // {
737
- // "symbol": "BTC_USDC",
738
- // "priceChange": "0",
739
- // "priceChangePercent": "0",
740
- // "weightedAvgPrice": "0",
741
- // "lastPrice": "2.00",
742
- // "lastQty": "10.000",
743
- // "bestBidPrice": "1646.00",
744
- // "bestBidQty": "10.000",
745
- // "bestAskPrice": "1646.00",
746
- // "bestAskQty": "10.000",
747
- // "openPrice": "0.00",
748
- // "highPrice": "0.00",
749
- // "lowPrice": "0.00",
750
- // "volume": "0.000",
751
- // "quoteVolume": "0.00",
752
- // "openTime": 1700142658697,
753
- // "closeTime": 1700142658697,
754
- // "openInterestBase": "1.000",
755
- // "openInterestQuote": "0.43112300"
756
- // }
757
- //
758
- // fetchTickers
759
- //
760
- // "ETH_USDC": {
761
- // "priceChange": "0",
762
- // "priceChangePercent": "0",
763
- // "openPrice": "1646.15",
764
- // "highPrice": "1646.15",
765
- // "lowPrice": "1646.15",
766
- // "lastPrice": "1646.15",
767
- // "quoteVolume": "13.17",
768
- // "volume": "0.008",
769
- // "markPrice": "1645.15"
770
- // }
771
- //
772
- // fetchMarkPrice
773
- //
774
- // {
775
- // "markPrice": "100.00",
776
- // "indexPrice": "100.00",
777
- // "ltp": "101.34",
778
- // "movingFundingRate": "0.08",
779
- // "payoutFundingRate": "-0.03",
780
- // "nextFundingPayout": 1711555532146
781
- // }
782
- //
783
- const marketId = this.safeString(ticker, 'symbol');
784
- if (marketId !== undefined) {
785
- market = this.market(marketId);
786
- }
787
- const symbol = market['symbol'];
788
- const open = this.safeString(ticker, 'openPrice');
789
- const high = this.safeString(ticker, 'highPrice');
790
- const low = this.safeString(ticker, 'lowPrice');
791
- const close = this.safeString(ticker, 'lastPrice');
792
- const quoteVolume = this.safeString(ticker, 'quoteVolume');
793
- const baseVolume = this.safeString(ticker, 'volume');
794
- const percentage = this.safeString(ticker, 'priceChangePercent');
795
- const change = this.safeString(ticker, 'priceChange');
796
- let ts = this.safeInteger(ticker, 'closeTime');
797
- if (ts === 0) {
798
- ts = undefined;
799
- }
800
- const datetime = this.iso8601(ts);
801
- const bid = this.safeString(ticker, 'bestBidPrice');
802
- const bidVolume = this.safeString(ticker, 'bestBidQty');
803
- const ask = this.safeString(ticker, 'bestAskPrice');
804
- const askVolume = this.safeString(ticker, 'bestAskQty');
805
- return this.safeTicker({
806
- 'symbol': symbol,
807
- 'timestamp': ts,
808
- 'datetime': datetime,
809
- 'high': high,
810
- 'low': low,
811
- 'bid': bid,
812
- 'bidVolume': bidVolume,
813
- 'ask': ask,
814
- 'askVolume': askVolume,
815
- 'vwap': undefined,
816
- 'open': open,
817
- 'close': close,
818
- 'last': undefined,
819
- 'previousClose': undefined,
820
- 'change': change,
821
- 'percentage': percentage,
822
- 'average': undefined,
823
- 'baseVolume': baseVolume,
824
- 'quoteVolume': quoteVolume,
825
- 'markPrice': this.safeString(ticker, 'markPrice'),
826
- 'indexPrice': this.safeString(ticker, 'indexPrice'),
827
- 'info': ticker,
828
- }, market);
829
- }
830
- /**
831
- * @method
832
- * @name defx#fetchOHLCV
833
- * @see https://api-docs.defx.com/#54b71951-1472-4670-b5af-4c2dc41e73d0
834
- * @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
835
- * @param {string} symbol unified symbol of the market to fetch OHLCV data for
836
- * @param {string} timeframe the length of time each candle represents
837
- * @param {int} [since] timestamp in ms of the earliest candle to fetch
838
- * @param {int} [limit] max=1000, max=100 when since is defined and is less than (now - (999 * (timeframe in ms)))
839
- * @param {object} [params] extra parameters specific to the exchange API endpoint
840
- * @param {int} [params.until] the latest time in ms to fetch orders for
841
- * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
842
- */
843
- async fetchOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
844
- await this.loadMarkets();
845
- const market = this.market(symbol);
846
- const maxLimit = 1000;
847
- if (limit === undefined) {
848
- limit = maxLimit;
849
- }
850
- limit = Math.min(maxLimit, limit);
851
- const request = {
852
- 'symbol': market['id'],
853
- 'interval': this.safeString(this.timeframes, timeframe, timeframe),
854
- 'limit': limit,
855
- };
856
- const until = this.safeInteger2(params, 'until', 'till');
857
- params = this.omit(params, ['until', 'till']);
858
- request['endTime'] = (until === undefined) ? this.milliseconds() : until;
859
- if (since === undefined) {
860
- request['startTime'] = 0;
861
- }
862
- else {
863
- request['startTime'] = since;
864
- if (until === undefined) {
865
- const timeframeInSeconds = this.parseTimeframe(timeframe);
866
- const timeframeInMilliseconds = timeframeInSeconds * 1000;
867
- const totalTimeframeInMilliseconds = limit * timeframeInMilliseconds;
868
- request['endTime'] = this.sum(since, totalTimeframeInMilliseconds);
869
- }
870
- }
871
- const response = await this.v1PublicGetSymbolsSymbolOhlc(this.extend(request, params));
872
- //
873
- // [
874
- // {
875
- // "symbol": "BTC_USDC",
876
- // "open": "0.00",
877
- // "high": "0.00",
878
- // "low": "0.00",
879
- // "close": "0.00",
880
- // "volume": "0.000",
881
- // "quoteAssetVolume": "0.00",
882
- // "takerBuyAssetVolume": "0.000",
883
- // "takerBuyQuoteAssetVolume": "0.00",
884
- // "numberOfTrades": 0,
885
- // "start": 1702453663894,
886
- // "end": 1702453663894,
887
- // "isClosed": true
888
- // }
889
- // ]
890
- //
891
- return this.parseOHLCVs(response, market, timeframe, since, limit);
892
- }
893
- parseOHLCV(ohlcv, market = undefined) {
894
- // example response in fetchOHLCV
895
- return [
896
- this.safeInteger(ohlcv, 'start'),
897
- this.safeNumber(ohlcv, 'open'),
898
- this.safeNumber(ohlcv, 'high'),
899
- this.safeNumber(ohlcv, 'low'),
900
- this.safeNumber(ohlcv, 'close'),
901
- this.safeNumber(ohlcv, 'volume'),
902
- ];
903
- }
904
- /**
905
- * @method
906
- * @name defx#fetchTrades
907
- * @description get the list of most recent trades for a particular symbol
908
- * @see https://api-docs.defx.com/#5865452f-ea32-4f13-bfbc-03af5f5574fd
909
- * @param {string} symbol unified symbol of the market to fetch trades for
910
- * @param {int} [since] timestamp in ms of the earliest trade to fetch
911
- * @param {int} [limit] the maximum amount of trades to fetch
912
- * @param {object} [params] extra parameters specific to the exchange API endpoint
913
- * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
914
- */
915
- async fetchTrades(symbol, since = undefined, limit = undefined, params = {}) {
916
- await this.loadMarkets();
917
- const market = this.market(symbol);
918
- const maxLimit = 50;
919
- if (limit === undefined) {
920
- limit = maxLimit;
921
- }
922
- limit = Math.min(maxLimit, limit);
923
- const request = {
924
- 'symbol': market['id'],
925
- 'limit': limit,
926
- };
927
- const response = await this.v1PublicGetSymbolsSymbolTrades(this.extend(request, params));
928
- //
929
- // [
930
- // {
931
- // "buyerMaker": "false",
932
- // "price": "2.0000",
933
- // "qty": "10.0000",
934
- // "symbol": "BTC_USDC",
935
- // "timestamp": "1702453663894"
936
- // }
937
- // ]
938
- //
939
- return this.parseTrades(response, market, since, limit);
940
- }
941
- /**
942
- * @method
943
- * @name defx#fetchMyTrades
944
- * @description fetch all trades made by the user
945
- * @see https://api-docs.defx.com/#06b5b33c-2fc6-48de-896c-fc316f5871a7
946
- * @param {string} symbol unified symbol of the market to fetch trades for
947
- * @param {int} [since] timestamp in ms of the earliest trade to fetch
948
- * @param {int} [limit] the maximum amount of trades to fetch
949
- * @param {object} [params] extra parameters specific to the exchange API endpoint
950
- * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
951
- */
952
- async fetchMyTrades(symbol = undefined, since = undefined, limit = undefined, params = {}) {
953
- await this.loadMarkets();
954
- const request = {};
955
- if (symbol !== undefined) {
956
- const market = this.market(symbol);
957
- request['symbols'] = market['id'];
958
- }
959
- if (limit !== undefined) {
960
- const maxLimit = 100;
961
- limit = Math.min(maxLimit, limit);
962
- request['pageSize'] = limit;
963
- }
964
- const response = await this.v1PrivateGetApiTrades(this.extend(request, params));
965
- //
966
- // {
967
- // "data": [
968
- // {
969
- // "id": "0192f665-c05b-7ba0-a080-8b6c99083489",
970
- // "orderId": "757730811259651728",
971
- // "time": "2024-11-04T08:58:36.474Z",
972
- // "symbol": "SOL_USDC",
973
- // "side": "SELL",
974
- // "price": "160.43600000",
975
- // "qty": "1.00",
976
- // "fee": "0.08823980",
977
- // "role": "TAKER",
978
- // "pnl": "0.00000000"
979
- // }
980
- // ]
981
- // }
982
- //
983
- const data = this.safeList(response, 'data', []);
984
- return this.parseTrades(data, undefined, since, limit);
985
- }
986
- parseTrade(trade, market = undefined) {
987
- //
988
- // fetchTrades
989
- // {
990
- // "buyerMaker": "false",
991
- // "price": "2.0000",
992
- // "qty": "10.0000",
993
- // "symbol": "BTC_USDC",
994
- // "timestamp": "1702453663894"
995
- // }
996
- //
997
- // fetchMyTrades
998
- // {
999
- // "id": "0192f665-c05b-7ba0-a080-8b6c99083489",
1000
- // "orderId": "757730811259651728",
1001
- // "time": "2024-11-04T08:58:36.474Z",
1002
- // "symbol": "SOL_USDC",
1003
- // "side": "SELL",
1004
- // "price": "160.43600000",
1005
- // "qty": "1.00",
1006
- // "fee": "0.08823980",
1007
- // "role": "TAKER",
1008
- // "pnl": "0.00000000"
1009
- // }
1010
- //
1011
- const time = this.safeString(trade, 'time');
1012
- const timestamp = this.safeInteger(trade, 'timestamp', this.parse8601(time));
1013
- const marketId = this.safeString(trade, 'symbol');
1014
- market = this.safeMarket(marketId, market);
1015
- const symbol = market['symbol'];
1016
- const price = this.safeString(trade, 'price');
1017
- const amount = this.safeString(trade, 'qty');
1018
- const id = this.safeString(trade, 'id');
1019
- const oid = this.safeString(trade, 'orderId');
1020
- const takerOrMaker = this.safeStringLower(trade, 'role');
1021
- const buyerMaker = this.safeBool(trade, 'buyerMaker');
1022
- let side = this.safeStringLower(trade, 'side');
1023
- if (buyerMaker !== undefined) {
1024
- if (buyerMaker) {
1025
- side = 'sell';
1026
- }
1027
- else {
1028
- side = 'buy';
1029
- }
1030
- }
1031
- return this.safeTrade({
1032
- 'id': id,
1033
- 'timestamp': timestamp,
1034
- 'datetime': this.iso8601(timestamp),
1035
- 'symbol': symbol,
1036
- 'side': side,
1037
- 'price': price,
1038
- 'amount': amount,
1039
- 'cost': undefined,
1040
- 'order': oid,
1041
- 'takerOrMaker': takerOrMaker,
1042
- 'type': undefined,
1043
- 'fee': {
1044
- 'cost': this.safeString(trade, 'fee'),
1045
- 'currency': 'USDC',
1046
- },
1047
- 'info': trade,
1048
- }, market);
1049
- }
1050
- /**
1051
- * @method
1052
- * @name defx#fetchOrderBook
1053
- * @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
1054
- * @see https://api-docs.defx.com/#6c1a2971-8325-4e7d-9962-e0bfcaacf9c4
1055
- * @param {string} symbol unified symbol of the market to fetch the order book for
1056
- * @param {int} [limit] the maximum amount of order book entries to return
1057
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1058
- * @param {string} [params.slab] slab from market.info.depthSlabs
1059
- * @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure} indexed by market symbols
1060
- */
1061
- async fetchOrderBook(symbol, limit = undefined, params = {}) {
1062
- await this.loadMarkets();
1063
- const market = this.market(symbol);
1064
- if (limit === undefined) {
1065
- limit = 10; // limit must be one of [5, 10, 20]
1066
- }
1067
- const marketInfo = this.safeDict(market, 'info', {});
1068
- const slab = this.safeList(marketInfo, 'depthSlabs', []);
1069
- const request = {
1070
- 'symbol': market['id'],
1071
- 'level': limit,
1072
- 'slab': this.safeString(slab, 0),
1073
- };
1074
- const response = await this.v1PublicGetSymbolsSymbolDepthLevelSlab(this.extend(request, params));
1075
- //
1076
- // {
1077
- // "symbol": "ETH_USDC",
1078
- // "level": "5",
1079
- // "slab": "1",
1080
- // "lastTradeTimestamp": "1708313446812",
1081
- // "timestamp": "1708313446812",
1082
- // "bids": [
1083
- // {
1084
- // "price": "1646.16",
1085
- // "qty": "0.001"
1086
- // }
1087
- // ],
1088
- // "asks": [
1089
- // {
1090
- // "price": "1646.16",
1091
- // "qty": "0.001"
1092
- // }
1093
- // ]
1094
- // }
1095
- //
1096
- const timestamp = this.safeInteger(response, 'timestamp');
1097
- return this.parseOrderBook(response, symbol, timestamp, 'bids', 'asks', 'price', 'qty');
1098
- }
1099
- /**
1100
- * @method
1101
- * @name defx#fetchMarkPrice
1102
- * @description fetches mark price for the market
1103
- * @see https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7
1104
- * @param {string} symbol unified symbol of the market to fetch the ticker for
1105
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1106
- * @param {string} [params.subType] "linear" or "inverse"
1107
- * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
1108
- */
1109
- async fetchMarkPrice(symbol, params = {}) {
1110
- await this.loadMarkets();
1111
- const market = this.market(symbol);
1112
- const request = {
1113
- 'symbol': market['id'],
1114
- };
1115
- const response = await this.v1PublicGetSymbolsSymbolPrices(this.extend(request, params));
1116
- //
1117
- // {
1118
- // "markPrice": "100.00",
1119
- // "indexPrice": "100.00",
1120
- // "ltp": "101.34",
1121
- // "movingFundingRate": "0.08",
1122
- // "payoutFundingRate": "-0.03",
1123
- // "nextFundingPayout": 1711555532146
1124
- // }
1125
- //
1126
- return this.parseTicker(response, market);
1127
- }
1128
- /**
1129
- * @method
1130
- * @name defx#fetchFundingRate
1131
- * @description fetch the current funding rate
1132
- * @see https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7
1133
- * @param {string} symbol unified market symbol
1134
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1135
- * @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
1136
- */
1137
- async fetchFundingRate(symbol, params = {}) {
1138
- await this.loadMarkets();
1139
- const market = this.market(symbol);
1140
- const request = {
1141
- 'symbol': market['id'],
1142
- };
1143
- const response = await this.v1PublicGetSymbolsSymbolPrices(this.extend(request, params));
1144
- //
1145
- // {
1146
- // "markPrice": "100.00",
1147
- // "indexPrice": "100.00",
1148
- // "ltp": "101.34",
1149
- // "movingFundingRate": "0.08",
1150
- // "payoutFundingRate": "-0.03",
1151
- // "nextFundingPayout": 1711555532146
1152
- // }
1153
- //
1154
- return this.parseFundingRate(response, market);
1155
- }
1156
- parseFundingRate(contract, market = undefined) {
1157
- //
1158
- // {
1159
- // "markPrice": "100.00",
1160
- // "indexPrice": "100.00",
1161
- // "ltp": "101.34",
1162
- // "movingFundingRate": "0.08",
1163
- // "payoutFundingRate": "-0.03",
1164
- // "nextFundingPayout": 1711555532146
1165
- // }
1166
- //
1167
- const markPrice = this.safeNumber(contract, 'markPrice');
1168
- const indexPrice = this.safeNumber(contract, 'indexPrice');
1169
- const fundingRateRaw = this.safeString(contract, 'payoutFundingRate');
1170
- const fundingRate = Precise.stringDiv(fundingRateRaw, '100');
1171
- const fundingTime = this.safeInteger(contract, 'nextFundingPayout');
1172
- return {
1173
- 'info': contract,
1174
- 'symbol': market['symbol'],
1175
- 'markPrice': markPrice,
1176
- 'indexPrice': indexPrice,
1177
- 'interestRate': undefined,
1178
- 'estimatedSettlePrice': undefined,
1179
- 'timestamp': undefined,
1180
- 'datetime': undefined,
1181
- 'fundingRate': this.parseNumber(fundingRate),
1182
- 'fundingTimestamp': fundingTime,
1183
- 'fundingDatetime': this.iso8601(fundingTime),
1184
- 'nextFundingRate': undefined,
1185
- 'nextFundingTimestamp': undefined,
1186
- 'nextFundingDatetime': undefined,
1187
- 'previousFundingRate': undefined,
1188
- 'previousFundingTimestamp': undefined,
1189
- 'previousFundingDatetime': undefined,
1190
- 'interval': undefined,
1191
- };
1192
- }
1193
- /**
1194
- * @method
1195
- * @name defx#fetchBalance
1196
- * @description query for balance and get the amount of funds available for trading or funds locked in orders
1197
- * @see https://api-docs.defx.com/#26414338-14f7-40a1-b246-f8ea8571493f
1198
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1199
- * @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
1200
- */
1201
- async fetchBalance(params = {}) {
1202
- await this.loadMarkets();
1203
- const response = await this.v1PrivateGetApiWalletBalance(params);
1204
- //
1205
- // {
1206
- // "assets": [
1207
- // {
1208
- // "asset": "USDC",
1209
- // "balance": "0.000"
1210
- // }
1211
- // ]
1212
- // }
1213
- //
1214
- const data = this.safeList(response, 'assets');
1215
- return this.parseBalance(data);
1216
- }
1217
- parseBalance(balances) {
1218
- const result = {
1219
- 'info': balances,
1220
- };
1221
- for (let i = 0; i < balances.length; i++) {
1222
- const balance = balances[i];
1223
- const code = this.safeCurrencyCode(this.safeString(balance, 'asset'));
1224
- const account = this.account();
1225
- account['total'] = this.safeString(balance, 'balance');
1226
- result[code] = account;
1227
- }
1228
- return this.safeBalance(result);
1229
- }
1230
- /**
1231
- * @method
1232
- * @name defx#createOrder
1233
- * @description create a trade order
1234
- * @see https://api-docs.defx.com/#ba222d88-8856-4d3c-87a9-7cec07bb2622
1235
- * @param {string} symbol unified symbol of the market to create an order in
1236
- * @param {string} type 'market' or 'limit'
1237
- * @param {string} side 'buy' or 'sell'
1238
- * @param {float} amount how much of currency you want to trade in units of base currency
1239
- * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1240
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1241
- * @param {float} [params.triggerPrice] The price a trigger order is triggered at
1242
- * @param {string} [params.reduceOnly] for swap and future reduceOnly is a string 'true' or 'false' that cant be sent with close position set to true or in hedge mode. For spot margin and option reduceOnly is a boolean.
1243
- * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
1244
- */
1245
- async createOrder(symbol, type, side, amount, price = undefined, params = {}) {
1246
- await this.loadMarkets();
1247
- const market = this.market(symbol);
1248
- const reduceOnly = this.safeBool2(params, 'reduceOnly', 'reduce_only');
1249
- params = this.omit(params, ['reduceOnly', 'reduce_only']);
1250
- const orderType = type.toUpperCase();
1251
- const orderSide = side.toUpperCase();
1252
- const request = {
1253
- 'symbol': market['id'],
1254
- 'side': orderSide,
1255
- 'type': orderType,
1256
- };
1257
- const takeProfitPrice = this.safeString(params, 'takeProfitPrice');
1258
- const triggerPrice = this.safeString2(params, 'stopPrice', 'triggerPrice');
1259
- const isMarket = orderType === 'MARKET';
1260
- const isLimit = orderType === 'LIMIT';
1261
- const timeInForce = this.safeStringUpper(params, 'timeInForce');
1262
- if (timeInForce !== undefined) {
1263
- // GTC, IOC, FOK, AON
1264
- request['timeInForce'] = timeInForce;
1265
- }
1266
- else {
1267
- if (isLimit) {
1268
- request['timeInForce'] = 'GTC';
1269
- }
1270
- }
1271
- if (reduceOnly) {
1272
- request['reduceOnly'] = reduceOnly;
1273
- }
1274
- const clientOrderId = this.safeString(params, 'clientOrderId');
1275
- if (clientOrderId !== undefined) {
1276
- request['newClientOrderId'] = clientOrderId;
1277
- }
1278
- if (triggerPrice !== undefined || takeProfitPrice !== undefined) {
1279
- request['workingType'] = 'MARK_PRICE';
1280
- if (takeProfitPrice !== undefined) {
1281
- request['stopPrice'] = this.priceToPrecision(symbol, takeProfitPrice);
1282
- if (isMarket) {
1283
- request['type'] = 'TAKE_PROFIT_MARKET';
1284
- }
1285
- else {
1286
- request['type'] = 'TAKE_PROFIT_LIMIT';
1287
- }
1288
- }
1289
- else {
1290
- request['stopPrice'] = this.priceToPrecision(symbol, triggerPrice);
1291
- if (isMarket) {
1292
- request['type'] = 'STOP_MARKET';
1293
- }
1294
- else {
1295
- request['type'] = 'STOP_LIMIT';
1296
- }
1297
- }
1298
- }
1299
- if (isLimit && price !== undefined) {
1300
- request['price'] = this.priceToPrecision(symbol, price);
1301
- }
1302
- request['quantity'] = this.amountToPrecision(symbol, amount);
1303
- params = this.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id', 'postOnly', 'timeInForce', 'stopPrice', 'triggerPrice', 'takeProfitPrice']);
1304
- const response = await this.v1PrivatePostApiOrder(this.extend(request, params));
1305
- //
1306
- // {
1307
- // "success": true,
1308
- // "data": {
1309
- // "orderId": "",
1310
- // "clientOrderId": "",
1311
- // "cumulativeQty": "",
1312
- // "cumulativeQuote": "",
1313
- // "executedQty": "",
1314
- // "avgPrice": "",
1315
- // "origQty": "",
1316
- // "price": "",
1317
- // "reduceOnly": true,
1318
- // "side": "",
1319
- // "status": "",
1320
- // "symbol": "",
1321
- // "timeInForce": "",
1322
- // "type": "",
1323
- // "workingType": ""
1324
- // }
1325
- // }
1326
- //
1327
- const data = this.safeDict(response, 'data');
1328
- return this.parseOrder(data, market);
1329
- }
1330
- parseOrderStatus(status) {
1331
- if (status !== undefined) {
1332
- const statuses = {
1333
- 'NEW': 'open',
1334
- 'OPEN': 'open',
1335
- 'CANCELLED': 'canceled',
1336
- 'REJECTED': 'rejected',
1337
- 'FILLED': 'closed',
1338
- };
1339
- return this.safeString(statuses, status, status);
1340
- }
1341
- return status;
1342
- }
1343
- parseOrder(order, market = undefined) {
1344
- //
1345
- // {
1346
- // "orderId": "746472647227344528",
1347
- // "createdAt": "2024-10-25T16:49:31.077Z",
1348
- // "updatedAt": "2024-10-25T16:49:31.378Z",
1349
- // "clientOrderId": "0192c495-49c3-71ee-b3d3-7442a2090807",
1350
- // "reduceOnly": false,
1351
- // "side": "SELL",
1352
- // "status": "FILLED",
1353
- // "symbol": "SOL_USDC",
1354
- // "timeInForce": "GTC",
1355
- // "type": "MARKET",
1356
- // "origQty": "0.80",
1357
- // "executedQty": "0.80",
1358
- // "cumulativeQuote": "137.87440000",
1359
- // "avgPrice": "172.34300000",
1360
- // "totalPnL": "0.00000000",
1361
- // "totalFee": "0.07583092",
1362
- // "workingType": null,
1363
- // "postOnly": false,
1364
- // "linkedOrderParentType": null,
1365
- // "isTriggered": false,
1366
- // "slippagePercentage": "5"
1367
- // }
1368
- //
1369
- const orderId = this.safeString(order, 'orderId');
1370
- const clientOrderId = this.safeString(order, 'clientOrderId');
1371
- const marketId = this.safeString(order, 'symbol');
1372
- market = this.safeMarket(marketId, market);
1373
- const symbol = market['symbol'];
1374
- const price = this.safeString(order, 'price');
1375
- const amount = this.safeString(order, 'origQty');
1376
- const orderType = this.safeStringLower(order, 'type');
1377
- const status = this.safeString(order, 'status');
1378
- const side = this.safeStringLower(order, 'side');
1379
- const filled = this.omitZero(this.safeString(order, 'executedQty'));
1380
- const average = this.omitZero(this.safeString(order, 'avgPrice'));
1381
- const timeInForce = this.safeStringLower(order, 'timeInForce');
1382
- let takeProfitPrice = undefined;
1383
- let triggerPrice = undefined;
1384
- if (orderType !== undefined) {
1385
- if (orderType.indexOf('take_profit') >= 0) {
1386
- takeProfitPrice = this.safeString(order, 'stopPrice');
1387
- }
1388
- else {
1389
- triggerPrice = this.safeString(order, 'stopPrice');
1390
- }
1391
- }
1392
- const timestamp = this.parse8601(this.safeString(order, 'createdAt'));
1393
- const lastTradeTimestamp = this.parse8601(this.safeString(order, 'updatedAt'));
1394
- return this.safeOrder({
1395
- 'id': orderId,
1396
- 'clientOrderId': clientOrderId,
1397
- 'timestamp': timestamp,
1398
- 'datetime': this.iso8601(timestamp),
1399
- 'lastTradeTimestamp': lastTradeTimestamp,
1400
- 'lastUpdateTimestamp': lastTradeTimestamp,
1401
- 'status': this.parseOrderStatus(status),
1402
- 'symbol': symbol,
1403
- 'type': orderType,
1404
- 'timeInForce': timeInForce,
1405
- 'postOnly': this.safeBool(order, 'postOnly'),
1406
- 'reduceOnly': this.safeBool(order, 'reduceOnly'),
1407
- 'side': side,
1408
- 'price': price,
1409
- 'triggerPrice': triggerPrice,
1410
- 'takeProfitPrice': takeProfitPrice,
1411
- 'stopLossPrice': undefined,
1412
- 'average': average,
1413
- 'amount': amount,
1414
- 'filled': filled,
1415
- 'remaining': undefined,
1416
- 'cost': undefined,
1417
- 'trades': undefined,
1418
- 'fee': {
1419
- 'cost': this.safeString(order, 'totalFee'),
1420
- 'currency': 'USDC',
1421
- },
1422
- 'info': order,
1423
- }, market);
1424
- }
1425
- /**
1426
- * @method
1427
- * @name defx#cancelOrder
1428
- * @see https://api-docs.defx.com/#09186f23-f8d1-4993-acf4-9974d8a6ddb0
1429
- * @description cancels an open order
1430
- * @param {string} id order id
1431
- * @param {string} symbol unified symbol of the market the order was made in
1432
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1433
- * @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
1434
- */
1435
- async cancelOrder(id, symbol = undefined, params = {}) {
1436
- await this.loadMarkets();
1437
- const request = {
1438
- 'orderId': id,
1439
- 'idType': 'orderId',
1440
- };
1441
- const clientOrderId = this.safeStringN(params, ['clOrdID', 'clientOrderId', 'client_order_id']);
1442
- const isByClientOrder = clientOrderId !== undefined;
1443
- if (isByClientOrder) {
1444
- if (symbol === undefined) {
1445
- throw new ArgumentsRequired(this.id + ' cancelOrder() requires a symbol argument');
1446
- }
1447
- const market = this.market(symbol);
1448
- request['orderId'] = clientOrderId;
1449
- request['idType'] = 'clientOrderId';
1450
- request['symbol'] = market['id'];
1451
- }
1452
- params = this.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id']);
1453
- const response = await this.v1PrivateDeleteApiOrderOrderId(this.extend(request, params));
1454
- //
1455
- // {
1456
- // "success": true
1457
- // }
1458
- //
1459
- const extendParams = { 'symbol': symbol };
1460
- if (isByClientOrder) {
1461
- extendParams['clientOrderId'] = clientOrderId;
1462
- }
1463
- else {
1464
- extendParams['id'] = id;
1465
- }
1466
- return this.extend(this.parseOrder(response), extendParams);
1467
- }
1468
- /**
1469
- * @method
1470
- * @name defx#cancelAllOrders
1471
- * @description cancel all open orders
1472
- * @see https://api-docs.defx.com/#db5531da-3692-4a53-841f-6ad6495f823a
1473
- * @param {string} symbol unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
1474
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1475
- * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
1476
- */
1477
- async cancelAllOrders(symbol = undefined, params = {}) {
1478
- await this.loadMarkets();
1479
- const market = this.market(symbol);
1480
- const request = {
1481
- 'symbols': [market['id']],
1482
- };
1483
- const response = await this.v1PrivateDeleteApiOrdersAllOpen(this.extend(request, params));
1484
- //
1485
- // {
1486
- // "data": {
1487
- // "msg": "The operation of cancel all open order is done."
1488
- // }
1489
- // }
1490
- //
1491
- return [this.safeOrder({ 'info': response })];
1492
- }
1493
- /**
1494
- * @method
1495
- * @name defx#fetchPosition
1496
- * @description fetch data on a single open contract trade position
1497
- * @see https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e
1498
- * @param {string} symbol unified market symbol of the market the position is held in, default is undefined
1499
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1500
- * @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
1501
- */
1502
- async fetchPosition(symbol, params = {}) {
1503
- if (symbol === undefined) {
1504
- throw new ArgumentsRequired(this.id + ' fetchPosition() requires a symbol argument');
1505
- }
1506
- await this.loadMarkets();
1507
- const market = this.market(symbol);
1508
- const request = {
1509
- 'symbol': market['id'],
1510
- };
1511
- const response = await this.v1PrivateGetApiPositionActive(this.extend(request, params));
1512
- //
1513
- // {
1514
- // "data": [
1515
- // {
1516
- // "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
1517
- // "symbol": "SOL_USDC",
1518
- // "positionSide": "SHORT",
1519
- // "entryPrice": "172.34300000",
1520
- // "quantity": "0.80",
1521
- // "marginAmount": "20.11561173",
1522
- // "marginAsset": "USDC",
1523
- // "pnl": "0.00000000"
1524
- // }
1525
- // ]
1526
- // }
1527
- //
1528
- const data = this.safeList(response, 'data', []);
1529
- const first = this.safeDict(data, 0, {});
1530
- return this.parsePosition(first, market);
1531
- }
1532
- /**
1533
- * @method
1534
- * @name defx#fetchPositions
1535
- * @description fetch all open positions
1536
- * @see https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e
1537
- * @param {string[]} [symbols] list of unified market symbols
1538
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1539
- * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
1540
- */
1541
- async fetchPositions(symbols = undefined, params = {}) {
1542
- await this.loadMarkets();
1543
- const response = await this.v1PrivateGetApiPositionActive(params);
1544
- //
1545
- // {
1546
- // "data": [
1547
- // {
1548
- // "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
1549
- // "symbol": "SOL_USDC",
1550
- // "positionSide": "SHORT",
1551
- // "entryPrice": "172.34300000",
1552
- // "quantity": "0.80",
1553
- // "marginAmount": "20.11561173",
1554
- // "marginAsset": "USDC",
1555
- // "pnl": "0.00000000"
1556
- // }
1557
- // ]
1558
- // }
1559
- //
1560
- const positions = this.safeList(response, 'data', []);
1561
- return this.parsePositions(positions, symbols);
1562
- }
1563
- parsePosition(position, market = undefined) {
1564
- //
1565
- // {
1566
- // "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
1567
- // "symbol": "SOL_USDC",
1568
- // "positionSide": "SHORT",
1569
- // "entryPrice": "172.34300000",
1570
- // "quantity": "0.80",
1571
- // "marginAmount": "20.11561173",
1572
- // "marginAsset": "USDC",
1573
- // "pnl": "0.00000000"
1574
- // }
1575
- //
1576
- const marketId = this.safeString(position, 'symbol');
1577
- market = this.safeMarket(marketId, market);
1578
- const size = Precise.stringAbs(this.safeString(position, 'quantity'));
1579
- const side = this.safeStringLower(position, 'positionSide');
1580
- const unrealisedPnl = this.omitZero(this.safeString(position, 'pnl'));
1581
- const entryPrice = this.omitZero(this.safeString(position, 'entryPrice'));
1582
- const initialMargin = this.safeString(position, 'marginAmount');
1583
- return this.safePosition({
1584
- 'info': position,
1585
- 'id': this.safeString(position, 'positionId'),
1586
- 'symbol': market['symbol'],
1587
- 'timestamp': undefined,
1588
- 'datetime': undefined,
1589
- 'lastUpdateTimestamp': undefined,
1590
- 'initialMargin': this.parseNumber(initialMargin),
1591
- 'initialMarginPercentage': undefined,
1592
- 'maintenanceMargin': undefined,
1593
- 'maintenanceMarginPercentage': undefined,
1594
- 'entryPrice': this.parseNumber(entryPrice),
1595
- 'notional': undefined,
1596
- 'leverage': undefined,
1597
- 'unrealizedPnl': this.parseNumber(unrealisedPnl),
1598
- 'realizedPnl': undefined,
1599
- 'contracts': this.parseNumber(size),
1600
- 'contractSize': this.safeNumber(market, 'contractSize'),
1601
- 'marginRatio': undefined,
1602
- 'liquidationPrice': undefined,
1603
- 'markPrice': undefined,
1604
- 'lastPrice': undefined,
1605
- 'collateral': undefined,
1606
- 'marginMode': undefined,
1607
- 'side': side,
1608
- 'percentage': undefined,
1609
- 'stopLossPrice': undefined,
1610
- 'takeProfitPrice': undefined,
1611
- 'hedged': undefined,
1612
- });
1613
- }
1614
- /**
1615
- * @method
1616
- * @name defx#fetchOrder
1617
- * @description fetches information on an order made by the user
1618
- * @see https://api-docs.defx.com/#44f82dd5-26b3-4e1f-b4aa-88ceddd65237
1619
- * @param {string} id the order id
1620
- * @param {string} symbol unified symbol of the market the order was made in
1621
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1622
- * @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
1623
- */
1624
- async fetchOrder(id, symbol = undefined, params = {}) {
1625
- await this.loadMarkets();
1626
- const request = {
1627
- 'orderId': id,
1628
- 'idType': 'orderId',
1629
- };
1630
- const clientOrderId = this.safeStringN(params, ['clOrdID', 'clientOrderId', 'client_order_id']);
1631
- params = this.omit(params, ['clOrdID', 'clientOrderId', 'client_order_id']);
1632
- if (clientOrderId !== undefined) {
1633
- if (symbol === undefined) {
1634
- throw new ArgumentsRequired(this.id + ' fetchOrder() requires a symbol argument');
1635
- }
1636
- const market = this.market(symbol);
1637
- request['orderId'] = clientOrderId;
1638
- request['idType'] = 'clientOrderId';
1639
- request['symbol'] = market['id'];
1640
- }
1641
- const response = await this.v1PrivateGetApiOrderOrderId(this.extend(request, params));
1642
- //
1643
- // {
1644
- // "success": true,
1645
- // "data": {
1646
- // "orderId": "555068654076559792",
1647
- // "createdAt": "2024-05-08T05:45:42.148Z",
1648
- // "updatedAt": "2024-05-08T05:45:42.166Z",
1649
- // "clientOrderId": "dummyClientOrderId",
1650
- // "reduceOnly": false,
1651
- // "side": "SELL",
1652
- // "status": "REJECTED",
1653
- // "symbol": "BTC_USDC",
1654
- // "timeInForce": "GTC",
1655
- // "type": "TAKE_PROFIT_MARKET",
1656
- // "origQty": "1.000",
1657
- // "executedQty": "0.000",
1658
- // "cumulativeQuote": "0.00",
1659
- // "avgPrice": "0.00",
1660
- // "stopPrice": "65000.00",
1661
- // "totalPnL": "0.00",
1662
- // "workingType": "MARK_PRICE",
1663
- // "postOnly": false
1664
- // }
1665
- // }
1666
- //
1667
- const data = this.safeDict(response, 'data');
1668
- return this.parseOrder(data);
1669
- }
1670
- /**
1671
- * @method
1672
- * @name defx#fetchOrders
1673
- * @description fetches information on multiple orders made by the user
1674
- * @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1675
- * @param {string} symbol unified market symbol
1676
- * @param {int} [since] the earliest time in ms to fetch open orders for
1677
- * @param {int} [limit] the maximum number of open order structures to retrieve
1678
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1679
- * @param {int} [params.until] the latest time in ms to fetch orders for
1680
- * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
1681
- */
1682
- async fetchOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
1683
- await this.loadMarkets();
1684
- const request = {};
1685
- if (symbol !== undefined) {
1686
- const market = this.market(symbol);
1687
- request['symbols'] = market['id'];
1688
- }
1689
- const until = this.safeInteger(params, 'until');
1690
- if (until !== undefined) {
1691
- params = this.omit(params, 'until');
1692
- request['end'] = this.iso8601(until);
1693
- }
1694
- if (since !== undefined) {
1695
- request['start'] = this.iso8601(since);
1696
- }
1697
- if (limit !== undefined) {
1698
- const maxLimit = 100;
1699
- limit = Math.min(maxLimit, limit);
1700
- request['pageSize'] = limit;
1701
- }
1702
- const response = await this.v1PrivateGetApiOrders(this.extend(request, params));
1703
- //
1704
- // {
1705
- // "data": [
1706
- // {
1707
- // "orderId": "746472647227344528",
1708
- // "createdAt": "2024-10-25T16:49:31.077Z",
1709
- // "updatedAt": "2024-10-25T16:49:31.378Z",
1710
- // "clientOrderId": "0192c495-49c3-71ee-b3d3-7442a2090807",
1711
- // "reduceOnly": false,
1712
- // "side": "SELL",
1713
- // "status": "FILLED",
1714
- // "symbol": "SOL_USDC",
1715
- // "timeInForce": "GTC",
1716
- // "type": "MARKET",
1717
- // "origQty": "0.80",
1718
- // "executedQty": "0.80",
1719
- // "cumulativeQuote": "137.87440000",
1720
- // "avgPrice": "172.34300000",
1721
- // "totalPnL": "0.00000000",
1722
- // "totalFee": "0.07583092",
1723
- // "workingType": null,
1724
- // "postOnly": false,
1725
- // "linkedOrderParentType": null,
1726
- // "isTriggered": false,
1727
- // "slippagePercentage": 5
1728
- // }
1729
- // ]
1730
- // }
1731
- //
1732
- const data = this.safeList(response, 'data', []);
1733
- return this.parseOrders(data, undefined, since, limit);
1734
- }
1735
- /**
1736
- * @method
1737
- * @name defx#fetchOpenOrders
1738
- * @description fetch all unfilled currently open orders
1739
- * @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1740
- * @param {string} symbol unified market symbol
1741
- * @param {int} [since] the earliest time in ms to fetch open orders for
1742
- * @param {int} [limit] the maximum number of open order structures to retrieve
1743
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1744
- * @param {int} [params.until] the latest time in ms to fetch orders for
1745
- * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
1746
- */
1747
- async fetchOpenOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
1748
- const req = {
1749
- 'statuses': 'OPEN',
1750
- };
1751
- return await this.fetchOrders(symbol, since, limit, this.extend(req, params));
1752
- }
1753
- /**
1754
- * @method
1755
- * @name defx#fetchClosedOrders
1756
- * @description fetches information on multiple closed orders made by the user
1757
- * @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1758
- * @param {string} symbol unified market symbol
1759
- * @param {int} [since] the earliest time in ms to fetch open orders for
1760
- * @param {int} [limit] the maximum number of open order structures to retrieve
1761
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1762
- * @param {int} [params.until] the latest time in ms to fetch orders for
1763
- * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
1764
- */
1765
- async fetchClosedOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
1766
- const req = {
1767
- 'statuses': 'FILLED',
1768
- };
1769
- return await this.fetchOrders(symbol, since, limit, this.extend(req, params));
1770
- }
1771
- /**
1772
- * @method
1773
- * @name defx#fetchCanceledOrders
1774
- * @description fetches information on multiple canceled orders made by the user
1775
- * @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
1776
- * @param {string} symbol unified market symbol
1777
- * @param {int} [since] the earliest time in ms to fetch open orders for
1778
- * @param {int} [limit] the maximum number of open order structures to retrieve
1779
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1780
- * @param {int} [params.until] the latest time in ms to fetch orders for
1781
- * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
1782
- */
1783
- async fetchCanceledOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
1784
- const req = {
1785
- 'statuses': 'CANCELED',
1786
- };
1787
- return await this.fetchOrders(symbol, since, limit, this.extend(req, params));
1788
- }
1789
- /**
1790
- * @method
1791
- * @name defx#closePosition
1792
- * @description closes an open position for a market
1793
- * @see https://api-docs.defx.com/#b2c08074-c4d9-4e50-b637-0d6c498fa29e
1794
- * @param {string} symbol unified CCXT market symbol
1795
- * @param {string} [side] one-way mode: 'buy' or 'sell', hedge-mode: 'long' or 'short'
1796
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1797
- * @param {string} [params.positionId] the position id you want to close
1798
- * @param {string} [params.type] 'MARKET' or 'LIMIT'
1799
- * @param {string} [params.quantity] how much of currency you want to trade in units of base currency
1800
- * @param {string} [params.price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1801
- * @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
1802
- */
1803
- async closePosition(symbol, side = undefined, params = {}) {
1804
- await this.loadMarkets();
1805
- const positionId = this.safeString(params, 'positionId');
1806
- if (positionId === undefined) {
1807
- throw new ArgumentsRequired(this.id + ' closePosition() requires a positionId');
1808
- }
1809
- const type = this.safeStringUpper(params, 'type');
1810
- if (type === undefined) {
1811
- throw new ArgumentsRequired(this.id + ' closePosition() requires a type');
1812
- }
1813
- const quantity = this.safeString(params, 'quantity');
1814
- if (quantity === undefined) {
1815
- throw new ArgumentsRequired(this.id + ' closePosition() requires a quantity');
1816
- }
1817
- const request = {
1818
- 'positionId': positionId,
1819
- 'type': type,
1820
- 'quantity': quantity,
1821
- };
1822
- if (type !== 'MARKET') {
1823
- const price = this.safeString(params, 'price');
1824
- if (price === undefined) {
1825
- throw new ArgumentsRequired(this.id + ' closePosition() requires a price');
1826
- }
1827
- request['price'] = price;
1828
- }
1829
- params = this.omit(params, ['positionId', 'type', 'quantity', 'price']);
1830
- const response = await this.v1PrivateDeleteApiPositionPositionId(this.extend(request, params));
1831
- //
1832
- // {}
1833
- //
1834
- return response;
1835
- }
1836
- /**
1837
- * @method
1838
- * @name defx#closeAllPositions
1839
- * @description closes all open positions for a market type
1840
- * @see https://api-docs.defx.com/#d6f63b43-100e-47a9-998c-8b6c0c72d204
1841
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1842
- * @returns {object[]} A list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
1843
- */
1844
- async closeAllPositions(params = {}) {
1845
- await this.loadMarkets();
1846
- const response = await this.v1PrivateDeleteApiPositionAll(params);
1847
- //
1848
- // {
1849
- // "data": [
1850
- // {
1851
- // "positionId": "d6ca1a27-28ad-47ae-b244-0bda5ac37b2b",
1852
- // "success": true
1853
- // }
1854
- // ]
1855
- // }
1856
- //
1857
- const data = this.safeList(response, 'data', []);
1858
- return this.parsePositions(data, undefined, params);
1859
- }
1860
- /**
1861
- * @method
1862
- * @name defx#fetchLedger
1863
- * @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
1864
- * @see https://api-docs.defx.com/#38cc8974-794f-48c0-b959-db045a0ee565
1865
- * @param {string} [code] unified currency code
1866
- * @param {int} [since] timestamp in ms of the earliest ledger entry
1867
- * @param {int} [limit] max number of ledger entries to return
1868
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1869
- * @param {int} [params.until] timestamp in ms of the latest ledger entry
1870
- * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
1871
- * @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
1872
- */
1873
- async fetchLedger(code = undefined, since = undefined, limit = undefined, params = {}) {
1874
- await this.loadMarkets();
1875
- let paginate = false;
1876
- [paginate, params] = this.handleOptionAndParams(params, 'fetchLedger', 'paginate');
1877
- if (paginate) {
1878
- return await this.fetchPaginatedCallDynamic('fetchLedger', code, since, limit, params);
1879
- }
1880
- const request = {};
1881
- if (since !== undefined) {
1882
- request['start'] = since;
1883
- }
1884
- else {
1885
- request['start'] = 0;
1886
- }
1887
- const until = this.safeInteger(params, 'until');
1888
- if (until !== undefined) {
1889
- params = this.omit(params, 'until');
1890
- request['end'] = until;
1891
- }
1892
- else {
1893
- request['end'] = this.milliseconds();
1894
- }
1895
- const response = await this.v1PrivateGetApiWalletTransactions(this.extend(request, params));
1896
- const data = this.safeList(response, 'transactions', []);
1897
- return this.parseLedger(data, undefined, since, limit);
1898
- }
1899
- parseLedgerEntry(item, currency = undefined) {
1900
- //
1901
- // {
1902
- // "id": "01JCSZS6H5VQND3GF5P98SJ29C",
1903
- // "timestamp": 1731744012054,
1904
- // "type": "FundingFee",
1905
- // "amount": "0.02189287",
1906
- // "asset": "USDC",
1907
- // "operation": "CREDIT"
1908
- // }
1909
- //
1910
- const amount = this.safeString(item, 'amount');
1911
- const currencyId = this.safeString(item, 'asset');
1912
- const code = this.safeCurrencyCode(currencyId, currency);
1913
- currency = this.safeCurrency(currencyId, currency);
1914
- const timestamp = this.safeInteger(item, 'timestamp');
1915
- const type = this.safeString(item, 'type');
1916
- return this.safeLedgerEntry({
1917
- 'info': item,
1918
- 'id': this.safeString(item, 'id'),
1919
- 'direction': undefined,
1920
- 'account': undefined,
1921
- 'referenceAccount': undefined,
1922
- 'referenceId': undefined,
1923
- 'type': this.parseLedgerEntryType(type),
1924
- 'currency': code,
1925
- 'amount': this.parseNumber(amount),
1926
- 'timestamp': timestamp,
1927
- 'datetime': this.iso8601(timestamp),
1928
- 'before': undefined,
1929
- 'after': undefined,
1930
- 'status': undefined,
1931
- 'fee': undefined,
1932
- }, currency);
1933
- }
1934
- parseLedgerEntryType(type) {
1935
- const ledgerType = {
1936
- 'FundingFee': 'fee',
1937
- 'FeeRebate': 'fee',
1938
- 'FeeKickback': 'fee',
1939
- 'RealizedPnl': 'trade',
1940
- 'LiquidationClearance': 'trade',
1941
- 'Transfer': 'transfer',
1942
- 'ReferralPayout': 'referral',
1943
- 'Commission': 'commission',
1944
- };
1945
- return this.safeString(ledgerType, type, type);
1946
- }
1947
- /**
1948
- * @method
1949
- * @name defx#withdraw
1950
- * @description make a withdrawal
1951
- * @see https://api-docs.defx.com/#2600f503-63ed-4672-b8f6-69ea5f03203b
1952
- * @param {string} code unified currency code
1953
- * @param {float} amount the amount to withdraw
1954
- * @param {string} address the address to withdraw to
1955
- * @param {string} tag
1956
- * @param {object} [params] extra parameters specific to the exchange API endpoint
1957
- * @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
1958
- */
1959
- async withdraw(code, amount, address, tag = undefined, params = {}) {
1960
- await this.loadMarkets();
1961
- const currency = this.currency(code);
1962
- const request = {
1963
- 'amount': this.currencyToPrecision(code, amount),
1964
- 'asset': currency['id'],
1965
- // 'network': 'ARB_SEPOLIA',
1966
- // 'chainId': '421614',
1967
- };
1968
- const response = await this.v1PrivatePostApiTransfersBridgeWithdrawal(this.extend(request, params));
1969
- //
1970
- // {
1971
- // "transactionId": "0x301e5851e5aefa733abfbc8b30817ca3b61601e0ddf1df8c59656fb888b0bc9c"
1972
- // }
1973
- //
1974
- return this.parseTransaction(response, currency);
1975
- }
1976
- parseTransaction(transaction, currency = undefined) {
1977
- //
1978
- // withdraw
1979
- //
1980
- // {
1981
- // "transactionId": "0x301e5851e5aefa733abfbc8b30817ca3b61601e0ddf1df8c59656fb888b0bc9c"
1982
- // }
1983
- //
1984
- const txid = this.safeString(transaction, 'transactionId');
1985
- return {
1986
- 'info': transaction,
1987
- 'id': undefined,
1988
- 'txid': txid,
1989
- 'timestamp': undefined,
1990
- 'datetime': undefined,
1991
- 'network': undefined,
1992
- 'address': undefined,
1993
- 'addressTo': undefined,
1994
- 'addressFrom': undefined,
1995
- 'tag': undefined,
1996
- 'tagTo': undefined,
1997
- 'tagFrom': undefined,
1998
- 'type': undefined,
1999
- 'amount': undefined,
2000
- 'currency': this.safeCurrencyCode(undefined, currency),
2001
- 'status': undefined,
2002
- 'updated': undefined,
2003
- 'internal': undefined,
2004
- 'comment': undefined,
2005
- 'fee': undefined,
2006
- };
2007
- }
2008
- /**
2009
- * @method
2010
- * @name defx#setLeverage
2011
- * @description set the level of leverage for a market
2012
- * @see https://api-docs.defx.com/#4cb4ecc4-6c61-4194-8353-be67faaf7ca7
2013
- * @param {float} leverage the rate of leverage
2014
- * @param {string} symbol unified market symbol
2015
- * @param {object} [params] extra parameters specific to the exchange API endpoint
2016
- * @returns {object} response from the exchange
2017
- */
2018
- async setLeverage(leverage, symbol = undefined, params = {}) {
2019
- if (symbol === undefined) {
2020
- throw new ArgumentsRequired(this.id + ' setLeverage() requires a symbol argument');
2021
- }
2022
- await this.loadMarkets();
2023
- const request = {
2024
- 'leverage': this.numberToString(leverage),
2025
- };
2026
- const market = this.market(symbol);
2027
- request['symbol'] = market['id'];
2028
- const response = await this.v1PrivatePostApiUsersMetadataLeverage(this.extend(request, params));
2029
- //
2030
- // {
2031
- // "success": true,
2032
- // "data": {
2033
- // "leverage": "11",
2034
- // "symbol": "BTC_USDC"
2035
- // }
2036
- // }
2037
- //
2038
- const data = this.safeDict(response, 'data', {});
2039
- return this.parseLeverage(data, market);
2040
- }
2041
- parseLeverage(leverage, market = undefined) {
2042
- //
2043
- // "data": {
2044
- // "leverage": "11",
2045
- // "symbol": "BTC_USDC"
2046
- // }
2047
- //
2048
- const marketId = this.safeString(leverage, 'symbol');
2049
- const leverageValue = this.safeInteger(leverage, 'leverage');
2050
- return {
2051
- 'info': leverage,
2052
- 'symbol': this.safeSymbol(marketId, market),
2053
- 'marginMode': undefined,
2054
- 'longLeverage': leverageValue,
2055
- 'shortLeverage': leverageValue,
2056
- };
2057
- }
2058
- nonce() {
2059
- return this.milliseconds();
2060
- }
2061
- sign(path, section = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
2062
- const version = section[0];
2063
- const access = section[1];
2064
- const pathWithParams = this.implodeParams(path, params);
2065
- let url = this.implodeHostname(this.urls['api'][access]);
2066
- url += '/' + version + '/';
2067
- params = this.omit(params, this.extractParams(path));
2068
- params = this.keysort(params);
2069
- if (access === 'public') {
2070
- url += 'open/' + pathWithParams;
2071
- if (Object.keys(params).length) {
2072
- url += '?' + this.rawencode(params);
2073
- }
2074
- }
2075
- else {
2076
- this.checkRequiredCredentials();
2077
- headers = { 'X-DEFX-SOURCE': 'ccxt' };
2078
- url += 'auth/' + pathWithParams;
2079
- const nonce = this.milliseconds().toString();
2080
- let payload = nonce;
2081
- if (method === 'GET' || path === 'api/order/{orderId}') {
2082
- payload += this.rawencode(params);
2083
- if (Object.keys(params).length) {
2084
- url += '?' + this.rawencode(params);
2085
- }
2086
- }
2087
- else {
2088
- if (params !== undefined) {
2089
- body = this.json(params);
2090
- payload += body;
2091
- }
2092
- headers['Content-Type'] = 'application/json';
2093
- }
2094
- const signature = this.hmac(this.encode(payload), this.encode(this.secret), sha256);
2095
- headers['X-DEFX-APIKEY'] = this.apiKey;
2096
- headers['X-DEFX-TIMESTAMP'] = nonce;
2097
- headers['X-DEFX-SIGNATURE'] = signature;
2098
- }
2099
- return { 'url': url, 'method': method, 'body': body, 'headers': headers };
2100
- }
2101
- handleErrors(httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
2102
- if (!response) {
2103
- return undefined; // fallback to default error handler
2104
- }
2105
- // {"errorCode":404,"errorMessage":"Not Found"}
2106
- // {"msg":"Missing auth signature","code":"missing_auth_signature"}
2107
- // {"success":false,"err":{"msg":"Invalid order id","code":"invalid_order_id"}}
2108
- const success = this.safeBool(response, 'success');
2109
- const err = this.safeDict(response, 'err', response);
2110
- const errorCode = this.safeString2(err, 'errorCode', 'code');
2111
- if (!success) {
2112
- const feedback = this.id + ' ' + this.json(response);
2113
- this.throwBroadlyMatchedException(this.exceptions['broad'], body, feedback);
2114
- this.throwExactlyMatchedException(this.exceptions['exact'], errorCode, feedback);
2115
- }
2116
- return undefined;
2117
- }
2118
- defaultNetworkCodeForCurrency(code) {
2119
- const currencyItem = this.currency(code);
2120
- const networks = currencyItem['networks'];
2121
- const networkKeys = Object.keys(networks);
2122
- for (let i = 0; i < networkKeys.length; i++) {
2123
- const network = networkKeys[i];
2124
- if (network === 'ETH') {
2125
- return network;
2126
- }
2127
- }
2128
- // if it was not returned according to above options, then return the first network of currency
2129
- return this.safeValue(networkKeys, 0);
2130
- }
2131
- setSandboxMode(enable) {
2132
- super.setSandboxMode(enable);
2133
- this.options['sandboxMode'] = enable;
2134
- }
2135
- }