ccxt 4.5.48 → 4.5.50

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 (60) hide show
  1. package/README.md +7 -5
  2. package/dist/ccxt.browser.min.js +10 -10
  3. package/dist/cjs/ccxt.js +6 -1
  4. package/dist/cjs/src/abstract/weex.js +11 -0
  5. package/dist/cjs/src/base/Exchange.js +48 -13
  6. package/dist/cjs/src/bitget.js +1 -0
  7. package/dist/cjs/src/btcbox.js +1 -1
  8. package/dist/cjs/src/bullish.js +2 -1
  9. package/dist/cjs/src/gate.js +0 -1
  10. package/dist/cjs/src/hibachi.js +1 -1
  11. package/dist/cjs/src/kraken.js +1 -0
  12. package/dist/cjs/src/krakenfutures.js +10 -1
  13. package/dist/cjs/src/kucoin.js +5 -1
  14. package/dist/cjs/src/lighter.js +312 -144
  15. package/dist/cjs/src/mexc.js +7 -12
  16. package/dist/cjs/src/okx.js +46 -1
  17. package/dist/cjs/src/paradex.js +5 -2
  18. package/dist/cjs/src/pro/binance.js +1 -1
  19. package/dist/cjs/src/pro/cex.js +1 -1
  20. package/dist/cjs/src/pro/coinbase.js +1 -1
  21. package/dist/cjs/src/pro/hyperliquid.js +361 -1
  22. package/dist/cjs/src/pro/lighter.js +339 -18
  23. package/dist/cjs/src/pro/weex.js +1906 -0
  24. package/dist/cjs/src/weex.js +3823 -0
  25. package/js/ccxt.d.ts +8 -2
  26. package/js/ccxt.js +6 -2
  27. package/js/src/abstract/myokx.d.ts +34 -0
  28. package/js/src/abstract/okx.d.ts +34 -0
  29. package/js/src/abstract/okxus.d.ts +34 -0
  30. package/js/src/abstract/weex.d.ts +83 -0
  31. package/js/src/abstract/weex.js +11 -0
  32. package/js/src/base/Exchange.d.ts +5 -1
  33. package/js/src/base/Exchange.js +48 -13
  34. package/js/src/bitget.js +1 -0
  35. package/js/src/btcbox.js +1 -1
  36. package/js/src/bullish.js +2 -1
  37. package/js/src/gate.js +0 -1
  38. package/js/src/hibachi.js +1 -1
  39. package/js/src/kraken.js +1 -0
  40. package/js/src/krakenfutures.js +10 -1
  41. package/js/src/kucoin.d.ts +4 -0
  42. package/js/src/kucoin.js +5 -1
  43. package/js/src/lighter.d.ts +12 -2
  44. package/js/src/lighter.js +313 -145
  45. package/js/src/mexc.d.ts +2 -0
  46. package/js/src/mexc.js +7 -12
  47. package/js/src/okx.js +46 -1
  48. package/js/src/paradex.js +5 -2
  49. package/js/src/pro/binance.js +1 -1
  50. package/js/src/pro/cex.js +1 -1
  51. package/js/src/pro/coinbase.js +1 -1
  52. package/js/src/pro/hyperliquid.d.ts +48 -1
  53. package/js/src/pro/hyperliquid.js +362 -2
  54. package/js/src/pro/lighter.d.ts +37 -2
  55. package/js/src/pro/lighter.js +339 -18
  56. package/js/src/pro/weex.d.ts +330 -0
  57. package/js/src/pro/weex.js +1905 -0
  58. package/js/src/weex.d.ts +675 -0
  59. package/js/src/weex.js +3822 -0
  60. package/package.json +1 -1
