-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
rest-client-v5.ts
2488 lines (2299 loc) · 70.8 KB
/
rest-client-v5.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
APIResponseV3,
APIResponseV3WithTime,
AccountBorrowCollateralLimitV5,
AccountCoinBalanceV5,
AccountInfoV5,
AccountMarginModeV5,
AccountOrderV5,
AccountTypeV5,
AddOrReduceMarginParamsV5,
AddOrReduceMarginResultV5,
AffiliateUserInfoV5,
AllCoinsBalanceV5,
AllowedDepositCoinInfoV5,
AmendOrderParamsV5,
ApiKeyInfoV5,
AssetInfoV5,
BatchAmendOrderParamsV5,
BatchAmendOrderResultV5,
BatchCancelOrderParamsV5,
BatchCancelOrderResultV5,
BatchCreateOrderResultV5,
BatchOrderParamsV5,
BatchOrdersResponseV5,
BorrowCryptoLoanParamsV5,
BorrowHistoryRecordV5,
BrokerIssuedVoucherV5,
BrokerVoucherSpecV5,
CancelAllOrdersParamsV5,
CancelOrderParamsV5,
CategoryCursorListV5,
CategoryListV5,
CategorySymbolListV5,
CategoryV5,
ClosedPnLV5,
CoinExchangeRecordV5,
CoinGreeksV5,
CoinInfoV5,
CollateralInfoV5,
CompletedLoanOrderV5,
ConfirmNewRiskLimitParamsV5,
ConvertCoinSpecV5,
ConvertCoinsParamsV5,
ConvertHistoryRecordV5,
ConvertQuoteV5,
ConvertStatusV5,
CreateSubApiKeyParamsV5,
CreateSubApiKeyResultV5,
CreateSubMemberParamsV5,
CreateSubMemberResultV5,
CursorListV5,
CursorRowsV5,
DCPInfoV5,
DeleteSubMemberParamsV5,
DeliveryPriceV5,
DeliveryRecordV5,
DepositAddressResultV5,
DepositRecordV5,
ExchangeBrokerAccountInfoV5,
ExchangeBrokerEarningResultV5,
ExchangeBrokerSubAccountDepositRecordV5,
ExecutionV5,
FeeRateV5,
FundingRateHistoryResponseV5,
GetAccountCoinBalanceParamsV5,
GetAccountHistoricOrdersParamsV5,
GetAccountOrdersParamsV5,
GetAllCoinsBalanceParamsV5,
GetAllowedDepositCoinInfoParamsV5,
GetAssetInfoParamsV5,
GetBorrowHistoryParamsV5,
GetBrokerIssuedVoucherParamsV5,
GetBrokerSubAccountDepositsV5,
GetClassicTransactionLogsParamsV5,
GetClosedPnLParamsV5,
GetCoinExchangeRecordParamsV5,
GetCompletedLoanOrderHistoryParamsV5,
GetConvertHistoryParamsV5,
GetDeliveryPriceParamsV5,
GetDeliveryRecordParamsV5,
GetDepositRecordParamsV5,
GetExchangeBrokerEarningsParamsV5,
GetExecutionListParamsV5,
GetFeeRateParamsV5,
GetFundingRateHistoryParamsV5,
GetHistoricalVolatilityParamsV5,
GetIndexPriceKlineParamsV5,
GetInstrumentsInfoParamsV5,
GetInsuranceParamsV5,
GetInternalDepositRecordParamsV5,
GetInternalTransferParamsV5,
GetKlineParamsV5,
GetLoanLTVAdjustmentHistoryParamsV5,
GetLongShortRatioParamsV5,
GetMarkPriceKlineParamsV5,
GetMovePositionHistoryParamsV5,
GetOpenInterestParamsV5,
GetOptionDeliveryPriceParamsV5,
GetOrderbookParamsV5,
GetPreUpgradeClosedPnlParamsV5,
GetPreUpgradeOptionDeliveryRecordParamsV5,
GetPreUpgradeOrderHistoryParamsV5,
GetPreUpgradeTradeHistoryParamsV5,
GetPreUpgradeTransactionLogParamsV5,
GetPreUpgradeUSDCSessionParamsV5,
GetPremiumIndexPriceKlineParamsV5,
GetPublicTradingHistoryParamsV5,
GetRepaymentHistoryParamsV5,
GetRiskLimitParamsV5,
GetSettlementRecordParamsV5,
GetSpotLeveragedTokenOrderHistoryParamsV5,
GetSubAccountAllApiKeysParamsV5,
GetSubAccountDepositRecordParamsV5,
GetTickersParamsV5,
GetTransactionLogParamsV5,
GetUniversalTransferRecordsParamsV5,
GetUnpaidLoanOrdersParamsV5,
GetVIPMarginDataParamsV5,
GetWalletBalanceParamsV5,
GetWithdrawalRecordsParamsV5,
HistoricalVolatilityV5,
InstrumentInfoResponseV5,
InsuranceResponseV5,
InternalDepositRecordV5,
InternalTransferRecordV5,
IssueVoucherParamsV5,
LeverageTokenInfoV5,
LeveragedTokenMarketResultV5,
LoanLTVAdjustmentHistoryV5,
LongShortRatioV5,
MMPModifyParamsV5,
MMPStateV5,
MovePositionHistoryV5,
MovePositionParamsV5,
MovePositionResultV5,
OHLCKlineV5,
OHLCVKlineV5,
OpenInterestResponseV5,
OptionDeliveryPriceV5,
OrderParamsV5,
OrderResultV5,
OrderSideV5,
OrderbookResponseV5,
PositionInfoParamsV5,
PositionV5,
PreUpgradeOptionsDelivery,
PreUpgradeTransaction,
PreUpgradeUSDCSessionSettlement,
PublicTradeV5,
PurchaseSpotLeveragedTokenParamsV5,
PurchaseSpotLeveragedTokenResultV5,
RedeemSpotLeveragedTokenParamsV5,
RedeemSpotLeveragedTokenResultV5,
RepayLiabilityParamsV5,
RepayLiabilityResultV5,
RepaymentHistoryV5,
RequestConvertQuoteParamsV5,
RiskLimitV5,
SetAutoAddMarginParamsV5,
SetCollateralCoinParamsV5,
SetLeverageParamsV5,
SetRiskLimitParamsV5,
SetRiskLimitResultV5,
SetTPSLModeParamsV5,
SetTradingStopParamsV5,
SettlementRecordV5,
SpotBorrowCheckResultV5,
SpotLeveragedTokenOrderHistoryV5,
SpotMarginStateV5,
SubAccountAllApiKeysResultV5,
SubMemberV5,
SwitchIsolatedMarginParamsV5,
SwitchPositionModeParamsV5,
TPSLModeV5,
TickerLinearInverseV5,
TickerOptionV5,
TickerSpotV5,
TransactionLogV5,
UnifiedAccountUpgradeResultV5,
UniversalTransferParamsV5,
UniversalTransferRecordV5,
UnpaidLoanOrderV5,
UpdateApiKeyParamsV5,
UpdateApiKeyResultV5,
VIPMarginDataV5,
VaspEntityV5,
VipBorrowableCoinsV5,
VipCollateralCoinsV5,
WalletBalanceV5,
WithdrawParamsV5,
WithdrawalRecordV5,
} from './types';
import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient';
/**
* REST API client for V5 REST APIs
*
* https://bybit-exchange.github.io/docs/v5/intro
*/
export class RestClientV5 extends BaseRestClient {
/**
*
****** Custom SDK APIs
*
*/
/**
* This method is used to get the latency and time sync between the client and the server.
* This is not official API endpoint and is only used for internal testing purposes.
* Use this method to check the latency and time sync between the client and the server.
* Final values might vary slightly, but it should be within few ms difference.
* If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub.
*/
async fetchLatencySummary(): Promise<any> {
const clientTimeReqStart = Date.now();
const serverTime = await this.getServerTime();
const clientTimeReqEnd = Date.now();
const serverTimeMs = serverTime.time;
const roundTripTime = clientTimeReqEnd - clientTimeReqStart;
const estimatedOneWayLatency = Math.floor(roundTripTime / 2);
// Adjust server time by adding estimated one-way latency
const adjustedServerTime = serverTimeMs + estimatedOneWayLatency;
// Calculate time difference between adjusted server time and local time
const timeDifference = adjustedServerTime - clientTimeReqEnd;
const result = {
localTime: clientTimeReqEnd,
serverTime: serverTimeMs,
roundTripTime,
estimatedOneWayLatency,
adjustedServerTime,
timeDifference,
};
console.log('Time synchronization results:');
console.log(result);
console.log(
`Your approximate latency to exchange server:
One way: ${estimatedOneWayLatency}ms.
Round trip: ${roundTripTime}ms.
`,
);
if (timeDifference > 500) {
console.warn(
`WARNING! Time difference between server and client clock is greater than 500ms. It is currently ${timeDifference}ms.
Consider adjusting your system clock to avoid unwanted clock sync errors!
Visit https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow for more information`,
);
} else {
console.log(
`Time difference between server and client clock is within acceptable range of 500ms. It is currently ${timeDifference}ms.`,
);
}
return result;
}
/**
*
****** Misc Bybit APIs
*
*/
getClientType() {
return REST_CLIENT_TYPE_ENUM.v3;
}
async fetchServerTime(): Promise<number> {
const res = await this.getServerTime();
return Number(res.time) / 1000;
}
getServerTime(): Promise<
APIResponseV3WithTime<{ timeSecond: string; timeNano: string }>
> {
return this.get('/v5/market/time');
}
requestDemoTradingFunds(): Promise<{}> {
return this.postPrivate('/v5/account/demo-apply-money');
}
/**
*
****** Market APIs
*
*/
/**
* Query the kline data. Charts are returned in groups based on the requested interval.
*
* Covers: Spot / Linear contract / Inverse contract
*/
getKline(
params: GetKlineParamsV5,
): Promise<
APIResponseV3WithTime<
CategorySymbolListV5<OHLCVKlineV5[], 'spot' | 'linear' | 'inverse'>
>
> {
return this.get('/v5/market/kline', params);
}
/**
* Query the mark price kline data. Charts are returned in groups based on the requested interval.
*
* Covers: Linear contract / Inverse contract
*/
getMarkPriceKline(
params: GetMarkPriceKlineParamsV5,
): Promise<
APIResponseV3WithTime<
CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'>
>
> {
return this.get('/v5/market/mark-price-kline', params);
}
/**
* Query the index price kline data. Charts are returned in groups based on the requested interval.
*
* Covers: Linear contract / Inverse contract
*/
getIndexPriceKline(
params: GetIndexPriceKlineParamsV5,
): Promise<
APIResponseV3WithTime<
CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'>
>
> {
return this.get('/v5/market/index-price-kline', params);
}
/**
* Retrieve the premium index price kline data. Charts are returned in groups based on the requested interval.
*
* Covers: Linear contract
*/
getPremiumIndexPriceKline(
params: GetPremiumIndexPriceKlineParamsV5,
): Promise<
APIResponseV3WithTime<CategorySymbolListV5<OHLCKlineV5[], 'linear'>>
> {
return this.get('/v5/market/premium-index-price-kline', params);
}
/**
* Query a list of instruments of online trading pair.
*
* Covers: Spot / Linear contract / Inverse contract / Option
*
* Note: Spot does not support pagination, so limit & cursor are invalid.
*/
getInstrumentsInfo<C extends CategoryV5>(
params: GetInstrumentsInfoParamsV5 & { category: C },
): Promise<APIResponseV3WithTime<InstrumentInfoResponseV5<C>>> {
return this.get('/v5/market/instruments-info', params);
}
/**
* Query orderbook data
*
* Covers: Spot / Linear contract / Inverse contract / Option
*/
getOrderbook(
params: GetOrderbookParamsV5,
): Promise<APIResponseV3WithTime<OrderbookResponseV5>> {
return this.get('/v5/market/orderbook', params);
}
getTickers(
params: GetTickersParamsV5<'linear' | 'inverse'>,
): Promise<
APIResponseV3WithTime<
CategoryListV5<TickerLinearInverseV5[], 'linear' | 'inverse'>
>
>;
getTickers(
params: GetTickersParamsV5<'option'>,
): Promise<APIResponseV3WithTime<CategoryListV5<TickerOptionV5[], 'option'>>>;
getTickers(
params: GetTickersParamsV5<'spot'>,
): Promise<APIResponseV3WithTime<CategoryListV5<TickerSpotV5[], 'spot'>>>;
/**
* Query the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.
*
* Covers: Spot / Linear contract / Inverse contract / Option
*/
getTickers(
params: GetTickersParamsV5,
): Promise<
APIResponseV3WithTime<
| CategoryListV5<TickerLinearInverseV5[], 'linear' | 'inverse'>
| CategoryListV5<TickerOptionV5[], 'option'>
| CategoryListV5<TickerSpotV5[], 'spot'>
>
> {
return this.get('/v5/market/tickers', params);
}
/**
* Query historical funding rate. Each symbol has a different funding interval.
*
* Covers: Linear contract / Inverse perpetual
*/
getFundingRateHistory(
params: GetFundingRateHistoryParamsV5,
): Promise<
APIResponseV3WithTime<
CategoryListV5<FundingRateHistoryResponseV5[], 'linear' | 'inverse'>
>
> {
return this.get('/v5/market/funding/history', params);
}
/**
* Query recent public trading data in Bybit.
*
* Covers: Spot / Linear contract / Inverse contract / Option
*/
getPublicTradingHistory(
params: GetPublicTradingHistoryParamsV5,
): Promise<
APIResponseV3WithTime<CategoryListV5<PublicTradeV5[], CategoryV5>>
> {
return this.get('/v5/market/recent-trade', params);
}
/**
* Get open interest of each symbol.
*
* Covers: Linear contract / Inverse contract
*/
getOpenInterest(
params: GetOpenInterestParamsV5,
): Promise<APIResponseV3WithTime<OpenInterestResponseV5>> {
return this.get('/v5/market/open-interest', params);
}
/**
* Query option historical volatility
* Covers: Option
*/
getHistoricalVolatility(
params: GetHistoricalVolatilityParamsV5,
): Promise<
APIResponseV3WithTime<CategoryListV5<HistoricalVolatilityV5[], 'option'>>
> {
return this.get('/v5/market/historical-volatility', params);
}
/**
* Query Bybit insurance pool data (BTC/USDT/USDC etc). The data is updated every 24 hours.
*/
getInsurance(
params?: GetInsuranceParamsV5,
): Promise<APIResponseV3WithTime<InsuranceResponseV5>> {
return this.get('/v5/market/insurance', params);
}
/**
* Query risk limit of futures
*
* Covers: Linear contract / Inverse contract
*/
getRiskLimit(
params?: GetRiskLimitParamsV5,
): Promise<
APIResponseV3WithTime<CategoryListV5<RiskLimitV5[], 'inverse' | 'linear'>>
> {
return this.get('/v5/market/risk-limit', params);
}
/**
* Get the delivery price for option
*
* Covers: Option
*
* @deprecated use getDeliveryPrice() instead
*/
getOptionDeliveryPrice(
params: GetOptionDeliveryPriceParamsV5,
): Promise<
APIResponseV3WithTime<CategoryCursorListV5<OptionDeliveryPriceV5[]>>
> {
return this.get('/v5/market/delivery-price', params);
}
/**
* Get the delivery price of Inverse futures, USDC futures and Options
*
* Covers: USDC futures / Inverse futures / Option
*/
getDeliveryPrice(
params: GetDeliveryPriceParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<DeliveryPriceV5[]>>> {
return this.get('/v5/market/delivery-price', params);
}
getLongShortRatio(
params: GetLongShortRatioParamsV5,
): Promise<APIResponseV3WithTime<{ list: LongShortRatioV5[] }>> {
return this.get('/v5/market/account-ratio', params);
}
/**
*
****** Trade APIs
*
*/
submitOrder(
params: OrderParamsV5,
): Promise<APIResponseV3WithTime<OrderResultV5>> {
return this.postPrivate('/v5/order/create', params);
}
amendOrder(
params: AmendOrderParamsV5,
): Promise<APIResponseV3WithTime<OrderResultV5>> {
return this.postPrivate('/v5/order/amend', params);
}
cancelOrder(
params: CancelOrderParamsV5,
): Promise<APIResponseV3WithTime<OrderResultV5>> {
return this.postPrivate('/v5/order/cancel', params);
}
/**
* Query unfilled or partially filled orders in real-time. To query older order records, please use the order history interface.
*/
getActiveOrders(
params: GetAccountOrdersParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<AccountOrderV5[]>>> {
return this.getPrivate('/v5/order/realtime', params);
}
cancelAllOrders(
params: CancelAllOrdersParamsV5,
): Promise<APIResponseV3WithTime<{ list: OrderResultV5[] }>> {
return this.postPrivate('/v5/order/cancel-all', params);
}
/**
* Query order history. As order creation/cancellation is asynchronous, the data returned from this endpoint may delay.
*
* If you want to get real-time order information, you could query this endpoint or rely on the websocket stream (recommended).
*/
getHistoricOrders(
params: GetAccountHistoricOrdersParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<AccountOrderV5[]>>> {
return this.getPrivate('/v5/order/history', params);
}
/**
* This endpoint allows you to place more than one order in a single request.
* Covers: Option (UTA, UTA Pro) / USDT Perpetual, UDSC Perpetual, USDC Futures (UTA Pro)
*
* Make sure you have sufficient funds in your account when placing an order.
* Once an order is placed, according to the funds required by the order,
* the funds in your account will be frozen by the corresponding amount during the life cycle of the order.
*
* A maximum of 20 orders can be placed per request. The returned data list is divided into two lists.
* The first list indicates whether or not the order creation was successful and the second list details the created order information.
* The structure of the two lists are completely consistent.
*/
batchSubmitOrders(
category: 'option' | 'linear',
orders: BatchOrderParamsV5[],
): Promise<
APIResponseV3WithTime<BatchOrdersResponseV5<BatchCreateOrderResultV5[]>>
> {
return this.postPrivate('/v5/order/create-batch', {
category,
request: orders,
});
}
/**
* This endpoint allows you to amend more than one open order in a single request.
* Covers: Option (UTA, UTA Pro) / USDT Perpetual, UDSC Perpetual, USDC Futures (UTA Pro)
*
* You can modify unfilled or partially filled orders. Conditional orders are not supported.
*
* A maximum of 20 orders can be amended per request.
*/
batchAmendOrders(
category: 'option' | 'linear',
orders: BatchAmendOrderParamsV5[],
): Promise<
APIResponseV3WithTime<BatchOrdersResponseV5<BatchAmendOrderResultV5[]>>
> {
return this.postPrivate('/v5/order/amend-batch', {
category,
request: orders,
});
}
/**
* This endpoint allows you to cancel more than one open order in a single request.
* Covers: Option (UTA, UTA Pro) / USDT Perpetual, UDSC Perpetual, USDC Futures (UTA Pro)
*
* You must specify orderId or orderLinkId. If orderId and orderLinkId is not matched, the system will process orderId first.
*
* You can cancel unfilled or partially filled orders. A maximum of 20 orders can be cancelled per request.
*/
batchCancelOrders(
category: 'option' | 'linear',
orders: BatchCancelOrderParamsV5[],
): Promise<
APIResponseV3WithTime<BatchOrdersResponseV5<BatchCancelOrderResultV5[]>>
> {
return this.postPrivate('/v5/order/cancel-batch', {
category,
request: orders,
});
}
/**
* Query the qty and amount of borrowable coins in spot account.
*
* Covers: Spot (Unified Account)
*/
getSpotBorrowCheck(
symbol: string,
side: OrderSideV5,
): Promise<APIResponseV3WithTime<SpotBorrowCheckResultV5>> {
return this.getPrivate('/v5/order/spot-borrow-check', {
category: 'spot',
symbol,
side,
});
}
/**
* This endpoint allows you to set the disconnection protect time window. Covers: option (unified account).
*
* If you need to turn it on/off, you can contact your client manager for consultation and application.
* The default time window is 10 seconds.
*
* Only for institutional clients!
*
* If it doesn't work, use v2!
*/
setDisconnectCancelAllWindow(
category: 'option',
timeWindow: number,
): Promise<APIResponseV3<undefined>> {
return this.postPrivate('/v5/order/disconnected-cancel-all', {
category,
timeWindow,
});
}
/**
* This endpoint allows you to set the disconnection protect time window. Covers: option (unified account).
*
* If you need to turn it on/off, you can contact your client manager for consultation and application.
* The default time window is 10 seconds.
*
* Only for institutional clients!
*/
setDisconnectCancelAllWindowV2(params: {
product: 'OPTION' | 'SPOT' | 'DERIVATIVES';
timeWindow: number;
}): Promise<APIResponseV3<undefined>> {
return this.postPrivate('/v5/order/disconnected-cancel-all', params);
}
/**
*
****** Position APIs
*
*/
/**
* Query real-time position data, such as position size, cumulative realizedPNL.
*
* 0: cross margin. 1: isolated margin
*
* Unified account covers: Linear contract / Options
*
* Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures
*
* Note: this will give a 404 error if you query the `option` category if your account is not unified
*/
getPositionInfo(
params: PositionInfoParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<PositionV5[]>>> {
return this.getPrivate('/v5/position/list', params);
}
/**
* Set the leverage
*
* Unified account covers: Linear contract
*
* Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures
*
* Note: Under one-way mode, buyLeverage must be the same as sellLeverage
*/
setLeverage(params: SetLeverageParamsV5): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/set-leverage', params);
}
/**
* Select cross margin mode or isolated margin mode.
* 0: cross margin. 1: isolated margin
*
* Covers: USDT perpetual (Normal account) / Inverse contract (Normal account).
*
* Switching margin modes will cause orders in progress to be cancelled.
* Please make sure that there are no open orders before you switch margin modes.
*/
switchIsolatedMargin(
params: SwitchIsolatedMarginParamsV5,
): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/switch-isolated', params);
}
/**
* This endpoint sets the take profit/stop loss (TP/SL) mode to full or partial.
*
* Unified account covers: Linear contract; normal account covers: USDT perpetual, inverse perpetual, inverse futures.
*
* For partial TP/SL mode, you can set the TP/SL size smaller than position size.
*/
setTPSLMode(
params: SetTPSLModeParamsV5,
): Promise<APIResponseV3WithTime<{ tpSlMode: TPSLModeV5 }>> {
return this.postPrivate('/v5/position/set-tpsl-mode', params);
}
/**
* Switches the position mode for USDT perpetual and Inverse futures.
*
* If you are in one-way Mode, you can only open one position on Buy or Sell side.
*
* If you are in hedge mode, you can open both Buy and Sell side positions simultaneously.
*
* Position mode. 0: Merged Single. 3: Both Sides.
*/
switchPositionMode(
params: SwitchPositionModeParamsV5,
): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/switch-mode', params);
}
/**
* The risk limit will limit the maximum position value you can hold under different margin requirements.
* If you want to hold a bigger position size, you need more margin.
*
* This interface can set the risk limit of a single position.
* If the order exceeds the current risk limit when placing an order, it will be rejected.
*/
setRiskLimit(
params: SetRiskLimitParamsV5,
): Promise<APIResponseV3WithTime<SetRiskLimitResultV5>> {
return this.postPrivate('/v5/position/set-risk-limit', params);
}
/**
* This endpoint allows you to set the take profit, stop loss or trailing stop for a position.
* Passing these parameters will create conditional orders by the system internally.
*
* The system will cancel these orders if the position is closed, and adjust the qty according to the size of the open position.
*
* Unified account covers: Linear contract.
* Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures.
*/
setTradingStop(
params: SetTradingStopParamsV5,
): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/trading-stop', params);
}
/**
* This endpoint allows you to turn on/off auto-add-margin for an isolated margin position.
*
* Covers: USDT perpetual (Normal Account).
*/
setAutoAddMargin(
params: SetAutoAddMarginParamsV5,
): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/set-auto-add-margin', params);
}
/**
* Manually add or reduce margin for isolated margin position
*
* Unified account covers: USDT perpetual / USDC perpetual / USDC futures / Inverse contract
* Normal account covers: USDT perpetual / Inverse contract
*/
addOrReduceMargin(
params: AddOrReduceMarginParamsV5,
): Promise<APIResponseV3WithTime<AddOrReduceMarginResultV5>> {
return this.postPrivate('/v5/position/add-margin', params);
}
/**
* Query users' execution records, sorted by execTime in descending order
*
* Unified account covers: Spot / Linear contract / Options
* Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures
*/
getExecutionList(
params: GetExecutionListParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<ExecutionV5[]>>> {
return this.getPrivate('/v5/execution/list', params);
}
/**
* Query user's closed profit and loss records. The results are sorted by createdTime in descending order.
*
* Unified account covers: Linear contract
* Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures
*/
getClosedPnL(
params: GetClosedPnLParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<ClosedPnLV5[]>>> {
return this.getPrivate('/v5/position/closed-pnl', params);
}
/**
* Move positions between sub-master, master-sub, or sub-sub UIDs.
*
* Unified account covers: USDT perpetual / USDC contract / Spot / Option
*
* INFO
* The endpoint can only be called by master UID api key
* UIDs must be the same master-sub account relationship
* The trades generated from move-position endpoint will not be displayed in the Recent Trade (Rest API & Websocket)
* There is no trading fee
* fromUid and toUid both should be Unified trading accounts, and they need to be one-way mode when moving the positions
* Please note that once executed, you will get execType=MovePosition entry from Get Trade History, Get Closed Pnl, and stream from Execution.
*/
movePosition(
params: MovePositionParamsV5,
): Promise<APIResponseV3WithTime<MovePositionResultV5>> {
return this.postPrivate('/v5/position/move-positions', params);
}
/**
* Query moved position data by master UID api key.
*
* Unified account covers: USDT perpetual / USDC contract / Spot / Option
*/
getMovePositionHistory(params?: GetMovePositionHistoryParamsV5): Promise<
APIResponseV3WithTime<{
list: MovePositionHistoryV5[];
nextPageCursor: string;
}>
> {
return this.getPrivate('/v5/position/move-history', params);
}
/**
* Confirm new risk limit.
*
* It is only applicable when the user is marked as only reducing positions (please see the isReduceOnly field in the Get Position Info interface).
* After the user actively adjusts the risk level, this interface is called to try to calculate the adjusted risk level, and if it passes (retCode=0),
* the system will remove the position reduceOnly mark. You are recommended to call Get Position Info to check isReduceOnly field.
*
* Unified account covers: USDT perpetual / USDC contract / Inverse contract
* Classic account covers: USDT perpetual / Inverse contract
*/
confirmNewRiskLimit(
params: ConfirmNewRiskLimitParamsV5,
): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/confirm-pending-mmr', params);
}
/**
*
****** Pre-upgrade APIs
*
*/
/**
* Get those orders which occurred before you upgrade the account to Unified account.
*
* For now, it only supports to query USDT perpetual, USDC perpetual, Inverse perpetual and futures.
*
* - can get all status in 7 days
* - can only get filled orders beyond 7 days
*/
getPreUpgradeOrderHistory(
params: GetPreUpgradeOrderHistoryParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<AccountOrderV5[]>>> {
return this.getPrivate('/v5/pre-upgrade/order/history', params);
}
/**
* Get users' execution records which occurred before you upgrade the account to Unified account, sorted by execTime in descending order
*
* For now, it only supports to query USDT perpetual, Inverse perpetual and futures.
*
* - You may have multiple executions in a single order.
* - You can query by symbol, baseCoin, orderId and orderLinkId, and if you pass multiple params,
* the system will process them according to this priority: orderId > orderLinkId > symbol > baseCoin.
*/
getPreUpgradeTradeHistory(
params: GetPreUpgradeTradeHistoryParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<ExecutionV5[]>>> {
return this.getPrivate('/v5/pre-upgrade/execution/list', params);
}
/**
* Query user's closed profit and loss records. The results are sorted by createdTime in descending order.
*
* For now, it only supports to query USDT perpetual, Inverse perpetual and futures.
*/
getPreUpgradeClosedPnl(
params: GetPreUpgradeClosedPnlParamsV5,
): Promise<APIResponseV3WithTime<CategoryCursorListV5<ClosedPnLV5[]>>> {
return this.getPrivate('/v5/pre-upgrade/position/closed-pnl', params);
}
/**
* Query transaction logs which occurred in the USDC Derivatives wallet before the account was upgraded to a Unified account.
*
* You can get USDC Perpetual, Option records.
*
* INFO
* USDC Perpeual & Option support the recent 6 months data. Please download older data via GUI
*/
getPreUpgradeTransactions(
params: GetPreUpgradeTransactionLogParamsV5,
): Promise<
APIResponseV3WithTime<{
list: PreUpgradeTransaction[];
nextPageCursor: string;
}>
> {
return this.getPrivate('/v5/pre-upgrade/account/transaction-log', params);
}
/**
* Query delivery records of Option before you upgraded the account to a Unified account, sorted by deliveryTime in descending order.
*
* INFO
* Supports the recent 6 months data. Please download older data via GUI
*/
getPreUpgradeOptionDeliveryRecord(
params: GetPreUpgradeOptionDeliveryRecordParamsV5,
): Promise<
APIResponseV3WithTime<CategoryCursorListV5<PreUpgradeOptionsDelivery[]>>
> {
return this.getPrivate('/v5/pre-upgrade/asset/delivery-record', params);
}
/**
* Query session settlement records of USDC perpetual before you upgrade the account to Unified account.
*
* INFO
* USDC Perpetual support the recent 6 months data. Please download older data via GUI
*/
getPreUpgradeUSDCSessionSettlements(
params: GetPreUpgradeUSDCSessionParamsV5,
): Promise<
APIResponseV3WithTime<
CategoryCursorListV5<PreUpgradeUSDCSessionSettlement[]>
>
> {
return this.getPrivate('/v5/pre-upgrade/asset/settlement-record', params);
}
/**
*
****** Account APIs
*
*/
/**
* Obtain wallet balance, query asset information of each currency, and account risk rate information under unified margin mode.
*
* By default, currency information with assets or liabilities of 0 is not returned.
*/
getWalletBalance(
params: GetWalletBalanceParamsV5,
): Promise<APIResponseV3WithTime<{ list: WalletBalanceV5[] }>> {
return this.getPrivate('/v5/account/wallet-balance', params);
}
/**
* Upgrade to unified account.
*