ccxt 4.4.35 → 4.4.36

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