@@ -0,0 +1,3823 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var weex$1 = require('./abstract/weex.js');
6
+ var errors = require('./base/errors.js');
7
+ var Precise = require('./base/Precise.js');
8
+ var number = require('./base/functions/number.js');
9
+ var sha256 = require('./static_dependencies/noble-hashes/sha256.js');
10
+
11
+ // ----------------------------------------------------------------------------
12
+ // ---------------------------------------------------------------------------
13
+ /**
14
+ * @class weex
15
+ * @augments Exchange
16
+ */
17
+ class weex extends weex$1["default"] {
18
+ describe() {
19
+ return this.deepExtend(super.describe(), {
20
+ 'id': 'weex',
21
+ 'name': 'Weex',
22
+ 'countries': ['SG'],
23
+ 'rateLimit': 20,
24
+ 'version': 'v3',
25
+ 'certified': false,
26
+ 'pro': true,
27
+ 'has': {
28
+ 'CORS': undefined,
29
+ 'spot': true,
30
+ 'margin': false,
31
+ 'swap': true,
32
+ 'future': false,
33
+ 'option': false,
34
+ 'addMargin': true,
35
+ 'borrowCrossMargin': false,
36
+ 'borrowIsolatedMargin': false,
37
+ 'borrowMargin': false,
38
+ 'cancelAllOrders': true,
39
+ 'cancelOrder': true,
40
+ 'cancelOrders': true,
41
+ 'cancelOrdersWithClientOrderId': true,
42
+ 'cancelOrderWithClientOrderId': true,
43
+ 'closeAllPositions': true,
44
+ 'closePosition': true,
45
+ 'createDepositAddress': false,
46
+ 'createLimitBuyOrder': true,
47
+ 'createLimitOrder': true,
48
+ 'createLimitSellOrder': true,
49
+ 'createMarketBuyOrder': true,
50
+ 'createMarketBuyOrderWithCost': false,
51
+ 'createMarketOrder': true,
52
+ 'createMarketOrderWithCost': false,
53
+ 'createMarketSellOrder': true,
54
+ 'createMarketSellOrderWithCost': false,
55
+ 'createOrder': true,
56
+ 'createOrders': false,
57
+ 'createOrderWithTakeProfitAndStopLoss': true,
58
+ 'createPostOnlyOrder': false,
59
+ 'createReduceOnlyOrder': true,
60
+ 'createStopLimitOrder': false,
61
+ 'createStopLossOrder': true,
62
+ 'createTakeProfitOrder': true,
63
+ 'createTrailingAmountOrder': false,
64
+ 'createTrailingPercentOrder': false,
65
+ 'createTriggerOrder': false,
66
+ 'deposit': false,
67
+ 'editOrder': false,
68
+ 'editOrders': false,
69
+ 'editOrderWithClientOrderId': false,
70
+ 'fetchAccounts': false,
71
+ 'fetchADLRank': false,
72
+ 'fetchBalance': true,
73
+ 'fetchBidsAsks': true,
74
+ 'fetchBorrowInterest': false,
75
+ 'fetchBorrowRate': false,
76
+ 'fetchBorrowRateHistories': false,
77
+ 'fetchBorrowRateHistory': false,
78
+ 'fetchBorrowRates': false,
79
+ 'fetchBorrowRatesPerSymbol': false,
80
+ 'fetchCanceledAndClosedOrders': true,
81
+ 'fetchCanceledOrders': true,
82
+ 'fetchClosedOrder': false,
83
+ 'fetchClosedOrders': true,
84
+ 'fetchConvertCurrencies': false,
85
+ 'fetchConvertQuote': false,
86
+ 'fetchConvertTrade': false,
87
+ 'fetchConvertTradeHistory': false,
88
+ 'fetchCrossBorrowRate': false,
89
+ 'fetchCrossBorrowRates': false,
90
+ 'fetchCurrencies': true,
91
+ 'fetchDeposit': false,
92
+ 'fetchDepositAddress': false,
93
+ 'fetchDepositAddresses': false,
94
+ 'fetchDepositAddressesByNetwork': false,
95
+ 'fetchDeposits': false,
96
+ 'fetchDepositsWithdrawals': false,
97
+ 'fetchDepositWithdrawFee': false,
98
+ 'fetchDepositWithdrawFees': false,
99
+ 'fetchFundingHistory': false,
100
+ 'fetchFundingInterval': false,
101
+ 'fetchFundingIntervals': false,
102
+ 'fetchFundingRate': true,
103
+ 'fetchFundingRateHistory': true,
104
+ 'fetchFundingRates': true,
105
+ 'fetchGreeks': false,
106
+ 'fetchIndexOHLCV': true,
107
+ 'fetchIsolatedBorrowRate': false,
108
+ 'fetchIsolatedBorrowRates': false,
109
+ 'fetchIsolatedPositions': false,
110
+ 'fetchL2OrderBook': false,
111
+ 'fetchL3OrderBook': false,
112
+ 'fetchLastPrices': false,
113
+ 'fetchLedger': true,
114
+ 'fetchLedgerEntry': false,
115
+ 'fetchLeverage': true,
116
+ 'fetchLeverages': true,
117
+ 'fetchLeverageTiers': false,
118
+ 'fetchLiquidations': false,
119
+ 'fetchLongShortRatio': false,
120
+ 'fetchLongShortRatioHistory': false,
121
+ 'fetchMarginAdjustmentHistory': false,
122
+ 'fetchMarginMode': true,
123
+ 'fetchMarginModes': true,
124
+ 'fetchMarketLeverageTiers': false,
125
+ 'fetchMarkets': true,
126
+ 'fetchMarkOHLCV': true,
127
+ 'fetchMarkPrices': false,
128
+ 'fetchMyLiquidations': false,
129
+ 'fetchMySettlementHistory': false,
130
+ 'fetchMyTrades': true,
131
+ 'fetchOHLCV': true,
132
+ 'fetchOpenInterest': true,
133
+ 'fetchOpenInterestHistory': false,
134
+ 'fetchOpenInterests': false,
135
+ 'fetchOpenOrder': false,
136
+ 'fetchOpenOrders': true,
137
+ 'fetchOption': false,
138
+ 'fetchOptionChain': false,
139
+ 'fetchOrder': true,
140
+ 'fetchOrderBook': true,
141
+ 'fetchOrderBooks': false,
142
+ 'fetchOrders': true,
143
+ 'fetchOrdersByStatus': false,
144
+ 'fetchOrderTrades': true,
145
+ 'fetchOrderWithClientOrderId': true,
146
+ 'fetchPosition': true,
147
+ 'fetchPositionADLRank': false,
148
+ 'fetchPositionHistory': false,
149
+ 'fetchPositionMode': true,
150
+ 'fetchPositions': true,
151
+ 'fetchPositionsADLRank': false,
152
+ 'fetchPositionsForSymbol': true,
153
+ 'fetchPositionsHistory': false,
154
+ 'fetchPositionsRisk': false,
155
+ 'fetchPremiumIndexOHLCV': false,
156
+ 'fetchSettlementHistory': false,
157
+ 'fetchStatus': true,
158
+ 'fetchTicker': true,
159
+ 'fetchTickers': true,
160
+ 'fetchTime': true,
161
+ 'fetchTrades': true,
162
+ 'fetchTradingFee': true,
163
+ 'fetchTradingFees': false,
164
+ 'fetchTradingLimits': false,
165
+ 'fetchTransactionFee': false,
166
+ 'fetchTransactionFees': false,
167
+ 'fetchTransactions': false,
168
+ 'fetchTransfer': false,
169
+ 'fetchTransfers': true,
170
+ 'fetchUnderlyingAssets': false,
171
+ 'fetchVolatilityHistory': false,
172
+ 'fetchWithdrawAddresses': false,
173
+ 'fetchWithdrawal': false,
174
+ 'fetchWithdrawals': false,
175
+ 'fetchWithdrawalWhitelist': false,
176
+ 'privateAPI': false,
177
+ 'publicAPI': false,
178
+ 'reduceMargin': true,
179
+ 'repayCrossMargin': false,
180
+ 'repayIsolatedMargin': false,
181
+ 'sandbox': false,
182
+ 'setLeverage': true,
183
+ 'setMargin': false,
184
+ 'setMarginMode': true,
185
+ 'setPositionMode': true,
186
+ 'signIn': false,
187
+ 'transfer': false,
188
+ 'withdraw': false,
189
+ },
190
+ 'urls': {
191
+ 'logo': 'https://github.com/user-attachments/assets/ccbadb2d-5035-403d-898f-dce831bdc936',
192
+ 'api': {
193
+ 'public': 'https://api-spot.weex.com',
194
+ 'private': 'https://api-spot.weex.com',
195
+ 'contract': 'https://api-contract.weex.com',
196
+ 'contractPrivate': 'https://api-contract.weex.com',
197
+ },
198
+ 'www': 'https://www.weex.com',
199
+ 'doc': [
200
+ 'https://www.weex.com/api-doc',
201
+ ],
202
+ 'referral': 'https://www.weex.com/register?vipCode=qfyh',
203
+ },
204
+ 'api': {
205
+ 'public': {
206
+ // multiply public endpoints weight by 5
207
+ 'get': {
208
+ 'api/v3/time': 5,
209
+ 'api/v3/coins': 25,
210
+ 'api/v3/exchangeInfo': 100,
211
+ 'api/v3/ping': 5,
212
+ 'api/v3/apiTradingSymbols': 25,
213
+ 'api/v3/market/ticker/price': 20,
214
+ 'api/v3/market/ticker/24hr': 10,
215
+ 'api/v3/market/trades': 125,
216
+ 'api/v3/market/klines': 10,
217
+ 'api/v3/market/depth': 25,
218
+ 'api/v3/market/ticker/bookTicker': 20, // done
219
+ },
220
+ },
221
+ 'private': {
222
+ 'get': {
223
+ 'api/v3/account/': 5,
224
+ 'api/v3/account/transferRecords': 3,
225
+ 'api/v3/order': 2,
226
+ 'api/v3/openOrders': 3,
227
+ 'api/v3/allOrders': 10,
228
+ 'api/v3/myTrades': 5,
229
+ 'api/v3/rebate/affiliate/getAffiliateUIDs': 20,
230
+ 'api/v3/rebate/affiliate/getChannelUserTradeAndAsset': 20,
231
+ 'api/v3/rebate/affiliate/getAffiliateCommission': 20,
232
+ 'api/v3/rebate/affiliate/getInternalWithdrawalStatus': 100,
233
+ 'api/v3/rebate/affiliate/querySubChannelTransactions': 10,
234
+ 'api/v3/agency/verifyReferrals': 20,
235
+ 'api/v3/agency/getAssert': 20,
236
+ 'api/v3/agency/getDealData': 20, // not unified
237
+ },
238
+ 'post': {
239
+ 'api/v3/account/bills': 5,
240
+ 'api/v3/account/fundingBills': 5,
241
+ 'api/v3/order': 5,
242
+ 'api/v3/order/batch': 50,
243
+ 'api/v3/rebate/affiliate/internalWithdrawal': 100, // not unified
244
+ },
245
+ 'delete': {
246
+ 'api/v3/order': 1,
247
+ 'api/v3/openOrders': 1,
248
+ 'api/v3/order/batch': 10, // done
249
+ },
250
+ },
251
+ 'contract': {
252
+ // multiply public endpoints weight by 5
253
+ 'get': {
254
+ 'capi/v3/market/time': 5,
255
+ 'capi/v3/market/exchangeInfo': 5,
256
+ 'capi/v3/market/depth': 5,
257
+ 'capi/v3/market/ticker/24hr': 200,
258
+ 'capi/v3/market/ticker/bookTicker': 5,
259
+ 'capi/v3/market/trades': 25,
260
+ 'capi/v3/market/klines': 5,
261
+ 'capi/v3/market/indexPriceKlines': 5,
262
+ 'capi/v3/market/markPriceKlines': 5,
263
+ 'capi/v3/market/historyKlines': 25,
264
+ 'capi/v3/market/symbolPrice': 5,
265
+ 'capi/v3/market/openInterest': 10,
266
+ 'capi/v3/market/premiumIndex': 5,
267
+ 'capi/v3/market/fundingRate': 25,
268
+ 'capi/v3/market/apiTradingSymbols': 25, // not unified
269
+ },
270
+ },
271
+ 'contractPrivate': {
272
+ 'get': {
273
+ 'capi/v3/account/balance': 10,
274
+ 'capi/v3/account/commissionRate': 10,
275
+ 'capi/v3/account/accountConfig': 10,
276
+ 'capi/v3/account/symbolConfig': 10,
277
+ 'capi/v3/account/position/allPosition': 15,
278
+ 'capi/v3/account/position/singlePosition': 3,
279
+ 'capi/v3/order': 3,
280
+ 'capi/v3/openOrders': 5,
281
+ 'capi/v3/order/history': 10,
282
+ 'capi/v3/userTrades': 5,
283
+ 'capi/v3/openAlgoOrders': 3,
284
+ 'capi/v3/allAlgoOrders': 10, // not unified - capi/v3/order/history returns both regular and algo orders
285
+ },
286
+ 'post': {
287
+ 'capi/v3/account/income': 5,
288
+ 'capi/v3/account/marginType': 50,
289
+ 'capi/v3/account/leverage': 20,
290
+ 'capi/v3/account/positionMargin': 30,
291
+ 'capi/v3/account/modifyAutoAppendMargin': 30,
292
+ 'capi/v3/order': 5,
293
+ 'capi/v3/batchOrders': 10,
294
+ 'capi/v3/closePositions': 50,
295
+ 'capi/v3/algoOrder': 5,
296
+ 'capi/v3/placeTpSlOrder': 5,
297
+ 'capi/v3/modifyTpSlOrder': 5, // not unified
298
+ },
299
+ 'delete': {
300
+ 'capi/v3/order': 3,
301
+ 'capi/v3/batchOrders': 10,
302
+ 'capi/v3/allOpenOrders': 10,
303
+ 'capi/v3/algoOrder': 3,
304
+ 'capi/v3/algoOpenOrders': 10, // done
305
+ },
306
+ },
307
+ },
308
+ 'requiredCredentials': {
309
+ 'apiKey': true,
310
+ 'secret': true,
311
+ 'password': true,
312
+ },
313
+ 'timeframes': {
314
+ '1m': '1m',
315
+ '5m': '5m',
316
+ '15m': '15m',
317
+ '30m': '30m',
318
+ '1h': '1h',
319
+ '2h': '2h',
320
+ '4h': '4h',
321
+ '6h': '6h',
322
+ '8h': '8h',
323
+ '12h': '12h',
324
+ '1d': '1d',
325
+ '1w': '1w',
326
+ '1M': '1M',
327
+ },
328
+ 'precisionMode': number.TICK_SIZE,
329
+ 'exceptions': {
330
+ 'exact': {
331
+ '-1000': errors.ExchangeError,
332
+ '-1054': errors.ExchangeError,
333
+ '-1040': errors.AuthenticationError,
334
+ '-1041': errors.AuthenticationError,
335
+ '-1042': errors.AuthenticationError,
336
+ '-1043': errors.AuthenticationError,
337
+ '-1044': errors.AuthenticationError,
338
+ '-1045': errors.BadRequest,
339
+ '-1046': errors.BadRequest,
340
+ '-1047': errors.AuthenticationError,
341
+ '-1049': errors.AuthenticationError,
342
+ '-1050': errors.PermissionDenied,
343
+ '-1051': errors.PermissionDenied,
344
+ '-1052': errors.PermissionDenied,
345
+ '-1053': errors.PermissionDenied,
346
+ '-1055': errors.PermissionDenied,
347
+ '-1056': errors.PermissionDenied,
348
+ '-1057': errors.PermissionDenied,
349
+ '-1058': errors.PermissionDenied,
350
+ '-1115': errors.InvalidOrder,
351
+ '-1116': errors.InvalidOrder,
352
+ '-1117': errors.InvalidOrder,
353
+ '-1121': errors.BadSymbol,
354
+ '-1128': errors.BadRequest,
355
+ '-1135': errors.BadRequest,
356
+ '-1140': errors.BadRequest,
357
+ '-1141': errors.ArgumentsRequired,
358
+ '-1142': errors.BadRequest,
359
+ '-1150': errors.BadRequest,
360
+ '-1160': errors.BadRequest,
361
+ '-1170': errors.BadRequest,
362
+ '-1171': errors.BadRequest,
363
+ '-1180': errors.InvalidOrder,
364
+ '-1190': errors.PermissionDenied,
365
+ '-2007': errors.BadSymbol,
366
+ '-2200': errors.OrderNotFound,
367
+ '-3006': errors.InvalidOrder,
368
+ '-3007': errors.InvalidOrder,
369
+ '-3200': errors.InvalidOrder,
370
+ '-3235': errors.PermissionDenied,
371
+ '-3236': errors.PermissionDenied,
372
+ '-3313': errors.InvalidOrder,
373
+ '-3613': errors.ExchangeError,
374
+ 'FAILED_ORDER_NOT_FOUND': errors.OrderNotFound, // {"orderId":121231,"status":"FAILED","errorMsg":"FAILED_ORDER_NOT_FOUND"}
375
+ },
376
+ 'broad': {
377
+ 'amount not enough': errors.InsufficientFunds,
378
+ 'INVALID_ARGUMENT': errors.BadRequest, // {"result":false,"id":1,"msg":"INVALID_ARGUMENT: invalid symbol : ASDFS_SPBL"}
379
+ },
380
+ },
381
+ 'fees': {
382
+ 'trading': {
383
+ 'feeSide': 'get',
384
+ 'tierBased': true,
385
+ 'percentage': true,
386
+ 'taker': this.parseNumber('0.1'),
387
+ 'maker': this.parseNumber('0.1'),
388
+ 'tiers': {
389
+ 'taker': [
390
+ [this.parseNumber('0'), this.parseNumber('0.1')],
391
+ [this.parseNumber('500000'), this.parseNumber('0.09')],
392
+ [this.parseNumber('1000000'), this.parseNumber('0.08')],
393
+ [this.parseNumber('2000000'), this.parseNumber('0.06')],
394
+ [this.parseNumber('5000000'), this.parseNumber('0.05')],
395
+ [this.parseNumber('10000000'), this.parseNumber('0.04')],
396
+ [this.parseNumber('25000000'), this.parseNumber('0.03')],
397
+ [this.parseNumber('50000000'), this.parseNumber('0.02')],
398
+ [this.parseNumber('100000000'), this.parseNumber('0')],
399
+ ],
400
+ 'maker': [
401
+ [this.parseNumber('0'), this.parseNumber('0.1')],
402
+ [this.parseNumber('500000'), this.parseNumber('0.08')],
403
+ [this.parseNumber('1000000'), this.parseNumber('0.07')],
404
+ [this.parseNumber('2000000'), this.parseNumber('0.05')],
405
+ [this.parseNumber('5000000'), this.parseNumber('0.04')],
406
+ [this.parseNumber('10000000'), this.parseNumber('0.03')],
407
+ [this.parseNumber('25000000'), this.parseNumber('0.02')],
408
+ [this.parseNumber('50000000'), this.parseNumber('0.01')],
409
+ [this.parseNumber('100000000'), this.parseNumber('0')],
410
+ ],
411
+ },
412
+ },
413
+ 'spot': {
414
+ 'feeSide': 'get',
415
+ 'tierBased': true,
416
+ 'percentage': true,
417
+ 'taker': this.parseNumber('0.1'),
418
+ 'maker': this.parseNumber('0.1'),
419
+ 'tiers': {
420
+ 'taker': [
421
+ [this.parseNumber('0'), this.parseNumber('0.1')],
422
+ [this.parseNumber('500000'), this.parseNumber('0.09')],
423
+ [this.parseNumber('1000000'), this.parseNumber('0.08')],
424
+ [this.parseNumber('2000000'), this.parseNumber('0.06')],
425
+ [this.parseNumber('5000000'), this.parseNumber('0.05')],
426
+ [this.parseNumber('10000000'), this.parseNumber('0.04')],
427
+ [this.parseNumber('25000000'), this.parseNumber('0.03')],
428
+ [this.parseNumber('50000000'), this.parseNumber('0.02')],
429
+ [this.parseNumber('100000000'), this.parseNumber('0')],
430
+ ],
431
+ 'maker': [
432
+ [this.parseNumber('0'), this.parseNumber('0.1')],
433
+ [this.parseNumber('500000'), this.parseNumber('0.08')],
434
+ [this.parseNumber('1000000'), this.parseNumber('0.07')],
435
+ [this.parseNumber('2000000'), this.parseNumber('0.05')],
436
+ [this.parseNumber('5000000'), this.parseNumber('0.04')],
437
+ [this.parseNumber('10000000'), this.parseNumber('0.03')],
438
+ [this.parseNumber('25000000'), this.parseNumber('0.02')],
439
+ [this.parseNumber('50000000'), this.parseNumber('0.01')],
440
+ [this.parseNumber('100000000'), this.parseNumber('0')],
441
+ ],
442
+ },
443
+ },
444
+ 'contract': {
445
+ 'feeSide': 'quote',
446
+ 'tierBased': true,
447
+ 'percentage': true,
448
+ 'taker': this.parseNumber('0.08'),
449
+ 'maker': this.parseNumber('0.02'),
450
+ 'tiers': {
451
+ 'taker': [
452
+ [this.parseNumber('0'), this.parseNumber('0.08')],
453
+ [this.parseNumber('1000000'), this.parseNumber('0.075')],
454
+ [this.parseNumber('5000000'), this.parseNumber('0.06')],
455
+ [this.parseNumber('10000000'), this.parseNumber('0.055')],
456
+ [this.parseNumber('30000000'), this.parseNumber('0.05')],
457
+ [this.parseNumber('50000000'), this.parseNumber('0.048')],
458
+ [this.parseNumber('100000000'), this.parseNumber('0.045')],
459
+ [this.parseNumber('300000000'), this.parseNumber('0.042')],
460
+ [this.parseNumber('500000000'), this.parseNumber('0.04')],
461
+ ],
462
+ 'maker': [
463
+ [this.parseNumber('0'), this.parseNumber('0.02')],
464
+ [this.parseNumber('1000000'), this.parseNumber('0.02')],
465
+ [this.parseNumber('5000000'), this.parseNumber('0.018')],
466
+ [this.parseNumber('10000000'), this.parseNumber('0.018')],
467
+ [this.parseNumber('30000000'), this.parseNumber('0.016')],
468
+ [this.parseNumber('50000000'), this.parseNumber('0.016')],
469
+ [this.parseNumber('100000000'), this.parseNumber('0.014')],
470
+ [this.parseNumber('300000000'), this.parseNumber('0.012')],
471
+ [this.parseNumber('500000000'), this.parseNumber('0.01')],
472
+ ],
473
+ },
474
+ },
475
+ },
476
+ 'commonCurrencies': {
477
+ 'XBT': 'XBT',
478
+ },
479
+ 'options': {
480
+ 'partner': 'b-WEEX111125',
481
+ 'timeDifference': 0,
482
+ 'adjustForTimeDifference': false,
483
+ 'accountsByType': {
484
+ 'spot': 'spot',
485
+ 'trading': 'spot',
486
+ 'fund': 'funding',
487
+ 'funding': 'funding',
488
+ 'swap': 'contract',
489
+ 'contract': 'contract',
490
+ 'futures': 'contract',
491
+ },
492
+ 'networks': {
493
+ 'BEP20': 'BEP20(BSC)',
494
+ 'BSC': 'BEP20(BSC)',
495
+ 'ERC20': 'ERC20',
496
+ 'ETH': 'ERC20',
497
+ 'POLYGON': 'POLYGON(MATIC)',
498
+ 'MATIC': 'POLYGON(MATIC)',
499
+ 'ARBITRUM': 'ARBITRUM(ARB)',
500
+ 'ARB': 'ARBITRUM(ARB)',
501
+ 'SOLANA': 'SOLANA(SOL)',
502
+ 'SOL': 'SOLANA(SOL)',
503
+ 'OP': 'OPTIMISM(OP)',
504
+ 'OPTIMISM': 'OPTIMISM(OP)',
505
+ 'AVALANCHEC': 'AVALANCHE_C(AVAX_C)',
506
+ 'AVAXC': 'AVALANCHE_C(AVAX_C)',
507
+ },
508
+ 'networksById': {
509
+ 'BEP20(BSC)': 'BEP20',
510
+ 'ERC20': 'ERC20',
511
+ 'POLYGON(MATIC)': 'MATIC',
512
+ 'ARBITRUM(ARB)': 'ARB',
513
+ 'SOLANA(SOL)': 'SOL',
514
+ 'OPTIMISM(OP)': 'OP',
515
+ 'AVALANCHE_C(AVAX_C)': 'AVAXC',
516
+ },
517
+ 'timeframes': {
518
+ 'spot': {
519
+ '1m': '1m',
520
+ '5m': '5m',
521
+ '15m': '15m',
522
+ '30m': '30m',
523
+ '1h': '1h',
524
+ '2h': '2h',
525
+ '4h': '4h',
526
+ '6h': '6h',
527
+ '8h': '8h',
528
+ '12h': '12h',
529
+ '1d': '1d',
530
+ '1w': '1w',
531
+ '1M': '1M',
532
+ },
533
+ 'contract': {
534
+ '1m': '1m',
535
+ '5m': '5m',
536
+ '15m': '15m',
537
+ '30m': '30m',
538
+ '1h': '1h',
539
+ '4h': '4h',
540
+ '12h': '12h',
541
+ '1d': '1d',
542
+ '1w': '1w',
543
+ },
544
+ },
545
+ },
546
+ 'features': {
547
+ 'spot': {
548
+ 'sandbox': false,
549
+ 'createOrder': {
550
+ 'test': false,
551
+ 'marginMode': false,
552
+ 'triggerPrice': false,
553
+ 'triggerPriceType': undefined,
554
+ 'triggerDirection': undefined,
555
+ 'stopLossPrice': false,
556
+ 'takeProfitPrice': false,
557
+ 'attachedStopLossTakeProfit': undefined,
558
+ 'timeInForce': {
559
+ 'IOC': true,
560
+ 'FOK': true,
561
+ 'PO': false,
562
+ 'GTD': false,
563
+ },
564
+ 'hedged': false,
565
+ 'trailing': false,
566
+ 'leverage': false,
567
+ 'marketBuyByCost': false,
568
+ 'marketBuyRequiresPrice': false,
569
+ 'selfTradePrevention': false,
570
+ 'iceberg': false,
571
+ },
572
+ 'createOrders': {
573
+ 'max': 10,
574
+ },
575
+ 'fetchMyTrades': {
576
+ 'marginMode': false,
577
+ 'limit': 100,
578
+ 'daysBack': undefined,
579
+ 'untilDays': undefined,
580
+ 'symbolRequired': true,
581
+ },
582
+ 'fetchOrder': {
583
+ 'marginMode': false,
584
+ 'trigger': false,
585
+ 'trailing': false,
586
+ 'symbolRequired': false,
587
+ },
588
+ 'fetchOpenOrders': {
589
+ 'marginMode': false,
590
+ 'limit': 100,
591
+ 'trigger': false,
592
+ 'trailing': false,
593
+ 'symbolRequired': false,
594
+ },
595
+ 'fetchOrders': {
596
+ 'marginMode': false,
597
+ 'limit': 1000,
598
+ 'daysBack': 100000,
599
+ 'untilDays': 100000,
600
+ 'trigger': false,
601
+ 'trailing': false,
602
+ 'symbolRequired': true,
603
+ },
604
+ 'fetchClosedOrders': undefined,
605
+ 'fetchOHLCV': {
606
+ 'limit': 300,
607
+ },
608
+ },
609
+ 'forDerivs': {
610
+ 'sandbox': false,
611
+ 'createOrder': {
612
+ 'marginMode': true,
613
+ 'triggerPrice': false,
614
+ 'triggerPriceType': undefined,
615
+ 'triggerDirection': false,
616
+ 'stopLossPrice': true,
617
+ 'takeProfitPrice': true,
618
+ 'attachedStopLossTakeProfit': {
619
+ 'triggerPriceType': {
620
+ 'last': true,
621
+ 'mark': true,
622
+ 'index': false,
623
+ },
624
+ 'price': false,
625
+ },
626
+ 'timeInForce': {
627
+ 'IOC': true,
628
+ 'FOK': true,
629
+ 'PO': false,
630
+ 'GTD': false,
631
+ },
632
+ 'hedged': false,
633
+ 'trailing': false,
634
+ 'leverage': false,
635
+ 'marketBuyByCost': false,
636
+ 'marketBuyRequiresPrice': false,
637
+ 'selfTradePrevention': false,
638
+ 'iceberg': false,
639
+ },
640
+ 'createOrders': {
641
+ 'max': 10,
642
+ },
643
+ 'fetchMyTrades': {
644
+ 'marginMode': false,
645
+ 'limit': 100,
646
+ 'daysBack': undefined,
647
+ 'untilDays': undefined,
648
+ 'symbolRequired': false,
649
+ },
650
+ 'fetchOrder': {
651
+ 'marginMode': false,
652
+ 'trigger': false,
653
+ 'trailing': false,
654
+ 'symbolRequired': false,
655
+ },
656
+ 'fetchOpenOrders': {
657
+ 'marginMode': false,
658
+ 'limit': 100,
659
+ 'trigger': true,
660
+ 'trailing': false,
661
+ 'symbolRequired': false,
662
+ },
663
+ 'fetchOrders': undefined,
664
+ 'fetchCanceledAndClosedOrders': {
665
+ 'marginMode': false,
666
+ 'limit': 1000,
667
+ 'daysBack': 100000,
668
+ 'untilDays': 100000,
669
+ 'trigger': false,
670
+ 'trailing': false,
671
+ 'symbolRequired': false,
672
+ },
673
+ 'fetchClosedOrders': undefined,
674
+ 'fetchOHLCV': {
675
+ 'limit': 1000, // 100 for historical
676
+ },
677
+ },
678
+ 'swap': {
679
+ 'linear': {
680
+ 'extends': 'forDerivs',
681
+ },
682
+ 'inverse': undefined,
683
+ },
684
+ },
685
+ });
686
+ }
687
+ nonce() {
688
+ return this.milliseconds() - this.options['timeDifference'];
689
+ }
690
+ /**
691
+ * @method
692
+ * @name weex#fetchStatus
693
+ * @description the latest known information on the availability of the exchange API
694
+ * @see https://www.weex.com/api-doc/spot/ConfigAPI/Ping
695
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
696
+ * @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
697
+ */
698
+ async fetchStatus(params = {}) {
699
+ const response = await this.publicGetApiV3Ping(params);
700
+ // reutns an empty response if the exchange is alive, otherwise will trigger an error
701
+ return {
702
+ 'status': 'ok',
703
+ 'updated': undefined,
704
+ 'eta': undefined,
705
+ 'url': undefined,
706
+ 'info': response,
707
+ };
708
+ }
709
+ /**
710
+ * @method
711
+ * @name weex#fetchTime
712
+ * @description fetches the current integer timestamp in milliseconds from the exchange server
713
+ * @see https://www.weex.com/api-doc/spot/ConfigAPI/GetServerTime
714
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetServerTime
715
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
716
+ * @param {string} [params.type] 'spot' or 'swap', default is 'spot'
717
+ * @returns {int} the current integer timestamp in milliseconds from the exchange server
718
+ */
719
+ async fetchTime(params = {}) {
720
+ let type = undefined;
721
+ [type, params] = this.handleMarketTypeAndParams('fetchTime', undefined, params);
722
+ let response = undefined;
723
+ if (type !== 'spot') {
724
+ response = await this.contractGetCapiV3MarketTime(params);
725
+ }
726
+ else {
727
+ response = await this.publicGetApiV3Time(params);
728
+ }
729
+ //
730
+ // {
731
+ // "serverTime": 1764505776347
732
+ // }
733
+ //
734
+ return this.safeInteger(response, 'serverTime');
735
+ }
736
+ /**
737
+ * @method
738
+ * @name weex#fetchCurrencies
739
+ * @description fetches all available currencies on an exchange
740
+ * @see https://www.weex.com/api-doc/spot/ConfigAPI/CurrencyInfo
741
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
742
+ * @returns {object} an associative dictionary of currencies
743
+ */
744
+ async fetchCurrencies(params = {}) {
745
+ const response = await this.publicGetApiV3Coins(params);
746
+ //
747
+ // [
748
+ // {
749
+ // "coin": "BTC",
750
+ // "depositAllEnable": true,
751
+ // "withdrawAllEnable": true,
752
+ // "name": "BTC",
753
+ // "networkList": [
754
+ // {
755
+ // "network": "BTC",
756
+ // "coin": "BTC",
757
+ // "withdrawIntegerMultiple": 1E-8,
758
+ // "isDefault": true,
759
+ // "depositEnable": true,
760
+ // "withdrawEnable": true,
761
+ // "depositDesc": null,
762
+ // "withdrawDesc": null,
763
+ // "name": "BTC",
764
+ // "withdrawFee": "0.00016",
765
+ // "withdrawMin": "0.002",
766
+ // "depositDust": "0.00001",
767
+ // "minConfirm": 3,
768
+ // "withdrawTag": false,
769
+ // "contractAddressUrl": "https://www.blockchain.com/explorer/mempool/",
770
+ // "contractAddress": "btc"
771
+ // },
772
+ // {
773
+ // "network": "BEP20(BSC)",
774
+ // "coin": "BTC",
775
+ // "withdrawIntegerMultiple": 1E-8,
776
+ // "isDefault": false,
777
+ // "depositEnable": true,
778
+ // "withdrawEnable": false,
779
+ // "depositDesc": null,
780
+ // "withdrawDesc": null,
781
+ // "name": "BEP20(BSC)",
782
+ // "withdrawFee": "0.00001",
783
+ // "withdrawMin": "0.00006",
784
+ // "depositDust": "0.00003",
785
+ // "minConfirm": 61,
786
+ // "withdrawTag": false,
787
+ // "contractAddressUrl": "",
788
+ // "contractAddress": ""
789
+ // }
790
+ // ]
791
+ // },
792
+ // {
793
+ // "coin": "USDT",
794
+ // "depositAllEnable": true,
795
+ // "withdrawAllEnable": true,
796
+ // "name": "USDT",
797
+ // "networkList": [
798
+ // {
799
+ // "network": "TRC20",
800
+ // "coin": "USDT",
801
+ // "withdrawIntegerMultiple": 1E-8,
802
+ // "isDefault": true,
803
+ // "depositEnable": true,
804
+ // "withdrawEnable": true,
805
+ // "depositDesc": null,
806
+ // "withdrawDesc": null,
807
+ // "name": "TRC20",
808
+ // "withdrawFee": "1.5",
809
+ // "withdrawMin": "10",
810
+ // "depositDust": "0.1",
811
+ // "minConfirm": 20,
812
+ // "withdrawTag": false,
813
+ // "contractAddressUrl": "https://tronscan.org/#/token20/",
814
+ // "contractAddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
815
+ // },
816
+ // {
817
+ // "network": "ERC20",
818
+ // "coin": "USDT",
819
+ // "withdrawIntegerMultiple": 1E-8,
820
+ // "isDefault": false,
821
+ // "depositEnable": true,
822
+ // "withdrawEnable": true,
823
+ // "depositDesc": null,
824
+ // "withdrawDesc": null,
825
+ // "name": "ERC20",
826
+ // "withdrawFee": "1",
827
+ // "withdrawMin": "20",
828
+ // "depositDust": "0.1",
829
+ // "minConfirm": 12,
830
+ // "withdrawTag": false,
831
+ // "contractAddressUrl": "https://etherscan.io/token/",
832
+ // "contractAddress": "0xdac17f958d2ee523a2206206994597c13d831ec7"
833
+ // },
834
+ // {
835
+ // "network": "AVALANCHE_C(AVAX_C)",
836
+ // "coin": "USDT",
837
+ // "withdrawIntegerMultiple": 1E-8,
838
+ // "isDefault": false,
839
+ // "depositEnable": true,
840
+ // "withdrawEnable": true,
841
+ // "depositDesc": null,
842
+ // "withdrawDesc": null,
843
+ // "name": "AVALANCHE_C(AVAX_C)",
844
+ // "withdrawFee": "0.5",
845
+ // "withdrawMin": "10",
846
+ // "depositDust": "0.1",
847
+ // "minConfirm": 35,
848
+ // "withdrawTag": false,
849
+ // "contractAddressUrl": "https://avascan.info/blockchain/c/token/",
850
+ // "contractAddress": "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7"
851
+ // }
852
+ // ]
853
+ // }
854
+ // ]
855
+ //
856
+ const result = {};
857
+ for (let i = 0; i < response.length; i++) {
858
+ const currency = this.safeDict(response, i);
859
+ const currencyId = this.safeString(currency, 'coin');
860
+ const code = this.safeCurrencyCode(currencyId);
861
+ const name = this.safeString(currency, 'name');
862
+ const networks = {};
863
+ const chains = this.safeList(currency, 'networkList', []);
864
+ for (let j = 0; j < chains.length; j++) {
865
+ const chain = this.safeDict(chains, j);
866
+ const networkId = this.safeString(chain, 'network');
867
+ const networkCode = this.networkIdToCode(networkId);
868
+ networks[networkCode] = {
869
+ 'info': chain,
870
+ 'id': networkId,
871
+ 'network': networkCode,
872
+ 'active': undefined,
873
+ 'deposit': this.safeBool(chain, 'depositEnable'),
874
+ 'withdraw': this.safeBool(chain, 'withdrawEnable'),
875
+ 'fee': this.safeNumber(chain, 'withdrawFee'),
876
+ 'precision': this.safeNumber(chain, 'withdrawIntegerMultiple'),
877
+ 'isDefault': this.safeBool(chain, 'isDefault', false),
878
+ 'limits': {
879
+ 'withdraw': {
880
+ 'min': this.safeNumber(chain, 'withdrawMin'),
881
+ 'max': undefined,
882
+ },
883
+ 'deposit': {
884
+ 'min': this.safeNumber(chain, 'depositDust'),
885
+ 'max': undefined,
886
+ },
887
+ },
888
+ };
889
+ }
890
+ const networkKeys = Object.keys(networks);
891
+ const networksLength = networkKeys.length;
892
+ const emptyChains = networksLength === 0; // non-functional coins
893
+ const valueForEmpty = emptyChains ? false : undefined;
894
+ result[code] = this.safeCurrencyStructure({
895
+ 'info': currency,
896
+ 'code': code,
897
+ 'id': currencyId,
898
+ 'type': 'crypto',
899
+ 'name': name,
900
+ 'active': undefined,
901
+ 'deposit': valueForEmpty,
902
+ 'withdraw': valueForEmpty,
903
+ 'fee': undefined,
904
+ 'precision': undefined,
905
+ 'limits': {
906
+ 'amount': {
907
+ 'min': undefined,
908
+ 'max': undefined,
909
+ },
910
+ 'withdraw': {
911
+ 'min': undefined,
912
+ 'max': undefined,
913
+ },
914
+ 'deposit': {
915
+ 'min': undefined,
916
+ 'max': undefined,
917
+ },
918
+ },
919
+ 'networks': networks,
920
+ });
921
+ }
922
+ return result;
923
+ }
924
+ /**
925
+ * @method
926
+ * @name weex#fetchMarkets
927
+ * @description retrieves data on all markets for exchagne
928
+ * @see https://www.weex.com/api-doc/spot/ConfigAPI/GetProductInfo // spot
929
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetContractInfo // contract
930
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
931
+ * @returns {object[]} an array of objects representing market data
932
+ */
933
+ async fetchMarkets(params = {}) {
934
+ if (this.options['adjustForTimeDifference']) {
935
+ await this.loadTimeDifference();
936
+ }
937
+ const promises = [
938
+ this.publicGetApiV3ExchangeInfo(params),
939
+ this.contractGetCapiV3MarketExchangeInfo(params),
940
+ ];
941
+ const [spotResponse, contractResponse] = await Promise.all(promises);
942
+ const spotArray = this.safeList(spotResponse, 'symbols', []);
943
+ const contractArray = this.safeList(contractResponse, 'symbols', []);
944
+ const result = this.arrayConcat(spotArray, contractArray);
945
+ return this.parseMarkets(result);
946
+ }
947
+ parseMarket(market) {
948
+ //
949
+ // spot
950
+ // {
951
+ // "symbol": "ETHUSDT",
952
+ // "status": "TRADING",
953
+ // "baseAsset": "ETH",
954
+ // "baseAssetPrecision": "8",
955
+ // "quoteAsset": "USDT",
956
+ // "quoteAssetPrecision": "8",
957
+ // "tickSize": "0.01",
958
+ // "stepSize": "0.00001",
959
+ // "minTradeAmount": "0.0001",
960
+ // "maxTradeAmount": "99999",
961
+ // "takerFeeRate": "0.001",
962
+ // "makerFeeRate": "0.001",
963
+ // "buyLimitPriceRatio": "0.1",
964
+ // "sellLimitPriceRatio": "0.1",
965
+ // "marketBuyLimitSize": "99999",
966
+ // "marketSellLimitSize": "99999",
967
+ // "marketFallbackPriceRatio": "0",
968
+ // "enableTrade": true,
969
+ // "enableDisplay": true,
970
+ // "displayDigitMerge": "0.01,0.1,0.5,1,5",
971
+ // "displayNew": false,
972
+ // "displayHot": false
973
+ // }
974
+ //
975
+ // contract
976
+ // {
977
+ // "symbol": "ETHUSDT",
978
+ // "baseAsset": "ETH",
979
+ // "quoteAsset": "USDT",
980
+ // "marginAsset": "USDT",
981
+ // "pricePrecision": "2",
982
+ // "quantityPrecision": "3",
983
+ // "baseAssetPrecision": "2",
984
+ // "quotePrecision": "8",
985
+ // "contractVal": "0.001",
986
+ // "delivery": [
987
+ // "00:00:00",
988
+ // "08:00:00",
989
+ // "16:00:00"
990
+ // ],
991
+ // "forwardContractFlag": true,
992
+ // "minLeverage": "1",
993
+ // "maxLeverage": "400",
994
+ // "buyLimitPriceRatio": "0.01",
995
+ // "sellLimitPriceRatio": "0.01",
996
+ // "makerFeeRate": "0.0002",
997
+ // "takerFeeRate": "0.0008",
998
+ // "minOrderSize": "0.001",
999
+ // "maxOrderSize": "1000000",
1000
+ // "maxPositionSize": "5000000",
1001
+ // "marketOpenLimitSize": "2300"
1002
+ // }
1003
+ //
1004
+ const id = this.safeString(market, 'symbol');
1005
+ const baseId = this.safeString(market, 'baseAsset');
1006
+ const quoteId = this.safeString(market, 'quoteAsset');
1007
+ const settleId = this.safeString(market, 'marginAsset');
1008
+ const base = this.safeCurrencyCode(baseId);
1009
+ const quote = this.safeCurrencyCode(quoteId);
1010
+ const settle = this.safeCurrencyCode(settleId);
1011
+ let active = true;
1012
+ let symbol = base + '/' + quote;
1013
+ let isSpot = true;
1014
+ let isLinear = undefined;
1015
+ let isInverse = undefined;
1016
+ if (settle !== undefined) {
1017
+ symbol += ':' + settle;
1018
+ isSpot = false;
1019
+ if (settle === quote) {
1020
+ isLinear = true;
1021
+ isInverse = false;
1022
+ }
1023
+ else if (settle === base) {
1024
+ isLinear = false;
1025
+ isInverse = true;
1026
+ }
1027
+ }
1028
+ else {
1029
+ active = this.safeBool(market, 'enableTrade');
1030
+ }
1031
+ let amountPrecision = this.safeNumber(market, 'stepSize');
1032
+ let pricePrecision = this.safeNumber(market, 'tickSize');
1033
+ if (amountPrecision === undefined) {
1034
+ const amountPrecisionString = this.parsePrecision(this.safeString(market, 'quantityPrecision'));
1035
+ const pricePrecisionString = this.parsePrecision(this.safeString(market, 'pricePrecision'));
1036
+ amountPrecision = this.parseNumber(amountPrecisionString);
1037
+ pricePrecision = this.parseNumber(pricePrecisionString);
1038
+ }
1039
+ const fees = this.safeDict(this.fees, isSpot ? 'spot' : 'contract', {});
1040
+ return this.safeMarketStructure({
1041
+ 'id': id,
1042
+ 'lowercaseId': id.toLowerCase(),
1043
+ 'numericId': this.safeInteger(market, 'contractId'),
1044
+ 'symbol': symbol,
1045
+ 'base': base,
1046
+ 'quote': quote,
1047
+ 'settle': settle,
1048
+ 'baseId': baseId,
1049
+ 'quoteId': quoteId,
1050
+ 'settleId': settleId,
1051
+ 'type': isSpot ? 'spot' : 'swap',
1052
+ 'spot': isSpot,
1053
+ 'margin': false,
1054
+ 'swap': !isSpot,
1055
+ 'future': false,
1056
+ 'option': false,
1057
+ 'active': active,
1058
+ 'contract': !isSpot,
1059
+ 'linear': isLinear,
1060
+ 'inverse': isInverse,
1061
+ 'taker': this.safeNumber(market, 'takerFeeRate'),
1062
+ 'maker': this.safeNumber(market, 'makerFeeRate'),
1063
+ 'feeSide': fees['feeSide'],
1064
+ 'contractSize': this.safeNumber(market, 'contractVal'),
1065
+ 'expiry': undefined,
1066
+ 'expiryDatetime': undefined,
1067
+ 'strike': undefined,
1068
+ 'optionType': undefined,
1069
+ 'precision': {
1070
+ 'amount': amountPrecision,
1071
+ 'price': pricePrecision,
1072
+ },
1073
+ 'limits': {
1074
+ 'leverage': {
1075
+ 'min': this.safeNumber(market, 'minLeverage'),
1076
+ 'max': this.safeNumber(market, 'maxLeverage'),
1077
+ },
1078
+ 'amount': {
1079
+ 'min': this.safeNumber2(market, 'minTradeAmount', 'minOrderSize'),
1080
+ 'max': this.safeNumber2(market, 'maxTradeAmount', 'maxOrderSize'),
1081
+ },
1082
+ 'price': {
1083
+ 'min': undefined,
1084
+ 'max': undefined,
1085
+ },
1086
+ 'cost': {
1087
+ 'min': undefined,
1088
+ 'max': undefined,
1089
+ },
1090
+ },
1091
+ 'created': undefined,
1092
+ 'percentage': fees['percentage'],
1093
+ 'tierBased': fees['tierBased'],
1094
+ 'tiers': fees['tiers'],
1095
+ 'info': market,
1096
+ });
1097
+ }
1098
+ /**
1099
+ * @method
1100
+ * @name weex#fetchTickers
1101
+ * @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
1102
+ * @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetAllTickerInfo // spot
1103
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetTicker24h // contract
1104
+ * @param {string} symbols 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.type] 'spot' or 'swap', default is 'spot' (used if symbols are not provided)
1107
+ * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
1108
+ */
1109
+ async fetchTickers(symbols = undefined, params = {}) {
1110
+ await this.loadMarkets();
1111
+ symbols = this.marketSymbols(symbols, undefined, true, true);
1112
+ const market = this.getMarketFromSymbols(symbols);
1113
+ let marketType = undefined;
1114
+ [marketType, params] = this.handleMarketTypeAndParams('fetchTickers', market, params);
1115
+ let symbolsLength = 0;
1116
+ if (symbols !== undefined) {
1117
+ symbolsLength = symbols.length;
1118
+ }
1119
+ const request = {};
1120
+ if (symbolsLength === 1) {
1121
+ request['symbol'] = market['id'];
1122
+ }
1123
+ let response = undefined;
1124
+ if (marketType === 'spot') {
1125
+ //
1126
+ // [
1127
+ // {
1128
+ // "symbol": "ETHUSDT",
1129
+ // "priceChange": "-72.98",
1130
+ // "priceChangePercent": "-0.033811",
1131
+ // "lastPrice": "2085.46",
1132
+ // "bidPrice": "2085.44",
1133
+ // "bidQty": "1.53848",
1134
+ // "askPrice": "2085.47",
1135
+ // "askQty": "1.87504",
1136
+ // "openPrice": "2158.44",
1137
+ // "highPrice": "2168.40",
1138
+ // "lowPrice": "2061.12",
1139
+ // "volume": "157359.56105",
1140
+ // "quoteVolume": "331284305.7193626",
1141
+ // "openTime": 1775493000000,
1142
+ // "closeTime": 1775579400000,
1143
+ // "count": 59727
1144
+ // }
1145
+ // ]
1146
+ //
1147
+ response = await this.publicGetApiV3MarketTicker24hr(this.extend(request, params));
1148
+ }
1149
+ else {
1150
+ //
1151
+ // [
1152
+ // {
1153
+ // "symbol": "ETHUSDT",
1154
+ // "priceChange": "-75.49",
1155
+ // "priceChangePercent": "-0.034992",
1156
+ // "lastPrice": "2081.80",
1157
+ // "openPrice": "2157.29",
1158
+ // "highPrice": "2167.51",
1159
+ // "lowPrice": "2059.17",
1160
+ // "volume": "623160.426",
1161
+ // "quoteVolume": "1310647345.19346",
1162
+ // "openTime": 1775493000000,
1163
+ // "closeTime": 1775579400000,
1164
+ // "markPrice": "2081.8",
1165
+ // "indexPrice": "2082.75"
1166
+ // }
1167
+ // ]
1168
+ //
1169
+ response = await this.contractGetCapiV3MarketTicker24hr(this.extend(request, params));
1170
+ }
1171
+ if (!Array.isArray(response)) {
1172
+ response = [response];
1173
+ }
1174
+ return this.parseTickers(response, symbols);
1175
+ }
1176
+ /**
1177
+ * @method
1178
+ * @name weex#fetchBidsAsks
1179
+ * @description fetches the bid and ask price and volume for multiple markets
1180
+ * @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetBookTicker // spot
1181
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetBookTicker // contract
1182
+ * @param {string[]|undefined} symbols unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
1183
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1184
+ * @param {string} [params.type] 'spot' or 'swap', default is 'spot' (used if symbols are not provided)
1185
+ * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
1186
+ */
1187
+ async fetchBidsAsks(symbols = undefined, params = {}) {
1188
+ symbols = this.marketSymbols(symbols, undefined, true, true);
1189
+ const market = this.getMarketFromSymbols(symbols);
1190
+ let marketType = undefined;
1191
+ [marketType, params] = this.handleMarketTypeAndParams('fetchTickers', market, params);
1192
+ let response = undefined;
1193
+ if (marketType === 'spot') {
1194
+ response = await this.publicGetApiV3MarketTickerBookTicker(params);
1195
+ }
1196
+ else {
1197
+ response = await this.contractGetCapiV3MarketTickerBookTicker(params);
1198
+ }
1199
+ if (!Array.isArray(response)) {
1200
+ response = [response];
1201
+ }
1202
+ return this.parseTickers(response, symbols);
1203
+ }
1204
+ parseTicker(ticker, market = undefined) {
1205
+ //
1206
+ // spot
1207
+ // {
1208
+ // "symbol": "ETHUSDT",
1209
+ // "priceChange": "-72.98",
1210
+ // "priceChangePercent": "-0.033811",
1211
+ // "lastPrice": "2085.46",
1212
+ // "bidPrice": "2085.44",
1213
+ // "bidQty": "1.53848",
1214
+ // "askPrice": "2085.47",
1215
+ // "askQty": "1.87504",
1216
+ // "openPrice": "2158.44",
1217
+ // "highPrice": "2168.40",
1218
+ // "lowPrice": "2061.12",
1219
+ // "volume": "157359.56105",
1220
+ // "quoteVolume": "331284305.7193626",
1221
+ // "openTime": 1775493000000,
1222
+ // "closeTime": 1775579400000,
1223
+ // "count": 59727
1224
+ // }
1225
+ //
1226
+ // swap
1227
+ // {
1228
+ // "symbol": "ETHUSDT",
1229
+ // "priceChange": "-75.49",
1230
+ // "priceChangePercent": "-0.034992",
1231
+ // "lastPrice": "2081.80",
1232
+ // "openPrice": "2157.29",
1233
+ // "highPrice": "2167.51",
1234
+ // "lowPrice": "2059.17",
1235
+ // "volume": "623160.426",
1236
+ // "quoteVolume": "1310647345.19346",
1237
+ // "openTime": 1775493000000,
1238
+ // "closeTime": 1775579400000,
1239
+ // "markPrice": "2081.8",
1240
+ // "indexPrice": "2082.75"
1241
+ // }
1242
+ //
1243
+ const marketId = this.safeString(ticker, 'symbol');
1244
+ const markPrice = this.safeString(ticker, 'markPrice');
1245
+ let marketType = 'spot';
1246
+ if (markPrice !== undefined) {
1247
+ marketType = 'swap';
1248
+ }
1249
+ market = this.safeMarket(marketId, market, undefined, marketType);
1250
+ const timestamp = this.safeInteger2(ticker, 'closeTime', 'time');
1251
+ return this.safeTicker({
1252
+ 'symbol': market['symbol'],
1253
+ 'timestamp': timestamp,
1254
+ 'datetime': this.iso8601(timestamp),
1255
+ 'high': this.safeString(ticker, 'highPrice'),
1256
+ 'low': this.safeString(ticker, 'lowPrice'),
1257
+ 'bid': this.safeString(ticker, 'bidPrice'),
1258
+ 'bidVolume': this.safeString(ticker, 'bidQty'),
1259
+ 'ask': this.safeString(ticker, 'askPrice'),
1260
+ 'askVolume': this.safeString(ticker, 'askQty'),
1261
+ 'vwap': undefined,
1262
+ 'open': this.safeString(ticker, 'openPrice'),
1263
+ 'close': this.safeString(ticker, 'lastPrice'),
1264
+ 'last': this.safeString(ticker, 'lastPrice'),
1265
+ 'previousClose': undefined,
1266
+ 'change': this.safeString(ticker, 'priceChange'),
1267
+ 'percentage': this.safeString(ticker, 'priceChangePercent'),
1268
+ 'average': undefined,
1269
+ 'baseVolume': this.safeString(ticker, 'volume'),
1270
+ 'quoteVolume': this.safeString(ticker, 'quoteVolume'),
1271
+ 'markPrice': markPrice,
1272
+ 'indexPrice': this.safeString(ticker, 'indexPrice'),
1273
+ 'info': ticker,
1274
+ }, market);
1275
+ }
1276
+ /**
1277
+ * @method
1278
+ * @name weex#fetchOrderBook
1279
+ * @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
1280
+ * @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetDepthData // spot
1281
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetDepthData // contract
1282
+ * @param {string} symbol unified symbol of the market to fetch the order book for
1283
+ * @param {int} [limit] the maximum amount of order book entries to return (default 15, max 200)
1284
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1285
+ * @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure} indexed by market symbols
1286
+ */
1287
+ async fetchOrderBook(symbol, limit = undefined, params = {}) {
1288
+ await this.loadMarkets();
1289
+ const market = this.market(symbol);
1290
+ const request = {
1291
+ 'symbol': market['id'],
1292
+ };
1293
+ if ((limit !== undefined) && (limit > 15)) {
1294
+ request['limit'] = 200; // default is 15, max is 200
1295
+ }
1296
+ let response = undefined;
1297
+ if (market['spot']) {
1298
+ response = await this.publicGetApiV3MarketDepth(this.extend(request, params));
1299
+ }
1300
+ else {
1301
+ response = await this.contractGetCapiV3MarketDepth(this.extend(request, params));
1302
+ }
1303
+ //
1304
+ // {
1305
+ // "asks": [
1306
+ // [
1307
+ // "2096.77",
1308
+ // "45.592"
1309
+ // ]
1310
+ // ],
1311
+ // "bids": [
1312
+ // [
1313
+ // "2096.76",
1314
+ // "49.162"
1315
+ // ]
1316
+ // ],
1317
+ // "lastUpdateId": 14138610208
1318
+ // }
1319
+ //
1320
+ const orderbook = this.parseOrderBook(response, symbol);
1321
+ orderbook['nonce'] = this.safeInteger(response, 'lastUpdateId');
1322
+ return orderbook;
1323
+ }
1324
+ /**
1325
+ * @method
1326
+ * @name weex#fetchOHLCV
1327
+ * @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
1328
+ * @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetKLineData // spot
1329
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetKlines // contract last price
1330
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetIndexPriceKlines // contract index price
1331
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetMarkPriceKlines // contract mark price
1332
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetHistoryKlines // contract historical klines
1333
+ * @param {string} symbol unified symbol of the market to fetch OHLCV data for
1334
+ * @param {string} timeframe the length of time each candle represents
1335
+ * @param {int} [since] timestamp in ms of the earliest candle to fetch
1336
+ * @param {int} [limit] the maximum amount of candles to fetch (default 100, max 300)
1337
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1338
+ * Check fetchSpotOHLCV() and fetchContractOHLCV() for more details on the extra parameters that can be used in params
1339
+ * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
1340
+ */
1341
+ async fetchOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
1342
+ await this.loadMarkets();
1343
+ const market = this.market(symbol);
1344
+ if (market['spot']) {
1345
+ return await this.fetchSpotOHLCV(symbol, timeframe, since, limit, params);
1346
+ }
1347
+ else {
1348
+ return await this.fetchContractOHLCV(symbol, timeframe, since, limit, params);
1349
+ }
1350
+ }
1351
+ /**
1352
+ * @method
1353
+ * @ignore
1354
+ * @name weex#fetchSpotOHLCV
1355
+ * @description helper method for fetchOHLCV
1356
+ * @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetKLineData
1357
+ * @param {string} symbol unified symbol of the market to fetch OHLCV data for
1358
+ * @param {string} timeframe the length of time each candle represents
1359
+ * @param {int} [since] timestamp in ms of the earliest candle to fetch
1360
+ * @param {int} [limit] the maximum amount of candles to fetch
1361
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1362
+ * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
1363
+ */
1364
+ async fetchSpotOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
1365
+ await this.loadMarkets();
1366
+ const market = this.market(symbol);
1367
+ const request = {
1368
+ 'symbol': market['id'],
1369
+ 'interval': this.safeString(this.timeframes, timeframe, timeframe),
1370
+ };
1371
+ const response = await this.publicGetApiV3MarketKlines(this.extend(request, params));
1372
+ return this.parseOHLCVs(response, market, timeframe, since, limit);
1373
+ }
1374
+ /**
1375
+ * @method
1376
+ * @ignore
1377
+ * @name weex#fetchContractOHLCV
1378
+ * @description helper method for fetchOHLCV
1379
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetKlines // contract last price
1380
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetIndexPriceKlines // contract index price
1381
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetMarkPriceKlines // contract mark price
1382
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetHistoryKlines // contract historical klines
1383
+ * @param {string} symbol unified symbol of the market to fetch OHLCV data for
1384
+ * @param {string} timeframe the length of time each candle represents
1385
+ * @param {int} [since] timestamp in ms of the earliest candle to fetch
1386
+ * @param {int} [limit] the maximum amount of candles to fetch (default 100, max 100 for historical klines, max 1000 for other contract klines)
1387
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1388
+ * @param {int} [params.until] timestamp in ms of the latest candle to fetch
1389
+ * @param {boolean} [params.paginate] whether to automatically paginate requests until the required number of candles is returned
1390
+ * @param {boolean} [params.historical] whether to fetch historical klines (default is false). If false, will fetch last price klines
1391
+ * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
1392
+ */
1393
+ async fetchContractOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
1394
+ await this.loadMarkets();
1395
+ const maxHistoricalLimit = 100;
1396
+ let paginate = false;
1397
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchOHLCV', 'paginate');
1398
+ if (paginate) {
1399
+ params = this.extend(params, { 'historical': true });
1400
+ return await this.fetchPaginatedCallDeterministic('fetchOHLCV', symbol, since, limit, timeframe, params, maxHistoricalLimit);
1401
+ }
1402
+ const until = this.safeInteger(params, 'until');
1403
+ let historical = false;
1404
+ [historical, params] = this.handleOptionAndParams(params, 'fetchOHLCV', 'historical');
1405
+ const timeframeOption = this.safeDict(this.options, 'timeframes', {});
1406
+ const contractTimeframes = this.safeDict(timeframeOption, 'contract', {});
1407
+ const market = this.market(symbol);
1408
+ const request = {
1409
+ 'symbol': market['id'],
1410
+ 'interval': this.safeString(contractTimeframes, timeframe, timeframe),
1411
+ };
1412
+ const priceType = this.safeStringUpper(params, 'price');
1413
+ params = this.omit(params, ['historical', 'until', 'price']);
1414
+ let response = undefined;
1415
+ if (historical) {
1416
+ if (priceType !== undefined) {
1417
+ request['priceType'] = priceType;
1418
+ }
1419
+ let startTime = since;
1420
+ let endTime = until;
1421
+ if ((since === undefined) || (until === undefined)) {
1422
+ const now = this.milliseconds();
1423
+ const duration = this.parseTimeframe(timeframe) * 1000;
1424
+ const numberOfCandles = limit ? limit : maxHistoricalLimit;
1425
+ const timeDelta = numberOfCandles * duration;
1426
+ if ((since === undefined) && (until === undefined)) {
1427
+ endTime = now;
1428
+ startTime = now - timeDelta;
1429
+ }
1430
+ else if (since === undefined) {
1431
+ startTime = until - timeDelta;
1432
+ }
1433
+ else {
1434
+ endTime = since + timeDelta;
1435
+ }
1436
+ }
1437
+ request['startTime'] = startTime;
1438
+ request['endTime'] = endTime;
1439
+ response = await this.contractGetCapiV3MarketHistoryKlines(this.extend(request, params));
1440
+ }
1441
+ else {
1442
+ if (limit !== undefined) {
1443
+ request['limit'] = limit;
1444
+ }
1445
+ if (priceType === 'MARK') {
1446
+ response = await this.contractGetCapiV3MarketMarkPriceKlines(this.extend(request, params));
1447
+ }
1448
+ else if (priceType === 'INDEX') {
1449
+ response = await this.contractGetCapiV3MarketIndexPriceKlines(this.extend(request, params));
1450
+ }
1451
+ else {
1452
+ response = await this.contractGetCapiV3MarketKlines(this.extend(request, params));
1453
+ }
1454
+ }
1455
+ return this.parseOHLCVs(response, market, timeframe, since, limit);
1456
+ }
1457
+ parseOHLCV(ohlcv, market = undefined) {
1458
+ return [
1459
+ this.safeInteger(ohlcv, 0),
1460
+ this.safeNumber(ohlcv, 1),
1461
+ this.safeNumber(ohlcv, 2),
1462
+ this.safeNumber(ohlcv, 3),
1463
+ this.safeNumber(ohlcv, 4),
1464
+ this.safeNumber(ohlcv, 5),
1465
+ ];
1466
+ }
1467
+ /**
1468
+ * @method
1469
+ * @name weex#fetchTrades
1470
+ * @description get the list of most recent trades for a particular symbol
1471
+ * @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetTradeData // spot
1472
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetRecentTrades // contract
1473
+ * @param {string} symbol unified symbol of the market to fetch trades for
1474
+ * @param {int} [since] timestamp in ms of the earliest trade to fetch
1475
+ * @param {int} [limit] the maximum amount of trades to fetch (default 100, max 1000)
1476
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1477
+ * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
1478
+ */
1479
+ async fetchTrades(symbol, since = undefined, limit = undefined, params = {}) {
1480
+ await this.loadMarkets();
1481
+ const market = this.market(symbol);
1482
+ const request = {
1483
+ 'symbol': market['id'],
1484
+ };
1485
+ if (limit !== undefined) {
1486
+ request['limit'] = limit;
1487
+ }
1488
+ let response = undefined;
1489
+ if (market['spot']) {
1490
+ response = await this.publicGetApiV3MarketTrades(this.extend(request, params));
1491
+ }
1492
+ else {
1493
+ response = await this.contractGetCapiV3MarketTrades(this.extend(request, params));
1494
+ }
1495
+ //
1496
+ // [
1497
+ // {
1498
+ // "id": "875fba11-f8a1-42ad-915d-012ccb375e8a",
1499
+ // "price": "2114.77",
1500
+ // "qty": "0.01000",
1501
+ // "quoteQty": "21.1477000",
1502
+ // "time": 1775594995485,
1503
+ // "isBuyerMaker": false,
1504
+ // "isBestMatch": true
1505
+ // }
1506
+ // ]
1507
+ //
1508
+ return this.parseTrades(response, market, since, limit);
1509
+ }
1510
+ parseTrade(trade, market = undefined) {
1511
+ //
1512
+ // fetchTrades
1513
+ // {
1514
+ // "id": "875fba11-f8a1-42ad-915d-012ccb375e8a",
1515
+ // "price": "2114.77",
1516
+ // "qty": "0.01000",
1517
+ // "quoteQty": "21.1477000",
1518
+ // "time": 1775594995485,
1519
+ // "isBuyerMaker": false,
1520
+ // "isBestMatch": true
1521
+ // }
1522
+ //
1523
+ // fetchMyTrades (spot)
1524
+ // {
1525
+ // "symbol": "DOGEUSDT",
1526
+ // "id": 736825748291060702,
1527
+ // "orderId": 736825748215563230,
1528
+ // "price": "0.09349",
1529
+ // "qty": "250.0",
1530
+ // "quoteQty": "23.3725",
1531
+ // "commission": "0.0233725",
1532
+ // "time": 1775672947953,
1533
+ // "isBuyer": false
1534
+ // }
1535
+ //
1536
+ // fetchMyTrades (contract)
1537
+ // {
1538
+ // "id": 737074389731770728,
1539
+ // "orderId": 737074043320009064,
1540
+ // "symbol": "DOGEUSDT",
1541
+ // "buyer": true,
1542
+ // "commission": "0.00183500",
1543
+ // "commissionAsset": "USDT",
1544
+ // "maker": true,
1545
+ // "price": "0.09175",
1546
+ // "qty": "100",
1547
+ // "quoteQty": "9.17500",
1548
+ // "realizedPnl": "0",
1549
+ // "side": "BUY",
1550
+ // "positionSide": "LONG",
1551
+ // "time": 1775732228692
1552
+ // }
1553
+ //
1554
+ const timestamp = this.safeInteger(trade, 'time');
1555
+ const isBuyer = this.safeBool(trade, 'isBuyer');
1556
+ let side = this.safeStringLower(trade, 'side');
1557
+ if (isBuyer !== undefined) {
1558
+ side = isBuyer ? 'buy' : 'sell';
1559
+ }
1560
+ let isSpot = true;
1561
+ if (market === undefined) {
1562
+ const marketId = this.safeString(trade, 'symbol');
1563
+ const realizedPnl = this.safeString(trade, 'realizedPnl');
1564
+ const marketType = (realizedPnl !== undefined) ? 'swap' : 'spot';
1565
+ market = this.safeMarket(marketId, undefined, undefined, marketType);
1566
+ isSpot = marketType === 'spot';
1567
+ }
1568
+ else {
1569
+ isSpot = market['spot'];
1570
+ }
1571
+ let fee = undefined;
1572
+ const commission = this.safeString(trade, 'commission');
1573
+ if (commission !== undefined) {
1574
+ const commissionAsset = this.safeString(trade, 'commissionAsset');
1575
+ let feeCurrency = this.safeCurrencyCode(commissionAsset);
1576
+ if (isSpot) {
1577
+ if (side === 'buy') {
1578
+ feeCurrency = market['base'];
1579
+ }
1580
+ else {
1581
+ feeCurrency = market['quote'];
1582
+ }
1583
+ }
1584
+ fee = {
1585
+ 'cost': commission,
1586
+ 'currency': feeCurrency,
1587
+ };
1588
+ }
1589
+ const isMaker = this.safeBool(trade, 'maker');
1590
+ let takerOrMaker = undefined;
1591
+ if (isMaker !== undefined) {
1592
+ takerOrMaker = isMaker ? 'maker' : 'taker';
1593
+ }
1594
+ return this.safeTrade({
1595
+ 'info': trade,
1596
+ 'id': this.safeString(trade, 'id'),
1597
+ 'order': this.safeString(trade, 'orderId'),
1598
+ 'timestamp': timestamp,
1599
+ 'datetime': this.iso8601(timestamp),
1600
+ 'symbol': market['symbol'],
1601
+ 'type': undefined,
1602
+ 'takerOrMaker': takerOrMaker,
1603
+ 'side': side,
1604
+ 'price': this.safeString(trade, 'price'),
1605
+ 'amount': this.safeString(trade, 'qty'),
1606
+ 'cost': this.safeString(trade, 'quoteQty'),
1607
+ 'fee': fee,
1608
+ }, market);
1609
+ }
1610
+ /**
1611
+ * @method
1612
+ * @name weex#fetchOpenInterest
1613
+ * @description retrieves the open interest of a contract trading pair
1614
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetOpenInterest
1615
+ * @param {string} symbol unified CCXT market symbol
1616
+ * @param {object} [params] exchange specific parameters
1617
+ * @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
1618
+ */
1619
+ async fetchOpenInterest(symbol, params = {}) {
1620
+ await this.loadMarkets();
1621
+ const market = this.market(symbol);
1622
+ const request = {
1623
+ 'symbol': market['id'],
1624
+ };
1625
+ const response = await this.contractGetCapiV3MarketOpenInterest(this.extend(request, params));
1626
+ return this.parseOpenInterest(response, market);
1627
+ }
1628
+ parseOpenInterest(interest, market = undefined) {
1629
+ //
1630
+ // {
1631
+ // "symbol": "ETHUSDT",
1632
+ // "openInterest": "1772356.352",
1633
+ // "time": 1775595582598
1634
+ // }
1635
+ //
1636
+ const marketId = this.safeString(interest, 'symbol');
1637
+ const symbol = this.safeSymbol(marketId, market, undefined, 'swap');
1638
+ const timestamp = this.safeInteger(interest, 'time');
1639
+ return this.safeOpenInterest({
1640
+ 'symbol': symbol,
1641
+ 'openInterestAmount': this.safeString(interest, 'openInterest'),
1642
+ 'openInterestValue': undefined,
1643
+ 'timestamp': timestamp,
1644
+ 'datetime': this.iso8601(timestamp),
1645
+ 'info': interest,
1646
+ }, market);
1647
+ }
1648
+ /**
1649
+ * @method
1650
+ * @name weex#fetchFundingRates
1651
+ * @description fetch the funding rate for multiple markets
1652
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetCurrentFundingRate
1653
+ * @param {string[]|undefined} symbols list of unified market symbols
1654
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1655
+ * @param {string} [params.subType] "linear" or "inverse"
1656
+ * @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rates-structure}, indexed by market symbols
1657
+ */
1658
+ async fetchFundingRates(symbols = undefined, params = {}) {
1659
+ await this.loadMarkets();
1660
+ symbols = this.marketSymbols(symbols);
1661
+ let symbolsLength = 0;
1662
+ if (symbols !== undefined) {
1663
+ symbolsLength = symbols.length;
1664
+ }
1665
+ const request = {};
1666
+ if (symbolsLength === 1) {
1667
+ const market = this.getMarketFromSymbols(symbols);
1668
+ request['symbol'] = market['id'];
1669
+ }
1670
+ const response = await this.contractGetCapiV3MarketPremiumIndex(this.extend(request, params));
1671
+ //
1672
+ // [
1673
+ // {
1674
+ // "symbol": "ETHUSDT",
1675
+ // "markPrice": "2133.71",
1676
+ // "indexPrice": "2134.44",
1677
+ // "forecastFundingRate": "0.00005618",
1678
+ // "lastFundingRate": "0.00001031",
1679
+ // "interestRate": "0.001",
1680
+ // "nextFundingTime": 1775606400000,
1681
+ // "time": 1775597594265,
1682
+ // "collectCycle": 480
1683
+ // }
1684
+ // ]
1685
+ //
1686
+ return this.parseFundingRates(response, symbols);
1687
+ }
1688
+ parseFundingRate(contract, market = undefined) {
1689
+ const marketId = this.safeString(contract, 'symbol');
1690
+ const symbol = this.safeSymbol(marketId, market, undefined, 'swap');
1691
+ const timestamp = this.safeInteger(contract, 'time');
1692
+ const nextFundingTimestamp = this.safeInteger(contract, 'nextFundingTime');
1693
+ let interval = undefined;
1694
+ const collectCycle = this.safeString(contract, 'collectCycle');
1695
+ if (collectCycle !== undefined) {
1696
+ interval = Precise["default"].stringDiv(collectCycle, '60');
1697
+ interval = interval + 'h';
1698
+ }
1699
+ return {
1700
+ 'info': contract,
1701
+ 'symbol': symbol,
1702
+ 'markPrice': this.safeNumber(contract, 'markPrice'),
1703
+ 'indexPrice': this.safeNumber(contract, 'indexPrice'),
1704
+ 'interestRate': this.safeNumber(contract, 'interestRate'),
1705
+ 'estimatedSettlePrice': undefined,
1706
+ 'timestamp': timestamp,
1707
+ 'datetime': this.iso8601(timestamp),
1708
+ 'fundingRate': this.safeNumber(contract, 'lastFundingRate'),
1709
+ 'fundingTimestamp': timestamp,
1710
+ 'fundingDatetime': this.iso8601(timestamp),
1711
+ 'nextFundingRate': this.safeNumber(contract, 'forecastFundingRate'),
1712
+ 'nextFundingTimestamp': nextFundingTimestamp,
1713
+ 'nextFundingDatetime': this.iso8601(nextFundingTimestamp),
1714
+ 'previousFundingRate': undefined,
1715
+ 'previousFundingTimestamp': undefined,
1716
+ 'previousFundingDatetime': undefined,
1717
+ 'interval': interval,
1718
+ };
1719
+ }
1720
+ /**
1721
+ * @method
1722
+ * @name weex#fetchFundingRateHistory
1723
+ * @description fetches historical funding rate prices
1724
+ * @see https://www.weex.com/api-doc/contract/Market_API/GetFundingRateHistory
1725
+ * @param {string} symbol unified symbol of the market to fetch the funding rate history for
1726
+ * @param {int} [since] timestamp in ms of the earliest funding rate to fetch
1727
+ * @param {int} [limit] the maximum amount of funding rate records to fetch (default 100, max 1000)
1728
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1729
+ * @param {int} [params.until] timestamp in ms of the latest funding rate
1730
+ * @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
1731
+ */
1732
+ async fetchFundingRateHistory(symbol = undefined, since = undefined, limit = undefined, params = {}) {
1733
+ if (symbol === undefined) {
1734
+ throw new errors.ArgumentsRequired(this.id + ' fetchFundingRateHistory() requires a symbol argument');
1735
+ }
1736
+ await this.loadMarkets();
1737
+ const market = this.market(symbol);
1738
+ let request = {
1739
+ 'symbol': market['id'],
1740
+ };
1741
+ if (since !== undefined) {
1742
+ request['startTime'] = since;
1743
+ }
1744
+ if (limit !== undefined) {
1745
+ request['limit'] = limit;
1746
+ }
1747
+ [request, params] = this.handleUntilOption('endTime', request, params);
1748
+ const response = await this.contractGetCapiV3MarketFundingRate(this.extend(request, params));
1749
+ return this.parseFundingRateHistories(response, market, since, limit);
1750
+ }
1751
+ parseFundingRateHistory(contract, market = undefined) {
1752
+ //
1753
+ // {
1754
+ // "symbol": "ETHUSDT",
1755
+ // "fundingRate": "0.00001031",
1756
+ // "fundingTime": 1775577600000,
1757
+ // "markPrice": "2079.26"
1758
+ // }
1759
+ //
1760
+ const marketId = this.safeString(contract, 'symbol');
1761
+ const symbol = this.safeSymbol(marketId, market, undefined, 'swap');
1762
+ const timestamp = this.safeInteger(contract, 'fundingTime');
1763
+ return {
1764
+ 'info': contract,
1765
+ 'symbol': symbol,
1766
+ 'fundingRate': this.safeNumber(contract, 'fundingRate'),
1767
+ 'timestamp': timestamp,
1768
+ 'datetime': this.iso8601(timestamp),
1769
+ };
1770
+ }
1771
+ /**
1772
+ * @method
1773
+ * @name weex#fetchBalance
1774
+ * @see https://www.weex.com/api-doc/spot/AccountAPI/GetAccountBalance // spot
1775
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetAccountBalance // contract
1776
+ * @description query for balance and get the amount of funds available for trading or funds locked in positions
1777
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1778
+ * @param {string} [params.type] 'spot' or 'swap' (default is 'spot')
1779
+ * @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure}
1780
+ */
1781
+ async fetchBalance(params = {}) {
1782
+ let type = undefined;
1783
+ [type, params] = this.handleMarketTypeAndParams('fetchBalance', undefined, params);
1784
+ let response = undefined;
1785
+ if (type === 'spot') {
1786
+ //
1787
+ // {
1788
+ // "makerCommission": 0,
1789
+ // "takerCommission": 0,
1790
+ // "commissionRates": {
1791
+ // "maker": "0.00000000",
1792
+ // "taker": "0.00000000"
1793
+ // },
1794
+ // "canTrade": true,
1795
+ // "canWithdraw": true,
1796
+ // "canDeposit": true,
1797
+ // "updateTime": 1775601317093,
1798
+ // "accountType": "SPOT",
1799
+ // "balances": [
1800
+ // {
1801
+ // "asset": "USDT",
1802
+ // "free": "20.00000000",
1803
+ // "locked": "0"
1804
+ // }
1805
+ // ],
1806
+ // "permissions": [
1807
+ // "SPOT"
1808
+ // ],
1809
+ // "uid": 8886281669
1810
+ // }
1811
+ //
1812
+ response = await this.privateGetApiV3Account(params);
1813
+ }
1814
+ else {
1815
+ //
1816
+ // [
1817
+ // {
1818
+ // "asset": "USDT",
1819
+ // "balance": "20.00000000",
1820
+ // "availableBalance": "20.00000000",
1821
+ // "frozen": "0",
1822
+ // "unrealizePnl": "0"
1823
+ // }
1824
+ // ]
1825
+ //
1826
+ response = await this.contractPrivateGetCapiV3AccountBalance(params);
1827
+ }
1828
+ return this.parseBalance(response);
1829
+ }
1830
+ parseBalance(response) {
1831
+ const result = {
1832
+ 'info': response,
1833
+ };
1834
+ const balances = this.safeList(response, 'balances', response);
1835
+ for (let i = 0; i < balances.length; i++) {
1836
+ const entry = this.safeDict(balances, i);
1837
+ const id = this.safeString(entry, 'asset');
1838
+ const code = this.safeCurrencyCode(id);
1839
+ const account = this.account();
1840
+ account['free'] = this.safeString2(entry, 'availableBalance', 'free');
1841
+ account['used'] = this.safeString2(entry, 'frozen', 'locked');
1842
+ account['total'] = this.safeString(entry, 'balance');
1843
+ result[code] = account;
1844
+ }
1845
+ return this.safeBalance(result);
1846
+ }
1847
+ /**
1848
+ * @method
1849
+ * @name weex#fetchTransfers
1850
+ * @description fetch a history of internal transfers made on an account
1851
+ * @see https://www.weex.com/api-doc/spot/AccountAPI/TransferRecords
1852
+ * @param {string} [code] unified currency code of the currency transferred
1853
+ * @param {int} [since] the earliest time in ms to fetch transfers for
1854
+ * @param {int} [limit] the maximum number of transfers structures to retrieve (default 10, max 100)
1855
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1856
+ * @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)
1857
+ * @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
1858
+ */
1859
+ async fetchTransfers(code = undefined, since = undefined, limit = undefined, params = {}) {
1860
+ await this.loadMarkets();
1861
+ let request = {};
1862
+ let currency = undefined;
1863
+ if (code !== undefined) {
1864
+ currency = this.currency(code);
1865
+ }
1866
+ const maxLimit = 100;
1867
+ let paginate = false;
1868
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchTransfers', 'paginate', false);
1869
+ if (paginate) {
1870
+ return await this.fetchPaginatedCallDynamic('fetchTransfers', code, since, limit, params, maxLimit);
1871
+ }
1872
+ if (since !== undefined) {
1873
+ request['after'] = since;
1874
+ }
1875
+ if (limit !== undefined) {
1876
+ request['limit'] = limit;
1877
+ }
1878
+ [request, params] = this.handleUntilOption('before', request, params);
1879
+ const response = await this.privateGetApiV3AccountTransferRecords(this.extend(request, params));
1880
+ //
1881
+ // [
1882
+ // {
1883
+ // "coinName": "USDT",
1884
+ // "status": "Successful",
1885
+ // "toType": "",
1886
+ // "toSymbol": "",
1887
+ // "fromType": "",
1888
+ // "fromSymbol": "",
1889
+ // "amount": "20.00000000",
1890
+ // "tradeTime": "1775605824252"
1891
+ // }
1892
+ // ]
1893
+ //
1894
+ return this.parseTransfers(response, currency, since, limit);
1895
+ }
1896
+ parseTransfer(transfer, currency = undefined) {
1897
+ const timestamp = this.safeInteger(transfer, 'tradeTime');
1898
+ const currencyId = this.safeString(transfer, 'coinName');
1899
+ const currencyCode = this.safeCurrencyCode(currencyId, currency);
1900
+ const status = this.safeString(transfer, 'status');
1901
+ return {
1902
+ 'info': transfer,
1903
+ 'id': undefined,
1904
+ 'timestamp': timestamp,
1905
+ 'datetime': this.iso8601(timestamp),
1906
+ 'currency': currencyCode,
1907
+ 'amount': this.safeNumber(transfer, 'amount'),
1908
+ 'fromAccount': this.safeStringLower(transfer, 'fromType'),
1909
+ 'toAccount': this.safeStringLower(transfer, 'toType'),
1910
+ 'status': this.parseTransferStatus(status),
1911
+ };
1912
+ }
1913
+ parseTransferStatus(status) {
1914
+ const statuses = {
1915
+ 'Successful': 'ok',
1916
+ };
1917
+ return this.safeString(statuses, status, status);
1918
+ }
1919
+ /**
1920
+ * @method
1921
+ * @name weex#createOrder
1922
+ * @description Create an order on the exchange
1923
+ * @see https://www.weex.com/api-doc/spot/orderApi/PlaceOrder // spot
1924
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/PlaceOrder // contract
1925
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/PlacePendingOrder // contract trigger
1926
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/PlaceTpSlOrder // contract take profit / stop loss
1927
+ * @param {string} symbol Unified CCXT market symbol
1928
+ * @param {string} type 'limit' or 'market'
1929
+ * @param {string} side 'buy' or 'sell'
1930
+ * @param {float} amount the amount of currency to trade
1931
+ * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1932
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1933
+ * Check createSpotOrder() and createContractOrder() for more details on the extra parameters that can be used in params
1934
+ * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
1935
+ */
1936
+ async createOrder(symbol, type, side, amount, price = undefined, params = {}) {
1937
+ await this.loadMarkets();
1938
+ const market = this.market(symbol);
1939
+ if (market['contract']) {
1940
+ return await this.createContractOrder(symbol, type, side, amount, price, params);
1941
+ }
1942
+ else {
1943
+ return await this.createSpotOrder(symbol, type, side, amount, price, params);
1944
+ }
1945
+ }
1946
+ /**
1947
+ * @method
1948
+ * @name weex#createSpotOrder
1949
+ * @description helper method for creating spot orders
1950
+ * @see https://www.weex.com/api-doc/spot/orderApi/PlaceOrder
1951
+ * @param {string} symbol Unified CCXT market symbol
1952
+ * @param {string} type 'limit' or 'market'
1953
+ * @param {string} side 'buy' or 'sell'
1954
+ * @param {float} amount the amount of currency to trade
1955
+ * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
1956
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
1957
+ * @param {string} [params.clientOrderId] client order id
1958
+ * @param {string} [params.timeInForce] 'GTC', 'IOC', or 'FOK'
1959
+ * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
1960
+ */
1961
+ async createSpotOrder(symbol, type, side, amount, price = undefined, params = {}) {
1962
+ await this.loadMarkets();
1963
+ const market = this.market(symbol);
1964
+ const request = this.createSpotOrderRequest(symbol, type, side, amount, price, params);
1965
+ const response = await this.privatePostApiV3Order(request);
1966
+ //
1967
+ // {
1968
+ // "symbol": "DOGEUSDT",
1969
+ // "orderId": 736557215397183592,
1970
+ // "clientOrderId": "c4551206d34641efbeb64abaa066946d",
1971
+ // "transactTime": 1775608924724
1972
+ // }
1973
+ //
1974
+ return this.parseOrder(response, market);
1975
+ }
1976
+ createSpotOrderRequest(symbol, type, side, amount, price = undefined, params = {}) {
1977
+ const market = this.market(symbol);
1978
+ const request = {
1979
+ 'symbol': market['id'],
1980
+ 'side': side.toUpperCase(),
1981
+ 'type': type.toUpperCase(),
1982
+ 'quantity': this.amountToPrecision(symbol, amount),
1983
+ };
1984
+ if (type === 'limit') {
1985
+ request['price'] = this.priceToPrecision(symbol, price);
1986
+ }
1987
+ let clientOrderId = this.safeString(params, 'clientOrderId');
1988
+ params = this.omit(params, 'clientOrderId');
1989
+ if (clientOrderId === undefined) {
1990
+ const partner = this.safeString(params, 'partner', 'b-WEEX111125');
1991
+ clientOrderId = partner + '-' + this.uuid22();
1992
+ }
1993
+ request['newClientOrderId'] = clientOrderId;
1994
+ // timeInForce is passed directly from params
1995
+ return this.extend(request, params);
1996
+ }
1997
+ /**
1998
+ * @method
1999
+ * @name weex#createContractOrder
2000
+ * @description helper method for creating contract orders
2001
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/PlaceOrder
2002
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/PlacePendingOrder
2003
+ * @param {string} symbol Unified CCXT market symbol
2004
+ * @param {string} type 'limit' or 'market'
2005
+ * @param {string} side 'buy' or 'sell'
2006
+ * @param {float} amount the amount of currency to trade
2007
+ * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
2008
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2009
+ * @param {string} [params.clientOrderId] client order id
2010
+ * @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered and the triggerPriceType
2011
+ * @param {float} [params.takeProfit.triggerPrice] The price at which the take profit order will be triggered
2012
+ * @param {string} [params.takeProfit.triggerPriceType] The type of the trigger price for the take profit order, either 'last' or 'mark' (default is 'last')
2013
+ * @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered and the triggerPriceType
2014
+ * @param {float} [params.stopLoss.triggerPrice] The price at which the stop loss order will be triggered
2015
+ * @param {string} [params.stopLoss.triggerPriceType] The type of the trigger price for the stop loss order, either 'last' or 'mark' (default is 'last')
2016
+ * @param {float} [params.stopLossPrice] price to trigger stop-loss orders
2017
+ * @param {string} [params.stopLossPriceType] The type of the trigger price for the stop loss order, either 'last' or 'mark' (default is 'last')
2018
+ * @param {float} [params.takeProfitPrice] price to trigger take-profit orders
2019
+ * @param {string} [params.takeProfitPriceType] The type of the trigger price for the take profit order, either 'last' or 'mark' (default is 'last')
2020
+ * @param {bool} [params.reduceOnly] A mark to reduce the position size only. Set to false by default. Need to set the position size when reduceOnly is true.
2021
+ * @param {string} [params.timeInForce] GTC, IOC, or FOK (default is GTC for limit orders)
2022
+ * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
2023
+ */
2024
+ async createContractOrder(symbol, type, side, amount, price = undefined, params = {}) {
2025
+ await this.loadMarkets();
2026
+ const market = this.market(symbol);
2027
+ const request = this.createContractOrderRequest(symbol, type, side, amount, price, params);
2028
+ const triggerPrice = this.safeString(request, 'triggerPrice');
2029
+ let response = undefined;
2030
+ if (triggerPrice !== undefined) {
2031
+ response = await this.contractPrivatePostCapiV3AlgoOrder(request);
2032
+ }
2033
+ else {
2034
+ response = await this.contractPrivatePostCapiV3Order(request);
2035
+ }
2036
+ return this.parseOrder(response, market);
2037
+ }
2038
+ createContractOrderRequest(symbol, type, side, amount, price = undefined, params = {}) {
2039
+ const market = this.market(symbol);
2040
+ const request = {
2041
+ 'symbol': market['id'],
2042
+ 'side': side.toUpperCase(),
2043
+ 'quantity': this.amountToPrecision(symbol, amount),
2044
+ 'type': type.toUpperCase(),
2045
+ };
2046
+ const isMarketOrder = (type === 'market');
2047
+ if (!isMarketOrder) {
2048
+ request['price'] = this.priceToPrecision(symbol, price);
2049
+ }
2050
+ const [triggerPrice, stopLossPrice, takeProfitPrice, query] = this.handleTriggerPricesAndParams(symbol, params);
2051
+ if (triggerPrice !== undefined) {
2052
+ throw new errors.NotSupported(this.id + ' createOrder() does not support the triggerPrice parameter');
2053
+ }
2054
+ const isStopLoss = (stopLossPrice !== undefined);
2055
+ const isTakeProfit = (takeProfitPrice !== undefined);
2056
+ let reduceOnly = this.safeBool(query, 'reduceOnly');
2057
+ if (isStopLoss || isTakeProfit) {
2058
+ reduceOnly = true;
2059
+ }
2060
+ const isReduceOnly = (reduceOnly === true);
2061
+ let positionSide = 'LONG';
2062
+ if (isReduceOnly) {
2063
+ if (side === 'buy') {
2064
+ positionSide = 'SHORT';
2065
+ }
2066
+ }
2067
+ else if (side === 'sell') {
2068
+ positionSide = 'SHORT';
2069
+ }
2070
+ request['positionSide'] = positionSide;
2071
+ const takeProfit = this.safeDict(params, 'takeProfit');
2072
+ const hasTakeProfit = (takeProfit !== undefined);
2073
+ const stopLoss = this.safeDict(params, 'stopLoss');
2074
+ const hasStopLoss = (stopLoss !== undefined);
2075
+ const timeInForce = this.safeString(params, 'timeInForce');
2076
+ let clientOrderId = this.safeString(params, 'clientOrderId');
2077
+ if (clientOrderId === undefined) {
2078
+ const partner = this.safeString(params, 'partner', 'b-WEEX111125');
2079
+ clientOrderId = partner + '-' + this.uuid22();
2080
+ }
2081
+ const callerMethodName = this.safeString(params, 'callerMethodName');
2082
+ if (isStopLoss || isTakeProfit) {
2083
+ if (callerMethodName === 'createOrders') {
2084
+ throw new errors.NotSupported(this.id + ' createOrders() does not support stop loss and take profit orders');
2085
+ }
2086
+ if (timeInForce !== undefined) {
2087
+ throw new errors.BadRequest(this.id + ' createOrder() cannot use timeInForce parameter with stopLoss and takeProfit orders');
2088
+ }
2089
+ if (hasStopLoss || hasTakeProfit) {
2090
+ throw new errors.BadRequest(this.id + ' createOrder() cannot use both stopLossPrice/takeProfitPrice parameters and stopLoss/takeProfit objects in params at the same time');
2091
+ }
2092
+ if (isStopLoss && isTakeProfit) {
2093
+ throw new errors.BadRequest(this.id + ' createOrder() cannot use both stopLossPrice and takeProfitPrice parameters at the same time');
2094
+ }
2095
+ request['clientAlgoId'] = clientOrderId;
2096
+ let orderType = undefined;
2097
+ if (isStopLoss) {
2098
+ const stopLossPriceType = this.safeString2(params, 'stopLossPriceType', 'triggerPriceType');
2099
+ if (stopLossPriceType !== undefined) {
2100
+ params['SlWorkingType'] = this.encodeTriggerPriceType(stopLossPriceType);
2101
+ }
2102
+ params['triggerPrice'] = this.priceToPrecision(symbol, stopLossPrice);
2103
+ if (isMarketOrder) {
2104
+ orderType = 'STOP_MARKET';
2105
+ }
2106
+ else {
2107
+ orderType = 'STOP';
2108
+ }
2109
+ }
2110
+ else if (isTakeProfit) {
2111
+ const takeProfitPriceType = this.safeString2(params, 'takeProfitPriceType', 'triggerPriceType');
2112
+ if (takeProfitPriceType !== undefined) {
2113
+ params['TpWorkingType'] = this.encodeTriggerPriceType(takeProfitPriceType);
2114
+ }
2115
+ params['triggerPrice'] = this.priceToPrecision(symbol, takeProfitPrice);
2116
+ if (isMarketOrder) {
2117
+ orderType = 'TAKE_PROFIT_MARKET';
2118
+ }
2119
+ else {
2120
+ orderType = 'TAKE_PROFIT';
2121
+ }
2122
+ }
2123
+ params['type'] = orderType;
2124
+ }
2125
+ else {
2126
+ if (!isMarketOrder && timeInForce === undefined) {
2127
+ request['timeInForce'] = 'GTC';
2128
+ }
2129
+ request['newClientOrderId'] = clientOrderId;
2130
+ if (hasStopLoss) {
2131
+ const stopLossTriggerPrice = this.safeNumber(stopLoss, 'triggerPrice');
2132
+ request['slTriggerPrice'] = this.priceToPrecision(symbol, stopLossTriggerPrice);
2133
+ const stopLossPriceType = this.safeString(stopLoss, 'triggerPriceType');
2134
+ if (stopLossPriceType !== undefined) {
2135
+ params['SlWorkingType'] = this.encodeTriggerPriceType(stopLossPriceType);
2136
+ }
2137
+ }
2138
+ if (hasTakeProfit) {
2139
+ const takeProfitTriggerPrice = this.safeNumber(takeProfit, 'triggerPrice');
2140
+ request['tpTriggerPrice'] = this.priceToPrecision(symbol, takeProfitTriggerPrice);
2141
+ const takeProfitPriceType = this.safeString(takeProfit, 'triggerPriceType');
2142
+ if (takeProfitPriceType !== undefined) {
2143
+ params['TpWorkingType'] = this.encodeTriggerPriceType(takeProfitPriceType);
2144
+ }
2145
+ }
2146
+ }
2147
+ params = this.omit(params, ['takeProfit', 'stopLoss', 'stopLossPrice', 'takeProfitPrice', 'triggerPriceType', 'stopLossPriceType', 'takeProfitPriceType', 'clientOrderId', 'callerMethodName']);
2148
+ return this.extend(request, params);
2149
+ }
2150
+ encodeTriggerPriceType(triggerPriceType) {
2151
+ const types = {
2152
+ 'mark': 'MARK_PRICE',
2153
+ 'last': 'CONTRACT_PRICE',
2154
+ };
2155
+ return this.safeString(types, triggerPriceType, triggerPriceType);
2156
+ }
2157
+ /**
2158
+ * @method
2159
+ * @name weex#cancelOrder
2160
+ * @description cancels an open order
2161
+ * @see https://www.weex.com/api-doc/spot/orderApi/CancelOrder // spot
2162
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/CancelOrder // contract
2163
+ * @param {string} id order id
2164
+ * @param {string} [symbol] unified symbol of the market the order was made in
2165
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2166
+ * @param {string} [params.type] 'spot' or 'swap' (default is 'spot')
2167
+ * @param {boolean} [params.trigger] *contract orders only* whether the order to cancel is a trigger order
2168
+ * @param {string} [params.clientOrderId] *non-trigger orders only* a unique id for the order
2169
+ * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
2170
+ */
2171
+ async cancelOrder(id, symbol = undefined, params = {}) {
2172
+ await this.loadMarkets();
2173
+ let market = undefined;
2174
+ if (symbol !== undefined) {
2175
+ market = this.market(symbol);
2176
+ }
2177
+ let type = undefined;
2178
+ [type, params] = this.handleMarketTypeAndParams('cancelOrder', market, params);
2179
+ const trigger = this.safeBool(params, 'trigger', false);
2180
+ if (trigger && id === undefined) {
2181
+ throw new errors.ArgumentsRequired(this.id + ' cancelOrder() requires an id argument for trigger orders');
2182
+ }
2183
+ const request = {};
2184
+ const clientOrderId = this.safeString(params, 'clientOrderId');
2185
+ params = this.omit(params, ['clientOrderId', 'trigger']);
2186
+ if (clientOrderId !== undefined) {
2187
+ request['origClientOrderId'] = clientOrderId;
2188
+ }
2189
+ else if (id === undefined) {
2190
+ throw new errors.ArgumentsRequired(this.id + ' cancelOrder() requires an id argument or clientOrderId parameter');
2191
+ }
2192
+ else {
2193
+ request['orderId'] = id;
2194
+ }
2195
+ let response = undefined;
2196
+ if (type === 'spot') {
2197
+ // by orderId
2198
+ // {
2199
+ // "orderId": 736775987680772200,
2200
+ // "status": "CANCELED"
2201
+ // }
2202
+ //
2203
+ // by clientOrderId
2204
+ // {
2205
+ // "origClientOrderId": "test_cancel_order",
2206
+ // "status": "CANCELED"
2207
+ // }
2208
+ //
2209
+ response = await this.privateDeleteApiV3Order(this.extend(request, params));
2210
+ }
2211
+ else if (trigger) {
2212
+ response = await this.contractPrivateDeleteCapiV3AlgoOrder(this.extend(request, params));
2213
+ }
2214
+ else {
2215
+ response = await this.contractPrivateDeleteCapiV3Order(this.extend(request, params));
2216
+ }
2217
+ const order = this.parseOrder(response, market);
2218
+ order['status'] = 'canceled';
2219
+ return order;
2220
+ }
2221
+ /**
2222
+ * @method
2223
+ * @name weex#cancelAllOrders
2224
+ * @description cancel all open orders
2225
+ * @see https://www.weex.com/api-doc/spot/orderApi/Cancel-Symbol-Orders // spot
2226
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/CancelAllOrders // contract
2227
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/CancelAllPendingOrders // contract trigger
2228
+ * @param {string} symbol unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
2229
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2230
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2231
+ * @param {boolean} [params.trigger] *swap only* true for cancelling trigger orders (default is false)
2232
+ * @returns Response from the exchange
2233
+ */
2234
+ async cancelAllOrders(symbol = undefined, params = {}) {
2235
+ await this.loadMarkets();
2236
+ const request = {};
2237
+ let market = undefined;
2238
+ if (symbol !== undefined) {
2239
+ market = this.market(symbol);
2240
+ request['symbol'] = market['id'];
2241
+ }
2242
+ let marketType = undefined;
2243
+ [marketType, params] = this.handleMarketTypeAndParams('cancelAllOrders', market, params);
2244
+ const trigger = this.safeBool(params, 'trigger', false);
2245
+ params = this.omit(params, 'trigger');
2246
+ let response = undefined;
2247
+ if (marketType === 'spot') {
2248
+ if (symbol === undefined) {
2249
+ throw new errors.ArgumentsRequired(this.id + ' cancelAllOrders() requires a symbol argument for spot markets');
2250
+ }
2251
+ response = await this.privateDeleteApiV3OpenOrders(this.extend(request, params));
2252
+ }
2253
+ else if (trigger) {
2254
+ response = await this.contractPrivateDeleteCapiV3AlgoOpenOrders(this.extend(request, params));
2255
+ }
2256
+ else {
2257
+ response = await this.contractPrivateDeleteCapiV3AllOpenOrders(this.extend(request, params));
2258
+ }
2259
+ const extendedParams = {
2260
+ 'status': 'canceled',
2261
+ };
2262
+ return this.parseOrders(response, market, undefined, undefined, extendedParams);
2263
+ }
2264
+ /**
2265
+ * @method
2266
+ * @name weex#cancelOrders
2267
+ * @description cancel multiple orders
2268
+ * @see https://www.weex.com/api-doc/spot/orderApi/BulkCancel // spot
2269
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/CancelOrdersBatch // contract
2270
+ * @param {string[]} ids order ids
2271
+ * @param {string} [symbol] unified market symbol, default is undefined
2272
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2273
+ * @param {string[]} [params.clientOrderIds] client order ids (could be an alternative to ids)
2274
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2275
+ * @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
2276
+ */
2277
+ async cancelOrders(ids, symbol = undefined, params = {}) {
2278
+ await this.loadMarkets();
2279
+ const request = {};
2280
+ let market = undefined;
2281
+ if (symbol !== undefined) {
2282
+ market = this.market(symbol);
2283
+ }
2284
+ let marketType = undefined;
2285
+ [marketType, params] = this.handleMarketTypeAndParams('cancelOrders', market, params);
2286
+ const isSpot = (marketType === 'spot');
2287
+ const clientOrderIds = this.safeList(params, 'clientOrderIds');
2288
+ params = this.omit(params, 'clientOrderIds');
2289
+ if (clientOrderIds !== undefined) {
2290
+ if (isSpot) {
2291
+ request['origClientOrderIds'] = clientOrderIds;
2292
+ }
2293
+ else {
2294
+ request['origClientOrderIdList'] = clientOrderIds;
2295
+ }
2296
+ }
2297
+ else if (ids !== undefined) {
2298
+ if (isSpot) {
2299
+ request['orderIds'] = ids;
2300
+ }
2301
+ else {
2302
+ request['orderIdList'] = ids;
2303
+ }
2304
+ }
2305
+ else {
2306
+ throw new errors.ArgumentsRequired(this.id + ' cancelOrders() requires an ids argument or clientOrderIds parameter');
2307
+ }
2308
+ let response = undefined;
2309
+ if (isSpot) {
2310
+ response = await this.privateDeleteApiV3OrderBatch(this.extend(request, params));
2311
+ }
2312
+ else {
2313
+ response = await this.contractPrivateDeleteCapiV3BatchOrders(this.extend(request, params));
2314
+ }
2315
+ const ordersResponse = this.safeList(response, 'orderList', []);
2316
+ const extendedParams = {
2317
+ 'status': 'canceled',
2318
+ };
2319
+ return this.parseOrders(ordersResponse, market, undefined, undefined, extendedParams);
2320
+ }
2321
+ /**
2322
+ * @method
2323
+ * @name weex#fetchOrder
2324
+ * @description fetches information on an order made by the user
2325
+ * @see https://www.weex.com/api-doc/spot/orderApi/OrderDetails // spot
2326
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetSingleOrderInfo // contract
2327
+ * @param {string} id order id
2328
+ * @param {string} symbol unified symbol of the market the order was made in
2329
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2330
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2331
+ * @param {string} [params.clientOrderId] *spot only* a unique id for the order, used if id is not provided
2332
+ * @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
2333
+ */
2334
+ async fetchOrder(id, symbol = undefined, params = {}) {
2335
+ await this.loadMarkets();
2336
+ let market = undefined;
2337
+ if (symbol !== undefined) {
2338
+ market = this.market(symbol);
2339
+ }
2340
+ let marketType = undefined;
2341
+ [marketType, params] = this.handleMarketTypeAndParams('fetchOrder', market, params);
2342
+ const isSpot = (marketType === 'spot');
2343
+ const request = {};
2344
+ if ((id === undefined) && !isSpot) {
2345
+ throw new errors.ArgumentsRequired(this.id + ' fetchOrder() requires an id argument for non-spot markets');
2346
+ }
2347
+ const clientOrderId = this.safeString(params, 'clientOrderId');
2348
+ params = this.omit(params, 'clientOrderId');
2349
+ if (clientOrderId !== undefined) {
2350
+ request['origClientOrderId'] = clientOrderId;
2351
+ }
2352
+ else if (id === undefined) {
2353
+ throw new errors.ArgumentsRequired(this.id + ' fetchOrder() requires an id argument or clientOrderId parameter for spot markets');
2354
+ }
2355
+ else {
2356
+ request['orderId'] = id;
2357
+ }
2358
+ let response = undefined;
2359
+ if (isSpot) {
2360
+ //
2361
+ // {
2362
+ // "symbol": "DOGEUSDT",
2363
+ // "orderId": 736800333186991070,
2364
+ // "clientOrderId": "082007092f624a18bb7af2ab42e7c8e8",
2365
+ // "price": "0.08500",
2366
+ // "origQty": "300.0",
2367
+ // "executedQty": "0",
2368
+ // "cummulativeQuoteQty": "0",
2369
+ // "status": "NEW",
2370
+ // "timeInForce": "GTC",
2371
+ // "type": "LIMIT",
2372
+ // "side": "BUY",
2373
+ // "time": 1775666888520,
2374
+ // "updateTime": 1775666888536,
2375
+ // "isWorking": true
2376
+ // }
2377
+ //
2378
+ response = await this.privateGetApiV3Order(this.extend(request, params));
2379
+ }
2380
+ else {
2381
+ response = await this.contractPrivateGetCapiV3Order(this.extend(request, params));
2382
+ }
2383
+ return this.parseOrder(response, market);
2384
+ }
2385
+ /**
2386
+ * @method
2387
+ * @name weex#fetchOpenOrders
2388
+ * @see https://www.weex.com/api-doc/spot/orderApi/UnfinishedOrders // spot
2389
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetCurrentOrderStatus // contract
2390
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetCurrentPendingOrders // contract trigger
2391
+ * @description fetch all unfilled currently open orders
2392
+ * @param {string} symbol unified market symbol
2393
+ * @param {int} [since] the earliest time in ms to fetch open orders for
2394
+ * @param {int} [limit] the maximum number of open orders structures to retrieve
2395
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2396
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2397
+ * @param {boolean} [params.trigger] *swap only* whether to fetch trigger orders (default is false)
2398
+ * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
2399
+ */
2400
+ async fetchOpenOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
2401
+ await this.loadMarkets();
2402
+ let market = undefined;
2403
+ if (symbol !== undefined) {
2404
+ market = this.market(symbol);
2405
+ }
2406
+ let marketType = undefined;
2407
+ [marketType, params] = this.handleMarketTypeAndParams('fetchOpenOrders', market, params);
2408
+ const isSpot = (marketType === 'spot');
2409
+ let paginate = false;
2410
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchOpenOrders', 'paginate', false);
2411
+ const maxLimit = 100;
2412
+ if (paginate) {
2413
+ if (isSpot) {
2414
+ throw new errors.NotSupported(this.id + ' fetchOpenOrders() pagination is not supported for spot markets');
2415
+ }
2416
+ return await this.fetchPaginatedCallDynamic('fetchOpenOrders', symbol, since, limit, params, maxLimit);
2417
+ }
2418
+ let request = {};
2419
+ if (symbol !== undefined) {
2420
+ request['symbol'] = market['id'];
2421
+ }
2422
+ let response = undefined;
2423
+ if (isSpot) {
2424
+ //
2425
+ // [
2426
+ // {
2427
+ // "symbol": "DOGEUSDT",
2428
+ // "orderId": 736807745679786974,
2429
+ // "clientOrderId": "e6dc41082bf342f580a19264d82dab31",
2430
+ // "price": "0.12000",
2431
+ // "origQty": "299.0",
2432
+ // "executedQty": "0",
2433
+ // "cummulativeQuoteQty": "0",
2434
+ // "status": "NEW",
2435
+ // "timeInForce": "GTC",
2436
+ // "type": "LIMIT",
2437
+ // "side": "SELL",
2438
+ // "time": 1775668655796,
2439
+ // "updateTime": 1775668655810,
2440
+ // "isWorking": true
2441
+ // }
2442
+ // ]
2443
+ //
2444
+ response = await this.privateGetApiV3OpenOrders(this.extend(request, params));
2445
+ }
2446
+ else {
2447
+ if (since !== undefined) {
2448
+ request['startTime'] = since;
2449
+ }
2450
+ if (limit !== undefined) {
2451
+ request['limit'] = limit;
2452
+ }
2453
+ [request, params] = this.handleUntilOption('endTime', request, params);
2454
+ const trigger = this.safeBool(params, 'trigger', false);
2455
+ if (trigger) {
2456
+ params = this.omit(params, 'trigger');
2457
+ //
2458
+ // [
2459
+ // {
2460
+ // "algoId": 737074389748547944,
2461
+ // "clientAlgoId": "d574f517-cea5-433e-b029-415590d3bb80",
2462
+ // "algoType": "CONDITIONAL",
2463
+ // "orderType": "STOP_MARKET",
2464
+ // "symbol": "DOGEUSDT",
2465
+ // "side": "SELL",
2466
+ // "positionSide": "LONG",
2467
+ // "timeInForce": "IOC",
2468
+ // "quantity": "100",
2469
+ // "algoStatus": "UNTRIGGERED",
2470
+ // "actualOrderId": 737074043320009064,
2471
+ // "actualPrice": "0.00000",
2472
+ // "triggerPrice": "0.02000",
2473
+ // "price": "0.00000",
2474
+ // "tpTriggerPrice": null,
2475
+ // "tpPrice": null,
2476
+ // "slTriggerPrice": null,
2477
+ // "slPrice": null,
2478
+ // "tpOrderType": null,
2479
+ // "workingType": "CONTRACT_PRICE",
2480
+ // "closePosition": false,
2481
+ // "reduceOnly": true,
2482
+ // "createTime": 1775732228695,
2483
+ // "updateTime": 1775732228695,
2484
+ // "triggerTime": 0
2485
+ // }
2486
+ // ]
2487
+ //
2488
+ response = await this.contractPrivateGetCapiV3OpenAlgoOrders(this.extend(request, params));
2489
+ }
2490
+ else {
2491
+ //
2492
+ // [
2493
+ // {
2494
+ // "avgPrice": "0.00000",
2495
+ // "clientOrderId": "857e1482-3225-44ce-bc0a-947714c5cabc",
2496
+ // "cumQuote": "0",
2497
+ // "executedQty": "0",
2498
+ // "orderId": 737185556881998184,
2499
+ // "origQty": "1400",
2500
+ // "price": "0.05000",
2501
+ // "reduceOnly": false,
2502
+ // "side": "BUY",
2503
+ // "positionSide": "LONG",
2504
+ // "status": "NEW",
2505
+ // "stopPrice": "0",
2506
+ // "symbol": "DOGEUSDT",
2507
+ // "time": 1775758733006,
2508
+ // "timeInForce": "GTC",
2509
+ // "type": "LIMIT",
2510
+ // "updateTime": 1775758733006,
2511
+ // "workingType": "UNKNOWN_PRICE_TYPE"
2512
+ // }
2513
+ // ]
2514
+ //
2515
+ response = await this.contractPrivateGetCapiV3OpenOrders(this.extend(request, params));
2516
+ }
2517
+ }
2518
+ const extendedParams = {
2519
+ 'status': 'open',
2520
+ };
2521
+ return this.parseOrders(response, market, since, limit, extendedParams);
2522
+ }
2523
+ /**
2524
+ * @method
2525
+ * @name weex#fetchClosedOrders
2526
+ * @description fetches information on multiple closed orders made by the user
2527
+ * @see https://www.weex.com/api-doc/spot/orderApi/HistoryOrders // spot
2528
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetOrderHistory // contract
2529
+ * @param {string} symbol unified market symbol of the market orders were made in
2530
+ * @param {int} [since] the earliest time in ms to fetch orders for
2531
+ * @param {int} [limit] the maximum number of order structures to retrieve
2532
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2533
+ * @param {int} [params.until] the latest time in ms to fetch orders for
2534
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2535
+ * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
2536
+ */
2537
+ async fetchClosedOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
2538
+ await this.loadMarkets();
2539
+ let market = undefined;
2540
+ if (symbol !== undefined) {
2541
+ market = this.market(symbol);
2542
+ }
2543
+ let marketType = undefined;
2544
+ [marketType, params] = this.handleMarketTypeAndParams('fetchClosedOrders', market, params);
2545
+ let orders = undefined;
2546
+ if (marketType === 'spot') {
2547
+ if (symbol === undefined) {
2548
+ throw new errors.ArgumentsRequired(this.id + ' fetchClosedOrders() requires a symbol argument for spot markets');
2549
+ }
2550
+ orders = await this.fetchOrders(symbol, since, undefined, params);
2551
+ }
2552
+ else {
2553
+ orders = await this.fetchCanceledAndClosedOrders(symbol, since, limit, params);
2554
+ }
2555
+ return this.filterBy(orders, 'status', 'closed');
2556
+ }
2557
+ /**
2558
+ * @method
2559
+ * @name weex#fetchCanceledOrders
2560
+ * @description fetches information on multiple canceled orders made by the user
2561
+ * @see https://www.weex.com/api-doc/spot/orderApi/HistoryOrders // spot
2562
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetOrderHistory // contract
2563
+ * @param {string} symbol unified market symbol of the market orders were made in
2564
+ * @param {int} [since] the earliest time in ms to fetch orders for
2565
+ * @param {int} [limit] the maximum number of order structures to retrieve
2566
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2567
+ * @param {int} [params.until] the latest time in ms to fetch orders for
2568
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2569
+ * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
2570
+ */
2571
+ async fetchCanceledOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
2572
+ await this.loadMarkets();
2573
+ let market = undefined;
2574
+ if (symbol !== undefined) {
2575
+ market = this.market(symbol);
2576
+ }
2577
+ let marketType = undefined;
2578
+ [marketType, params] = this.handleMarketTypeAndParams('fetchCanceledOrders', market, params);
2579
+ let orders = undefined;
2580
+ if (marketType === 'spot') {
2581
+ if (symbol === undefined) {
2582
+ throw new errors.ArgumentsRequired(this.id + ' fetchCanceledOrders() requires a symbol argument for spot markets');
2583
+ }
2584
+ orders = await this.fetchOrders(symbol, since, undefined, params);
2585
+ }
2586
+ else {
2587
+ orders = await this.fetchCanceledAndClosedOrders(symbol, since, limit, params);
2588
+ }
2589
+ return this.filterBy(orders, 'status', 'canceled');
2590
+ }
2591
+ /**
2592
+ * @method
2593
+ * @name weex#fetchOrders
2594
+ * @description fetches information on multiple spot orders made by the user
2595
+ * @see https://www.weex.com/api-doc/spot/orderApi/HistoryOrders // spot
2596
+ * @param {string} symbol unified market symbol of the market orders were made in (required for spot orders)
2597
+ * @param {int} [since] the earliest time in ms to fetch orders for
2598
+ * @param {int} [limit] the maximum number of order structures to retrieve
2599
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2600
+ * @param {object} [params.until] end time, ms
2601
+ * @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)
2602
+ * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
2603
+ */
2604
+ async fetchOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
2605
+ if (symbol === undefined) {
2606
+ throw new errors.ArgumentsRequired(this.id + ' fetchOrders() requires a symbol argument');
2607
+ }
2608
+ await this.loadMarkets();
2609
+ const market = this.market(symbol);
2610
+ if (!market['spot']) {
2611
+ throw new errors.NotSupported(this.id + ' fetchOrders() supports spot markets only');
2612
+ }
2613
+ const maxLimit = 1000;
2614
+ let paginate = false;
2615
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchOrders', 'paginate', false);
2616
+ if (paginate) {
2617
+ return await this.fetchPaginatedCallDynamic('fetchOrders', symbol, since, limit, params, maxLimit);
2618
+ }
2619
+ let request = {
2620
+ 'symbol': market['id'],
2621
+ };
2622
+ if (since !== undefined) {
2623
+ request['startTime'] = since;
2624
+ }
2625
+ if (limit !== undefined) {
2626
+ request['limit'] = Math.min(limit, maxLimit);
2627
+ }
2628
+ [request, params] = this.handleUntilOption('endTime', request, params);
2629
+ const response = await this.privateGetApiV3AllOrders(this.extend(request, params));
2630
+ //
2631
+ // [
2632
+ // {
2633
+ // "symbol": "DOGEUSDT",
2634
+ // "orderId": 736806838401500126,
2635
+ // "clientOrderId": "e93fcb1423fc4b4982fd02eb3bc4955c",
2636
+ // "price": "0.09365",
2637
+ // "origQty": "300.0",
2638
+ // "executedQty": "300.0",
2639
+ // "cummulativeQuoteQty": "28.095",
2640
+ // "status": "FILLED",
2641
+ // "timeInForce": "IOC",
2642
+ // "type": "MARKET",
2643
+ // "side": "BUY",
2644
+ // "time": 1775668439484,
2645
+ // "updateTime": 1775668439498,
2646
+ // "isWorking": false
2647
+ // }
2648
+ // ]
2649
+ //
2650
+ return this.parseOrders(response, market, since, limit);
2651
+ }
2652
+ /**
2653
+ * @method
2654
+ * @name weex#fetchCanceledAndClosedOrders
2655
+ * @description fetches information on multiple closed and canceled orders made by the user
2656
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetOrderHistory // contract
2657
+ * @param {string} [symbol] unified market symbol of the market orders were made in (required for spot orders)
2658
+ * @param {int} [since] the earliest time in ms to fetch orders for
2659
+ * @param {int} [limit] the maximum number of order structures to retrieve
2660
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2661
+ * @param {object} [params.until] end time, ms
2662
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2663
+ * @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)
2664
+ * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
2665
+ */
2666
+ async fetchCanceledAndClosedOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
2667
+ await this.loadMarkets();
2668
+ let market = undefined;
2669
+ if (symbol !== undefined) {
2670
+ market = this.market(symbol);
2671
+ }
2672
+ let marketType = undefined;
2673
+ [marketType, params] = this.handleMarketTypeAndParams('fetchOrders', market, params);
2674
+ if (marketType === 'spot') {
2675
+ throw new errors.NotSupported(this.id + ' fetchCanceledAndClosedOrders() does not support spot markets. Use fetchOrders() instead and filter by status "canceled" or "closed"');
2676
+ }
2677
+ let paginate = false;
2678
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchOrders', 'paginate', false);
2679
+ const maxLimit = 1000;
2680
+ if (paginate) {
2681
+ return await this.fetchPaginatedCallDynamic('fetchOrders', symbol, since, limit, params, maxLimit);
2682
+ }
2683
+ let request = {};
2684
+ if (symbol !== undefined) {
2685
+ request['symbol'] = market['id'];
2686
+ }
2687
+ if (since !== undefined) {
2688
+ request['startTime'] = since;
2689
+ }
2690
+ if (limit !== undefined) {
2691
+ request['limit'] = limit;
2692
+ }
2693
+ [request, params] = this.handleUntilOption('endTime', request, params);
2694
+ const response = await this.contractPrivateGetCapiV3OrderHistory(this.extend(request, params));
2695
+ //
2696
+ // [
2697
+ // {
2698
+ // "avgPrice": "0.00000",
2699
+ // "clientOrderId": "7bd80776-0c3f-4ed9-ab9c-a616d66fac5e",
2700
+ // "cumQuote": "0",
2701
+ // "executedQty": "0",
2702
+ // "orderId": 737074389744353640,
2703
+ // "origQty": "100",
2704
+ // "price": "0.00000",
2705
+ // "reduceOnly": true,
2706
+ // "side": "SELL",
2707
+ // "positionSide": "LONG",
2708
+ // "status": "CANCELED",
2709
+ // "stopPrice": "1.00000",
2710
+ // "symbol": "DOGEUSDT",
2711
+ // "time": 1775732228695,
2712
+ // "timeInForce": "IOC",
2713
+ // "type": "TAKE_PROFIT_MARKET",
2714
+ // "updateTime": 1775732228695,
2715
+ // "workingType": "CONTRACT_PRICE"
2716
+ // }
2717
+ // ]
2718
+ //
2719
+ return this.parseOrders(response, market, since, limit);
2720
+ }
2721
+ parseOrder(order, market = undefined) {
2722
+ //
2723
+ // createOrder (spot)
2724
+ // {
2725
+ // "symbol": "DOGEUSDT",
2726
+ // "orderId": 736557215397183592,
2727
+ // "clientOrderId": "c4551206d34641efbeb64abaa066946d",
2728
+ // "transactTime": 1775608924724
2729
+ // }
2730
+ //
2731
+ // fetchOpenOrders / fetchOrders / fetchOrder (spot)
2732
+ // {
2733
+ // "symbol": "DOGEUSDT",
2734
+ // "orderId": 736800333186991070,
2735
+ // "clientOrderId": "082007092f624a18bb7af2ab42e7c8e8",
2736
+ // "price": "0.08500",
2737
+ // "origQty": "300.0",
2738
+ // "executedQty": "0",
2739
+ // "cummulativeQuoteQty": "0",
2740
+ // "status": "NEW",
2741
+ // "timeInForce": "GTC",
2742
+ // "type": "LIMIT",
2743
+ // "side": "BUY",
2744
+ // "time": 1775666888520,
2745
+ // "updateTime": 1775666888536,
2746
+ // "isWorking": true
2747
+ // }
2748
+ //
2749
+ // fetchOpenOrders (contract)
2750
+ // {
2751
+ // "avgPrice": "0.00000",
2752
+ // "clientOrderId": "857e1482-3225-44ce-bc0a-947714c5cabc",
2753
+ // "cumQuote": "0",
2754
+ // "executedQty": "0",
2755
+ // "orderId": 737185556881998184,
2756
+ // "origQty": "1400",
2757
+ // "price": "0.05000",
2758
+ // "reduceOnly": false,
2759
+ // "side": "BUY",
2760
+ // "positionSide": "LONG",
2761
+ // "status": "NEW",
2762
+ // "stopPrice": "0",
2763
+ // "symbol": "DOGEUSDT",
2764
+ // "time": 1775758733006,
2765
+ // "timeInForce": "GTC",
2766
+ // "type": "LIMIT",
2767
+ // "updateTime": 1775758733006,
2768
+ // "workingType": "UNKNOWN_PRICE_TYPE"
2769
+ // }
2770
+ //
2771
+ // fetchOpenOrders (contract-trigger)
2772
+ // {
2773
+ // "algoId": 737074389748547944,
2774
+ // "clientAlgoId": "d574f517-cea5-433e-b029-415590d3bb80",
2775
+ // "algoType": "CONDITIONAL",
2776
+ // "orderType": "STOP_MARKET",
2777
+ // "symbol": "DOGEUSDT",
2778
+ // "side": "SELL",
2779
+ // "positionSide": "LONG",
2780
+ // "timeInForce": "IOC",
2781
+ // "quantity": "100",
2782
+ // "algoStatus": "UNTRIGGERED",
2783
+ // "actualOrderId": 737074043320009064,
2784
+ // "actualPrice": "0.00000",
2785
+ // "triggerPrice": "0.02000",
2786
+ // "price": "0.00000",
2787
+ // "tpTriggerPrice": null,
2788
+ // "tpPrice": null,
2789
+ // "slTriggerPrice": null,
2790
+ // "slPrice": null,
2791
+ // "tpOrderType": null,
2792
+ // "workingType": "CONTRACT_PRICE",
2793
+ // "closePosition": false,
2794
+ // "reduceOnly": true,
2795
+ // "createTime": 1775732228695,
2796
+ // "updateTime": 1775732228695,
2797
+ // "triggerTime": 0
2798
+ // }
2799
+ //
2800
+ // fetchCanceledAndClosedOrders (swap only)
2801
+ // {
2802
+ // "avgPrice": "0.00000",
2803
+ // "clientOrderId": "7bd80776-0c3f-4ed9-ab9c-a616d66fac5e",
2804
+ // "cumQuote": "0",
2805
+ // "executedQty": "0",
2806
+ // "orderId": 737074389744353640,
2807
+ // "origQty": "100",
2808
+ // "price": "0.00000",
2809
+ // "reduceOnly": true,
2810
+ // "side": "SELL",
2811
+ // "positionSide": "LONG",
2812
+ // "status": "CANCELED",
2813
+ // "stopPrice": "1.00000",
2814
+ // "symbol": "DOGEUSDT",
2815
+ // "time": 1775732228695,
2816
+ // "timeInForce": "IOC",
2817
+ // "type": "TAKE_PROFIT_MARKET",
2818
+ // "updateTime": 1775732228695,
2819
+ // "workingType": "CONTRACT_PRICE"
2820
+ // }
2821
+ //
2822
+ const errorCode = this.safeString(order, 'errorCode');
2823
+ const errorMessage = this.safeString(order, 'errorMsg');
2824
+ if ((errorCode !== undefined) || (errorMessage !== undefined)) {
2825
+ this.handleOrderOrPositionError(errorCode, errorMessage, order);
2826
+ }
2827
+ if (market === undefined) {
2828
+ const marketId = this.safeString(order, 'symbol');
2829
+ const positionSide = this.safeString(order, 'positionSide');
2830
+ const marketType = (positionSide === undefined) ? 'spot' : 'swap';
2831
+ market = this.safeMarket(marketId, undefined, undefined, marketType);
2832
+ }
2833
+ const timestamp = this.safeIntegerN(order, ['transactTime', 'time', 'createTime']);
2834
+ const rawStatus = this.safeStringLower(order, 'status');
2835
+ const triggerPrice = this.omitZero(this.safeString2(order, 'triggerPrice', 'stopPrice'));
2836
+ const rawType = this.safeStringUpper2(order, 'type', 'orderType');
2837
+ let takeProfitPrice = undefined;
2838
+ let stopLossPrice = undefined;
2839
+ if (rawType === 'TAKE_PROFIT_MARKET' || rawType === 'TAKE_PROFIT') {
2840
+ takeProfitPrice = triggerPrice;
2841
+ }
2842
+ else if (rawType === 'STOP_LOSS' || rawType === 'STOP' || rawType === 'STOP_MARKET') {
2843
+ stopLossPrice = triggerPrice;
2844
+ }
2845
+ return this.safeOrder({
2846
+ 'id': this.safeStringN(order, ['orderId', 'algoId', 'successOrderId']),
2847
+ 'clientOrderId': this.safeStringN(order, ['clientOrderId', 'origClientOrderId', 'clientAlgoId']),
2848
+ 'symbol': this.safeString(market, 'symbol'),
2849
+ 'type': this.parseOrderType(rawType),
2850
+ 'timeInForce': this.safeString(order, 'timeInForce'),
2851
+ 'postOnly': undefined,
2852
+ 'reduceOnly': this.safeBool(order, 'reduceOnly'),
2853
+ 'side': this.safeStringLower(order, 'side'),
2854
+ 'amount': this.safeString2(order, 'origQty', 'quantity'),
2855
+ 'price': this.safeString(order, 'price'),
2856
+ 'triggerPrice': triggerPrice,
2857
+ 'cost': this.safeString2(order, 'cummulativeQuoteQty', 'cumQuote'),
2858
+ 'filled': this.safeString(order, 'executedQty'),
2859
+ 'remaining': undefined,
2860
+ 'timestamp': timestamp,
2861
+ 'datetime': this.iso8601(timestamp),
2862
+ 'fee': undefined,
2863
+ 'status': this.parseOrderStatus(rawStatus),
2864
+ 'lastTradeTimestamp': undefined,
2865
+ 'lastUpdateTimestamp': this.safeInteger(order, 'updateTime'),
2866
+ 'average': this.safeString(order, 'avgPrice'),
2867
+ 'trades': undefined,
2868
+ 'stopLossPrice': stopLossPrice,
2869
+ 'takeProfitPrice': takeProfitPrice,
2870
+ 'info': order,
2871
+ }, market);
2872
+ }
2873
+ parseOrderStatus(status) {
2874
+ const statuses = {
2875
+ 'new': 'open',
2876
+ 'partial_fill': 'closed',
2877
+ 'full_fill': 'closed',
2878
+ 'filled': 'closed',
2879
+ 'cancelled': 'canceled',
2880
+ 'canceled': 'canceled',
2881
+ 'rejected': 'rejected',
2882
+ 'untriggered': 'open',
2883
+ };
2884
+ return this.safeString(statuses, status, status);
2885
+ }
2886
+ parseOrderType(type) {
2887
+ const types = {
2888
+ 'LIMIT': 'limit',
2889
+ 'MARKET': 'market',
2890
+ 'STOP_LOSS': 'limit',
2891
+ 'STOP': 'limit',
2892
+ 'TAKE_PROFIT': 'limit',
2893
+ 'TAKE_PROFIT_MARKET': 'market',
2894
+ 'STOP_MARKET': 'market',
2895
+ };
2896
+ return this.safeString(types, type, type);
2897
+ }
2898
+ handleOrderOrPositionError(errorCode, errorMessage, order) {
2899
+ if (errorCode === undefined) {
2900
+ errorCode = '';
2901
+ }
2902
+ if (errorMessage === undefined) {
2903
+ errorMessage = '';
2904
+ }
2905
+ if ((errorCode === '') && (errorMessage === '')) {
2906
+ // some endpoints could return an empty string if there is no error
2907
+ return;
2908
+ }
2909
+ const feedback = this.id + ' ' + this.json(order);
2910
+ this.throwExactlyMatchedException(this.exceptions['exact'], errorMessage, feedback);
2911
+ this.throwExactlyMatchedException(this.exceptions['exact'], errorCode, feedback);
2912
+ this.throwBroadlyMatchedException(this.exceptions['broad'], errorMessage, feedback);
2913
+ this.throwBroadlyMatchedException(this.exceptions['broad'], errorCode, feedback);
2914
+ throw new errors.InvalidOrder(feedback);
2915
+ }
2916
+ /**
2917
+ * @method
2918
+ * @name weex#fetchOrderTrades
2919
+ * @description fetch all the trades made from a single order
2920
+ * @see https://www.weex.com/api-doc/spot/orderApi/TransactionDetails // spot
2921
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetTradeDetails // contract
2922
+ * @param {string} id order id
2923
+ * @param {string} [symbol] unified market symbol
2924
+ * @param {int} [since] the earliest time in ms to fetch trades for
2925
+ * @param {int} [limit] the maximum number of trades to retrieve
2926
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2927
+ * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
2928
+ */
2929
+ async fetchOrderTrades(id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
2930
+ await this.loadMarkets();
2931
+ const request = {
2932
+ 'orderId': id,
2933
+ };
2934
+ return await this.fetchMyTrades(symbol, since, limit, this.extend(request, params));
2935
+ }
2936
+ /**
2937
+ * @method
2938
+ * @name weex#fetchMyTrades
2939
+ * @see https://www.weex.com/api-doc/spot/orderApi/TransactionDetails // spot
2940
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/GetTradeDetails // contract
2941
+ * @description fetch all trades made by the user
2942
+ * @param {string} symbol unified market symbol
2943
+ * @param {int} [since] the earliest time in ms to fetch trades for
2944
+ * @param {int} [limit] the maximum number of trades structures to retrieve
2945
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
2946
+ * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
2947
+ * @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
2948
+ * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
2949
+ */
2950
+ async fetchMyTrades(symbol = undefined, since = undefined, limit = undefined, params = {}) {
2951
+ await this.loadMarkets();
2952
+ let market = undefined;
2953
+ if (symbol !== undefined) {
2954
+ market = this.market(symbol);
2955
+ }
2956
+ let marketType = undefined;
2957
+ [marketType, params] = this.handleMarketTypeAndParams('fetchMyTrades', market, params);
2958
+ const isSpot = (marketType === 'spot');
2959
+ if (isSpot && (symbol === undefined)) {
2960
+ throw new errors.ArgumentsRequired(this.id + ' fetchMyTrades() requires a symbol argument for spot markets');
2961
+ }
2962
+ let paginate = false;
2963
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchMyTrades', 'paginate', false);
2964
+ const maxLimit = 100;
2965
+ if (paginate) {
2966
+ return await this.fetchPaginatedCallDynamic('fetchMyTrades', symbol, since, limit, params, maxLimit);
2967
+ }
2968
+ let request = {};
2969
+ if (symbol !== undefined) {
2970
+ request['symbol'] = market['id'];
2971
+ }
2972
+ if (since !== undefined) {
2973
+ request['startTime'] = since;
2974
+ }
2975
+ if (limit !== undefined) {
2976
+ request['limit'] = limit;
2977
+ }
2978
+ [request, params] = this.handleUntilOption('endTime', request, params);
2979
+ let response = undefined;
2980
+ if (isSpot) {
2981
+ //
2982
+ // [
2983
+ // {
2984
+ // "symbol": "DOGEUSDT",
2985
+ // "id": 736825748291060702,
2986
+ // "orderId": 736825748215563230,
2987
+ // "price": "0.09349",
2988
+ // "qty": "250.0",
2989
+ // "quoteQty": "23.3725",
2990
+ // "commission": "0.0233725",
2991
+ // "time": 1775672947953,
2992
+ // "isBuyer": false
2993
+ // }
2994
+ // ]
2995
+ //
2996
+ response = await this.privateGetApiV3MyTrades(this.extend(request, params));
2997
+ }
2998
+ else {
2999
+ //
3000
+ // [
3001
+ // {
3002
+ // "id": 737074389731770728,
3003
+ // "orderId": 737074043320009064,
3004
+ // "symbol": "DOGEUSDT",
3005
+ // "buyer": true,
3006
+ // "commission": "0.00183500",
3007
+ // "commissionAsset": "USDT",
3008
+ // "maker": true,
3009
+ // "price": "0.09175",
3010
+ // "qty": "100",
3011
+ // "quoteQty": "9.17500",
3012
+ // "realizedPnl": "0",
3013
+ // "side": "BUY",
3014
+ // "positionSide": "LONG",
3015
+ // "time": 1775732228692
3016
+ // }
3017
+ // ]
3018
+ //
3019
+ response = await this.contractPrivateGetCapiV3UserTrades(this.extend(request, params));
3020
+ }
3021
+ return this.parseTrades(response, market, since, limit);
3022
+ }
3023
+ /**
3024
+ * @method
3025
+ * @name weex#fetchLedger
3026
+ * @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
3027
+ * @see https://www.weex.com/api-doc/spot/AccountAPI/GetBillRecords // spot
3028
+ * @see https://www.weex.com/api-doc/spot/AccountAPI/GetFundBillRecords // funding
3029
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetContractBills // contract
3030
+ * @param {string} [code] unified currency code, default is undefined
3031
+ * @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
3032
+ * @param {int} [limit] max number of ledger entries to return, default is undefined, max is 100
3033
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3034
+ * @param {int} [params.until] timestamp in ms of the latest ledger entry
3035
+ * @param {string} [params.type] 'spot', 'funding' or 'swap' (default is 'spot')
3036
+ * @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)
3037
+ * @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
3038
+ */
3039
+ async fetchLedger(code = undefined, since = undefined, limit = undefined, params = {}) {
3040
+ await this.loadMarkets();
3041
+ let paginate = false;
3042
+ [paginate, params] = this.handleOptionAndParams(params, 'fetchLedger', 'paginate', false);
3043
+ const maxLimit = 100;
3044
+ if (paginate) {
3045
+ return await this.fetchPaginatedCallDynamic('fetchLedger', code, since, limit, params, maxLimit);
3046
+ }
3047
+ let accountType = undefined;
3048
+ [accountType, params] = this.handleMarketTypeAndParams('fetchLedger', undefined, params);
3049
+ const accountsByType = this.safeDict(this.options, 'accountsByType', {});
3050
+ accountType = this.safeString(accountsByType, accountType, accountType);
3051
+ let request = {};
3052
+ let items = undefined;
3053
+ let currency = undefined;
3054
+ if (code !== undefined) {
3055
+ currency = this.currency(code);
3056
+ }
3057
+ if (accountType === 'contract') {
3058
+ if (code !== undefined) {
3059
+ request['currency'] = currency['id'];
3060
+ }
3061
+ if (since !== undefined) {
3062
+ request['startTime'] = since;
3063
+ }
3064
+ if (limit !== undefined) {
3065
+ request['limit'] = limit;
3066
+ }
3067
+ [request, params] = this.handleUntilOption('endTime', request, params);
3068
+ const contractResponse = await this.contractPrivatePostCapiV3AccountIncome(this.extend(request, params));
3069
+ items = this.safeList(contractResponse, 'items', []);
3070
+ }
3071
+ else if (accountType === 'funding') {
3072
+ if (since !== undefined) {
3073
+ request['startTime'] = since;
3074
+ }
3075
+ if (limit !== undefined) {
3076
+ request['pageSize'] = limit;
3077
+ }
3078
+ [request, params] = this.handleUntilOption('endTime', request, params);
3079
+ const fundingResponse = await this.privatePostApiV3AccountFundingBills(this.extend(request, params));
3080
+ items = this.safeList(fundingResponse, 'items', []);
3081
+ }
3082
+ else {
3083
+ if (since !== undefined) {
3084
+ request['after'] = since;
3085
+ }
3086
+ if (limit !== undefined) {
3087
+ request['limit'] = limit;
3088
+ }
3089
+ [request, params] = this.handleUntilOption('before', request, params);
3090
+ items = await this.privatePostApiV3AccountBills(this.extend(request, params));
3091
+ }
3092
+ return this.parseLedger(items, currency, since, limit);
3093
+ }
3094
+ parseLedgerEntry(item, currency = undefined) {
3095
+ //
3096
+ // spot
3097
+ // {
3098
+ // "billId": "736825748291061726",
3099
+ // "coinId": 82,
3100
+ // "coinName": "DOGE",
3101
+ // "bizType": "trade_out",
3102
+ // "fillSize": "250.0",
3103
+ // "fillValue": "23.372500",
3104
+ // "deltaAmount": "-250.0",
3105
+ // "afterAmount": "49.70000000",
3106
+ // "fees": "0",
3107
+ // "cTime": "1775672947953"
3108
+ // }
3109
+ //
3110
+ // contract
3111
+ // {
3112
+ // "billId": 736791763716407518,
3113
+ // "asset": "USDT",
3114
+ // "symbol": null,
3115
+ // "income": "-90.00000000",
3116
+ // "incomeType": "withdraw",
3117
+ // "balance": "106.00000000",
3118
+ // "fillFee": "0",
3119
+ // "time": 1775664845399,
3120
+ // "transferReason": "UNKNOWN_TRANSFER_REASON"
3121
+ // }
3122
+ //
3123
+ // funding
3124
+ // {
3125
+ // "billId": "16502414",
3126
+ // "coinId": 2,
3127
+ // "coinName": "USDT",
3128
+ // "bizType": "transfer_out",
3129
+ // "fillSize": null,
3130
+ // "fillValue": null,
3131
+ // "deltaAmount": "-100.00000000",
3132
+ // "afterAmount": "0.00000000",
3133
+ // "fees": "0.00000000",
3134
+ // "cTime": "1775664588931"
3135
+ // }
3136
+ //
3137
+ const currencyId = this.safeString2(item, 'coinName', 'asset');
3138
+ const code = this.safeCurrencyCode(currencyId, currency);
3139
+ currency = this.safeCurrency(currencyId, currency);
3140
+ const timestamp = this.safeInteger2(item, 'cTime', 'time');
3141
+ const amountRaw = this.safeString2(item, 'deltaAmount', 'income');
3142
+ const after = this.safeString2(item, 'afterAmount', 'balance');
3143
+ const before = Precise["default"].stringSub(after, amountRaw);
3144
+ const amount = this.parseNumber(Precise["default"].stringAbs(amountRaw));
3145
+ let direction = 'in';
3146
+ if (amountRaw.indexOf('-') >= 0) {
3147
+ direction = 'out';
3148
+ }
3149
+ let rawType = this.safeString2(item, 'bizType', 'incomeType');
3150
+ const transferReason = this.safeString(item, 'transferReason');
3151
+ const isContractEntry = (transferReason !== undefined);
3152
+ if (isContractEntry) {
3153
+ if ((rawType === 'withdraw') || (rawType === 'deposit')) {
3154
+ rawType = 'transfer';
3155
+ }
3156
+ }
3157
+ return this.safeLedgerEntry({
3158
+ 'info': item,
3159
+ 'id': this.safeString(item, 'billId'),
3160
+ 'timestamp': timestamp,
3161
+ 'datetime': this.iso8601(timestamp),
3162
+ 'direction': direction,
3163
+ 'account': undefined,
3164
+ 'referenceId': undefined,
3165
+ 'referenceAccount': undefined,
3166
+ 'type': this.parseLedgerType(rawType),
3167
+ 'currency': code,
3168
+ 'amount': amount,
3169
+ 'before': this.parseNumber(before),
3170
+ 'after': this.parseNumber(after),
3171
+ 'status': undefined,
3172
+ 'fee': {
3173
+ 'currency': code,
3174
+ 'cost': this.safeNumber2(item, 'fees', 'fillFee'),
3175
+ },
3176
+ }, currency);
3177
+ }
3178
+ parseLedgerType(type) {
3179
+ const types = {
3180
+ 'transfer_in': 'transfer',
3181
+ 'transfer_out': 'transfer',
3182
+ 'deposit': 'deposit',
3183
+ 'withdraw': 'withdrawal',
3184
+ 'trade_in': 'trade',
3185
+ 'trade_out': 'trade',
3186
+ 'position_open_long': 'trade',
3187
+ 'position_open_short': 'trade',
3188
+ 'position_close_long': 'trade',
3189
+ 'position_close_short': 'trade',
3190
+ };
3191
+ return this.safeString(types, type, type);
3192
+ }
3193
+ /**
3194
+ * @method
3195
+ * @name weex#fetchPositions
3196
+ * @description fetch all open positions
3197
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetAllPositions
3198
+ * @param {string[]} [symbols] list of unified market symbols
3199
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3200
+ * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
3201
+ */
3202
+ async fetchPositions(symbols = undefined, params = {}) {
3203
+ await this.loadMarkets();
3204
+ symbols = this.marketSymbols(symbols);
3205
+ const response = await this.contractPrivateGetCapiV3AccountPositionAllPosition(params);
3206
+ return this.parsePositions(response, symbols);
3207
+ }
3208
+ /**
3209
+ * @method
3210
+ * @name weex#fetchPosition
3211
+ * @description fetch data on an open position
3212
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSinglePosition
3213
+ * @param {string} symbol unified market symbol of the market the position is held in
3214
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3215
+ * @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
3216
+ */
3217
+ async fetchPosition(symbol, params = {}) {
3218
+ const positions = await this.fetchPositionsForSymbol(symbol, params);
3219
+ return this.safeDict(positions, 0);
3220
+ }
3221
+ /**
3222
+ * @method
3223
+ * @description fetch open positions for a single market
3224
+ * @name weex#fetchPositionsForSymbol
3225
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSinglePosition
3226
+ * @description fetch all open positions for specific symbol
3227
+ * @param {string} symbol unified market symbol
3228
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3229
+ * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
3230
+ */
3231
+ async fetchPositionsForSymbol(symbol, params = {}) {
3232
+ await this.loadMarkets();
3233
+ const market = this.market(symbol);
3234
+ const request = {
3235
+ 'symbol': market['id'],
3236
+ };
3237
+ const response = await this.contractPrivateGetCapiV3AccountPositionSinglePosition(this.extend(request, params));
3238
+ return this.parsePositions(response, [market['symbol']]);
3239
+ }
3240
+ parsePosition(position, market = undefined) {
3241
+ //
3242
+ // {
3243
+ // "id": 737191855967437160,
3244
+ // "asset": "USDT",
3245
+ // "symbol": "DOGEUSDT",
3246
+ // "side": "LONG",
3247
+ // "marginType": "CROSSED",
3248
+ // "separatedMode": "COMBINED",
3249
+ // "separatedOpenOrderId": 0,
3250
+ // "leverage": "20.00",
3251
+ // "size": "300",
3252
+ // "openValue": "27.96900",
3253
+ // "openFee": "0.02237520",
3254
+ // "fundingFee": "0",
3255
+ // "marginSize": "100",
3256
+ // "isolatedMargin": "0",
3257
+ // "isAutoAppendIsolatedMargin": false,
3258
+ // "cumOpenSize": "300",
3259
+ // "cumOpenValue": "27.96900",
3260
+ // "cumOpenFee": "0.02237520",
3261
+ // "cumCloseSize": "0",
3262
+ // "cumCloseValue": "0",
3263
+ // "cumCloseFee": "0",
3264
+ // "cumFundingFee": "0",
3265
+ // "cumLiquidateFee": "0",
3266
+ // "createdMatchSequenceId": 5762536243,
3267
+ // "updatedMatchSequenceId": 5762741613,
3268
+ // "createdTime": 1775760234825,
3269
+ // "updatedTime": 1775763170789,
3270
+ // "unrealizePnl": "0.00600",
3271
+ // "liquidatePrice": "0"
3272
+ // }
3273
+ //
3274
+ // watchPoisions
3275
+ // {
3276
+ // "id": "739004481374519656",
3277
+ // "coin": "USDT",
3278
+ // "symbol": "DOGEUSDT",
3279
+ // "side": "LONG",
3280
+ // "marginMode": "CROSSED",
3281
+ // "separatedMode": "COMBINED",
3282
+ // "separatedOpenOrderId": "0",
3283
+ // "leverage": "11",
3284
+ // "size": "100",
3285
+ // "openValue": "9.31100",
3286
+ // "openFee": "0.00744880",
3287
+ // "fundingFee": "0",
3288
+ // "isolatedMargin": "0",
3289
+ // "autoAppendIsolatedMargin": false,
3290
+ // "cumOpenSize": "100",
3291
+ // "cumOpenValue": "9.31100",
3292
+ // "cumOpenFee": "0.00744880",
3293
+ // "cumCloseSize": "0",
3294
+ // "cumCloseValue": "0",
3295
+ // "cumCloseFee": "0",
3296
+ // "cumFundingFee": "0",
3297
+ // "cumLiquidateFee": "0",
3298
+ // "createdMatchSequenceId": "5792711540",
3299
+ // "updatedMatchSequenceId": "5792711540",
3300
+ // "createdTime": "1776192398399",
3301
+ // "updatedTime": "1776192398399"
3302
+ // }
3303
+ //
3304
+ const errorMessage = this.safeString(position, 'errorMsg');
3305
+ const errorCode = this.safeString(position, 'errorCode');
3306
+ if (errorMessage !== undefined) {
3307
+ this.handleOrderOrPositionError(errorCode, errorMessage, position);
3308
+ }
3309
+ const marketId = this.safeString(position, 'symbol');
3310
+ market = this.safeMarket(marketId, market, undefined, 'contract');
3311
+ const timestamp = this.safeInteger(position, 'createdTime');
3312
+ const marginType = this.safeString2(position, 'marginType', 'marginMode');
3313
+ let marginMode = 'cross';
3314
+ if (marginType === 'ISOLATED') {
3315
+ marginMode = 'isolated';
3316
+ }
3317
+ const separatedMode = this.safeString(position, 'separatedMode');
3318
+ let hedged = undefined;
3319
+ if (separatedMode === 'COMBINED') {
3320
+ hedged = false;
3321
+ }
3322
+ else if (separatedMode === 'SEPARATED') {
3323
+ hedged = true;
3324
+ }
3325
+ return this.safePosition({
3326
+ 'symbol': market['symbol'],
3327
+ 'id': this.safeString2(position, 'id', 'positionId'),
3328
+ 'timestamp': timestamp,
3329
+ 'datetime': this.iso8601(timestamp),
3330
+ 'contracts': this.safeNumber(position, 'size'),
3331
+ 'contractSize': undefined,
3332
+ 'side': this.safeStringLower(position, 'side'),
3333
+ 'notional': this.safeNumber(position, 'openValue'),
3334
+ 'leverage': this.safeNumber(position, 'leverage'),
3335
+ 'unrealizedPnl': this.safeNumber(position, 'unrealizePnl'),
3336
+ 'realizedPnl': undefined,
3337
+ 'collateral': undefined,
3338
+ 'entryPrice': undefined,
3339
+ 'markPrice': undefined,
3340
+ 'liquidationPrice': this.safeNumber(position, 'liquidatePrice'),
3341
+ 'marginMode': marginMode,
3342
+ 'hedged': hedged,
3343
+ 'maintenanceMargin': undefined,
3344
+ 'maintenanceMarginPercentage': undefined,
3345
+ 'initialMargin': this.safeNumber(position, 'marginSize'),
3346
+ 'initialMarginPercentage': undefined,
3347
+ 'marginRatio': undefined,
3348
+ 'lastUpdateTimestamp': this.safeInteger(position, 'updatedTime'),
3349
+ 'lastPrice': undefined,
3350
+ 'stopLossPrice': undefined,
3351
+ 'takeProfitPrice': undefined,
3352
+ 'percentage': undefined,
3353
+ 'info': undefined,
3354
+ });
3355
+ }
3356
+ /**
3357
+ * @method
3358
+ * @name weex#closeAllPositions
3359
+ * @description closes all open positions for a market type
3360
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/ClosePositions
3361
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3362
+ * @returns {object[]} A list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
3363
+ */
3364
+ async closeAllPositions(params = {}) {
3365
+ await this.loadMarkets();
3366
+ const response = await this.contractPrivatePostCapiV3ClosePositions(params);
3367
+ //
3368
+ // [
3369
+ // {
3370
+ // "positionId": 737191855967437160,
3371
+ // "successOrderId": 737215340433375592,
3372
+ // "errorMessage": "",
3373
+ // "success": true
3374
+ // }
3375
+ // ]
3376
+ //
3377
+ return this.parsePositions(response);
3378
+ }
3379
+ /**
3380
+ * @method
3381
+ * @name weex#closePosition
3382
+ * @description closes open positions for a market
3383
+ * @see https://www.weex.com/api-doc/contract/Transaction_API/ClosePositions
3384
+ * @param {string} symbol Unified CCXT market symbol
3385
+ * @param {string} [side] not used by current exchange
3386
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3387
+ * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
3388
+ */
3389
+ async closePosition(symbol, side = undefined, params = {}) {
3390
+ await this.loadMarkets();
3391
+ const market = this.market(symbol);
3392
+ const request = {
3393
+ 'symbol': market['id'],
3394
+ };
3395
+ const response = await this.contractPrivatePostCapiV3ClosePositions(this.extend(request, params));
3396
+ const orders = this.parseOrders(response, market);
3397
+ return this.safeDict(orders, 0);
3398
+ }
3399
+ /**
3400
+ * @method
3401
+ * @name weex#fetchTradingFee
3402
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetCommissionRate // contract
3403
+ * @description fetch the trading fees for a contract market
3404
+ * @param {string} symbol unified market symbol
3405
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3406
+ * @returns {object} a [fee structure]{@link https://docs.ccxt.com/#/?id=fee-structure}
3407
+ */
3408
+ async fetchTradingFee(symbol, params = {}) {
3409
+ await this.loadMarkets();
3410
+ const market = this.market(symbol);
3411
+ if (market['spot']) {
3412
+ // spot markets return 0 for fees
3413
+ throw new errors.NotSupported(this.id + ' fetchTradingFee() is not supported for spot markets');
3414
+ }
3415
+ const request = {
3416
+ 'symbol': market['id'],
3417
+ };
3418
+ const response = await this.contractPrivateGetCapiV3AccountCommissionRate(this.extend(request, params));
3419
+ //
3420
+ // {
3421
+ // "symbol": "DOGEUSDT",
3422
+ // "makerCommissionRate": "0.0002",
3423
+ // "takerCommissionRate": "0.0008"
3424
+ // }
3425
+ //
3426
+ return this.parseTradingFee(response, market);
3427
+ }
3428
+ parseTradingFee(fee, market = undefined) {
3429
+ //
3430
+ // contract
3431
+ // {
3432
+ // "symbol": "DOGEUSDT",
3433
+ // "makerCommissionRate": "0.0002",
3434
+ // "takerCommissionRate": "0.0008"
3435
+ // }
3436
+ //
3437
+ const marketId = this.safeString(fee, 'symbol');
3438
+ return {
3439
+ 'info': fee,
3440
+ 'symbol': this.safeSymbol(marketId, market, undefined, 'contract'),
3441
+ 'maker': this.safeNumber(fee, 'makerCommissionRate'),
3442
+ 'taker': this.safeNumber(fee, 'takerCommissionRate'),
3443
+ 'percentage': true,
3444
+ 'tierBased': true,
3445
+ };
3446
+ }
3447
+ /**
3448
+ * @method
3449
+ * @name weex#fetchMarginMode
3450
+ * @description fetches the margin mode of a specific symbol
3451
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
3452
+ * @param {string} symbol unified symbol of the market the order was made in
3453
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3454
+ * @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/?id=margin-mode-structure}
3455
+ */
3456
+ async fetchMarginMode(symbol, params = {}) {
3457
+ await this.loadMarkets();
3458
+ const market = this.market(symbol);
3459
+ const request = {
3460
+ 'symbol': market['id'],
3461
+ };
3462
+ const response = await this.contractPrivateGetCapiV3AccountSymbolConfig(this.extend(request, params));
3463
+ //
3464
+ // [
3465
+ // {
3466
+ // "symbol": "DOGEUSDT",
3467
+ // "marginType": "CROSSED",
3468
+ // "separatedType": "COMBINED",
3469
+ // "crossLeverage": "20.00",
3470
+ // "isolatedLongLeverage": "20.00",
3471
+ // "isolatedShortLeverage": "20.00"
3472
+ // }
3473
+ // ]
3474
+ //
3475
+ const marginMode = this.safeDict(response, 0, {});
3476
+ return this.parseMarginMode(marginMode, market);
3477
+ }
3478
+ /**
3479
+ * @method
3480
+ * @name weex#fetchMarginModes
3481
+ * @description fetches margin modes the symbols, with symbols=undefined all markets are returned
3482
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
3483
+ * @param {string[]} symbols unified market symbols
3484
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3485
+ * @returns {object} a list of [margin mode structures]{@link https://docs.ccxt.com/?id=margin-mode-structure}
3486
+ */
3487
+ async fetchMarginModes(symbols = undefined, params = {}) {
3488
+ await this.loadMarkets();
3489
+ symbols = this.marketSymbols(symbols);
3490
+ const response = await this.contractPrivateGetCapiV3AccountSymbolConfig(params);
3491
+ return this.parseMarginModes(response, symbols, 'symbol', 'swap');
3492
+ }
3493
+ parseMarginMode(marginMode, market = undefined) {
3494
+ const marketId = this.safeString(marginMode, 'symbol');
3495
+ const marginType = this.safeString(marginMode, 'marginType');
3496
+ return {
3497
+ 'info': marginMode,
3498
+ 'symbol': this.safeSymbol(marketId, market, undefined, 'swap'),
3499
+ 'marginMode': this.parseMarginType(marginType),
3500
+ };
3501
+ }
3502
+ parseMarginType(marginType) {
3503
+ const marginTypes = {
3504
+ 'CROSSED': 'cross',
3505
+ 'ISOLATED': 'isolated',
3506
+ };
3507
+ return this.safeString(marginTypes, marginType, marginType);
3508
+ }
3509
+ /**
3510
+ * @method
3511
+ * @name weex#setMarginMode
3512
+ * @description set margin mode to 'cross' or 'isolated'
3513
+ * @see https://www.weex.com/api-doc/contract/Account_API/ChangeMarginModeTRADE
3514
+ * @param {string} marginMode 'cross' or 'isolated'
3515
+ * @param {string} symbol unified market symbol
3516
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3517
+ * @returns {object} response from the exchange
3518
+ */
3519
+ async setMarginMode(marginMode, symbol = undefined, params = {}) {
3520
+ if (symbol === undefined) {
3521
+ throw new errors.ArgumentsRequired(this.id + ' setMarginMode() requires a symbol argument');
3522
+ }
3523
+ await this.loadMarkets();
3524
+ const market = this.market(symbol);
3525
+ const request = {
3526
+ 'symbol': market['id'],
3527
+ 'marginType': this.encodeMarginMode(marginMode),
3528
+ };
3529
+ return await this.contractPrivatePostCapiV3AccountMarginType(this.extend(request, params));
3530
+ }
3531
+ encodeMarginMode(marginMode) {
3532
+ const marginTypes = {
3533
+ 'cross': 'CROSSED',
3534
+ 'isolated': 'ISOLATED',
3535
+ };
3536
+ const result = this.safeString(marginTypes, marginMode);
3537
+ if (result === undefined) {
3538
+ throw new errors.ArgumentsRequired(this.id + ' marginMode must be either cross or isolated');
3539
+ }
3540
+ return result;
3541
+ }
3542
+ /**
3543
+ * @method
3544
+ * @name weex#fetchLeverage
3545
+ * @description fetch the set leverage for a market
3546
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
3547
+ * @param {string} symbol unified market symbol
3548
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3549
+ * @returns {object} a [leverage structure]{@link https://docs.ccxt.com/?id=leverage-structure}
3550
+ */
3551
+ async fetchLeverage(symbol, params = {}) {
3552
+ await this.loadMarkets();
3553
+ const market = this.market(symbol);
3554
+ const request = {
3555
+ 'symbol': market['id'],
3556
+ };
3557
+ const response = await this.contractPrivateGetCapiV3AccountSymbolConfig(this.extend(request, params));
3558
+ const marginMode = this.safeDict(response, 0, {});
3559
+ return this.parseLeverage(marginMode, market);
3560
+ }
3561
+ /**
3562
+ * @method
3563
+ * @name weex#fetchLeverages
3564
+ * @description fetch the set leverage for all markets
3565
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
3566
+ * @param {string[]} [symbols] a list of unified market symbols
3567
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3568
+ * @returns {object} a list of [leverage structures]{@link https://docs.ccxt.com/#/?id=leverage-structure}
3569
+ */
3570
+ async fetchLeverages(symbols = undefined, params = {}) {
3571
+ await this.loadMarkets();
3572
+ symbols = this.marketSymbols(symbols);
3573
+ const response = await this.contractPrivateGetCapiV3AccountSymbolConfig(params);
3574
+ return this.parseLeverages(response, symbols, 'symbol', 'swap');
3575
+ }
3576
+ parseLeverage(leverage, market = undefined) {
3577
+ const marketId = this.safeString(leverage, 'symbol');
3578
+ const marginType = this.safeString(leverage, 'marginType');
3579
+ const marginMode = this.parseMarginType(marginType);
3580
+ const crossLeverage = this.safeNumber(leverage, 'crossLeverage');
3581
+ let longLeverage = this.safeNumber(leverage, 'isolatedLongLeverage');
3582
+ let shortLeverage = this.safeNumber(leverage, 'isolatedShortLeverage');
3583
+ if (marginMode === 'cross') {
3584
+ longLeverage = crossLeverage;
3585
+ shortLeverage = crossLeverage;
3586
+ }
3587
+ return {
3588
+ 'info': leverage,
3589
+ 'symbol': this.safeSymbol(marketId, market, undefined, 'swap'),
3590
+ 'marginMode': marginMode,
3591
+ 'longLeverage': longLeverage,
3592
+ 'shortLeverage': shortLeverage,
3593
+ };
3594
+ }
3595
+ /**
3596
+ * @method
3597
+ * @name weex#setLeverage
3598
+ * @description set the level of leverage for a market
3599
+ * @see https://www.weex.com/api-doc/contract/Account_API/UpdateLeverageTRADE
3600
+ * @param {float} leverage the rate of leverage
3601
+ * @param {string} symbol unified market symbol
3602
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3603
+ * @param {string} [params.marginMode] 'cross' or 'isolated' (default is 'cross' if specific leverage parameters are not provided)
3604
+ * @param {number} [params.crossLeverage] *cross margin mode only* leverage for cross margin mode when marginMode is 'cross'
3605
+ * @param {number} [params.isolatedLongLeverage] *isolated margin mode only* leverage for long positions when marginMode is 'isolated'
3606
+ * @param {number} [params.isolatedShortLeverage] *isolated margin mode only* leverage for short positions when marginMode is 'isolated'
3607
+ * If specific leverage parameters are not provided
3608
+ * the leverage value will be applied to both long and short positions if marginMode is 'isolated'
3609
+ * or to cross margin mode if marginMode is 'cross'
3610
+ * If marginMode is not provided and specific leverage parameters are not provided too
3611
+ * the leverage value will be applied to cross leverage
3612
+ * @returns {object} response from the exchange
3613
+ */
3614
+ async setLeverage(leverage, symbol = undefined, params = {}) {
3615
+ if (symbol === undefined) {
3616
+ throw new errors.ArgumentsRequired(this.id + ' setLeverage() requires a symbol argument');
3617
+ }
3618
+ await this.loadMarkets();
3619
+ const market = this.market(symbol);
3620
+ const request = {
3621
+ 'symbol': market['id'],
3622
+ };
3623
+ let marginMode = undefined;
3624
+ [marginMode, params] = this.handleMarginModeAndParams('setLeverage', params);
3625
+ if (marginMode !== undefined) {
3626
+ request['marginType'] = this.encodeMarginMode(marginMode);
3627
+ }
3628
+ const isolatedLongLeverage = this.safeNumber(params, 'isolatedLongLeverage');
3629
+ const isolatedShortLeverage = this.safeNumber(params, 'isolatedShortLeverage');
3630
+ const crossLeverage = this.safeNumber(params, 'crossLeverage');
3631
+ if ((isolatedLongLeverage === undefined) && (isolatedShortLeverage === undefined) && (crossLeverage === undefined)) {
3632
+ if (marginMode === 'isolated') {
3633
+ request['isolatedLongLeverage'] = leverage;
3634
+ request['isolatedShortLeverage'] = leverage;
3635
+ }
3636
+ else {
3637
+ request['crossLeverage'] = leverage;
3638
+ }
3639
+ }
3640
+ return await this.contractPrivatePostCapiV3AccountLeverage(this.extend(request, params));
3641
+ }
3642
+ /**
3643
+ * @method
3644
+ * @name weex#fetchPositionMode
3645
+ * @description fetchs the position mode, hedged or one way
3646
+ * @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
3647
+ * @param {string} symbol unified symbol of the market to fetch the order book for
3648
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3649
+ * @returns {object} an object detailing whether the market is in hedged or one-way mode
3650
+ */
3651
+ async fetchPositionMode(symbol = undefined, params = {}) {
3652
+ await this.loadMarkets();
3653
+ const market = this.market(symbol);
3654
+ const request = {
3655
+ 'symbol': market['id'],
3656
+ };
3657
+ const response = await this.contractPrivateGetCapiV3AccountSymbolConfig(this.extend(request, params));
3658
+ const entry = this.safeDict(response, 0, {});
3659
+ const separatedType = this.safeString(entry, 'separatedType');
3660
+ return {
3661
+ 'info': response,
3662
+ 'hedged': (separatedType === 'SEPARATED'),
3663
+ };
3664
+ }
3665
+ /**
3666
+ * @method
3667
+ * @name weex#setPositionMode
3668
+ * @description set hedged to true or false for a market
3669
+ * @see https://www.weex.com/api-doc/contract/Account_API/ChangeMarginModeTRADE
3670
+ * @param {bool} hedged set to true to use dualSidePosition
3671
+ * @param {string} symbol unified market symbol
3672
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3673
+ * @param {string} params.marginMode 'cross' or 'isolated' (default is 'cross')
3674
+ * @returns {object} response from the exchange
3675
+ */
3676
+ async setPositionMode(hedged, symbol = undefined, params = {}) {
3677
+ if (symbol === undefined) {
3678
+ throw new errors.ArgumentsRequired(this.id + ' setPositionMode() requires a symbol argument');
3679
+ }
3680
+ await this.loadMarkets();
3681
+ const market = this.market(symbol);
3682
+ let marginMode = undefined;
3683
+ [marginMode, params] = this.handleMarginModeAndParams('setPositionMode', params);
3684
+ if (marginMode === undefined) {
3685
+ throw new errors.ArgumentsRequired(this.id + ' setPositionMode() also sets marginMode, so a marginMode parameter is required');
3686
+ }
3687
+ const separatedType = hedged ? 'SEPARATED' : 'COMBINED';
3688
+ const request = {
3689
+ 'symbol': market['id'],
3690
+ 'marginType': this.encodeMarginMode(marginMode),
3691
+ 'separatedType': separatedType,
3692
+ };
3693
+ return await this.contractPrivatePostCapiV3AccountMarginType(this.extend(request, params));
3694
+ }
3695
+ async modifyMarginHelper(symbol, amount, type, params = {}) {
3696
+ await this.loadMarkets();
3697
+ const isolatedPositionId = this.safeStringN(params, ['positionId', 'id', 'isolatedPositionId']);
3698
+ if (isolatedPositionId === undefined) {
3699
+ throw new errors.ArgumentsRequired(this.id + ' modifyMarginHelper() requires a positionId parameter');
3700
+ }
3701
+ params = this.omit(params, ['positionId', 'id']);
3702
+ const market = this.market(symbol);
3703
+ const request = {
3704
+ 'isolatedPositionId': isolatedPositionId,
3705
+ 'amount': this.costToPrecision(symbol, amount),
3706
+ 'type': type,
3707
+ };
3708
+ const parsedType = (type === 1) ? 'add' : 'reduce';
3709
+ const response = await this.contractPrivatePostCapiV3AccountPositionMargin(this.extend(request, params));
3710
+ return this.extend(this.parseMarginModification(response, market), {
3711
+ 'amount': this.parseNumber(amount),
3712
+ 'type': parsedType,
3713
+ });
3714
+ }
3715
+ parseMarginModification(data, market = undefined) {
3716
+ //
3717
+ // {
3718
+ // "code": "200",
3719
+ // "msg": "success",
3720
+ // "requestTime": 1764505776347
3721
+ // }
3722
+ //
3723
+ const msg = this.safeString(data, 'msg');
3724
+ const status = (msg === 'success') ? 'ok' : 'failed';
3725
+ const timestamp = this.safeInteger(data, 'requestTime');
3726
+ return {
3727
+ 'info': data,
3728
+ 'symbol': market['symbol'],
3729
+ 'type': undefined,
3730
+ 'marginMode': 'isolated',
3731
+ 'amount': undefined,
3732
+ 'total': undefined,
3733
+ 'code': market['settle'],
3734
+ 'status': status,
3735
+ 'timestamp': timestamp,
3736
+ 'datetime': this.iso8601(timestamp),
3737
+ };
3738
+ }
3739
+ /**
3740
+ * @method
3741
+ * @name weex#reduceMargin
3742
+ * @description remove margin from a position
3743
+ * @see https://www.weex.com/api-doc/contract/Account_API/AdjustPositionMarginTRADE
3744
+ * @param {string} symbol unified market symbol
3745
+ * @param {float} amount the amount of margin to remove
3746
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3747
+ * @param {string} params.positionId the id of the position to reduce margin from, required
3748
+ * @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
3749
+ */
3750
+ async reduceMargin(symbol, amount, params = {}) {
3751
+ return await this.modifyMarginHelper(symbol, amount, 2, params);
3752
+ }
3753
+ /**
3754
+ * @method
3755
+ * @name weex#addMargin
3756
+ * @description add margin
3757
+ * @see https://www.weex.com/api-doc/contract/Account_API/AdjustPositionMarginTRADE
3758
+ * @param {string} symbol unified market symbol
3759
+ * @param {float} amount amount of margin to add
3760
+ * @param {object} [params] extra parameters specific to the exchange API endpoint
3761
+ * @param {string} params.positionId the id of the position to add margin to, required
3762
+ * @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
3763
+ */
3764
+ async addMargin(symbol, amount, params = {}) {
3765
+ return await this.modifyMarginHelper(symbol, amount, 1, params);
3766
+ }
3767
+ sign(path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
3768
+ let endpoint = this.implodeParams(path, params);
3769
+ const query = this.omit(params, this.extractParams(path));
3770
+ const isBatch = (path.indexOf('batch') >= 0);
3771
+ if (!isBatch && ((method === 'GET') || (method === 'DELETE'))) {
3772
+ if (Object.keys(query).length) {
3773
+ endpoint += '?' + this.urlencode(query);
3774
+ }
3775
+ }
3776
+ if ((api === 'private') || (api === 'contractPrivate')) {
3777
+ this.checkRequiredCredentials();
3778
+ const timestamp = this.numberToString(this.nonce());
3779
+ let payload = timestamp + method + '/' + endpoint;
3780
+ if ((method === 'POST') || isBatch) {
3781
+ body = this.json(query);
3782
+ payload += body;
3783
+ }
3784
+ const signature = this.hmac(this.encode(payload), this.encode(this.secret), sha256.sha256, 'base64');
3785
+ headers = {
3786
+ 'ACCESS-KEY': this.apiKey,
3787
+ 'ACCESS-SIGN': signature,
3788
+ 'ACCESS-PASSPHRASE': this.password,
3789
+ 'ACCESS-TIMESTAMP': timestamp,
3790
+ };
3791
+ if ((method === 'POST') || (method === 'DELETE')) {
3792
+ headers['Content-Type'] = 'application/json';
3793
+ }
3794
+ }
3795
+ else {
3796
+ headers = {
3797
+ 'User-Agent': 'ccxt',
3798
+ };
3799
+ }
3800
+ const url = this.urls['api'][api] + '/' + endpoint;
3801
+ return { 'url': url, 'method': method, 'body': body, 'headers': headers };
3802
+ }
3803
+ handleErrors(code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
3804
+ //
3805
+ // {
3806
+ // "code": -1140,
3807
+ // "msg": "Either orderId or origClientOrderId must be sent."
3808
+ // }
3809
+ //
3810
+ const message = this.safeString(response, 'msg');
3811
+ if (message !== undefined) {
3812
+ const errorCode = this.safeString(response, 'code');
3813
+ const feedback = this.id + ' ' + body;
3814
+ this.throwBroadlyMatchedException(this.exceptions['broad'], message, feedback);
3815
+ this.throwExactlyMatchedException(this.exceptions['exact'], errorCode, feedback);
3816
+ this.throwExactlyMatchedException(this.exceptions['exact'], message, feedback);
3817
+ throw new errors.ExchangeError(this.id + ' ' + body);
3818
+ }
3819
+ return undefined;
3820
+ }
3821
+ }
3822
+
3823
+ exports["default"] = weex;