diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 8e114a7..6c0b7aa 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -331,90 +331,102 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getServerTime()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L242) | | GET | `/api/v3/public/time` | -| [getInstruments()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L259) | | GET | `/api/v3/market/instruments` | -| [getTickers()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L268) | | GET | `/api/v3/market/tickers` | -| [getOrderBook()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L275) | | GET | `/api/v3/market/orderbook` | -| [getFills()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L284) | | GET | `/api/v3/market/fills` | -| [getProofOfReserves()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L293) | | GET | `/api/v3/market/proof-of-reserves` | -| [getOpenInterest()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L300) | | GET | `/api/v3/market/open-interest` | -| [getCandles()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L310) | | GET | `/api/v3/market/candles` | -| [getHistoryCandles()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L319) | | GET | `/api/v3/market/history-candles` | -| [getCurrentFundingRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L328) | | GET | `/api/v3/market/current-fund-rate` | -| [getHistoryFundingRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L337) | | GET | `/api/v3/market/history-fund-rate` | -| [getRiskReserve()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L346) | | GET | `/api/v3/market/risk-reserve` | -| [getDiscountRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L355) | | GET | `/api/v3/market/discount-rate` | -| [getMarginLoans()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L362) | | GET | `/api/v3/market/margin-loans` | -| [getPositionTier()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L371) | | GET | `/api/v3/market/position-tier` | -| [getContractsOi()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L380) | | GET | `/api/v3/market/oi-limit` | -| [getBalances()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L395) | :closed_lock_with_key: | GET | `/api/v3/account/assets` | -| [getFundingAssets()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L402) | :closed_lock_with_key: | GET | `/api/v3/account/funding-assets` | -| [getAccountSettings()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L411) | :closed_lock_with_key: | GET | `/api/v3/account/settings` | -| [setLeverage()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L418) | :closed_lock_with_key: | POST | `/api/v3/account/set-leverage` | -| [setHoldMode()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L425) | :closed_lock_with_key: | POST | `/api/v3/account/set-hold-mode` | -| [getFinancialRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L434) | :closed_lock_with_key: | GET | `/api/v3/account/financial-records` | -| [getRepayableCoins()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L446) | :closed_lock_with_key: | GET | `/api/v3/account/repayable-coins` | -| [getPaymentCoins()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L458) | :closed_lock_with_key: | GET | `/api/v3/account/payment-coins` | -| [submitRepay()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L470) | :closed_lock_with_key: | POST | `/api/v3/account/repay` | -| [getConvertRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L477) | :closed_lock_with_key: | GET | `/api/v3/account/convert-records` | -| [setDepositAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L492) | :closed_lock_with_key: | POST | `/api/v3/account/deposit-account` | -| [switchDeduct()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L501) | :closed_lock_with_key: | POST | `/api/v3/account/switch-deduct` | -| [getDeductInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L508) | :closed_lock_with_key: | GET | `/api/v3/account/deduct-info` | -| [getFeeRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L519) | :closed_lock_with_key: | GET | `/api/v3/account/fee-rate` | -| [getMaxTransferable()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L535) | :closed_lock_with_key: | GET | `/api/v3/account/max-transferable` | -| [getOpenInterestLimit()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L547) | :closed_lock_with_key: | GET | `/api/v3/account/open-interest-limit` | -| [downgradeAccountToClassic()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L562) | :closed_lock_with_key: | POST | `/api/v3/account/switch` | -| [getUnifiedAccountSwitchStatus()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L570) | :closed_lock_with_key: | GET | `/api/v3/account/switch-status` | -| [getTaxRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L586) | :closed_lock_with_key: | GET | `/api/v3/tax/records` | -| [createSubAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L601) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub` | -| [freezeSubAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L610) | :closed_lock_with_key: | POST | `/api/v3/user/freeze-sub` | -| [getSubUnifiedAssets()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L619) | :closed_lock_with_key: | GET | `/api/v3/account/sub-unified-assets` | -| [getSubAccountList()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L628) | :closed_lock_with_key: | GET | `/api/v3/user/sub-list` | -| [createSubAccountApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L641) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub-api` | -| [updateSubAccountApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L650) | :closed_lock_with_key: | POST | `/api/v3/user/update-sub-api` | -| [deleteSubAccountApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L659) | :closed_lock_with_key: | POST | `/api/v3/user/delete-sub-api` | -| [getSubAccountApiKeys()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L668) | :closed_lock_with_key: | GET | `/api/v3/user/sub-api-list` | -| [getTransferableCoins()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L687) | :closed_lock_with_key: | GET | `/api/v3/account/transferable-coins` | -| [submitTransfer()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L696) | :closed_lock_with_key: | POST | `/api/v3/account/transfer` | -| [subAccountTransfer()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L705) | :closed_lock_with_key: | POST | `/api/v3/account/sub-transfer` | -| [getSubTransferRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L717) | :closed_lock_with_key: | GET | `/api/v3/account/sub-transfer-record` | -| [getDepositAddress()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L735) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-address` | -| [getSubDepositAddress()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L744) | :closed_lock_with_key: | GET | `/api/v3/account/sub-deposit-address` | -| [getDepositRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L753) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-records` | -| [getSubDepositRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L762) | :closed_lock_with_key: | POST | `/api/v3/account/sub-deposit-records` | -| [submitWithdraw()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L777) | :closed_lock_with_key: | POST | `/api/v3/account/withdraw` | -| [getWithdrawRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L786) | :closed_lock_with_key: | GET | `/api/v3/account/withdrawal-records` | -| [submitNewOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L801) | :closed_lock_with_key: | POST | `/api/v3/trade/place-order` | -| [modifyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L810) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-order` | -| [cancelOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L819) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-order` | -| [placeBatchOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L828) | :closed_lock_with_key: | POST | `/api/v3/trade/place-batch` | -| [batchModifyOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L837) | :closed_lock_with_key: | POST | `/api/v3/trade/batch-modify-order` | -| [cancelBatchOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L846) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-batch` | -| [cancelAllOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L855) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-symbol-order` | -| [closeAllPositions()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L864) | :closed_lock_with_key: | POST | `/api/v3/trade/close-positions` | -| [getOrderInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L873) | :closed_lock_with_key: | GET | `/api/v3/trade/order-info` | -| [getUnfilledOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L882) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-orders` | -| [getHistoryOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L894) | :closed_lock_with_key: | GET | `/api/v3/trade/history-orders` | -| [getTradeFills()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L906) | :closed_lock_with_key: | GET | `/api/v3/trade/fills` | -| [getCurrentPosition()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L918) | :closed_lock_with_key: | GET | `/api/v3/position/current-position` | -| [getPositionHistory()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L929) | :closed_lock_with_key: | GET | `/api/v3/position/history-position` | -| [getMaxOpenAvailable()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L941) | :closed_lock_with_key: | POST | `/api/v3/account/max-open-available` | -| [getPositionAdlRank()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L950) | :closed_lock_with_key: | GET | `/api/v3/position/adlRank` | -| [countdownCancelAll()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L957) | :closed_lock_with_key: | POST | `/api/v3/trade/countdown-cancel-all` | -| [getLoanTransfered()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L972) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/transfered` | -| [getLoanSymbols()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L981) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/symbols` | -| [getLoanRiskUnit()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L990) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/risk-unit` | -| [getLoanRepaidHistory()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1001) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/repaid-history` | -| [getLoanProductInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1010) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/product-infos` | -| [getLoanOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1019) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/loan-order` | -| [getLoanLTVConvert()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1028) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ltv-convert` | -| [getLoanMarginCoinInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1037) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ensure-coins-convert` | -| [bindLoanUid()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1049) | :closed_lock_with_key: | POST | `/api/v3/ins-loan/bind-uid` | -| [submitStrategyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1064) | :closed_lock_with_key: | POST | `/api/v3/trade/place-strategy-order` | -| [modifyStrategyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1073) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-strategy-order` | -| [cancelStrategyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1082) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-strategy-order` | -| [getUnfilledStrategyOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1091) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-strategy-orders` | -| [getHistoryStrategyOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1100) | :closed_lock_with_key: | GET | `/api/v3/trade/history-strategy-orders` | +| [getServerTime()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L269) | | GET | `/api/v3/public/time` | +| [getInstruments()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L286) | | GET | `/api/v3/market/instruments` | +| [getTickers()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L295) | | GET | `/api/v3/market/tickers` | +| [getOrderBook()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L302) | | GET | `/api/v3/market/orderbook` | +| [getFills()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L311) | | GET | `/api/v3/market/fills` | +| [getProofOfReserves()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L320) | | GET | `/api/v3/market/proof-of-reserves` | +| [getOpenInterest()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L327) | | GET | `/api/v3/market/open-interest` | +| [getCandles()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L337) | | GET | `/api/v3/market/candles` | +| [getHistoryCandles()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L346) | | GET | `/api/v3/market/history-candles` | +| [getCurrentFundingRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L355) | | GET | `/api/v3/market/current-fund-rate` | +| [getHistoryFundingRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L364) | | GET | `/api/v3/market/history-fund-rate` | +| [getRiskReserve()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L373) | | GET | `/api/v3/market/risk-reserve` | +| [getDiscountRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L382) | | GET | `/api/v3/market/discount-rate` | +| [getMarginLoans()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L389) | | GET | `/api/v3/market/margin-loans` | +| [getPositionTier()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L398) | | GET | `/api/v3/market/position-tier` | +| [getContractsOi()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L407) | | GET | `/api/v3/market/oi-limit` | +| [getIndexComponents()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L416) | | GET | `/api/v3/market/index-components` | +| [getBalances()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L431) | :closed_lock_with_key: | GET | `/api/v3/account/assets` | +| [getFundingAssets()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L438) | :closed_lock_with_key: | GET | `/api/v3/account/funding-assets` | +| [getAccountSettings()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L447) | :closed_lock_with_key: | GET | `/api/v3/account/settings` | +| [setLeverage()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L454) | :closed_lock_with_key: | POST | `/api/v3/account/set-leverage` | +| [setHoldMode()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L461) | :closed_lock_with_key: | POST | `/api/v3/account/set-hold-mode` | +| [getFinancialRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L470) | :closed_lock_with_key: | GET | `/api/v3/account/financial-records` | +| [getRepayableCoins()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L482) | :closed_lock_with_key: | GET | `/api/v3/account/repayable-coins` | +| [getPaymentCoins()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L494) | :closed_lock_with_key: | GET | `/api/v3/account/payment-coins` | +| [submitRepay()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L506) | :closed_lock_with_key: | POST | `/api/v3/account/repay` | +| [getConvertRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L513) | :closed_lock_with_key: | GET | `/api/v3/account/convert-records` | +| [setDepositAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L528) | :closed_lock_with_key: | POST | `/api/v3/account/deposit-account` | +| [switchDeduct()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L537) | :closed_lock_with_key: | POST | `/api/v3/account/switch-deduct` | +| [getDeductInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L544) | :closed_lock_with_key: | GET | `/api/v3/account/deduct-info` | +| [getFeeRate()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L555) | :closed_lock_with_key: | GET | `/api/v3/account/fee-rate` | +| [getMaxTransferable()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L571) | :closed_lock_with_key: | GET | `/api/v3/account/max-transferable` | +| [getOpenInterestLimit()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L583) | :closed_lock_with_key: | GET | `/api/v3/account/open-interest-limit` | +| [downgradeAccountToClassic()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L598) | :closed_lock_with_key: | POST | `/api/v3/account/switch` | +| [getUnifiedAccountSwitchStatus()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L606) | :closed_lock_with_key: | GET | `/api/v3/account/switch-status` | +| [getTaxRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L622) | :closed_lock_with_key: | GET | `/api/v3/tax/records` | +| [createSubAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L637) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub` | +| [freezeSubAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L646) | :closed_lock_with_key: | POST | `/api/v3/user/freeze-sub` | +| [getSubUnifiedAssets()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L655) | :closed_lock_with_key: | GET | `/api/v3/account/sub-unified-assets` | +| [getSubAccountList()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L664) | :closed_lock_with_key: | GET | `/api/v3/user/sub-list` | +| [createSubAccountApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L677) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub-api` | +| [updateSubAccountApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L686) | :closed_lock_with_key: | POST | `/api/v3/user/update-sub-api` | +| [deleteSubAccountApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L695) | :closed_lock_with_key: | POST | `/api/v3/user/delete-sub-api` | +| [getSubAccountApiKeys()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L704) | :closed_lock_with_key: | GET | `/api/v3/user/sub-api-list` | +| [getTransferableCoins()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L723) | :closed_lock_with_key: | GET | `/api/v3/account/transferable-coins` | +| [submitTransfer()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L732) | :closed_lock_with_key: | POST | `/api/v3/account/transfer` | +| [subAccountTransfer()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L741) | :closed_lock_with_key: | POST | `/api/v3/account/sub-transfer` | +| [getSubTransferRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L753) | :closed_lock_with_key: | GET | `/api/v3/account/sub-transfer-record` | +| [getDepositAddress()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L771) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-address` | +| [getSubDepositAddress()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L780) | :closed_lock_with_key: | GET | `/api/v3/account/sub-deposit-address` | +| [getDepositRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L789) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-records` | +| [getSubDepositRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L798) | :closed_lock_with_key: | POST | `/api/v3/account/sub-deposit-records` | +| [submitWithdraw()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L813) | :closed_lock_with_key: | POST | `/api/v3/account/withdraw` | +| [getWithdrawRecords()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L822) | :closed_lock_with_key: | GET | `/api/v3/account/withdrawal-records` | +| [submitNewOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L837) | :closed_lock_with_key: | POST | `/api/v3/trade/place-order` | +| [modifyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L846) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-order` | +| [cancelOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L855) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-order` | +| [placeBatchOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L864) | :closed_lock_with_key: | POST | `/api/v3/trade/place-batch` | +| [batchModifyOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L873) | :closed_lock_with_key: | POST | `/api/v3/trade/batch-modify-order` | +| [cancelBatchOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L882) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-batch` | +| [cancelAllOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L891) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-symbol-order` | +| [closeAllPositions()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L900) | :closed_lock_with_key: | POST | `/api/v3/trade/close-positions` | +| [getOrderInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L909) | :closed_lock_with_key: | GET | `/api/v3/trade/order-info` | +| [getUnfilledOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L918) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-orders` | +| [getHistoryOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L930) | :closed_lock_with_key: | GET | `/api/v3/trade/history-orders` | +| [getTradeFills()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L942) | :closed_lock_with_key: | GET | `/api/v3/trade/fills` | +| [getCurrentPosition()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L954) | :closed_lock_with_key: | GET | `/api/v3/position/current-position` | +| [getPositionHistory()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L965) | :closed_lock_with_key: | GET | `/api/v3/position/history-position` | +| [getMaxOpenAvailable()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L977) | :closed_lock_with_key: | POST | `/api/v3/account/max-open-available` | +| [getPositionAdlRank()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L986) | :closed_lock_with_key: | GET | `/api/v3/position/adlRank` | +| [countdownCancelAll()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L993) | :closed_lock_with_key: | POST | `/api/v3/trade/countdown-cancel-all` | +| [getLoanTransfered()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1008) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/transfered` | +| [getLoanSymbols()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1017) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/symbols` | +| [getLoanRiskUnit()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1026) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/risk-unit` | +| [getLoanRepaidHistory()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1037) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/repaid-history` | +| [getLoanProductInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1046) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/product-infos` | +| [getLoanOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1055) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/loan-order` | +| [getLoanLTVConvert()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1064) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ltv-convert` | +| [getLoanMarginCoinInfo()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1073) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ensure-coins-convert` | +| [bindLoanUid()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1085) | :closed_lock_with_key: | POST | `/api/v3/ins-loan/bind-uid` | +| [submitStrategyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1100) | :closed_lock_with_key: | POST | `/api/v3/trade/place-strategy-order` | +| [modifyStrategyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1109) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-strategy-order` | +| [cancelStrategyOrder()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1118) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-strategy-order` | +| [getUnfilledStrategyOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1127) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-strategy-orders` | +| [getHistoryStrategyOrders()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1136) | :closed_lock_with_key: | GET | `/api/v3/trade/history-strategy-orders` | +| [createBrokerSubAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1157) | :closed_lock_with_key: | POST | `/api/v3/broker/create-sub` | +| [getBrokerSubAccountList()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1169) | :closed_lock_with_key: | GET | `/api/v3/broker/sub-list` | +| [modifyBrokerSubAccount()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1181) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-sub` | +| [brokerSubWithdrawal()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1196) | :closed_lock_with_key: | POST | `/api/v3/broker/sub-withdrawal` | +| [getBrokerSubDepositAddress()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1208) | :closed_lock_with_key: | POST | `/api/v3/broker/sub-deposit-address` | +| [getBrokerAllSubDepositWithdrawal()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1220) | :closed_lock_with_key: | GET | `/api/v3/broker/all-sub-deposit-withdrawal` | +| [getBrokerCommission()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1232) | :closed_lock_with_key: | GET | `/api/v3/broker/commission` | +| [createBrokerSubApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1244) | :closed_lock_with_key: | POST | `/api/v3/broker/create-sub-apikey` | +| [modifyBrokerSubApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1256) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-sub-apikey` | +| [deleteBrokerSubApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1272) | :closed_lock_with_key: | POST | `/api/v3/broker/delete-sub-apikey` | +| [getBrokerSubApiKey()](https://github.com/tiagosiebler/bitget-api/blob/master/src/rest-client-v3.ts#L1284) | :closed_lock_with_key: | GET | `/api/v3/broker/query-sub-apikey` | # websocket-api-client.ts diff --git a/examples/apidoc/RestClientV3/brokerSubWithdrawal.js b/examples/apidoc/RestClientV3/brokerSubWithdrawal.js new file mode 100644 index 0000000..50e6b7b --- /dev/null +++ b/examples/apidoc/RestClientV3/brokerSubWithdrawal.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/sub-withdrawal +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.brokerSubWithdrawal(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/createBrokerSubAccount.js b/examples/apidoc/RestClientV3/createBrokerSubAccount.js new file mode 100644 index 0000000..bdbfccb --- /dev/null +++ b/examples/apidoc/RestClientV3/createBrokerSubAccount.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/create-sub +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.createBrokerSubAccount(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/createBrokerSubApiKey.js b/examples/apidoc/RestClientV3/createBrokerSubApiKey.js new file mode 100644 index 0000000..9fd93f1 --- /dev/null +++ b/examples/apidoc/RestClientV3/createBrokerSubApiKey.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/create-sub-apikey +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.createBrokerSubApiKey(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/deleteBrokerSubApiKey.js b/examples/apidoc/RestClientV3/deleteBrokerSubApiKey.js new file mode 100644 index 0000000..ab3872a --- /dev/null +++ b/examples/apidoc/RestClientV3/deleteBrokerSubApiKey.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/delete-sub-apikey +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.deleteBrokerSubApiKey(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/getBrokerAllSubDepositWithdrawal.js b/examples/apidoc/RestClientV3/getBrokerAllSubDepositWithdrawal.js new file mode 100644 index 0000000..1dd99bb --- /dev/null +++ b/examples/apidoc/RestClientV3/getBrokerAllSubDepositWithdrawal.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/all-sub-deposit-withdrawal +// METHOD: GET +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.getBrokerAllSubDepositWithdrawal(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/getBrokerCommission.js b/examples/apidoc/RestClientV3/getBrokerCommission.js new file mode 100644 index 0000000..1ef974d --- /dev/null +++ b/examples/apidoc/RestClientV3/getBrokerCommission.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/commission +// METHOD: GET +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.getBrokerCommission(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/getBrokerSubAccountList.js b/examples/apidoc/RestClientV3/getBrokerSubAccountList.js new file mode 100644 index 0000000..2f84f54 --- /dev/null +++ b/examples/apidoc/RestClientV3/getBrokerSubAccountList.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/sub-list +// METHOD: GET +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.getBrokerSubAccountList(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/getBrokerSubApiKey.js b/examples/apidoc/RestClientV3/getBrokerSubApiKey.js new file mode 100644 index 0000000..684d0d3 --- /dev/null +++ b/examples/apidoc/RestClientV3/getBrokerSubApiKey.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/query-sub-apikey +// METHOD: GET +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.getBrokerSubApiKey(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/getBrokerSubDepositAddress.js b/examples/apidoc/RestClientV3/getBrokerSubDepositAddress.js new file mode 100644 index 0000000..d254a25 --- /dev/null +++ b/examples/apidoc/RestClientV3/getBrokerSubDepositAddress.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/sub-deposit-address +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.getBrokerSubDepositAddress(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/getIndexComponents.js b/examples/apidoc/RestClientV3/getIndexComponents.js new file mode 100644 index 0000000..734307b --- /dev/null +++ b/examples/apidoc/RestClientV3/getIndexComponents.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/market/index-components +// METHOD: GET +// PUBLIC: YES + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.getIndexComponents(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/modifyBrokerSubAccount.js b/examples/apidoc/RestClientV3/modifyBrokerSubAccount.js new file mode 100644 index 0000000..308fbbf --- /dev/null +++ b/examples/apidoc/RestClientV3/modifyBrokerSubAccount.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/modify-sub +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.modifyBrokerSubAccount(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClientV3/modifyBrokerSubApiKey.js b/examples/apidoc/RestClientV3/modifyBrokerSubApiKey.js new file mode 100644 index 0000000..ca60095 --- /dev/null +++ b/examples/apidoc/RestClientV3/modifyBrokerSubApiKey.js @@ -0,0 +1,24 @@ +import { RestClientV3 } from 'bitget-api'; +// or if you want to use the require syntax +// const { RestClientV3 } = require('bitget-api'); + + +// This example shows how to call this Bitget API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "bitget-api" for Bitget exchange +// This Bitget API SDK is available on npm via "npm install bitget-api" +// ENDPOINT: /api/v3/broker/modify-sub-apikey +// METHOD: POST +// PUBLIC: NO + +const client = new RestClientV3({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', + apiPass: 'insert_api_pass_here', +}); + +client.modifyBrokerSubApiKey(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index c5c5dc9..df5c2ce 100644 --- a/llms.txt +++ b/llms.txt @@ -38,7 +38,7 @@ Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files -- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ +- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/, dist/, lib/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter @@ -53,17 +53,6 @@ examples/ fasterHmacSign.ts rest-private-rsa.md rest-private-rsa.ts - deprecated-V1-REST/ - README.md - rest-private-futures.ts - rest-private-spot.ts - rest-public-futures.ts - rest-public-spot.ts - rest-trade-futures.ts - rest-trade-spot.ts - deprecated-V1-Websockets/ - ws-private.ts - ws-public.ts V2/ rest-private-futures.ts rest-private-spot.ts @@ -90,10 +79,6 @@ src/ enum.ts types/ request/ - v1/ - brokerV1.ts - futuresV1.ts - spotV1.ts v2/ broker.ts common.ts @@ -104,16 +89,13 @@ src/ spot.ts v3/ account.ts + broker.ts loan.ts public.ts strategy.ts trade.ts shared.ts response/ - v1/ - futures.ts - shared.ts - spot.ts v2/ broker.ts common.ts @@ -124,6 +106,7 @@ src/ spot.ts v3/ account.ts + broker.ts loan.ts public.ts strategy.ts @@ -135,18 +118,14 @@ src/ ws-events.ts ws-general.ts shared.ts - broker-client.ts - futures-client.ts index.ts rest-client-v2.ts rest-client-v3.ts - spot-client.ts websocket-api-client.ts - websocket-client-legacy-v1.ts websocket-client-v2.ts websocket-client-v3.ts webpack/ - webpack.config.js + webpack.config.cjs .eslintrc.cjs .gitignore .jshintrc @@ -157,7 +136,6 @@ LICENSE.md package.json postBuild.sh README.md -tea.yaml tsconfig.cjs.json tsconfig.esm.json tsconfig.json @@ -168,1891 +146,994 @@ Files ================================================================ ================ -File: examples/deprecated-V1-REST/README.md -================ -# Deprecated V1 REST API Examples - -These examples are for Bitget's V1 APIs, the previous generation of their API offering. - -If you're building new functionality, you should look at using the V2 APIs via the RestClientV2 class in this SDK. This covers all the newer functionality offered by Bitget's APIs - with significant upgrades on all aspects of their APIs: -https://www.bitget.com/api-doc/common/release-note - -The V1 REST clients will remain function until Bitget formally deprecates their V1 API. - -================ -File: examples/deprecated-V1-REST/rest-public-spot.ts -================ -import { SpotClient } from '../../src/index'; -⋮---- -// or -// import { SpotClient } from 'bitget-api'; - -================ -File: src/types/request/v1/brokerV1.ts +File: examples/auth/fasterHmacSign.ts ================ -export type BrokerProductType = - | 'umcbl' - | 'usdt' - | 'swap' - | 'dmcbl' - | 'mix' - | 'swap'; +import { createHmac } from 'crypto'; ⋮---- -export interface BrokerSubListRequest { - pageSize?: string; - lastEndId?: number; - status?: string; -} +import { DefaultLogger, RestClientV3, WebsocketClientV3 } from '../../src/'; ⋮---- -export interface BrokerSubWithdrawalRequest { - subUid: string; - coin: string; - address: string; - chain: string; - tag?: string; - amount: string; - remark?: string; - clientOid?: string; -} +// or +// import { createHmac } from 'crypto'; +// import { DefaultLogger, RestClientV3, WebsocketClientV3 } from 'bitget-api'; ⋮---- -export interface BrokerSubAPIKeyModifyRequest { - subUid: string; - apikey: string; - remark?: string; - ip?: string; - perm?: string; -} - -================ -File: src/types/request/v2/copytrading.ts -================ /** + * Injecting a custom signMessage function. * + * As of version 3.0.0 of the bitget-api Node.js/TypeScript/JavaScript + * SDK for Bitget, the SDK uses the Web Crypto API for signing requests. + * While it is compatible with Node and Browser environments, it is + * slightly slower than using Node's native crypto module (only + * available in backend Node environments). * - * Copy Trading | Future copy trading | Trader Api + * For latency sensitive users, you can inject the previous node crypto sign + * method (or your own even faster implementation), if this change affects you. * + * This example demonstrates how to inject a custom sign function, to achieve + * the same peformance as seen before the Web Crypto API was introduced. * + * For context on standard usage, the "signMessage" function is used: + * - During every single API call + * - After opening a new private WebSocket connection */ ⋮---- -export type CopyTradingProductTypeV2 = - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; -⋮---- -export interface GetFuturesTraderCurrentOrdersRequestV2 { - symbol?: string; - productType: CopyTradingProductTypeV2; - startTime?: string; - endTime?: string; - limit?: string; - idGreaterThan?: string; - idLessThan?: string; -} -⋮---- -export interface GetFuturesTraderHistoryOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - order?: 'asc' | 'desc'; - symbol?: string; - productType: CopyTradingProductTypeV2; -} -⋮---- -export interface ModifyFuturesTraderOrderTPSLRequestV2 { - trackingNo: string; - productType: CopyTradingProductTypeV2; - stopSurplusPrice?: string; - stopLossPrice?: string; -} -⋮---- -export interface GetFuturesTraderProfitShareDetailRequestV2 { - coin?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} -⋮---- -export interface FuturesTraderSymbolSettingRequestV2 { - symbol: string; - productType: CopyTradingProductTypeV2; - settingType: 'ADD' | 'DELETE' | 'UPDATE'; - stopSurplusRatio?: string; - stopLossRatio?: string; -} -⋮---- -export interface GetFuturesTraderFollowersRequestV2 { - pageNo?: string; - pageSize?: string; - startTime?: string; - endTime?: string; -} -⋮---- /** - * - * - * Copy Trading | Future copy trading | Follower Api - * - * - */ -⋮---- -export interface GetFollowerFuturesCurrentTrackingOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - symbol?: string; - productType: CopyTradingProductTypeV2; - traderId?: string; -} -⋮---- -export interface GetFollowerFuturesHistoryTrackingOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - symbol?: string; - productType: CopyTradingProductTypeV2; - traderId?: string; -} -⋮---- -export interface UpdateFuturesFollowerTPSLRequestV2 { - trackingNo: string; - symbol?: string; - productType: CopyTradingProductTypeV2; - stopSurplusPrice?: string; - stopLossPrice?: string; -} -⋮---- -export type AutoCopyOption = 'on' | 'off'; -export type FollowMode = 'basic' | 'advanced'; -export type LeverageType = 'position' | 'specify' | 'trader'; -export type TraceType = 'percent' | 'amount' | 'count'; + * Set this to true to enable demo trading: + */ ⋮---- -export interface FollowerCopyTradeSettingRequestV2 { - symbol: string; - productType: CopyTradingProductTypeV2; - marginType: 'trader' | 'specify'; - marginCoin?: string; - leverType: LeverageType; - longLeverage?: string; - shortLeverage?: string; - traceType: TraceType; - traceValue: string; - maxHoldSize?: string; - stopSurplusRatio?: string; - stopLossRatio?: string; -} +/** + * Overkill in almost every case, but if you need any optimisation available, + * you can inject a faster sign mechanism such as node's native createHmac: + */ ⋮---- -export interface UpdateFuturesFollowerSettingsRequestV2 { - traderId: string; - autoCopy?: AutoCopyOption; - mode?: FollowMode; - settings: FollowerCopyTradeSettingRequestV2[]; -} -export interface CloseFuturesFollowerPositionsRequestV2 { - productType: CopyTradingProductTypeV2; - trackingNo?: string; - symbol?: string; - marginCoin?: string; - marginMode?: 'isolated' | 'cross'; - holdSide?: 'long' | 'short'; -} +// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing ⋮---- -export interface GetFuturesFollowerTradersRequestV2 { - startTime?: string; - endTime?: string; - pageNo?: string; - pageSize?: string; -} +// trace: (...params) => console.log('trace', ...params), ⋮---- /** - * - * - * Copy Trading | Spot copy trading | Trader api - * - * - */ + * Set this to true to enable demo trading for the private account data WS + * Topics: order,execution,position,wallet,greeks + */ ⋮---- -export interface GetSpotTraderHistoryProfitRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - coin?: string; -} +/** + * Overkill in almost every case, but if you need any optimisation available, + * you can inject a faster sign mechanism such as node's native createHmac: + */ ⋮---- -export interface GetSpotTraderHistoryOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - symbol?: string; -} +function setWsClientEventListeners( + websocketClient: WebsocketClientV3, + accountRef: string, +): Promise ⋮---- -export interface GetSpotTraderCurrentOrdersRequestV2 { - symbol?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface GetSpotTraderFollowersRequestV2 { - pageNo?: string; - pageSize?: string; - startTime?: string; - endTime?: string; -} +// Simple promise to ensure we're subscribed before trying anything else ⋮---- -/** - * - * - * Copy Trading | Spot copy trading | Follower api - * - * - */ +// Start trading + +================ +File: examples/auth/rest-private-rsa.md +================ +# RSA Authentication with Bitget APIs in Node.js, JavaScript & TypeScript + +## Creating RSA Keys + +Officially, Bitget recommends downloading and running a key generator from their repo. Guidance for this can be found on the Bitget's website when trying to add a new RSA API key. + +However, openssl can be used to create the public & private key files using the following steps: + +```bash +# Generate a private key with either 2048 or 4096 bit length +openssl genrsa -out rsa-private-key.pem 4096 + +# Generate a corresponding public key +openssl rsa -in rsa-private-key.pem -pubout -out rsa-public-key.pem +``` + +## Using the RSA public key to get an API key from Bitget + +Once created, keep your **private key** completely secret! The **public** key needs to be provided to Bitget when creating new API credentials with the "Self-generated" option. + +Your public key should look something like this: + +```pem +-----BEGIN PUBLIC KEY----- +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1uWxxOXZUaX6AeZszf4x +rBsU6axA5ipwxG7VPihVgssphDrrSOD0hZqnBmtF2bvT9ee1U0XOfMn+H+J5SH+1 +jgUpfioqH0L+KXl6wmLoPsadgfJz0SiQlFnKTkDXvMmecr6cdMHi2qNEx4CMc68C +obvQ4Voz5qqpDwbohGtJh0p10PB//0Ejcoz0UwrTDq8BGeFmWa9pL/7h2vHtw+QU +UxlnGmt98M8KkKqqvVicMK+IVtng/QlDw9ofG2kQcbBkPRaTjNI+8ULtCDH0sOkZ +nT8PtGm4sEwmWH/dRWtUTWkMnUwCzuo/rWPb7WMprW2pKDTrLjUAr9M161t3Xa6W +JO03K3NOxupy7ilululLY8d/WKWYDOZMvS5bPiPRUoZqlJneC0CT/2q1W6GfWzsT +DCDTpgq/Ao7jTtnME9iadpwvFn0nMtNgJSrFDWPq8vKY9pRcEp/Na5qvIEOQIFnp +/kIDPuMf+LZwO8lGFO3jnndY+62835rm7t6ZNM3NLoNCarvUCEasobgDJHw7x7c1 +fW/OxYtLrWGdMpsP0MewgGJZXcT7mvlBjQ+JWLoyIc5rYMIDw9RLWUPnrlRCxvPp +sD9kDX7eaipdoik5yLyMaRvd16Vt9Bck/9pbSHazm41m/nd4KCZeGdsvrAA2beww +zFWQQV9EX6/VLBgbnGTsMe0CAwEAAQ== +-----END PUBLIC KEY----- +``` + +Submit this in the "Upload public key" form, shown when creating a new API key on Bitget and choosing the "self-generated"/RSA option. + +Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. + +After using the public key to create a new API key, you will be given an API Key such as the following: + +``` +SIHqWcDeRoj6gkOjLjQh1dnV1CD7IgwQTfL4LVa8wu04zNTYVSmJBIHsjQjgwWqt +``` + +This is the first piece, used as the "apiKey" in the [rest-private-rsa.ts](./rest-private-rsa.ts) example. + +## Using the RSA private key for RSA authentication with Bitget APIs in Node.js + +Your private key, if generated with the above steps, should look something like this (but with much more text): + +```pem +-----BEGIN RSA PRIVATE KEY----- +uayyi6wFTaNeG1/WCqhrowj2kCx8eB6NDZYl+OS9ZI9WC +q/44iFERNuP0TXvQx8tgvSZXyu4/G618QzKh0Ii1uAATt2upa8dp1uGl2U7EqBE8 +p5y4pPzJuwvB3j6LQON20u2Wpbg8PQZACMfKym7lYDO+9MloK/gAQpyeYJzbw92C +YE/ymq4JVjCMCQKCAQEA4/X0I9TO8vT0D0l83o693QA3C09uSZ6j9Obx5UrtDnA9 +sMkkRoe+R/vvIpVDzukMEEOmCuxbcdPoniVUKlTooK0Llo6JJ1l8CdFzQsOR97Pe +csB6pxkLLH2qHx05xPBy4PyoB +-----END RSA PRIVATE KEY----- +``` + +This is your secret, you should never share this with anyone, not even Bitget! Treat this like a password. + +As part of this authentication process, your private key is used to generate a signature (using `RSA-SHA256`). This SDK handles this process automatically for you. RSA authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. + +From here, simply use the key provided by Bitget as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. + +Based on the above example, the following would prepare the main REST client using the above credentials: + +```typescript +// Received after creating a new API key with a self-generated RSA public key on Bitget +const API_KEY = 'bg_0866563123123123123f567e83e52fd'; + +// The self-generated RSA private key, this is never directly given to Bitget, but used to generate a signature +// Note: this MUST include the "BEGIN PRIVATE KEY" header so that the SDK understands this is RSA auth +const rsaPrivateKey = ` +-----BEGIN PRIVATE KEY----- +MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC4kNgO71O0xkuH +FjHnr5pimpEeiGPAtDTAeJoS55+kVrh3ThHsm0ARf36zimU +gwrCWAnKqPlbqzWzs9mH9JvZWrEaOgWy +8wMSJ21vtz1rRJhfaUUsOC1KLoWyvzqWW44zKaxoKSqCUMJqDbxIq7RjGlmc8KGJ +scFWRSdfGEEpvqLlpTLoEtWHZP0pUUamSWrH/IgieFFhKaOPvmED24DJAlqSeEFw +z7TW4dfWPRgjCRu4AAfgCtjb+3/7ONeQfx5XFvKFM7VNi/9sRh+alRqpzKrlI +79bM1p/egrC4c8KUqrNk2s5c3HIU......THISISANEXAMPLE +-----END PRIVATE KEY----- +`; + +// This is set by you when registering your RSA API key in Bitget's website. +const API_PASS = 'TestingRSA'; + +const client = new RestClientV2({ + apiKey: API_KEY, + apiSecret: rsaPrivateKey, + apiPass: API_PASS, +}); + +const clientV3 = new RestClientV3({ + apiKey: API_KEY, + apiSecret: rsaPrivateKey, + apiPass: API_PASS, +}); +``` + +For a complete example, refer to the [rest-private-rsa.ts](./rest-private-rsa.ts) file on GitHub. + +================ +File: examples/auth/rest-private-rsa.ts +================ +import { RestClientV2, RestClientV3 } from '../../src'; ⋮---- -export interface SpotFollowerCopyTradeSettingV2 { - symbol: string; - traceType: 'percent' | 'amount' | 'count'; - maxHoldSize: string; - traceValue: string; - stopLossRatio?: string; - stopSurplusRatio?: string; -} +// Import frmo NPM: +// import { RestClientV2, RestClientV3 } from 'bitget-api'; +// or if you prefer require: +// const { RestClientV2, RestClientV3 } = require('bitget-api'); ⋮---- -export interface GetSpotFollowerHistoryOrdersRequestV2 { - symbol?: string; - traderId?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// Received after creating a new API key with a self-generated RSA public key on Bitget ⋮---- -export interface GetSpotFollowerOpenOrdersRequestV2 { - symbol?: string; - traderId?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// The self-generated RSA private key, this is never directly given to Bitget, but used to generate a signature +// Note: this MUST include the "BEGIN PRIVATE KEY" header so that the SDK understands this is RSA auth +⋮---- +// This is set by you when registering your RSA API key in Bitget's website. +⋮---- +// const wsClient = new WebsocketClientV2({ +// apiKey: API_KEY, +// apiSecret: rsaPrivateKey, +// apiPass: API_PASS, +// }); ================ -File: src/types/request/v2/earn.ts +File: examples/V2/rest-private-futures.ts ================ -/** - * - * - * Earn | Savings - * - * - */ +import { RestClientV2 } from '../../src/index'; ⋮---- -export interface GetEarnSavingsAssetsRequestV2 { - periodType: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// or +// import { RestClientV2 } from 'bitget-api'; ⋮---- -export interface GetEarnSavingsRecordsRequestV2 { - coin?: string; - periodType: string; - orderType?: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// read from environmental variables ⋮---- -export interface RedeemSavingsRequestV2 { - productId: string; - orderId?: string; - periodType: string; - amount: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-futures.ts ⋮---- -/** - * - * - * Earn | Shark Fin - * - * - */ +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetSharkfinAssetsRequestV2 { - status: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface GetSharkfinRecordsRequestV2 { - coin?: string; - type: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ ⋮---- -/** - * - * - * Earn | Loan - * - * - */ +startTime: fromTime.getTime() + '', // should be sent as a string +endTime: now.getTime() + '', // should be sent as a string + +================ +File: examples/V2/rest-private-spot.ts +================ +import { RestClientV2 } from '../../src/index'; ⋮---- -export interface GetLoanEstInterestAndBorrowableRequestV2 { - loanCoin: string; - pledgeCoin: string; - daily: 'SEVEN' | 'THIRTY'; - pledgeAmount?: string; -} +// or +// import { RestClientV2 } from 'bitget-api'; ⋮---- -export interface BorrowLoanRequestV2 { - loanCoin: string; - pledgeCoin: string; - daily: 'SEVEN' | 'THIRTY'; - pledgeAmount?: string; - loanAmount?: string; -} +// read from environmental variables ⋮---- -export interface RepayLoanRequestV2 { - orderId: string; - amount?: string; - repayUnlock?: string; - repayAll: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-spot.ts ⋮---- -export interface GetLoanRepayHistoryRequestV2 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - startTime: string; - endTime: string; - pageNo?: string; - pageSize?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface ModifyLoanPledgeRateRequestV2 { - orderId: string; - amount: string; - pledgeCoin: string; - reviseType: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface GetLoanPledgeRateHistoryRequestV2 { - orderId?: string; - reviseSide?: string; - pledgeCoin?: string; - startTime: string; - endTime: string; - pageNo?: string; - pageSize?: string; -} +/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ + +================ +File: examples/V2/rest-public-futures.ts +================ +import { RestClientV2 } from '../../src/index'; ⋮---- -export interface GetLoanHistoryRequestV2 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - status?: string; - startTime: string; - endTime: string; - pageNo?: string; - pageSize?: string; -} +// or +// import { RestClientV2 } from 'bitget-api'; ⋮---- -export interface GetLiquidationRecordsRequestV2 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - status?: string; - startTime: string; - endTime: string; - pageNo?: string; - pageSize?: string; -} +// Fetch the last 1000 1min candles for a symbol +⋮---- +const msPerCandle = 60 * 1000; // 60 seconds x 1000 ================ -File: src/types/request/v2/margin.ts +File: examples/V2/rest-public-spot.ts ================ -/** - * - * * Margin | Cross/Isolated | Order Record - * - */ +import { RestClientV2 } from '../../src/index'; ⋮---- -export interface GetBorrowHistoryRequestV2 { - loanId?: string; - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// or +// import { RestClientV2 } from 'bitget-api'; + +================ +File: examples/V2/rest-trade-futures.ts +================ +import { + FuturesPlaceOrderRequestV2, + RestClientV2, + WebsocketClientV2, +} from '../../src'; ⋮---- -export interface GetRepayHistoryRequestV2 { - repayId?: string; - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// or +// import { FuturesPlaceOrderRequestV2, RestClientV2, WebsocketClientV2 } from '../src'; ⋮---- -export interface GetInterestHistoryRequestV2 { - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// read from environmental variables ⋮---- -export interface GetLiquidationHistoryRequestV2 { - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-futures.ts ⋮---- -export interface GetFinancialHistoryRequestV2 { - marginType?: string; - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -/** - * - * * Margin | Cross/Isolated | Account - * - */ +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', +⋮---- +function logWSEvent(type, data) +⋮---- +// simple sleep function +function promiseSleep(milliseconds) ⋮---- /** + * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). * - * * Margin | Cross/Isolated | Trade + * It is designed to: + * - open a private websocket channel to log account events + * - check for any available USDT balance in the futures account + * - immediately open a minimum sized long position on BTCUSDT + * - check active positions + * - immediately send closing orders for any active futures positions + * - check positions again * */ ⋮---- -export type MarginOrderTypeV2 = 'limit' | 'market'; +// Add event listeners to log websocket events on account ⋮---- -export type MarginLoanTypeV2 = - | 'normal' - | 'autoLoan' - | 'autoRepay' - | 'autoLoanAndRepay'; +// futures private +// : account updates ⋮---- -export type MarginTimeInForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; +// : position updates ⋮---- -export type MarginOrderSideV2 = 'buy' | 'sell'; +// : order updates ⋮---- -export type MarginSTPModeV2 = - | 'none' - | 'cancel_taker' - | 'cancel_maker' - | 'cancel_both'; +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) ⋮---- -export interface MarginPlaceOrderRequestV2 { - symbol: string; - orderType: MarginOrderTypeV2; - price?: string; - loanType: MarginLoanTypeV2; - force: MarginTimeInForceV2; - baseSize?: string; - quoteSize?: string; - clientOid?: string; - side: MarginOrderSideV2; - stpMode?: MarginSTPModeV2; -} +// const balances = allBalances.filter((bal) => Number(bal.available) != 0); ⋮---- -export interface MarginBatchOrderEntry { - orderType: MarginOrderTypeV2; - price?: string; - loanType: MarginLoanTypeV2; - force: MarginTimeInForceV2; - baseSize?: string; - quoteSize?: string; - clientOid?: string; - side: MarginOrderSideV2; - stpMode?: MarginSTPModeV2; -} +// Loop through any active positions and send a closing market order on each position + +================ +File: examples/V2/rest-trade-spot.ts +================ +import { + RestClientV2, + SpotOrderRequestV2, + WebsocketClientV2, +} from '../../src/index'; ⋮---- -export interface MarginBatchOrdersRequestV2 { - symbol: string; - orderList: MarginBatchOrderEntry[]; -} +// import { RestClientV2, WebsocketClient } from '../src/index'; ⋮---- -export interface GetMarginCurrentOrdersRequestV2 { - symbol: string; - orderId?: string; - clientOid?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// read from environmental variables ⋮---- -export interface GetHistoryOrdersRequestV2 { - symbol: string; - orderId?: string; - enterPointSource?: string; - clientOid?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-spot.ts ⋮---- -export interface GetMarginOrderFillsRequestV2 { - symbol: string; - orderId?: string; - idLessThan?: string; - startTime: string; - endTime?: string; - limit?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetMarginLiquidationOrdersRequestV2 { - type?: 'swap' | 'place_order'; - symbol?: string; - fromCoin?: string; - toCoin?: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} - -================ -File: src/types/request/v2/spot.ts -================ -type SpotKlineIntervalV2 = - | '1min' - | '5min' - | '15min' - | '30min' - | '1h' - | '4h' - | '6h' - | '12h' - | '1day' - | '3day' - | '1week' - | '1M' - | '6Hutc' - | '12Hutc' - | '1Dutc' - | '3Dutc' - | '1Wutc' - | '1Mutc'; +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface SpotCandlesRequestV2 { - symbol: string; - granularity: SpotKlineIntervalV2; - startTime?: string; - endTime?: string; - limit?: string; -} +function logWSEvent(type, data) ⋮---- -export interface SpotHistoricCandlesRequestV2 { - symbol: string; - granularity: SpotKlineIntervalV2; - endTime?: string; - limit?: string; -} +// simple sleep function +function promiseSleep(milliseconds) ⋮---- -export interface SpotHistoricTradesRequestV2 { - symbol: string; - limit?: string; - idLessThan?: string; - startTime?: string; - endTime?: string; -} +/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ ⋮---- -/** - * - * * Spot | Trade - * - */ +// Add event listeners to log websocket events on account ⋮---- -export type SpotOrderSideV2 = 'buy' | 'sell'; +// Subscribe to private account topics +// spot private +// : account updates ⋮---- -export type SpotOrderTypeV2 = 'limit' | 'market'; +// : order updates (note: symbol is required) ⋮---- -export type SpotOrderForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) ⋮---- -export type SpotTPSLTypeV2 = 'normal' | 'tpsl'; +// console.log('balance: ', JSON.stringify(balances, null, 2)); + +================ +File: examples/V2/ws-demo-trading.ts +================ +import { DefaultLogger, WebsocketClientV2 } from '../../src'; ⋮---- -export type SpotSTPModeV2 = - | 'none' - | 'cancel_taker' - | 'cancel_maker' - | 'cancel_both'; +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export type SpotBatchModeV2 = 'single' | 'multiple'; +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -export interface SpotOrderRequestV2 { - symbol: string; - side: SpotOrderSideV2; - orderType: SpotOrderTypeV2; - force: SpotOrderForceV2; - price?: string; - size: string; - clientOid?: string; - triggerPrice?: string; - tpslType?: SpotTPSLTypeV2; - requestTime?: string; - receiveWindow?: string; - stpMode?: SpotSTPModeV2; - presetTakeProfitPrice?: string; - executeTakeProfitPrice?: string; - presetStopLossPrice?: string; - executeStopLossPrice?: string; -} +// restOptions: { +// optionally provide rest options, e.g. to pass through a proxy +// }, ⋮---- -export interface SpotCancelandSubmitOrderRequestV2 { - symbol: string; - price: string; - size: string; - orderId?: string; - clientOid?: string; - newClientOid?: string; - presetTakeProfitPrice?: string; - executeTakeProfitPrice?: string; - presetStopLossPrice?: string; - executeStopLossPrice?: string; -} +// Set demoTrading to true, to route all connections to the demo trading wss URLs: ⋮---- -export interface SpotCancelOrderRequestV2 { - symbol: string; - tpslType?: SpotTPSLTypeV2; - orderId?: string; - clientOid?: string; -} +// If using private topics, make sure to include API keys ⋮---- -export interface SpotBatchOrderRequestItemV2 { - symbol?: string; - side: SpotOrderSideV2; - orderType: SpotOrderTypeV2; - force: SpotOrderForceV2; - price?: string; - size: string; - clientOid?: string; - stpMode?: SpotSTPModeV2; - presetTakeProfitPrice?: string; - executeTakeProfitPrice?: string; - presetStopLossPrice?: string; - executeStopLossPrice?: string; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface SpotBatchOrderRequestV2 { - symbol?: string; - batchMode?: SpotBatchModeV2; - orderList: SpotBatchOrderRequestItemV2[]; -} +/** + * Public events + */ + +================ +File: examples/V2/ws-private.ts +================ +import { DefaultLogger, WebsocketClientV2 } from '../../src'; ⋮---- -export interface SpotBatchCancelOrderRequestV2 { - symbol?: string; - batchMode?: SpotBatchModeV2; - orderList: { - symbol?: string; - orderId?: string; - clientOid?: string; - }[]; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export interface GetSpotOrderInfoRequestV2 { - orderId?: string; - clientOid?: string; - requestTime?: string; - receiveWindow?: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -export interface GetSpotOpenOrdersRequestV2 { - symbol?: string; - startTime?: string; - endTime?: string; - idLessThan?: string; - limit?: string; - orderId?: string; - tpslType?: SpotTPSLTypeV2; - requestTime?: string; - receiveWindow?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetSpotHistoryOrdersRequestV2 { - symbol?: string; - startTime?: string; - endTime?: string; - idLessThan?: string; - limit?: string; - orderId?: string; - tpslType?: SpotTPSLTypeV2; - requestTime?: string; - receiveWindow?: string; -} +// restOptions: { +// optionally provide rest options, e.g. to pass through a proxy +// }, ⋮---- -export interface GetSpotFillsRequestV2 { - symbol: string; - orderId?: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +⋮---- +// auth happens async after the ws connection opens +⋮---- +// wsClient.subscribePublicSpotTickers(['BTCUSDT', 'LTCUSDT']); ⋮---- /** - * - * * Spot | Trigger Orders - * - */ + * Private account updates + */ ⋮---- -export type SpotPlanTypeV2 = 'amount' | 'total'; +// spot private +// : account updates ⋮---- -export type SpotTriggerTypeV2 = 'fill_price' | 'mark_price'; +// : order updates (note: symbol is required) +// wsClient.subscribeTopic('SPOT', 'orders', 'BTCUSDT'); ⋮---- -export interface SpotPlanOrderRequestV2 { - symbol: string; - side: SpotOrderSideV2; - triggerPrice: string; - orderType: SpotOrderTypeV2; - executePrice?: string; - planType?: SpotPlanTypeV2; - size: string; - triggerType: SpotTriggerTypeV2; - clientOid?: string; - force?: SpotOrderForceV2; - stpMode?: SpotSTPModeV2; -} +// futures private +// : account updates ⋮---- -export interface SpotModifyPlanOrderRequestV2 { - orderId?: string; - clientOid?: string; - triggerPrice: string; - orderType: SpotOrderTypeV2; - executePrice?: string; - size: string; -} +// : position updates +// wsClient.subscribeTopic('USDT-FUTURES', 'positions'); ⋮---- -export interface GetSpotCurrentPlanOrdersRequestV2 { - symbol: string; - limit?: string; - idLessThan?: string; - startTime?: string; - endTime?: string; -} +// : order updates +// wsClient.subscribeTopic('USDT-FUTURES', 'orders'); ⋮---- -export interface GetSpotHistoryPlanOrdersRequestV2 { - symbol: string; - startTime: string; - endTime: string; - limit?: string; -} +// : plan order updates +// wsClient.subscribeTopic('USDT-FUTURES', 'orders-algo'); ⋮---- -/** - * - * * Spot | Account - * - */ +// wsClient +// .getWsStore() +// .getKeys() +// .forEach((wsKey) => { +// const state = wsClient.getWsStore().get(wsKey); +// console.log(`${wsKey} state: `, state.subscribedTopics.values()); +// }); ⋮---- -export type SpotBillGroupTypeV2 = - | 'deposit' - | 'withdraw' - | 'transaction' - | 'transfer' - | 'other'; +// setTimeout(() => { +// wsClient.unsubscribeTopic('USDT-FUTURES', 'account'); +// }, 1000 * 2); ⋮---- -export type SpotBusinessTypeV2 = - | 'deposit' - | 'withdraw' - | 'buy' - | 'sell' - | 'deduction of handling fee' - | 'transfer-in' - | 'transfer-out' - | 'rebate rewards' - | 'airdrop rewards' - | 'USDT contract rewards' - | 'mix contract rewards' - | 'system lock' - | 'user lock'; +// setTimeout(() => { +// wsClient +// .getWsStore() +// .getKeys() +// .forEach((wsKey) => { +// const state = wsClient.getWsStore().get(wsKey); +// console.log(`${wsKey} state: `, state.subscribedTopics.values()); +// }); +// }, 1000 * 5); + +================ +File: examples/V2/ws-public.ts +================ +import { DefaultLogger, WebsocketClientV2, WS_KEY_MAP } from '../../src'; ⋮---- -export type SpotAccountTypeV2 = - | 'spot' - | 'p2p' - | 'coin_futures' - | 'usdt_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'isolated_margin'; +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export interface GetSpotAccountBillsRequestV2 { - coin?: string; - groupType?: SpotBillGroupTypeV2; - businessType?: SpotBusinessTypeV2; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// restOptions: { +// optionally provide rest options, e.g. to pass through a proxy +// }, ⋮---- -export interface SpotTransferRequestV2 { - fromType: SpotAccountTypeV2; - toType: SpotAccountTypeV2; - amount: string; - coin: string; - symbol: string; - clientOid?: string; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface SpotSubAccountTransferRequestV2 { - fromType: SpotAccountTypeV2; - toType: SpotAccountTypeV2; - amount: string; - coin: string; - symbol?: string; - clientOid?: string; - fromUserId: string; - toUserId: string; -} +/** + * Public events + */ ⋮---- -export interface SpotWithdrawalRequestV2 { - coin: string; - transferType: 'on_chain' | 'internal_transfer'; - address: string; - chain?: string; - innerToType?: 'email' | 'mobile' | 'uid'; - areaCode?: string; - tag?: string; - size: string; - remark?: string; - clientOid?: string; -} +// Spot public ⋮---- -export interface SpotMainSubTransferRecordRequestV2 { - coin?: string; - role?: 'initiator' | 'receiver'; - subUid?: string; - startTime?: string; - endTime?: string; - clientOid?: string; - limit?: string; - idLessThan?: string; -} +// tickers ⋮---- -export interface GetSpotTransferRecordRequestV2 { - coin: string; - fromType: SpotAccountTypeV2; - startTime?: string; - endTime?: string; - clientOid?: string; - limit?: string; - idLessThan?: string; -} +// candles +// wsClient.subscribeTopic('SPOT', 'candle1m', symbol); ⋮---- -export interface GetSpotSubAccountDepositRecordRequestV2 { - subUid: string; - coin?: string; - startTime?: string; - endTime?: string; - idLessThan?: string; - limit?: string; -} +// orderbook updates +// wsClient.subscribeTopic('SPOT', 'books', symbol); ⋮---- -export interface GetSpotWithdrawalRecordRequestV2 { - coin?: string; - clientOid?: string; - startTime: string; - endTime: string; - idLessThan?: string; - orderId?: string; - limit?: string; -} +// trades +// wsClient.subscribeTopic('SPOT', 'trade', symbol); ⋮---- -export interface GetSpotDepositRecordRequestV2 { - coin?: string; - orderId?: string; - startTime: string; - endTime: string; - idLessThan?: string; - limit?: string; -} +// Futures public +⋮---- +// tickers +// wsClient.subscribeTopic('USDT-FUTURES', 'ticker', symbol); +⋮---- +// candles +// wsClient.subscribeTopic('USDT-FUTURES', 'candle1m', symbol); +⋮---- +// orderbook updates +// wsClient.subscribeTopic('USDT-FUTURES', 'books', symbol); +⋮---- +// trades +// wsClient.subscribeTopic('USDT-FUTURES', 'trade', symbol); +⋮---- +// Topics are tracked per websocket type +// Get a list of subscribed topics (e.g. all public topics) (after a 5 second delay) ================ -File: src/types/request/v3/loan.ts +File: examples/V3/rest-private.ts ================ -export interface GetTransferedRequestV3 { - userId?: string; - coin: string; -} +import { RestClientV3 } from '../../src/index'; ⋮---- -export interface GetSymbolsRequestV3 { - productId: string; -} +// or +// import { RestClientV3 } from 'bitget-api'; ⋮---- -export interface GetRepaidHistoryRequestV3 { - startTime?: string; - endTime?: string; - limit?: string; -} +// read from environmental variables ⋮---- -export interface GetProductInfosRequestV3 { - productId: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-private-futures.ts ⋮---- -export interface GetLoanOrderRequestV3 { - orderId?: string; - startTime?: string; - endTime?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetEnsureCoinsRequestV3 { - productId: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface BindUidRequestV3 { - riskUnitId?: string; - uid: string; - operate: 'bind' | 'unbind'; -} +/** This is a simple script wrapped in a immediately invoked function expression, designed to check account assets for futures trading */ + +================ +File: examples/V3/rest-public-UTA-futures.ts +================ +import { RestClientV3 } from '../../src/index'; ⋮---- -export interface GetLTVConvertRequestV3 { - riskUnitId?: string; -} +// or +// import { RestClientV3 } from 'bitget-api'; ================ -File: src/types/request/v3/public.ts +File: examples/V3/rest-public-UTA-spot.ts ================ -export interface GetPublicFillsRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; - limit?: string; -} +import { RestClientV3 } from '../../src/index'; ⋮---- -export interface GetCandlesRequestV3 { - category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - interval: - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1H' - | '4H' - | '6H' - | '12H' - | '1D'; - startTime?: string; - endTime?: string; - type?: 'MARKET' | 'MARK' | 'INDEX'; - limit?: string; -} -⋮---- -export interface GetHistoryCandlesRequestV3 { - category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - interval: - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1H' - | '4H' - | '6H' - | '12H' - | '1D'; - startTime?: string; - endTime?: string; - type?: 'MARKET' | 'MARK' | 'INDEX'; - limit?: string; -} +// or +// import { RestClientV3 } from 'bitget-api'; + +================ +File: examples/V3/rest-trade-UTA-futures.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + PlaceOrderRequestV3, + RestClientV3, + WebsocketClientV3, +} from '../../src'; ⋮---- -export interface GetContractsOiRequestV3 { - symbol?: string; - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; -} +// or +// import { PlaceOrderRequestV3, RestClientV3, WebsocketClientV3 } from '../src'; ⋮---- -export interface GetCurrentFundingRateRequestV3 { - symbol: string; -} +// read from environmental variables ⋮---- -export interface GetHistoryFundingRateRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - cursor?: string; - limit?: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-futures.ts ⋮---- -export interface GetMarginLoansRequestV3 { - coin: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetOpenInterestRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface GetPositionTierRequestV3 { - category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - coin?: string; -} +function logWSEvent(type, data) ⋮---- -export interface GetRiskReserveRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; -} +// simple sleep function +function promiseSleep(milliseconds) ⋮---- -export interface GetInstrumentsRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; -} +/** + * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). + * + * It is designed to: + * - open a private websocket channel to log account events + * - check for any available USDT balance in the account + * - immediately open a minimum sized long position on BTCUSDT + * - check active positions + * - immediately send closing orders for any active futures positions + * - check positions again + * + */ ⋮---- -export interface GetOrderBookRequestV3 { - category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - limit?: string; -} +// Add event listeners to log websocket events on account ⋮---- -export interface GetTickersRequestV3 { - category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; -} - -================ -File: src/types/request/v3/strategy.ts -================ -export interface PlaceStrategyOrderRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - clientOid?: string; - type?: 'tpsl'; - tpslMode?: 'full' | 'partial'; - qty: string; - posSide: 'long' | 'short'; - tpTriggerBy?: 'market' | 'mark'; - slTriggerBy?: 'market' | 'mark'; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: 'limit' | 'market'; - slOrderType?: 'limit' | 'market'; - tpLimitPrice?: string; - slLimitPrice?: string; -} +// Subscribe to private topics for UTA account ⋮---- -export interface ModifyStrategyOrderRequestV3 { - orderId?: string; - clientOid?: string; - qty: string; - tpTriggerBy?: 'market' | 'mark'; - slTriggerBy?: 'market' | 'mark'; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: 'limit' | 'market'; - slOrderType?: 'limit' | 'market'; - tpLimitPrice?: string; - slLimitPrice?: string; -} +// Subscribe to position updates ⋮---- -export interface CancelStrategyOrderRequestV3 { - orderId?: string; - clientOid?: string; -} +// Subscribe to order updates ⋮---- -export interface GetUnfilledStrategyOrdersRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - type?: 'tpsl'; -} +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) ⋮---- -export interface GetHistoryStrategyOrdersRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - type?: 'tpsl'; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +// Loop through any active positions and send a closing market order on each position ================ -File: src/types/request/v3/trade.ts +File: examples/V3/rest-trade-UTA-spot.ts ================ -export interface BatchModifyOrderRequestV3 { - orderId?: string; - clientOid?: string; - qty?: string; - price?: string; - autoCancel?: 'yes' | 'no'; -} +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + PlaceOrderRequestV3, + RestClientV3, + WebsocketClientV3, +} from '../../src/index'; ⋮---- -export interface CancelAllOrdersRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; -} +// import { RestClientV3, WebsocketClientV3 } from '../src/index'; ⋮---- -export interface CancelBatchOrdersRequestV3 { - orderId?: string; - clientOid?: string; - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; -} +// read from environmental variables ⋮---- -export interface CloseAllPositionsRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - posSide?: 'long' | 'short'; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-spot.ts ⋮---- -export interface CancelOrderRequestV3 { - orderId?: string; - clientOid?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetMaxOpenAvailableRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; - orderType: 'limit' | 'market'; - side: 'buy' | 'sell'; - price?: string; - size?: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface GetOrderInfoRequestV3 { - orderId?: string; - clientOid?: string; -} +function logWSEvent(type, data) ⋮---- -export interface GetFillsRequestV3 { - orderId?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +// simple sleep function +function promiseSleep(milliseconds) ⋮---- -export interface GetUnfilledOrdersRequestV3 { - category?: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ ⋮---- -export interface GetHistoryOrdersRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetPositionHistoryRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetCurrentPositionRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - posSide?: 'long' | 'short'; -} -⋮---- -export interface ModifyOrderRequestV3 { - orderId?: string; - clientOid?: string; - qty?: string; - price?: string; - autoCancel?: 'yes' | 'no'; -} -⋮---- -export interface PlaceBatchOrdersRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; - qty: string; - price?: string; - side: 'buy' | 'sell'; - orderType: 'limit' | 'market'; - timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only'; - posSide?: 'long' | 'short'; - clientOid?: string; - reduceOnly?: 'yes' | 'no'; -} +// Add event listeners to log websocket events on account ⋮---- -export interface PlaceOrderRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; - qty: string; - price?: string; - side: 'buy' | 'sell'; - orderType: 'limit' | 'market'; - timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only'; - posSide?: 'long' | 'short'; - clientOid?: string; - reduceOnly?: 'yes' | 'no'; - stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; - takeProfitPrice?: string; - stopLossPrice?: string; - takeProfitTriggerType?: 'mark_price' | 'last_price'; - stopLossTriggerType?: 'mark_price' | 'last_price'; -} +// Subscribe to private account topics +// Account updates for UTA (unified trading account) ⋮---- -export interface CountdownCancelAllRequestV3 { - countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) -} +// Order updates for spot ⋮---- -countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) ================ -File: src/types/request/shared.ts +File: examples/V3/ws-api-client-trade.ts ================ -/** Pagination */ -export interface Pagination { - /** Time after */ - after?: string; - /** Time before */ - before?: string; - /** Elements per page */ - limit?: string; -} -⋮---- -/** Time after */ -⋮---- -/** Time before */ -⋮---- -/** Elements per page */ -⋮---- -export type OrderTimeInForce = 'normal' | 'post_only' | 'fok' | 'ioc'; -⋮---- -export interface GetHistoricTradesParams { - symbol: string; - limit?: string; - tradeId?: string; - startTime?: string; - endTime?: string; -} -⋮---- -/** - * The margin type, used directly in building the endpoint URL - */ -export type MarginType = 'crossed' | 'isolated'; +import { DefaultLogger } from '../../src'; +import { WebsocketAPIClient } from '../../src/websocket-api-client'; ⋮---- -export type FuturesProductTypeV2 = - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES' - | 'SUSDT-FUTURES' - | 'SCOIN-FUTURES' - | 'SUSDC-FUTURES'; +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketAPIClient } from 'bitget-api'; ⋮---- -export type FuturesPlanTypeV2 = - | 'profit_plan' - | 'loss_plan' - | 'moving_plan' - | 'pos_profit' - | 'pos_loss'; - -================ -File: src/types/response/v1/shared.ts -================ -export interface APIResponse { - code: string; - requestTime: number; - msg: 'success' | string; - data: T; -} +// function attachEventHandlers( +// wsClient: TWSClient, +// ): void { +// wsClient.on('update', (data) => { +// console.log('raw message received ', JSON.stringify(data)); +// }); +// wsClient.on('open', (data) => { +// console.log('ws connected', data.wsKey); +// }); +// wsClient.on('reconnect', ({ wsKey }) => { +// console.log('ws automatically reconnecting.... ', wsKey); +// }); +// wsClient.on('reconnected', (data) => { +// console.log('ws has reconnected ', data?.wsKey); +// }); +// wsClient.on('authenticated', (data) => { +// console.log('ws has authenticated ', data?.wsKey); +// }); +// } ⋮---- -export interface VIPFeeRate { - level: number; - dealAmount: string; - assetAmount: string; - takerFeeRate?: string; - makerFeeRate?: number; - withdrawAmount: string; - withdrawAmountUSDT: string; -} - -================ -File: src/types/response/v1/spot.ts -================ -export interface CoinBalance { - coinId: number; - coinName: string; - available: string; - frozen: string; - lock: string; - uTime: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -export interface SymbolRules { - symbol: string; - symbolName: string; - baseCoin: string; - quoteCoin: string; - minTradeAmount: string; - maxTradeAmount: string; - takerFeeRate: string; - makerFeeRate: string; - priceScale: string; - quantityScale: string; - status: string; -} -export interface SpotOrderResult { - orderId: string; - clientOrderId: string; -} +// Whether to use the demo trading wss connection +// demoTrading: true, ⋮---- -export interface SpotPlanOrder { - orderId: string; - clientOid: string; - symbol: string; - size: string; - executePrice: string; - triggerPrice: string; - status: string; - orderType: string; - side: string; - triggerType: string; - enterPointSource: string; - cTime: number; -} +// If you want your own event handlers instead of the default ones with logs, +// disable this setting and see the `attachEventHandlers` example below: +// attachEventListeners: false ⋮---- -export interface SpotMarketTrade { - symbol: string; - tradeId: string; - side: 'buy' | 'sell'; - fillPrice: string; - fillQuantity: string; - fillTime: string; -} +logger, // Optional: inject a custom logger ⋮---- -export interface SpotAccountAsset { - coin: string; - available: string; - frozen: string; - locked: string; - limitAvailable: string; - uTime: string; -} +// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled +// attachEventHandlers(wsClient.getWSClient()); ⋮---- -export interface SpotAccountBill { - cTime: string; - coino: string; - groupType: string; - businessType: - | 'SMALL_EXCHANGE_USER_IN' - | 'SMALL_EXCHANGE_USER_OUT' - | 'AIRDROP_REWARD' - | 'WITHDRAW' - | string; // TODO: complete list of possible values here? - size: string; - balance: string; - fees: string; - billd: string; -} +// Optional: prepare the WebSocket API connection in advance. +// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. ⋮---- -| string; // TODO: complete list of possible values here? - -================ -File: src/types/response/v2/common.ts -================ /** - * - * * Common | Notice - * - */ -⋮---- -export interface AnnouncementV2 { - annId: string; - annTitle: string; - annDesc: string; - cTime: string; - language: string; - annUrl: string; -} + * Bitget's WebSocket API be used like a REST API, through this SDK's WebsocketAPIClient. The WebsocketAPIClient is a utility class wrapped around WebsocketClientV3's sendWSAPIRequest() capabilities. + * + * Each request sent via the WebsocketAPIClient will automatically: + * - route via the active WS API connection + * - return a Promise, which automatically resolves/rejects when a matching response is received + * + * Note: this requires V3/UTA API keys! + */ ⋮---- /** - * - * * Common | Public - * - */ + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ ⋮---- /** - * - * * Common | Tax - * - */ + const res = { + "event": "trade", + "id": "1750034396082", + "category": "spot", + "topic": "place-order", + "args": [ + { + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx", + "cTime": "1750034397008" + } + ], + "code": "0", + "msg": "success", + "ts": "1750034397076" + }; + */ ⋮---- -export interface SpotTransactionRecordV2 { - id: string; - coin: string; - spotTaxType: string; - amount: string; - fee: string; - balance: string; - ts: string; -} +/** + * Batch Place Order Channel + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + */ ⋮---- -export interface FuturesTransactionRecordV2 { - id: string; - symbol: string; - marginCoin: string; - futureTaxType: string; - amount: string; - fee: string; - ts: string; -} +/** + * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. + */ ⋮---- -export interface MarginTransactionRecordV2 { - id: string; - coin: string; - marginTaxType: string; - amount: string; - fee: string; - total: string; - symbol: string; - ts: string; -} +/** + const res = { + "event": "trade", + "id": "1750035029506", + "category": "spot", + "topic": "batch-place", + "args": [ + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + }, + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750035029925" + } + */ ⋮---- -export interface P2PMerchantOrdersV2 { - id: string; - coin: string; - p2pTaxType: string; - total: string; - ts: string; -} +/** + * Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + */ ⋮---- /** - * - * * Common | P2P - * - */ + const res = { + "event": "trade", + "id": "1750034870205", + "topic": "cancel-order", + "args": [ + { + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750034870597" + } + */ ⋮---- -export interface P2PMerchantV2 { - registerTime: string; - nickName: string; - isOnline: string; - avgPaymentTime: string; - avgReleaseTime: string; - totalTrades: string; - totalBuy: string; - totalSell: string; - totalCompletionRate: string; - trades30d: string; - sell30d: string; - buy30d: string; - completionRate30d: string; -} +/** + * Batch Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + */ ⋮---- -export interface P2PMerchantInfoV2 { - registerTime: string; - nickName: string; - merchantId: string; - avgPaymentTime: string; - avgReleaseTime: string; - totalTrades: string; - totalBuy: string; - totalSell: string; - totalCompletionRate: string; - trades30d: string; - sell30d: string; - buy30d: string; - completionRate30d: string; - kycStatus: boolean; - emailBindStatus: boolean; - mobileBindStatus: boolean; - email: string; - mobile: string; -} +/** + const res = { + "event": "trade", + "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", + "topic": "batch-cancel", + "args": [ + { + "code": "0", + "msg": "Success", + "orderId": "xxxxxxxxxxxxx" + }, + { + "code": "25204", + "msg": "Order does not exist", + "orderId": "xxxxxxxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1751980011084" + } + */ + +================ +File: examples/V3/ws-api-trade-raw.ts +================ +import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; ⋮---- -export interface P2PMerchantOrderV2 { - orderId: string; - orderNo: string; - advNo: string; - side: string; - count: string; - coin: string; - price: string; - fiat: string; - withdrawTime: string; - representTime: string; - releaseTime: string; - paymentTime: string; - amount: string; - status: string; - buyerRealName: string; - sellerRealName: string; - ctime: string; - utime: string; - paymentInfo: { - paymethodName: string; - paymethodId: string; - paymethodInfo: { - name: string; - required: string; - type: string; - value: string; - }[]; - }; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV3 } from 'bitget-api'; ⋮---- -export interface P2PMerchantAdvertismentV2 { - advId: string; - advNo: string; - side: string; - advSize: string; - size: string; - coin: string; - price: string; - coinPrecision: string; - fiat: string; - fiatPrecision: string; - fiatSymbol: string; - status: string; - hide: string; - maxTradeAmount: string; - minTradeAmount: string; - payDuration: string; - turnoverNum: string; - turnoverRate: string; - label: string | null; - userLimitList: { - minCompleteNum: string; - maxCompleteNum: string; - placeOrderNum: string; - allowMerchantPlace: string; - completeRate30d: string; - country: string; - }; - paymentMethodList: { - paymentMethod: string; - paymentId: string; - paymentInfo: { - name: string; - required: boolean; - type: string; - }[]; - }[]; - merchantCertifiedList: { - imageUrl: string; - desc: string; - }[]; - utime: string; - ctime: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +⋮---- +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- /** - * - * * Common | Trading insights - * - */ + * Bitget's WebSocket API can be used via the sendWSAPIRequest() method. + * + * Use the `WS_KEY_MAP.v3Private` connection key for any requests. + * + * Note: this requires V3/UTA API keys! + * Note: for a better user experience, it is recommended to use the WebsocketAPIClient. + */ ⋮---- -export interface SpotWhaleNetFlowV2 { - volume: string; - date: string; -} +// Use the V3 private wss connection URL ⋮---- -export interface FuturesActiveBuySellVolumeV2 { - buyVolume: string; - sellVolume: string; - ts: string; -} +/** + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ ⋮---- -export interface FuturesActiveLongShortPositionV2 { - longPositionRatio: string; - shortPositionRatio: string; - longShortPositionRatio: string; - ts: string; -} +/** + const res = { + "event": "trade", + "id": "1750034396082", + "category": "spot", + "topic": "place-order", + "args": [ + { + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx", + "cTime": "1750034397008" + } + ], + "code": "0", + "msg": "success", + "ts": "1750034397076" + }; + */ ⋮---- -export interface LeveragedLongShortRatioV2 { - ts: string; - longShortRatio: string; -} +/** + * Batch Place Order Channel + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + */ ⋮---- -export interface MarginLoanGrowthRateV2 { - ts: string; - growthRate: string; -} +/** + * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. + */ ⋮---- -export interface IsolatedMarginBorrowingRatioV2 { - ts: string; - borrowRate: string; -} +/** + const res = { + "event": "trade", + "id": "1750035029506", + "category": "spot", + "topic": "batch-place", + "args": [ + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + }, + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750035029925" + } + */ ⋮---- -export interface FuturesLongShortRatioV2 { - longRatio: string; - shortRatio: string; - longShortRatio: string; - ts: string; -} +/** + * Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + */ ⋮---- -export interface SpotFundFlowV2 { - whaleBuyVolume: string; - dolphinBuyVolume: string; - fishBuyVolume: string; - whaleSellVolume: string; - dolphinSellVolume: string; - fishSellVolume: string; - whaleBuyRatio: string; - dolphinBuyRatio: string; - fishBuyRatio: string; - whaleSellRatio: string; - dolphinSellRatio: string; - fishSellRatio: string; -} +/** + const res = { + "event": "trade", + "id": "1750034870205", + "topic": "cancel-order", + "args": [ + { + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750034870597" + } + */ ⋮---- -export interface FuturesActiveLongShortAccountV2 { - longAccountRatio: string; - shortAccountRatio: string; - longShortAccountRatio: string; - ts: string; -} +/** + * Batch Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + */ ⋮---- /** - * - * * Common | Virtual Subaccount - * - */ + const res = { + "event": "trade", + "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", + "topic": "batch-cancel", + "args": [ + { + "code": "0", + "msg": "Success", + "orderId": "xxxxxxxxxxxxx" + }, + { + "code": "25204", + "msg": "Order does not exist", + "orderId": "xxxxxxxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1751980011084" + } + */ + +================ +File: examples/V3/ws-private.ts +================ +import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; ⋮---- -export interface CreateVirtualSubAccountV2 { - failureList: { - subaAccountName: string; - }[]; - successList: { - subaAccountUid: string; - subaAccountName: string; - status: string; - label: string; - permList: string[]; - cTime: string; - uTime: string; - }[]; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export interface CreateVirtualSubAccountAndApiKeyV2 { - subAccountUid: string; - subAccountName: string; - label: string; - subAccountApiKey: string; - secretKey: string; - permList: string[]; - ipList: string[]; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -export interface VirtualSubAccountV2 { - subAccountUid: string; - subAccountName: string; - status: string; - permList: string[]; - label: string; - accountType: string; - bindingTime: string; - cTime: string; - uTime: string; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface CreateVirtualSubAccountApiKeyV2 { - subAccountUid: string; - label: string; - subAccountApiKey: string; - secretKey: string; - permList: string[]; - ipList: string[]; -} +// You can subscribe to one topic at a time ⋮---- -export interface ModifyVirtualSubAccountApiKeyV2 { - subAccountUid: string; - label: string; - subAccountApiKey: string; - secretKey: string; - permList: string[]; - ipList: string[]; -} +instType: 'UTA', // Note: all account events go on the UTA instType ⋮---- -export interface SubAccountApiKeyItemV2 { - subAccountUid: string; - label: string; - subAccountApiKey: string; - permList: string[]; - ipList: string[]; -} +WS_KEY_MAP.v3Private, // This parameter points to private or public ⋮---- -/** - * - * * Common | Assets - * - */ +// Note: all account events go on the UTA instType ⋮---- -export interface FundingAssetV2 { - coin: string; - available: string; - frozen: string; - usdtValue: string; -} +// Or multiple at once: ⋮---- -export interface BotAssetV2 { - coin: string; - available: string; - equity: string; - bonus: string; - frozen: string; - usdtValue: string; -} -⋮---- -/** - * - * * Common | Convert - * - */ -⋮---- -export interface ConvertCurrencyV2 { - coin: string; - available: string; - maxAmount: string; - minAmount: string; -} -⋮---- -export interface ConvertQuotedPriceV2 { - fee: string; - fromCoinSize: string; - fromCoin: string; - cnvtPrice: string; - toCoinSize: string; - toCoin: string; - traceId: string; -} +// Topics are tracked per websocket type +// The below example will pull a list of subscribed topics on that connection (e.g. all private topics), after a 5 second delay: + +================ +File: examples/V3/ws-public.ts +================ +import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; ⋮---- -export interface ConvertTradeResponseV2 { - ts: string; - cnvtPrice: string; - toCoinSize: string; - toCoin: string; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export interface ConvertRecordV2 { - id: string; - ts: string; - cnvtPrice: string; - fee: string; - fromCoinSize: string; - fromCoin: string; - toCoinSize: string; - toCoin: string; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- /** - * - * * Common | BGB Convert - * - */ + * Public events + */ ⋮---- -export interface BGBConvertCoinV2 { - coin: string; - available: string; - bgbEstAmount: string; - precision: string; - feeDetail: { - feeRate: string; - fee: string; - }[]; - cTime: string; -} +// You can subscribe to one topic at a time ⋮---- -export interface ConvertBGBResponseV2 { - orderList: { - coin: string; - orderId: string; - }[]; -} +WS_KEY_MAP.v3Public, // This parameter points to private or public ⋮---- -export interface BGBConvertHistoryV2 { - orderId: string; - fromCoin: string; - fromAmount: string; - fromCoinPrice: string; - toCoin: string; - toAmount: string; - toCoinPrice: string; - feeDetail: { - feeCoin: string; - fee: string; - }[]; - status: string; - ctime: string; -} +// Or multiple at once: +⋮---- +// Topics are tracked per websocket type +// The below example will pull a list of subscribed topics on that connection (e.g. all public topics), after a 5 second delay: ================ -File: src/types/response/v2/copy-trading.ts +File: src/types/request/v2/copytrading.ts ================ /** * @@ -2062,124 +1143,61 @@ File: src/types/response/v2/copy-trading.ts * */ ⋮---- -export interface CTFuturesTraderCurrentOrderV2 { - trackingNo: string; - openOrderId: string; - symbol: string; - posSide: string; - openLeverage: string; - openPriceAvg: string; - openTime: string; - openSize: string; - presetStopSurplusPrice: string; - presetStopLossPrice: string; - openFee: string; - followCount: string; -} -⋮---- -export interface CTFuturesTraderCurrentOrdersV2 { - trackingList: CTFuturesTraderCurrentOrderV2[]; - endId: string; -} -⋮---- -export interface CTFuturesTraderHistoryOrderV2 { - trackingNo: string; - symbol: string; - openOrderId: string; - closeOrderId: string; - productType: string; - posSide: string; - openLeverage: string; - openPriceAvg: string; - openTime: string; - openSize: string; - closeSize: string; - closeTime: string; - closePriceAvg: string; - stopType: string; - achievedPL: string; - openFee: string; - closeFee: string; - cTime: string; -} -⋮---- -export interface CTFuturesTraderHistoryOrderV2 { - trackingList: CTFuturesTraderHistoryOrderV2[]; - endId: string; -} -⋮---- -export interface CTRateCTimeV2 { - rate: string; - ctime: string; -} -⋮---- -export interface CTAmountCTimeV2 { - amount: string; - ctime: string; -} -⋮---- -export interface CTFuturesTraderTotalOrderSummaryV2 { - roi: string; - tradingOrderNum: string; - totalFollowerNum: string; - currentFollowerNum: string; - totalpl: string; - gainNum: string; - lossNum: string; - winRate: string; - tradingPairsAvailableList: string[]; - lastWeekRoiList: CTRateCTimeV2[]; - lastWeekProfitList: CTAmountCTimeV2[]; - lastMonthRoiList: CTRateCTimeV2[]; - lastMonthProfitList: CTAmountCTimeV2[]; - totalEquity: string; -} +export type CopyTradingProductTypeV2 = + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; ⋮---- -export interface CTFuturesTraderProfitHistoryItemV2 { - coin: string; - profitCount: string; - lastProfitTime: string; +export interface GetFuturesTraderCurrentOrdersRequestV2 { + symbol?: string; + productType: CopyTradingProductTypeV2; + startTime?: string; + endTime?: string; + limit?: string; + idGreaterThan?: string; + idLessThan?: string; } ⋮---- -export interface CTFuturesTraderHistoryProfitSummaryV2 { - profitSummary: { - yesterdayProfit: string; - sumProfit: string; - waitProfit: string; - yesterdayTime: string; - }; - profitHistoryList: CTFuturesTraderProfitHistoryItemV2[]; +export interface GetFuturesTraderHistoryOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + order?: 'asc' | 'desc'; + symbol?: string; + productType: CopyTradingProductTypeV2; } ⋮---- -export interface CTFuturesTraderProfitShare { - profitId: string; - coin: string; - profit: string; - nickName: string; - profitTime: string; +export interface ModifyFuturesTraderOrderTPSLRequestV2 { + trackingNo: string; + productType: CopyTradingProductTypeV2; + stopSurplusPrice?: string; + stopLossPrice?: string; } ⋮---- -export interface CTFuturesTraderProfitShareHistoryV2 { - profitList: CTFuturesTraderProfitShare[]; - endId: string; +export interface GetFuturesTraderProfitShareDetailRequestV2 { + coin?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface CTFuturesTraderSymbolSettingsV2 { +export interface FuturesTraderSymbolSettingRequestV2 { symbol: string; - openTrader: string; - minOpenCount: string; - maxLeverage: string; - stopSurplusRatio: string; - stopLossRatio: string; + productType: CopyTradingProductTypeV2; + settingType: 'ADD' | 'DELETE' | 'UPDATE'; + stopSurplusRatio?: string; + stopLossRatio?: string; } ⋮---- -export interface CTFuturesTraderMyFollowersV2 { - accountEquity: string; - isRemove: string; - followerHeadPic: string; - followerName: string; - followerUid: string; - followerTime: string; +export interface GetFuturesTraderFollowersRequestV2 { + pageNo?: string; + pageSize?: string; + startTime?: string; + endTime?: string; } ⋮---- /** @@ -2190,80 +1208,76 @@ export interface CTFuturesTraderMyFollowersV2 { * */ ⋮---- -export interface CTFuturesFollowerCurrentOrdersV2 { - trackingNo: string; - traderName: string; - openOrderId: string; - closeOrderId: string; - traderId: string; - symbol: string; - posSide: string; - openLeverage: string; - openAvgPrice: string; - openTime: string; - openSize: string; - closeAvgPrice: string; - closeSize: string; - openMarginSz: string; - closeTime: string; +export interface GetFollowerFuturesCurrentTrackingOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + symbol?: string; + productType: CopyTradingProductTypeV2; + traderId?: string; } ⋮---- -export interface CTFuturesFollowerHistoryOrderV2 { - trackingNo: string; - posSide: string; - openLeverage: string; - openSize: string; - closeSize: string; - openPriceAvg: string; - closePriceAvg: string; - achievedPL: string; - openFee: string; - closeFee: string; - symbol: string; - profitRate: string; - netProfit: string; - openOrderId: string; - closeOrderId: string; - openTime: string; - closeTime: string; - traderId: string; - productType: string; +export interface GetFollowerFuturesHistoryTrackingOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + symbol?: string; + productType: CopyTradingProductTypeV2; + traderId?: string; } ⋮---- -export interface CTFuturesFollowerHistoryOrdersV2 { - trackingList: CTFuturesFollowerHistoryOrderV2[]; - endId: string; +export interface UpdateFuturesFollowerTPSLRequestV2 { + trackingNo: string; + symbol?: string; + productType: CopyTradingProductTypeV2; + stopSurplusPrice?: string; + stopLossPrice?: string; } ⋮---- -export interface CTFuturesFollowerSettingV2 { +export type AutoCopyOption = 'on' | 'off'; +export type FollowMode = 'basic' | 'advanced'; +export type LeverageType = 'position' | 'specify' | 'trader'; +export type TraceType = 'percent' | 'amount' | 'count'; +⋮---- +export interface FollowerCopyTradeSettingRequestV2 { symbol: string; - productType: string; - marginType: string; - marginCoin: string; - leverType: string; - longLeverage: string; - shortLeverage: string; - traceType: string; + productType: CopyTradingProductTypeV2; + marginType: 'trader' | 'specify'; + marginCoin?: string; + leverType: LeverageType; + longLeverage?: string; + shortLeverage?: string; + traceType: TraceType; + traceValue: string; + maxHoldSize?: string; + stopSurplusRatio?: string; + stopLossRatio?: string; } ⋮---- -export interface CTFuturesFollowerSettingsV2 { - followerEnable: string; - detailList: CTFuturesFollowerSettingV2[]; +export interface UpdateFuturesFollowerSettingsRequestV2 { + traderId: string; + autoCopy?: AutoCopyOption; + mode?: FollowMode; + settings: FollowerCopyTradeSettingRequestV2[]; +} +export interface CloseFuturesFollowerPositionsRequestV2 { + productType: CopyTradingProductTypeV2; + trackingNo?: string; + symbol?: string; + marginCoin?: string; + marginMode?: 'isolated' | 'cross'; + holdSide?: 'long' | 'short'; } ⋮---- -export interface CTFuturesFollowerMyTradersV2 { - certificationType: string; - traderId: string; - traderName: string; - maxFollowLimit: string; - followCount: string; - traceTotalMarginAmount: string; - traceTotalNetProfit: string; - traceTotalProfit: string; - currentTradingPairs: string[]; - followerTime: string; - bgbMaxFollowLimit: string; - bgbFollowCount: string; +export interface GetFuturesFollowerTradersRequestV2 { + startTime?: string; + endTime?: string; + pageNo?: string; + pageSize?: string; } ⋮---- /** @@ -2274,109 +1288,38 @@ export interface CTFuturesFollowerMyTradersV2 { * */ ⋮---- -export interface CTSpotTraderProfitSummaryV2 { - profitSummarys: { - yesterdayProfit: string; - yesterdayTime: string; - sumProfit: string; - waitProfit: string; - }; - profitHistoryList: { - coin: string; - profitCount: string; - lastProfitTime: string; - historysByDateList: { - profit: string; - profitTime: string; - }[]; - }[]; -} -⋮---- -export interface CTSpotTraderHistoryProfitShareItemV2 { - profitId: string; - coin: string; - distributeRatio: string; - profit: string; - followerName: string; - profitTime: string; -} -⋮---- -export interface CTSpotTraderHistoryProfitSharingV2 { - endId: string; - profitList: CTSpotTraderHistoryProfitShareItemV2[]; -} -⋮---- -export interface CTSpotTraderUnrealizedProfitV2 { - distributeRatio: string; - coin: string; - profit: string; - followerName: string; -} -⋮---- -export interface CTSpotTraderTotalOrderDetailV2 { - totalFollowerNum: string; - currentFollowerNum: string; - maxFollowerNum: string; - tradingOrderNum: string; - totalpl: string; - gainNum: string; - lossNum: string; - totalEquity: string; - winRate: string; - lastWeekRoiList: CTAmountCTimeV2[]; - lastMonthRoiList: CTRateCTimeV2[]; - lastWeekProfitList: CTAmountCTimeV2[]; - lastMonthProfitList: CTAmountCTimeV2[]; -} -⋮---- -export interface CTSpotTraderHistoryOrderV2 { - trackingNo: string; - fillSize: string; - buyPrice: string; - sellPrice: string; - achievedPL: string; - buyTime: string; - sellTime: string; - buyFee: string; - sellFee: string; - achievedPLR: string; - symbol: string; - netProfit: string; - followCount: string; -} -export interface CTSpotTraderHistoryOrdersV2 { - endId: string; - trackingList: CTSpotTraderHistoryOrderV2[]; +export interface GetSpotTraderHistoryProfitRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + coin?: string; } ⋮---- -export interface CTSpotTraderCurrentTrackingOrderV2 { - trackingNo: string; - orderId: string; - buyFillSize: string; - buyDelegateSize: string; - buyPrice: string; - unrealizedPL: string; - buyTime: string; - buyFee: string; - unrealizedPLR: string; - symbol: string; - stopLossPrice: string | null; - stopSurplusPrice: string | null; - followCount: string; +export interface GetSpotTraderHistoryOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + symbol?: string; } ⋮---- -export interface CTSpotTraderCurrentTrackingOrdersV2 { - endId: string; - trackingList: CTSpotTraderCurrentTrackingOrderV2[]; +export interface GetSpotTraderCurrentOrdersRequestV2 { + symbol?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface CTSpotTraderFollowerListV2 { - accountEquity: string; - isRemove: string; - followerHeadPic: string | null; - followerName: string; - followerUid: string; - followerTime: string; +export interface GetSpotTraderFollowersRequestV2 { + pageNo?: string; + pageSize?: string; + startTime?: string; + endTime?: string; } ⋮---- /** @@ -2387,100 +1330,37 @@ export interface CTSpotTraderFollowerListV2 { * */ ⋮---- -export interface CTSpotFollowerMyTraderV2 { - certificationType: string; - traceTotalAmount: string; - traceTotalNetProfit: string; - traceTotalProfit: string; - traderName: string; - traderId: string; - maxFollowLimit: string; - bgbMaxFollowLimit: string; - followCount: string; - bgbFollowCount: string; - followerTime: string; -} -⋮---- -export interface CTSpotFollowerMyTradersV2 { - resultList: CTSpotFollowerMyTraderV2[]; -} -⋮---- -export interface CTSpotFollowerTradeSettingV2 { - maxTraceAmount: string; - stopLossRation: string; - stopSurplusRation: string; - symbol: string; - traceType: string; -} -⋮---- -export interface CTSpotFollowerTradeSymbolSettingV2 { - maxStopLossRation: string; - maxStopSurplusRation: string; - maxTraceAmount: string; - maxTraceAmountSystem: string; - maxTraceSize: string; - maxTraceRation: string; - minStopLossRation: string; - minStopSurplusRation: string; - minTraceAmount: string; - minTraceSize: string; - minTraceRation: string; - sliderMaxStopLossRatio: string; - sliderMaxStopSurplusRatio: string; - symbol: string; -} -⋮---- -export interface CTSpotFollowerFollowConfigurationV2 { - enable: string; - profitRate: string; - settledInDays: string; - tradeSettingList: CTSpotFollowerTradeSettingV2[]; - tradeSymbolSettingList: CTSpotFollowerTradeSymbolSettingV2[]; - traderHeadPic: string; - traderName: string; -} -⋮---- -export interface CTSpotFollowerHistoryOrderV2 { - trackingNo: string; - traderId: string; - fillSize: string; - buyPrice: string; - sellPrice: string; - buyFee: string; - sellFee: string; - achievedPL: string; - achievedPLR: string; +export interface SpotFollowerCopyTradeSettingV2 { symbol: string; - buyTime: string; - sellTime: string; -} -export interface CTSpotFollowerHistoryOrdersV2 { - endId: string; - trackingList: CTSpotFollowerHistoryOrderV2[]; + traceType: 'percent' | 'amount' | 'count'; + maxHoldSize: string; + traceValue: string; + stopLossRatio?: string; + stopSurplusRatio?: string; } ⋮---- -export interface CTSpotFollowerCurrentOrderV2 { - trackingNo: string; - traderId: string; - buyFillSize: string; - buyDelegateSize: string; - buyPrice: string; - unrealizedPL: string; - buyTime: string; - buyFee: string; - unrealizedPLR: string; - symbol: string; - stopSurplusPrice: string | null; - stopLossPrice: string | null; +export interface GetSpotFollowerHistoryOrdersRequestV2 { + symbol?: string; + traderId?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface CTSpotFollowerCurrentOrdersV2 { - endId: string; - trackingList: CTSpotFollowerCurrentOrderV2[]; +export interface GetSpotFollowerOpenOrdersRequestV2 { + symbol?: string; + traderId?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ================ -File: src/types/response/v2/earn.ts +File: src/types/request/v2/earn.ts ================ /** * @@ -2490,4473 +1370,4623 @@ File: src/types/response/v2/earn.ts * */ ⋮---- -export interface EarnSavingsProductsV2 { - productId: string; - coin: string; +export interface GetEarnSavingsAssetsRequestV2 { periodType: string; - period: string; - apyType: string; - advanceRedeem: string; - settleMethod: string; - apyList: { - rateLevel: string; - minStepVal: string; - maxStepVal: string; - currentApy: string; - }[]; - status: string; - productLevel: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnSavingsAccountV2 { - btcAmount: string; - usdtAmount: string; - btc24hEarning: string; - usdt24hEarning: string; - btcTotalEarning: string; - usdtTotalEarning: string; +export interface GetEarnSavingsRecordsRequestV2 { + coin?: string; + periodType: string; + orderType?: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnSavingsAssetV2 { +export interface RedeemSavingsRequestV2 { productId: string; - orderId: string; - productCoin: string; - interestCoin: string; + orderId?: string; periodType: string; - period: string; - holdAmount: string; - lastProfit: string; - totalProfit: string; - holdDays: string; - status: string; - allowRedemption: string; - productLevel: string; - apy: { - rateLevel: string; - minApy: string; - maxApy: string; - currentApy: string; - }[]; -} -⋮---- -export interface EarnSavingsAssetsV2 { - resultList: EarnSavingsAssetV2[]; - endId: string; -} -⋮---- -export interface EarnSavingsRecordV2 { - orderId: string; - coinName: string; - settleCoinName: string; - productType: string; - period: string; - productLevel: string; amount: string; - ts: string; - orderType: string; -} -⋮---- -export interface EarnSavingsRecordsV2 { - resultList: EarnSavingsRecordV2[]; - endId: string; -} -⋮---- -export interface EarnSavingsSubscriptionDetailV2 { - singleMinAmount: string; - singleMaxAmount: string; - remainingAmount: string; - subscribePrecision: string; - profitPrecision: string; - subscribeTime: string; - interestTime: string; - settleTime: string; - expireTime: string; - redeemTime: string; - settleMethod: string; - apyList: { - rateLevel: string; - minStepVal: string; - maxStepVal: string; - currentApy: string; - }[]; - redeemDelay: string; } ⋮---- /** * * - * Earn | Earn Account + * Earn | Shark Fin * * */ ⋮---- +export interface GetSharkfinAssetsRequestV2 { + status: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; +} +⋮---- +export interface GetSharkfinRecordsRequestV2 { + coin?: string; + type: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; +} +⋮---- /** * * - * Earn | Shark Fin + * Earn | Loan * * */ ⋮---- -export interface EarnSharkfinProductV2 { - productId: string; - productName: string; - productCoin: string; - subscribeCoin: string; - farmingStartTime: string; - farmingEndTime: string; - lowerRate: string; - defaultRate: string; - upperRate: string; - period: string; - interestStartTime: string; - status: string; - minAmount: string; - limitAmount: string; - soldAmount: string; - endTime: string; - startTime: string; +export interface GetLoanEstInterestAndBorrowableRequestV2 { + loanCoin: string; + pledgeCoin: string; + daily: 'SEVEN' | 'THIRTY'; + pledgeAmount?: string; } ⋮---- -export interface EarnSharkfinProductsV2 { - resultList: EarnSharkfinProductV2[]; - endId: string; +export interface BorrowLoanRequestV2 { + loanCoin: string; + pledgeCoin: string; + daily: 'SEVEN' | 'THIRTY'; + pledgeAmount?: string; + loanAmount?: string; } ⋮---- -export interface EarnSharkfinAccountV2 { - btcSubscribeAmount: string; - usdtSubscribeAmount: string; - btcHistoricalAmount: string; - usdtHistoricalAmount: string; - btcTotalEarning: string; - usdtTotalEarning: string; +export interface RepayLoanRequestV2 { + orderId: string; + amount?: string; + repayUnlock?: string; + repayAll: string; } ⋮---- -export interface EarnSharkfinAssetV2 { - productId: string; - interestStartTime: string; - interestEndTime: string; - productCoin: string; - subscribeCoin: string; - trend: string; - settleTime: string; - interestAmount: string; - productStatus: string; -} -⋮---- -export interface EarnSharkfinAssetsV2 { - resultList: EarnSharkfinAssetV2[]; - endId: string; +export interface GetLoanRepayHistoryRequestV2 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + startTime: string; + endTime: string; + pageNo?: string; + pageSize?: string; } ⋮---- -export interface EarnSharkfinRecordV2 { +export interface ModifyLoanPledgeRateRequestV2 { orderId: string; - product: string; - period: string; amount: string; - ts: string; - type: string; + pledgeCoin: string; + reviseType: string; } -export interface EarnSharkfinRecordsV2 { - resultList: EarnSharkfinRecordV2[]; - endId: string; +⋮---- +export interface GetLoanPledgeRateHistoryRequestV2 { + orderId?: string; + reviseSide?: string; + pledgeCoin?: string; + startTime: string; + endTime: string; + pageNo?: string; + pageSize?: string; } ⋮---- -export interface EarnSharkfinSubscriptionDetailV2 { - productCoin: string; - subscribeCoin: string; - interestTime: string; - expirationTime: string; - minPrice: string; - currentPrice: string; - maxPrice: string; - minRate: string; - defaultRate: string; - maxRate: string; - period: string; - productMinAmount: string; - availableBalance: string; - userAmount: string; - remainingAmount: string; - profitPrecision: string; - subscribePrecision: string; +export interface GetLoanHistoryRequestV2 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + status?: string; + startTime: string; + endTime: string; + pageNo?: string; + pageSize?: string; } ⋮---- +export interface GetLiquidationRecordsRequestV2 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + status?: string; + startTime: string; + endTime: string; + pageNo?: string; + pageSize?: string; +} + +================ +File: src/types/request/v2/margin.ts +================ /** * - * - * Earn | Loan - * + * * Margin | Cross/Isolated | Order Record * */ ⋮---- -export interface EarnLoanCurrencyLoanInfoV2 { - coin: string; - hourRate7D: string; - rate7D: string; - hourRate30D: string; - rate30D: string; - minUsdt: string; - maxUsdt: string; - min: string; - max: string; -} -export interface EarnLoanCurrencyPledgeInfoV2 { - coin: string; - initRate: string; - supRate: string; - forceRate: string; - minUsdt: string; - maxUsdt: string; -} -⋮---- -export interface EarnLoanCurrenciesV2 { - loanInfos: EarnLoanCurrencyLoanInfoV2[]; - pledgeInfos: EarnLoanCurrencyPledgeInfoV2[]; -} -⋮---- -export interface EarnLoanOrdersV2 { - orderId: string; - loanCoin: string; - loanAmount: string; - interestAmount: string; - hourInterestRate: string; - pledgeCoin: string; - pledgeAmount: string; - pledgeRate: string; - supRate: string; - forceRate: string; - borrowTime: string; - expireTime: string; -} -⋮---- -export interface EarnLoanRepayResponseV2 { - loanCoin: string; - pledgeCoin: string; - repayAmount: string; - payInterest: string; - repayLoanAmount: string; - repayUnlockAmount: string; -} -⋮---- -export interface EarnLoanRepayHistoryV2 { - orderId: string; - loanCoin: string; - pledgeCoin: string; - repayAmount: string; - payInterest: string; - repayLoanAmount: string; - repayUnlockAmount: string; - repayTime: string; -} -⋮---- -export interface EarnLoanPledgeRateHistoryV2 { - loanCoin: string; - pledgeCoin: string; - orderId: string; - reviseTime: string; - reviseSide: string; - reviseAmount: string; - afterPledgeRate: string; - beforePledgeRate: string; +export interface GetBorrowHistoryRequestV2 { + loanId?: string; + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnLoanHistoryV2 { - orderId: string; - loanCoin: string; - pledgeCoin: string; - initPledgeAmount: string; - initLoanAmount: string; - hourRate: string; - daily: string; - borrowTime: string; - status: string; +export interface GetRepayHistoryRequestV2 { + repayId?: string; + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnLoanDebtPledgeInfoV2 { - coin: string; - amount: string; - amountUsdt: string; +export interface GetInterestHistoryRequestV2 { + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnLoanDebtLoanInfoV2 { - coin: string; - amount: string; - amountUsdt: string; +export interface GetLiquidationHistoryRequestV2 { + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnLoanDebtsV2 { - pledgeInfos: EarnLoanDebtPledgeInfoV2[]; - loanInfos: EarnLoanDebtLoanInfoV2[]; +export interface GetFinancialHistoryRequestV2 { + marginType?: string; + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface EarnLoanLiquidationRecordsV2 { - orderId: string; - loanCoin: string; - pledgeCoin: string; - reduceTime: string; - pledgeRate: string; - pledgePrice: string; - status: string; - pledgeAmount: string; - reduceFee: string; - residueAmount: string; - runlockAmount: string; - repayLoanAmount: string; -} - -================ -File: src/types/response/v2/margin.ts -================ /** * - * * Margin | Common + * * Margin | Cross/Isolated | Account * */ ⋮---- -export interface MarginCurrencyV2 { - symbol: string; - baseCoin: string; - quoteCoin: string; - maxCrossedLeverage: string; - maxIsolatedLeverage: string; - warningRiskRatio: string; - liquidationRiskRatio: string; - minTradeAmount: string; - maxTradeAmount: string; - takerFeeRate: string; - makerFeeRate: string; - pricePrecision: string; - quantityPrecision: string; - minTradeUSDT: string; - isBorrowable: boolean; - userMinBorrow: string; - status: string; - isIsolatedBaseBorrowable: boolean; - isIsolatedQuoteBorrowable: boolean; - isCrossBorrowable: boolean; -} -⋮---- /** * - * * Margin | Cross/Isolated | Order Record + * * Margin | Cross/Isolated | Trade * */ ⋮---- -export interface MarginBorrowHistoryItemV2 { - loanId: string; - coin: string; - borrowAmount: string; - borrowType: string; - cTime: string; - uTime: string; -} +export type MarginOrderTypeV2 = 'limit' | 'market'; ⋮---- -export interface MarginRepaymentHistoryItemV2 { - repayId: string; - coin: string; - repayAmount: string; - repayType: string; - repayInterest: string; - repayPrincipal: string; - symbol: string; - cTime: string; - uTime: string; -} +export type MarginLoanTypeV2 = + | 'normal' + | 'autoLoan' + | 'autoRepay' + | 'autoLoanAndRepay'; ⋮---- -export interface MarginInterestHistoryItemV2 { - interestId: string; - interestCoin: string; - dailyInterestRate: string; - loanCoin: string; - interestAmount: string; - interstType: string; - symbol: string; - cTime: string; - uTime: string; -} +export type MarginTimeInForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; ⋮---- -export interface MarginLiquidationHistoryItemV2 { - liqId: string; - symbol: string; - liqStartTime: string; - liqEndTime: string; - liqRiskRatio: string; - totalAssets: string; - totalDebt: string; - liqFee: string; - cTime: string; - uTime: string; -} +export type MarginOrderSideV2 = 'buy' | 'sell'; ⋮---- -export interface MarginFinancialHistoryItemV2 { - coin: string; +export type MarginSTPModeV2 = + | 'none' + | 'cancel_taker' + | 'cancel_maker' + | 'cancel_both'; +⋮---- +export interface MarginPlaceOrderRequestV2 { symbol: string; - marginId: string; - amount: string; - balance: string; - fee: string; - marginType: string; - cTime: string; - uTime: string; + orderType: MarginOrderTypeV2; + price?: string; + loanType: MarginLoanTypeV2; + force: MarginTimeInForceV2; + baseSize?: string; + quoteSize?: string; + clientOid?: string; + side: MarginOrderSideV2; + stpMode?: MarginSTPModeV2; } ⋮---- -/** - * - * * Margin | Cross/Isolated | Account - * - */ -⋮---- -export interface MarginAccountAssetV2 { - symbol: string; - coin: string; - totalAmount: string; - available: string; - frozen: string; - borrow: string; - interest: string; - net: string; - coupon: string; - cTime: string; - uTime: string; +export interface MarginBatchOrderEntry { + orderType: MarginOrderTypeV2; + price?: string; + loanType: MarginLoanTypeV2; + force: MarginTimeInForceV2; + baseSize?: string; + quoteSize?: string; + clientOid?: string; + side: MarginOrderSideV2; + stpMode?: MarginSTPModeV2; } ⋮---- -export interface CrossMaxBorrowableResponseV2 { - coin: string; - maxBorrowableAmount: string; +export interface MarginBatchOrdersRequestV2 { + symbol: string; + orderList: MarginBatchOrderEntry[]; } ⋮---- -export interface IsolatedMaxBorrowableResponseV2 { +export interface GetMarginCurrentOrdersRequestV2 { symbol: string; - baseCoin: string; - baseCoinMaxBorrowAmount: string; - quoteCoin: string; - quoteCoinMaxBorrowAmount: string; + orderId?: string; + clientOid?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface CrossMaxTransferableResponseV2 { - coin: string; - maxTransferOutAmount: string; +export interface GetHistoryOrdersRequestV2 { + symbol: string; + orderId?: string; + enterPointSource?: string; + clientOid?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface IsolatedMaxTransferableResponseV2 { - baseCoin: string; +export interface GetMarginOrderFillsRequestV2 { symbol: string; - baseCoinMaxTransferOutAmount: string; - quoteCoin: string; - quoteCoinMaxTransferOutAmount: string; + orderId?: string; + idLessThan?: string; + startTime: string; + endTime?: string; + limit?: string; } ⋮---- -export interface CrossInterestRateAndLimitResponseV2 { - transferable: boolean; - leverage: string; - coin: string; - borrowable: boolean; - dailyInterestRate: string; - annualInterestRate: string; - maxBorrowableAmount: string; - vipList: { - level: string; - limit: string; - dailyInterestRate: string; - annualInterestRate: string; - discountRate: string; - }[]; +export interface GetMarginLiquidationOrdersRequestV2 { + type?: 'swap' | 'place_order'; + symbol?: string; + fromCoin?: string; + toCoin?: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; } + +================ +File: src/types/request/v2/spot.ts +================ +type SpotKlineIntervalV2 = + | '1min' + | '5min' + | '15min' + | '30min' + | '1h' + | '4h' + | '6h' + | '12h' + | '1day' + | '3day' + | '1week' + | '1M' + | '6Hutc' + | '12Hutc' + | '1Dutc' + | '3Dutc' + | '1Wutc' + | '1Mutc'; ⋮---- -export interface IsolatedInterestRateAndLimitResponseV2 { +export interface SpotCandlesRequestV2 { symbol: string; - leverage: string; - baseCoin: string; - baseTransferable: boolean; - baseBorrowable: boolean; - baseDailyInterestRate: string; - baseAnnuallyInterestRate: string; - baseMaxBorrowableAmount: string; - baseVipList: { - level: string; - dailyInterestRate: string; - limit: string; - annuallyInterestRate: string; - discountRate: string; - }[]; - quoteCoin: string; - quoteTransferable: boolean; - quoteBorrowable: boolean; - quoteDailyInterestRate: string; - quoteAnnuallyInterestRate: string; - quoteMaxBorrowableAmount: string; - quoteList: { - level: string; - dailyInterestRate: string; - limit: string; - annuallyInterestRate: string; - discountRate: string; - }[]; + granularity: SpotKlineIntervalV2; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface CrossTierConfigurationResponseV2 { - tier: string; - leverage: string; - coin: string; - maxBorrowableAmount: string; - maintainMarginRate: string; +export interface SpotHistoricCandlesRequestV2 { + symbol: string; + granularity: SpotKlineIntervalV2; + endTime?: string; + limit?: string; } ⋮---- -export interface IsolatedTierConfigurationResponseV2 { - tier: string; +export interface SpotHistoricTradesRequestV2 { symbol: string; - leverage: string; - baseCoin: string; - quoteCoin: string; - baseMaxBorrowableAmount: string; - quoteMaxBorrowableAmount: string; - maintainMarginRate: string; - initRate: string; + limit?: string; + idLessThan?: string; + startTime?: string; + endTime?: string; } ⋮---- /** * - * * Margin | Cross/Isolated | Trade + * * Spot | Trade * */ ⋮---- -export interface MarginBatchOrdersResponseV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - clientOid: string; - errorMsg: string; - }[]; -} +export type SpotOrderSideV2 = 'buy' | 'sell'; ⋮---- -export interface MarginCurrentOrderV2 { - orderId: string; +export type SpotOrderTypeV2 = 'limit' | 'market'; +⋮---- +export type SpotOrderForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; +⋮---- +export type SpotTPSLTypeV2 = 'normal' | 'tpsl'; +⋮---- +export type SpotSTPModeV2 = + | 'none' + | 'cancel_taker' + | 'cancel_maker' + | 'cancel_both'; +⋮---- +export type SpotBatchModeV2 = 'single' | 'multiple'; +⋮---- +export interface SpotOrderRequestV2 { symbol: string; - orderType: string; - enterPointSource: string; - clientOid: string; - loanType: string; - price: string; - side: string; - status: string; - baseSize: string; - quoteSize: string; - priceAvg: string; + side: SpotOrderSideV2; + orderType: SpotOrderTypeV2; + force: SpotOrderForceV2; + price?: string; size: string; - amount: string; - force: string; - cTime: string; - uTime: string; + clientOid?: string; + triggerPrice?: string; + tpslType?: SpotTPSLTypeV2; + requestTime?: string; + receiveWindow?: string; + stpMode?: SpotSTPModeV2; + presetTakeProfitPrice?: string; + executeTakeProfitPrice?: string; + presetStopLossPrice?: string; + executeStopLossPrice?: string; } ⋮---- -export interface MarginHistoryOrderV2 { - orderId: string; +export interface SpotCancelandSubmitOrderRequestV2 { symbol: string; - orderType: string; - enterPointSource: string; - clientOid: string; - loanType: string; price: string; - side: string; - status: string; - baseSize: string; - quoteSize: string; - priceAvg: string; size: string; - amount: string; - force: string; - cTime: string; - uTime: string; + orderId?: string; + clientOid?: string; + newClientOid?: string; + presetTakeProfitPrice?: string; + executeTakeProfitPrice?: string; + presetStopLossPrice?: string; + executeStopLossPrice?: string; } ⋮---- -export interface MarginOrderFillV2 { - orderId: string; - tradeId: string; - orderType: string; - side: string; - priceAvg: string; - size: string; - amount: string; - tradeScope: string; - feeDetail: { - deduction: string; - feeCoin: string; - totalDeductionFee: string; - totalFee: string; - }; - cTime: string; - uTime: string; +export interface SpotCancelOrderRequestV2 { + symbol: string; + tpslType?: SpotTPSLTypeV2; + orderId?: string; + clientOid?: string; } ⋮---- -export interface MarginLiquidationOrderV2 { - symbol: string; - orderType: string; - side: string; - priceAvg: string; - price: string; - fillSize: string; +export interface SpotBatchOrderRequestItemV2 { + symbol?: string; + side: SpotOrderSideV2; + orderType: SpotOrderTypeV2; + force: SpotOrderForceV2; + price?: string; size: string; - amount: string; - orderId: string; - fromCoin: string; - toCoin: string; - fromSize: string; - toSize: string; - cTime: string; - uTime: string; + clientOid?: string; + stpMode?: SpotSTPModeV2; + presetTakeProfitPrice?: string; + executeTakeProfitPrice?: string; + presetStopLossPrice?: string; + executeStopLossPrice?: string; } - -================ -File: src/types/response/v2/spot.ts -================ -/** - * - * * Spot | Market - * - */ ⋮---- -export interface SpotCoinChainV2 { - chain: string; - needTag: boolean; - withdrawable: boolean; - rechargeable: boolean; - withdrawFee: string; - extraWithdrawFee: string; - depositConfirm: string; - withdrawConfirm: string; - minDepositAmount: string; - minWithdrawAmount: string; - browserUrl: string; - contractAddress: string; - withdrawStep: string; - withdrawMinScale: string; - congestion: string; +export interface SpotBatchOrderRequestV2 { + symbol?: string; + batchMode?: SpotBatchModeV2; + orderList: SpotBatchOrderRequestItemV2[]; } ⋮---- -export interface SpotCoinInfoV2 { - coinId: string; - coin: string; - transfer: boolean; - chains: SpotCoinChainV2[]; +export interface SpotBatchCancelOrderRequestV2 { + symbol?: string; + batchMode?: SpotBatchModeV2; + orderList: { + symbol?: string; + orderId?: string; + clientOid?: string; + }[]; } ⋮---- -export interface SpotSymbolInfoV2 { - symbol: string; - baseCoin: string; - quoteCoin: string; - minTradeAmount: string; - maxTradeAmount: string; - takerFeeRate: string; - makerFeeRate: string; - pricePrecision: string; - quantityPrecision: string; - quotePrecision: string; - minTradeUSDT: string; - status: string; - buyLimitPriceRatio: string; - sellLimitPriceRatio: string; - orderQuantity: string; - areaSymbol: string; +export interface GetSpotOrderInfoRequestV2 { + orderId?: string; + clientOid?: string; + requestTime?: string; + receiveWindow?: string; } ⋮---- -export interface SpotVipFeeRateV2 { - level: number; - dealAmount: string; - assetAmount: string; - takerFeeRate: string; - makerFeeRate: string; - btcWithdrawAmount: string; - usdtWithdrawAmount: string; +export interface GetSpotOpenOrdersRequestV2 { + symbol?: string; + startTime?: string; + endTime?: string; + idLessThan?: string; + limit?: string; + orderId?: string; + tpslType?: SpotTPSLTypeV2; + requestTime?: string; + receiveWindow?: string; } ⋮---- -export interface SpotTickerV2 { - symbol: string; - high24h: string; - open: string; - low24h: string; - lastPr: string; - quoteVolume: string; - baseVolume: string; - usdtVolume: string; - bidPr: string; - askPr: string; - bidSz: string; - askSz: string; - openUtc: string; - ts: string; - changeUtc24h: string; - change24h: string; +export interface GetSpotHistoryOrdersRequestV2 { + symbol?: string; + startTime?: string; + endTime?: string; + idLessThan?: string; + limit?: string; + orderId?: string; + tpslType?: SpotTPSLTypeV2; + requestTime?: string; + receiveWindow?: string; } ⋮---- -export interface SpotMergeDepthV2 { - asks: [string, string][]; - bids: [string, string][]; - ts: string; - scale: string; - precision: string; - isMaxPrecision: string; +export interface GetSpotFillsRequestV2 { + symbol: string; + orderId?: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface SpotOrderBookDepthV2 { - asks: [string, string][]; - bids: [string, string][]; - ts: string; -} +/** + * + * * Spot | Trigger Orders + * + */ ⋮---- -export type SpotCandlestickV2 = [ - string, // timestamp - string, // open - string, // high - string, // low - string, // close - string, // baseVolume - string, // usdtVolume - string, // quoteVolume -]; +export type SpotPlanTypeV2 = 'amount' | 'total'; ⋮---- -string, // timestamp -string, // open -string, // high -string, // low -string, // close -string, // baseVolume -string, // usdtVolume -string, // quoteVolume +export type SpotTriggerTypeV2 = 'fill_price' | 'mark_price'; ⋮---- -export interface SpotTradeV2 { +export interface SpotPlanOrderRequestV2 { symbol: string; - tradeId: string; - side: string; - price: string; + side: SpotOrderSideV2; + triggerPrice: string; + orderType: SpotOrderTypeV2; + executePrice?: string; + planType?: SpotPlanTypeV2; size: string; - ts: string; -} -⋮---- -/** - * - * * Spot | Trade - * - */ -⋮---- -export interface CancelAndSubmitSpotOrderResponseV2 { - orderId: string; - clientOid: string | null; - success: string; - msg: string | null; -} -⋮---- -export interface SubmitSpotBatchOrdersResponseV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - orderId: string; - clientOid: string; - errorMsg: string; - errorCode?: string; - }[]; + triggerType: SpotTriggerTypeV2; + clientOid?: string; + force?: SpotOrderForceV2; + stpMode?: SpotSTPModeV2; } ⋮---- -export interface SpotOrderInfoV2 { - userId: string; - symbol: string; - orderId: string; - clientOid: string; - price: string; +export interface SpotModifyPlanOrderRequestV2 { + orderId?: string; + clientOid?: string; + triggerPrice: string; + orderType: SpotOrderTypeV2; + executePrice?: string; size: string; - orderType: string; - side: string; - status: string; - priceAvg: string; - baseVolume: string; - quoteVolume: string; - enterPointSource: string; - feeDetail: { - BGB?: { - deduction: boolean; - feeCoinCode: string; - totalDeductionFee: string; - totalFee: string; - }; - newFees?: { - c: number; - d: number; - deduction: boolean; - r: string; - t: string; - totalDeductionFee: number; - }; - }; - orderSource: string; - cancelReason: string; - cTime: string; - uTime: string; } ⋮---- -export interface SpotOpenOrderV2 { - userId: string; +export interface GetSpotCurrentPlanOrdersRequestV2 { symbol: string; - orderId: string; - clientOid: string; - priceAvg: string; - size: string; - orderType: string; - side: string; - status: string; - basePrice: string; - baseVolume: string; - quoteVolume: string; - enterPointSource: string; - orderSource?: string; - presetTakeProfitPrice: string; - executeTakeProfitPrice: string; - presetStopLossPrice: string; - executeStopLossPrice: string; - cTime: string; - uTime?: string; - tpslType: string; - triggerPrice: string | null; + limit?: string; + idLessThan?: string; + startTime?: string; + endTime?: string; } ⋮---- -export interface SpotFillV2 { - userId: string; +export interface GetSpotHistoryPlanOrdersRequestV2 { symbol: string; - orderId: string; - tradeId: string; - orderType: string; - side: string; - priceAvg: string; - size: string; - amount: string; - feeDetail: { - deduction: string; - feeCoin: string; - totalDeductionFee: string; - totalFee: string; - }; - tradeScope: string; - cTime: string; - uTime: string; + startTime: string; + endTime: string; + limit?: string; } ⋮---- /** * - * * Spot | Trigger Orders + * * Spot | Account * */ ⋮---- -export interface SpotCurrentPlanOrderV2 { - orderId: string; - clientOid: string; - symbol: string; - size: string; - executePrice: string; - triggerPrice: string; - status: string; - orderType: string; - side: string; - planType: string; - triggerType: string; - enterPointSource: string; - uTime: string; - cTime: string; -} +export type SpotBillGroupTypeV2 = + | 'deposit' + | 'withdraw' + | 'transaction' + | 'transfer' + | 'other'; ⋮---- -export interface SpotHistoryPlanOrderV2 { - orderId: string; - clientOid: string; - symbol: string; - size: string; - executePrice: string; - triggerPrice: string; - status: string; - orderType: string; - side: string; - planType: string; - triggerType: string; - enterPointSource: string; - uTime: string; - cTime: string; -} +export type SpotBusinessTypeV2 = + | 'deposit' + | 'withdraw' + | 'buy' + | 'sell' + | 'deduction of handling fee' + | 'transfer-in' + | 'transfer-out' + | 'rebate rewards' + | 'airdrop rewards' + | 'USDT contract rewards' + | 'mix contract rewards' + | 'system lock' + | 'user lock'; ⋮---- -export interface SpotPlanSubOrderV2 { - orderId: string; - price: string; - type: string; - status: string; +export type SpotAccountTypeV2 = + | 'spot' + | 'p2p' + | 'coin_futures' + | 'usdt_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'isolated_margin'; +⋮---- +export interface GetSpotAccountBillsRequestV2 { + coin?: string; + groupType?: SpotBillGroupTypeV2; + businessType?: SpotBusinessTypeV2; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface SpotCancelPlanOrdersV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - orderId: string; - clientOid: string; - errorMsg: string; - }[]; +export interface SpotTransferRequestV2 { + fromType: SpotAccountTypeV2; + toType: SpotAccountTypeV2; + amount: string; + coin: string; + symbol: string; + clientOid?: string; } ⋮---- -/** - * - * * Spot | Account - * - */ +export interface SpotSubAccountTransferRequestV2 { + fromType: SpotAccountTypeV2; + toType: SpotAccountTypeV2; + amount: string; + coin: string; + symbol?: string; + clientOid?: string; + fromUserId: string; + toUserId: string; +} ⋮---- -export interface SpotAccountInfoV2 { - userId: string; - inviterId: string; - ips: string; - authorities: string[]; - parentId: number; - traderType: string; - channelCode: string; - channel: string; - regisTime: string; +export interface SpotWithdrawalRequestV2 { + coin: string; + transferType: 'on_chain' | 'internal_transfer'; + address: string; + chain?: string; + innerToType?: 'email' | 'mobile' | 'uid'; + areaCode?: string; + tag?: string; + size: string; + remark?: string; + clientOid?: string; } ⋮---- -export interface SpotAccountAssetV2 { - coin: string; - available: string; - frozen: string; - locked: string; - limitAvailable: string; - uTime: string; +export interface SpotMainSubTransferRecordRequestV2 { + coin?: string; + role?: 'initiator' | 'receiver'; + subUid?: string; + startTime?: string; + endTime?: string; + clientOid?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface SpotSubAccountAssetV2 { +export interface GetSpotTransferRecordRequestV2 { coin: string; - available: string; - limitAvailable: string; - frozen: string; - locked: string; - uTime: string; + fromType: SpotAccountTypeV2; + startTime?: string; + endTime?: string; + clientOid?: string; + limit?: string; + idLessThan?: string; } -export interface SpotSubAccountAssetsV2 { - userId: number; - assetsList: SpotSubAccountAssetV2[]; +⋮---- +export interface GetSpotSubAccountDepositRecordRequestV2 { + subUid: string; + coin?: string; + startTime?: string; + endTime?: string; + idLessThan?: string; + limit?: string; } ⋮---- -export interface SpotAccountBillV2 { - cTime: string; - coin: string; - groupType: string; - businessType: string; - size: string; - balance: string; - fees: string; - billId: string; +export interface GetSpotWithdrawalRecordRequestV2 { + coin?: string; + clientOid?: string; + startTime: string; + endTime: string; + idLessThan?: string; + orderId?: string; + limit?: string; } ⋮---- -export interface SpotMainSubTransferRecordV2 { - coin: string; - status: string; - toType: string; - fromType: string; - size: string; - ts: string; - clientOid: string; - transferId: string; - fromUserId: string; - toUserId: string; +export interface GetSpotDepositRecordRequestV2 { + coin?: string; + orderId?: string; + startTime: string; + endTime: string; + idLessThan?: string; + limit?: string; +} + +================ +File: src/types/request/v3/broker.ts +================ +export interface CreateBrokerSubAccountRequestV3 { + subaccountName: string; + label: string; } ⋮---- -export interface SpotTransferRecordV2 { - coin: string; - status: string; - toType: string; - toSymbol: string; - fromType: string; - fromSymbol: string; - size: string; - ts: string; - clientOid: string; - transferId: string; +export interface GetBrokerSubAccountListRequestV3 { + limit?: string; + cursor?: string; + status?: 'normal' | 'freeze'; } ⋮---- -export interface SpotDepositAddressV2 { - address: string; - chain: string; - coin: string; - tag: string; - url: string; +export interface ModifyBrokerSubAccountRequestV3 { + subUid: string; + status?: 'normal' | 'freeze'; + permList?: string[]; } ⋮---- -export interface SpotSubAccountDepositRecordV2 { - orderId: string; - tradeId: string; +export interface BrokerSubWithdrawalRequestV3 { + subUid: string; coin: string; - size: string; - status: string; - toAddress: string; - dest: string; - chain: string; - fromAddress: string; - clientOid?: string; - confirm?: string; + dest: 'on_chain' | 'internal_transfer'; + address: string; + amount: string; + chain?: string; tag?: string; - cTime: string; - uTime: string; + clientOid?: string; } ⋮---- -export interface SpotWithdrawalRecordV2 { - orderId: string; - tradeId: string; +export interface GetBrokerSubDepositAddressRequestV3 { + subUid: string; coin: string; - dest: string; - clientOid: string; - type: string; - tag: string; - size: string; - fee: string; - status: string; - toAddress: string; - fromAddress: string; - confirm: string; - chain: string; - cTime: string; - uTime: string; + chain?: string; } ⋮---- -export interface SpotDepositRecordV2 { - orderId: string; - tradeId: string; - coin: string; - type: string; - size: string; - status: string; - toAddress: string; - dest: string; - chain: string; - fromAddress: string; - cTime: string; - uTime: string; +export interface GetBrokerAllSubDepositWithdrawalRequestV3 { + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; + status?: 'pending' | 'fail' | 'success'; +} +⋮---- +export interface GetBrokerCommissionRequestV3 { + startTime?: string; + endTime?: string; + pageSize?: string; + pageNo?: string; + bizType?: 'spot' | 'futures'; + subBizType?: + | 'spot_trade' + | 'spot_margin' + | 'usdt_futures' + | 'usdc_futures' + | 'coin_futures'; +} +⋮---- +export interface CreateBrokerSubApiKeyRequestV3 { + subUid: string; + passphrase: string; + label: string; + ipList?: string[]; + permType: 'read_and_write' | 'readonly'; + permList: string[]; +} +⋮---- +export interface ModifyBrokerSubApiKeyRequestV3 { + subUid: string; + passphrase: string; + apiKey: string; + label?: string; + ipList?: string[]; + permType?: 'read_and_write' | 'readonly'; + permList?: string[]; +} +⋮---- +export interface DeleteBrokerSubApiKeyRequestV3 { + subUid: string; + apiKey: string; +} +⋮---- +export interface GetBrokerSubApiKeyRequestV3 { + subUid: string; } ================ -File: src/types/response/v3/loan.ts +File: src/types/request/v3/loan.ts ================ -export interface LoanTransfersV3 { +export interface GetTransferedRequestV3 { + userId?: string; coin: string; - transfered: string; - userId: string; } ⋮---- -export interface LoanSymbolSettingV3 { - symbol: string; - leverage: string; +export interface GetSymbolsRequestV3 { + productId: string; } ⋮---- -export interface LoanSymbolsV3 { +export interface GetRepaidHistoryRequestV3 { + startTime?: string; + endTime?: string; + limit?: string; +} +⋮---- +export interface GetProductInfosRequestV3 { productId: string; - spotSymbols: string[]; - marginLeverage: string; - usdtContractLeverage: string; - coinContractLeverage: string; - usdcContractLeverage: string; - usdtContractSymbols: LoanSymbolSettingV3[]; - coinContractSymbols: LoanSymbolSettingV3[]; - usdcContractSymbols: LoanSymbolSettingV3[]; } ⋮---- -export interface RepaidHistoryItemV3 { - repayOrderId: string; - businessType: 'normal' | 'liquidation'; - repayType: 'all' | 'part'; - repaidTime: string; - coin: string; - repayAmount: string; - repayInterest: string; +export interface GetLoanOrderRequestV3 { + orderId?: string; + startTime?: string; + endTime?: string; } ⋮---- -export interface LoanProductInfoV3 { +export interface GetEnsureCoinsRequestV3 { productId: string; - leverage: string; - supportUsdtContract: 'YES' | 'NO'; - supportCoinContract: 'YES' | 'NO'; - supportUsdcContract: 'YES' | 'NO'; - transferLine: string; - spotBuyLine: string; - usdtContractOpenLine: string; - coinContractOpenLine: string; - usdcContractOpenLine: string; - liquidationLine: string; - stopLiquidationLine: string; -} -⋮---- -export interface LoanOrderV3 { - orderId: string; - orderProductId: string; - uid: string; - loanTime: string; - loanCoin: string; - loanAmount: string; - unpaidAmount: string; - unpaidInterest: string; - repaidAmount: string; - repaidInterest: string; - reserve: string; - status: 'not_paid_off' | 'paid_off'; } ⋮---- -export interface CoinInfoV3 { - coin: string; - convertRatio: string; - maxConvertValue: string; -} -⋮---- -export interface BindUidResponseV3 { - riskUnitId: string; +export interface BindUidRequestV3 { + riskUnitId?: string; uid: string; operate: 'bind' | 'unbind'; } ⋮---- -export interface UnpaidInfoV3 { - coin: string; - unpaidQty: string; - unpaidInterest: string; -} -⋮---- -export interface BalanceInfoV3 { - coin: string; - price: string; - amount: string; - convertedUsdtAmount: string; -} -⋮---- -export interface LTVConvertResponseV3 { - ltv: string; - subAccountUids: string[]; - unpaidUsdtAmount: string; - usdtBalance: string; - unpaidInfo: UnpaidInfoV3[]; - balanceInfo: BalanceInfoV3[]; +export interface GetLTVConvertRequestV3 { + riskUnitId?: string; } ================ -File: src/types/response/v3/strategy.ts +File: src/types/request/v3/public.ts ================ -export interface PlaceStrategyOrderResponseV3 { - orderId: string; - clientOid: string; +export interface GetPublicFillsRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; + limit?: string; } ⋮---- -export interface ModifyStrategyOrderResponseV3 { - orderId: string; - clientOid: string; +export interface GetCandlesRequestV3 { + category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; + interval: + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1H' + | '4H' + | '6H' + | '12H' + | '1D'; + startTime?: string; + endTime?: string; + type?: 'MARKET' | 'MARK' | 'INDEX'; + limit?: string; } ⋮---- -export interface StrategyOrderV3 { - orderId: string; - clientOid: string; - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; +export interface GetHistoryCandlesRequestV3 { + category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; - qty: string; - posSide: 'long' | 'short'; - tpTriggerBy: 'market' | 'mark'; - slTriggerBy: 'market' | 'mark'; - takeProfit: string; - stopLoss: string; - tpOrderType: 'limit' | 'market'; - slOrderType: 'limit' | 'market'; - tpLimitPrice: string; - slLimitPrice: string; - createdTime: string; - updatedTime: string; + interval: + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1H' + | '4H' + | '6H' + | '12H' + | '1D'; + startTime?: string; + endTime?: string; + type?: 'MARKET' | 'MARK' | 'INDEX'; + limit?: string; } - -================ -File: src/types/websockets/ws-events.ts -================ -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; +⋮---- +export interface GetContractsOiRequestV3 { + symbol?: string; + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; } ⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike +export interface GetCurrentFundingRateRequestV3 { + symbol: string; +} ⋮---- -export interface WsBaseEvent { - action: TAction; - arg: unknown; - data: TData[]; +export interface GetHistoryFundingRateRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; + cursor?: string; + limit?: string; } ⋮---- -export interface WsSnapshotChannelEvent extends WsBaseEvent<'snapshot'> { - arg: { - instType: string; - channel: string; - instId: string; - }; +export interface GetMarginLoansRequestV3 { + coin: string; } ⋮---- -export interface WsSnapshotAccountEvent extends WsBaseEvent<'snapshot'> { - arg: { - instType: string; - channel: 'account'; - instId: string; - }; +export interface GetOpenInterestRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; } ⋮---- -export interface WsSnapshotPositionsEvent extends WsBaseEvent<'snapshot'> { - arg: { - instType: string; - channel: 'positions'; - instId: string; - }; +export interface GetPositionTierRequestV3 { + category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + coin?: string; } ⋮---- -export interface WsAccountSnapshotDataUMCBL { - marginCoin: string; - locked: string; - available: string; - maxOpenPosAvailable: string; - maxTransferOut: string; - equity: string; - usdtEquity: string; +export interface GetRiskReserveRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; } ⋮---- -export interface WsAccountSnapshotUMCBL extends WsBaseEvent<'snapshot'> { - arg: { - instType: 'umcbl'; - channel: 'account'; - instId: string; - }; - data: WsAccountSnapshotDataUMCBL[]; +export interface GetInstrumentsRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; } ⋮---- -export interface WsPositionSnapshotDataUMCBL { - posId: string; - instId: string; - instName: string; - marginCoin: string; - margin: string; - marginMode: string; - holdSide: string; - holdMode: string; - total: string; - available: string; - locked: string; - averageOpenPrice: string; - leverage: number; - achievedProfits: string; - upl: string; - uplRate: string; - liqPx: string; - keepMarginRate: string; - marginRate: string; - cTime: string; - uTime: string; - markPrice: string; +export interface GetOrderBookRequestV3 { + category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; + limit?: string; } ⋮---- -export interface WSPositionSnapshotUMCBL extends WsBaseEvent<'snapshot'> { - arg: { - instType: 'umcbl'; - channel: 'positions'; - instId: string; - }; - data: WsPositionSnapshotDataUMCBL[]; +export interface GetTickersRequestV3 { + category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; } - -================ -File: .jshintrc -================ -{ - "esversion": 8, - "asi": true, - "laxbreak": true, - "predef": [ "-Promise" ] +⋮---- +export interface GetIndexComponentsRequestV3 { + symbol: string; } ================ -File: .prettierrc +File: src/types/request/v3/strategy.ts ================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" +export interface PlaceStrategyOrderRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; + clientOid?: string; + type?: 'tpsl'; + tpslMode?: 'full' | 'partial'; + qty: string; + posSide: 'long' | 'short'; + tpTriggerBy?: 'market' | 'mark'; + slTriggerBy?: 'market' | 'mark'; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: 'limit' | 'market'; + slOrderType?: 'limit' | 'market'; + tpLimitPrice?: string; + slLimitPrice?: string; +} +⋮---- +export interface ModifyStrategyOrderRequestV3 { + orderId?: string; + clientOid?: string; + qty: string; + tpTriggerBy?: 'market' | 'mark'; + slTriggerBy?: 'market' | 'mark'; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: 'limit' | 'market'; + slOrderType?: 'limit' | 'market'; + tpLimitPrice?: string; + slLimitPrice?: string; +} +⋮---- +export interface CancelStrategyOrderRequestV3 { + orderId?: string; + clientOid?: string; +} +⋮---- +export interface GetUnfilledStrategyOrdersRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + type?: 'tpsl'; +} +⋮---- +export interface GetHistoryStrategyOrdersRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + type?: 'tpsl'; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ================ -File: LICENSE.md -================ -Copyright 2022 Tiago Siebler - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -================ -File: tea.yaml -================ -# https://tea.xyz/what-is-this-file ---- -version: 1.0.0 -codeOwners: - - '0xeb1a7BF44a801e33a339705A266Afc0Cba3D6D54' -quorum: 1 - -================ -File: examples/auth/fasterHmacSign.ts +File: src/types/request/v3/trade.ts ================ -import { createHmac } from 'crypto'; +export interface BatchModifyOrderRequestV3 { + orderId?: string; + clientOid?: string; + qty?: string; + price?: string; + autoCancel?: 'yes' | 'no'; +} ⋮---- -import { DefaultLogger, RestClientV3, WebsocketClientV3 } from '../../src/'; +export interface CancelAllOrdersRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; +} ⋮---- -// or -// import { createHmac } from 'crypto'; -// import { DefaultLogger, RestClientV3, WebsocketClientV3 } from 'bitget-api'; +export interface CancelBatchOrdersRequestV3 { + orderId?: string; + clientOid?: string; + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; +} ⋮---- -/** - * Injecting a custom signMessage function. - * - * As of version 3.0.0 of the bitget-api Node.js/TypeScript/JavaScript - * SDK for Bitget, the SDK uses the Web Crypto API for signing requests. - * While it is compatible with Node and Browser environments, it is - * slightly slower than using Node's native crypto module (only - * available in backend Node environments). - * - * For latency sensitive users, you can inject the previous node crypto sign - * method (or your own even faster implementation), if this change affects you. - * - * This example demonstrates how to inject a custom sign function, to achieve - * the same peformance as seen before the Web Crypto API was introduced. - * - * For context on standard usage, the "signMessage" function is used: - * - During every single API call - * - After opening a new private WebSocket connection - */ +export interface CloseAllPositionsRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + posSide?: 'long' | 'short'; +} ⋮---- -/** - * Set this to true to enable demo trading: - */ +export interface CancelOrderRequestV3 { + orderId?: string; + clientOid?: string; +} ⋮---- -/** - * Overkill in almost every case, but if you need any optimisation available, - * you can inject a faster sign mechanism such as node's native createHmac: - */ +export interface GetMaxOpenAvailableRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; + orderType: 'limit' | 'market'; + side: 'buy' | 'sell'; + price?: string; + size?: string; +} ⋮---- -// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing +export interface GetOrderInfoRequestV3 { + orderId?: string; + clientOid?: string; +} ⋮---- -// trace: (...params) => console.log('trace', ...params), +export interface GetFillsRequestV3 { + orderId?: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** - * Set this to true to enable demo trading for the private account data WS - * Topics: order,execution,position,wallet,greeks - */ +export interface GetUnfilledOrdersRequestV3 { + category?: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** - * Overkill in almost every case, but if you need any optimisation available, - * you can inject a faster sign mechanism such as node's native createHmac: - */ +export interface GetHistoryOrdersRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; +} ⋮---- -function setWsClientEventListeners( - websocketClient: WebsocketClientV3, - accountRef: string, -): Promise +export interface GetPositionHistoryRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; +} ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +export interface GetCurrentPositionRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + posSide?: 'long' | 'short'; +} ⋮---- -// Simple promise to ensure we're subscribed before trying anything else +export interface ModifyOrderRequestV3 { + orderId?: string; + clientOid?: string; + qty?: string; + price?: string; + autoCancel?: 'yes' | 'no'; +} ⋮---- -// Start trading - -================ -File: examples/auth/rest-private-rsa.md -================ -# RSA Authentication with Bitget APIs in Node.js, JavaScript & TypeScript - -## Creating RSA Keys - -Officially, Bitget recommends downloading and running a key generator from their repo. Guidance for this can be found on the Bitget's website when trying to add a new RSA API key. - -However, openssl can be used to create the public & private key files using the following steps: - -```bash -# Generate a private key with either 2048 or 4096 bit length -openssl genrsa -out rsa-private-key.pem 4096 - -# Generate a corresponding public key -openssl rsa -in rsa-private-key.pem -pubout -out rsa-public-key.pem -``` - -## Using the RSA public key to get an API key from Bitget - -Once created, keep your **private key** completely secret! The **public** key needs to be provided to Bitget when creating new API credentials with the "Self-generated" option. - -Your public key should look something like this: - -```pem ------BEGIN PUBLIC KEY----- -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1uWxxOXZUaX6AeZszf4x -rBsU6axA5ipwxG7VPihVgssphDrrSOD0hZqnBmtF2bvT9ee1U0XOfMn+H+J5SH+1 -jgUpfioqH0L+KXl6wmLoPsadgfJz0SiQlFnKTkDXvMmecr6cdMHi2qNEx4CMc68C -obvQ4Voz5qqpDwbohGtJh0p10PB//0Ejcoz0UwrTDq8BGeFmWa9pL/7h2vHtw+QU -UxlnGmt98M8KkKqqvVicMK+IVtng/QlDw9ofG2kQcbBkPRaTjNI+8ULtCDH0sOkZ -nT8PtGm4sEwmWH/dRWtUTWkMnUwCzuo/rWPb7WMprW2pKDTrLjUAr9M161t3Xa6W -JO03K3NOxupy7ilululLY8d/WKWYDOZMvS5bPiPRUoZqlJneC0CT/2q1W6GfWzsT -DCDTpgq/Ao7jTtnME9iadpwvFn0nMtNgJSrFDWPq8vKY9pRcEp/Na5qvIEOQIFnp -/kIDPuMf+LZwO8lGFO3jnndY+62835rm7t6ZNM3NLoNCarvUCEasobgDJHw7x7c1 -fW/OxYtLrWGdMpsP0MewgGJZXcT7mvlBjQ+JWLoyIc5rYMIDw9RLWUPnrlRCxvPp -sD9kDX7eaipdoik5yLyMaRvd16Vt9Bck/9pbSHazm41m/nd4KCZeGdsvrAA2beww -zFWQQV9EX6/VLBgbnGTsMe0CAwEAAQ== ------END PUBLIC KEY----- -``` - -Submit this in the "Upload public key" form, shown when creating a new API key on Bitget and choosing the "self-generated"/RSA option. - -Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. - -After using the public key to create a new API key, you will be given an API Key such as the following: - -``` -SIHqWcDeRoj6gkOjLjQh1dnV1CD7IgwQTfL4LVa8wu04zNTYVSmJBIHsjQjgwWqt -``` - -This is the first piece, used as the "apiKey" in the [rest-private-rsa.ts](./rest-private-rsa.ts) example. - -## Using the RSA private key for RSA authentication with Bitget APIs in Node.js - -Your private key, if generated with the above steps, should look something like this (but with much more text): - -```pem ------BEGIN RSA PRIVATE KEY----- -uayyi6wFTaNeG1/WCqhrowj2kCx8eB6NDZYl+OS9ZI9WC -q/44iFERNuP0TXvQx8tgvSZXyu4/G618QzKh0Ii1uAATt2upa8dp1uGl2U7EqBE8 -p5y4pPzJuwvB3j6LQON20u2Wpbg8PQZACMfKym7lYDO+9MloK/gAQpyeYJzbw92C -YE/ymq4JVjCMCQKCAQEA4/X0I9TO8vT0D0l83o693QA3C09uSZ6j9Obx5UrtDnA9 -sMkkRoe+R/vvIpVDzukMEEOmCuxbcdPoniVUKlTooK0Llo6JJ1l8CdFzQsOR97Pe -csB6pxkLLH2qHx05xPBy4PyoB ------END RSA PRIVATE KEY----- -``` - -This is your secret, you should never share this with anyone, not even Bitget! Treat this like a password. - -As part of this authentication process, your private key is used to generate a signature (using `RSA-SHA256`). This SDK handles this process automatically for you. RSA authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. - -From here, simply use the key provided by Bitget as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. - -Based on the above example, the following would prepare the main REST client using the above credentials: - -```typescript -// Received after creating a new API key with a self-generated RSA public key on Bitget -const API_KEY = 'bg_0866563123123123123f567e83e52fd'; - -// The self-generated RSA private key, this is never directly given to Bitget, but used to generate a signature -// Note: this MUST include the "BEGIN PRIVATE KEY" header so that the SDK understands this is RSA auth -const rsaPrivateKey = ` ------BEGIN PRIVATE KEY----- -MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC4kNgO71O0xkuH -FjHnr5pimpEeiGPAtDTAeJoS55+kVrh3ThHsm0ARf36zimU -gwrCWAnKqPlbqzWzs9mH9JvZWrEaOgWy -8wMSJ21vtz1rRJhfaUUsOC1KLoWyvzqWW44zKaxoKSqCUMJqDbxIq7RjGlmc8KGJ -scFWRSdfGEEpvqLlpTLoEtWHZP0pUUamSWrH/IgieFFhKaOPvmED24DJAlqSeEFw -z7TW4dfWPRgjCRu4AAfgCtjb+3/7ONeQfx5XFvKFM7VNi/9sRh+alRqpzKrlI -79bM1p/egrC4c8KUqrNk2s5c3HIU......THISISANEXAMPLE ------END PRIVATE KEY----- -`; - -// This is set by you when registering your RSA API key in Bitget's website. -const API_PASS = 'TestingRSA'; - -const client = new RestClientV2({ - apiKey: API_KEY, - apiSecret: rsaPrivateKey, - apiPass: API_PASS, -}); - -const clientV3 = new RestClientV3({ - apiKey: API_KEY, - apiSecret: rsaPrivateKey, - apiPass: API_PASS, -}); -``` - -For a complete example, refer to the [rest-private-rsa.ts](./rest-private-rsa.ts) file on GitHub. - -================ -File: examples/auth/rest-private-rsa.ts -================ -import { RestClientV2, RestClientV3 } from '../../src'; -⋮---- -// Import frmo NPM: -// import { RestClientV2, RestClientV3 } from 'bitget-api'; -// or if you prefer require: -// const { RestClientV2, RestClientV3 } = require('bitget-api'); -⋮---- -// Received after creating a new API key with a self-generated RSA public key on Bitget +export interface PlaceBatchOrdersRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; + qty: string; + price?: string; + side: 'buy' | 'sell'; + orderType: 'limit' | 'market'; + timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only'; + posSide?: 'long' | 'short'; + clientOid?: string; + reduceOnly?: 'yes' | 'no'; +} ⋮---- -// The self-generated RSA private key, this is never directly given to Bitget, but used to generate a signature -// Note: this MUST include the "BEGIN PRIVATE KEY" header so that the SDK understands this is RSA auth +export interface PlaceOrderRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; + qty: string; + price?: string; + side: 'buy' | 'sell'; + orderType: 'limit' | 'market'; + timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only'; + posSide?: 'long' | 'short'; + clientOid?: string; + reduceOnly?: 'yes' | 'no'; + stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; + takeProfitPrice?: string; + stopLossPrice?: string; + takeProfitTriggerType?: 'mark_price' | 'last_price'; + stopLossTriggerType?: 'mark_price' | 'last_price'; +} ⋮---- -// This is set by you when registering your RSA API key in Bitget's website. +export interface CountdownCancelAllRequestV3 { + countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) +} ⋮---- -// const wsClient = new WebsocketClientV2({ -// apiKey: API_KEY, -// apiSecret: rsaPrivateKey, -// apiPass: API_PASS, -// }); +countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) ================ -File: examples/deprecated-V1-REST/rest-private-futures.ts +File: src/types/request/shared.ts ================ -import { FuturesClient } from '../../src/index'; -⋮---- -// or -// import { SpotClient } from 'bitget-api'; -⋮---- -// read from environmental variables -⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', -⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ +/** Pagination */ +export interface Pagination { + /** Time after */ + after?: string; + /** Time before */ + before?: string; + /** Elements per page */ + limit?: string; +} ⋮---- -startTime: now.getTime() + '', // should be sent as a string -endTime: toTime.getTime() + '', // should be sent as a string - -================ -File: examples/deprecated-V1-REST/rest-private-spot.ts -================ -import { SpotClient } from '../../src/index'; +/** Time after */ ⋮---- -// or -// import { SpotClient } from 'bitget-api'; +/** Time before */ ⋮---- -// read from environmental variables +/** Elements per page */ ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +export type OrderTimeInForce = 'normal' | 'post_only' | 'fok' | 'ioc'; ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ - -================ -File: examples/deprecated-V1-REST/rest-public-futures.ts -================ -import { FuturesClient } from '../../src/index'; +export interface GetHistoricTradesParams { + symbol: string; + limit?: string; + tradeId?: string; + startTime?: string; + endTime?: string; +} ⋮---- -// or -// import { SpotClient } from 'bitget-api'; +/** + * The margin type, used directly in building the endpoint URL + */ +export type MarginType = 'crossed' | 'isolated'; ⋮---- -// Fetch the last 1000 1min candles for a symbol +export type FuturesProductTypeV2 = + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES' + | 'SUSDT-FUTURES' + | 'SCOIN-FUTURES' + | 'SUSDC-FUTURES'; ⋮---- -const msPerCandle = 60 * 1000; // 60 seconds x 1000 +export type FuturesPlanTypeV2 = + | 'profit_plan' + | 'loss_plan' + | 'moving_plan' + | 'pos_profit' + | 'pos_loss'; ================ -File: examples/deprecated-V1-REST/rest-trade-futures.ts +File: src/types/response/v2/common.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - FuturesClient, - isWsFuturesAccountSnapshotEvent, - isWsFuturesPositionsSnapshotEvent, - NewFuturesOrder, - WebsocketClientLegacyV1, -} from '../../src'; -⋮---- -// or -// import { -// FuturesClient, -// isWsFuturesAccountSnapshotEvent, -// isWsFuturesPositionsSnapshotEvent, -// NewFuturesOrder, -// WebsocketClient, -// } from 'bitget-api'; -⋮---- -// read from environmental variables -⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', -⋮---- -function logWSEvent(type, data) -⋮---- -// simple sleep function -function promiseSleep(milliseconds) +/** + * + * * Common | Notice + * + */ ⋮---- -// WARNING: for sensitive math you should be using a library such as decimal.js! -function roundDown(value, decimals) +export interface AnnouncementV2 { + annId: string; + annTitle: string; + annDesc: string; + cTime: string; + language: string; + annUrl: string; +} ⋮---- -/** WS event handler that uses type guards to narrow down event type */ -async function handleWsUpdate(event) +/** + * + * * Common | Public + * + */ ⋮---- /** - * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). * - * It is designed to: - * - open a private websocket channel to log account events - * - check for any available USDT balance in the futures account - * - immediately open a minimum sized long position on BTCUSDT - * - check active positions - * - immediately send closing orders for any active futures positions - * - check positions again + * * Common | Tax * - * The corresponding UI for this is at https://www.bitget.com/en/mix/usdt/BTCUSDT_UMCBL */ ⋮---- -// Add event listeners to log websocket events on account +export interface SpotTransactionRecordV2 { + id: string; + coin: string; + spotTaxType: string; + amount: string; + fee: string; + balance: string; + ts: string; +} ⋮---- -// Subscribe to private account topics -⋮---- -// : position updates -⋮---- -// : order updates -⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) -⋮---- -// const balances = allBalances.filter((bal) => Number(bal.available) != 0); +export interface FuturesTransactionRecordV2 { + id: string; + symbol: string; + marginCoin: string; + futureTaxType: string; + amount: string; + fee: string; + ts: string; +} ⋮---- -// Loop through any active positions and send a closing market order on each position - -================ -File: examples/deprecated-V1-REST/rest-trade-spot.ts -================ -import { SpotClient, WebsocketClientLegacyV1 } from '../../src/index'; +export interface MarginTransactionRecordV2 { + id: string; + coin: string; + marginTaxType: string; + amount: string; + fee: string; + total: string; + symbol: string; + ts: string; +} ⋮---- -// or -// import { SpotClient } from 'bitget-api'; +export interface P2PMerchantOrdersV2 { + id: string; + coin: string; + p2pTaxType: string; + total: string; + ts: string; +} ⋮---- -// read from environmental variables +/** + * + * * Common | P2P + * + */ ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +export interface P2PMerchantV2 { + registerTime: string; + nickName: string; + isOnline: string; + avgPaymentTime: string; + avgReleaseTime: string; + totalTrades: string; + totalBuy: string; + totalSell: string; + totalCompletionRate: string; + trades30d: string; + sell30d: string; + buy30d: string; + completionRate30d: string; +} ⋮---- -function logWSEvent(type, data) +export interface P2PMerchantInfoV2 { + registerTime: string; + nickName: string; + merchantId: string; + avgPaymentTime: string; + avgReleaseTime: string; + totalTrades: string; + totalBuy: string; + totalSell: string; + totalCompletionRate: string; + trades30d: string; + sell30d: string; + buy30d: string; + completionRate30d: string; + kycStatus: boolean; + emailBindStatus: boolean; + mobileBindStatus: boolean; + email: string; + mobile: string; +} ⋮---- -// simple sleep function -function promiseSleep(milliseconds) +export interface P2PMerchantOrderV2 { + orderId: string; + orderNo: string; + advNo: string; + side: string; + count: string; + coin: string; + price: string; + fiat: string; + withdrawTime: string; + representTime: string; + releaseTime: string; + paymentTime: string; + amount: string; + status: string; + buyerRealName: string; + sellerRealName: string; + ctime: string; + utime: string; + paymentInfo: { + paymethodName: string; + paymethodId: string; + paymethodInfo: { + name: string; + required: string; + type: string; + value: string; + }[]; + }; +} ⋮---- -// WARNING: for sensitive math you should be using a library such as decimal.js! -function roundDown(value, decimals) +export interface P2PMerchantAdvertismentV2 { + advId: string; + advNo: string; + side: string; + advSize: string; + size: string; + coin: string; + price: string; + coinPrecision: string; + fiat: string; + fiatPrecision: string; + fiatSymbol: string; + status: string; + hide: string; + maxTradeAmount: string; + minTradeAmount: string; + payDuration: string; + turnoverNum: string; + turnoverRate: string; + label: string | null; + userLimitList: { + minCompleteNum: string; + maxCompleteNum: string; + placeOrderNum: string; + allowMerchantPlace: string; + completeRate30d: string; + country: string; + }; + paymentMethodList: { + paymentMethod: string; + paymentId: string; + paymentInfo: { + name: string; + required: boolean; + type: string; + }[]; + }[]; + merchantCertifiedList: { + imageUrl: string; + desc: string; + }[]; + utime: string; + ctime: string; +} ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ +/** + * + * * Common | Trading insights + * + */ ⋮---- -// Add event listeners to log websocket events on account +export interface SpotWhaleNetFlowV2 { + volume: string; + date: string; +} ⋮---- -// Subscribe to private account topics +export interface FuturesActiveBuySellVolumeV2 { + buyVolume: string; + sellVolume: string; + ts: string; +} ⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +export interface FuturesActiveLongShortPositionV2 { + longPositionRatio: string; + shortPositionRatio: string; + longShortPositionRatio: string; + ts: string; +} ⋮---- -// const balances = allBalances.filter((bal) => Number(bal.available) != 0); +export interface LeveragedLongShortRatioV2 { + ts: string; + longShortRatio: string; +} ⋮---- -// console.log('balance: ', JSON.stringify(balances, null, 2)); +export interface MarginLoanGrowthRateV2 { + ts: string; + growthRate: string; +} ⋮---- -// const quantityRoundedDown = btcAmount - btcAmount % 0.01 - -================ -File: examples/deprecated-V1-Websockets/ws-public.ts -================ -import { DefaultLogger, WebsocketClientLegacyV1, WS_KEY_MAP } from '../../src'; +export interface IsolatedMarginBorrowingRatioV2 { + ts: string; + borrowRate: string; +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bitget-api'; +export interface FuturesLongShortRatioV2 { + longRatio: string; + shortRatio: string; + longShortRatio: string; + ts: string; +} ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, +export interface SpotFundFlowV2 { + whaleBuyVolume: string; + dolphinBuyVolume: string; + fishBuyVolume: string; + whaleSellVolume: string; + dolphinSellVolume: string; + fishSellVolume: string; + whaleBuyRatio: string; + dolphinBuyRatio: string; + fishBuyRatio: string; + whaleSellRatio: string; + dolphinSellRatio: string; + fishSellRatio: string; +} ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +export interface FuturesActiveLongShortAccountV2 { + longAccountRatio: string; + shortAccountRatio: string; + longShortAccountRatio: string; + ts: string; +} ⋮---- /** - * Public events - */ -⋮---- -// Spot public -// tickers -// wsClient.subscribeTopic('SP', 'ticker', symbol); -// // candles -// wsClient.subscribeTopic('SP', 'candle1m', symbol); -// // orderbook updates + * + * * Common | Virtual Subaccount + * + */ ⋮---- -// // trades -// wsClient.subscribeTopic('SP', 'trade', symbol); +export interface CreateVirtualSubAccountV2 { + failureList: { + subaAccountName: string; + }[]; + successList: { + subaAccountUid: string; + subaAccountName: string; + status: string; + label: string; + permList: string[]; + cTime: string; + uTime: string; + }[]; +} ⋮---- -// // Futures public -⋮---- -// // tickers -// wsClient.subscribeTopic('MC', 'ticker', symbol); -// // candles -// wsClient.subscribeTopic('MC', 'candle1m', symbol); -// // orderbook updates -// wsClient.subscribeTopic('MC', 'books', symbol); -// // trades -// wsClient.subscribeTopic('MC', 'trade', symbol); -⋮---- -// Topics are tracked per websocket type -// Get a list of subscribed topics (e.g. for spot topics) (after a 5 second delay) - -================ -File: examples/V2/rest-private-futures.ts -================ -import { RestClientV2 } from '../../src/index'; -⋮---- -// or -// import { RestClientV2 } from 'bitget-api'; +export interface CreateVirtualSubAccountAndApiKeyV2 { + subAccountUid: string; + subAccountName: string; + label: string; + subAccountApiKey: string; + secretKey: string; + permList: string[]; + ipList: string[]; +} ⋮---- -// read from environmental variables +export interface VirtualSubAccountV2 { + subAccountUid: string; + subAccountName: string; + status: string; + permList: string[]; + label: string; + accountType: string; + bindingTime: string; + cTime: string; + uTime: string; +} ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-futures.ts +export interface CreateVirtualSubAccountApiKeyV2 { + subAccountUid: string; + label: string; + subAccountApiKey: string; + secretKey: string; + permList: string[]; + ipList: string[]; +} ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +export interface ModifyVirtualSubAccountApiKeyV2 { + subAccountUid: string; + label: string; + subAccountApiKey: string; + secretKey: string; + permList: string[]; + ipList: string[]; +} ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +export interface SubAccountApiKeyItemV2 { + subAccountUid: string; + label: string; + subAccountApiKey: string; + permList: string[]; + ipList: string[]; +} ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ +/** + * + * * Common | Assets + * + */ ⋮---- -startTime: fromTime.getTime() + '', // should be sent as a string -endTime: now.getTime() + '', // should be sent as a string - -================ -File: examples/V2/rest-private-spot.ts -================ -import { RestClientV2 } from '../../src/index'; +export interface FundingAssetV2 { + coin: string; + available: string; + frozen: string; + usdtValue: string; +} ⋮---- -// or -// import { RestClientV2 } from 'bitget-api'; +export interface BotAssetV2 { + coin: string; + available: string; + equity: string; + bonus: string; + frozen: string; + usdtValue: string; +} ⋮---- -// read from environmental variables +/** + * + * * Common | Convert + * + */ ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-spot.ts +export interface ConvertCurrencyV2 { + coin: string; + available: string; + maxAmount: string; + minAmount: string; +} ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +export interface ConvertQuotedPriceV2 { + fee: string; + fromCoinSize: string; + fromCoin: string; + cnvtPrice: string; + toCoinSize: string; + toCoin: string; + traceId: string; +} ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +export interface ConvertTradeResponseV2 { + ts: string; + cnvtPrice: string; + toCoinSize: string; + toCoin: string; +} ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ - -================ -File: examples/V2/rest-public-futures.ts -================ -import { RestClientV2 } from '../../src/index'; +export interface ConvertRecordV2 { + id: string; + ts: string; + cnvtPrice: string; + fee: string; + fromCoinSize: string; + fromCoin: string; + toCoinSize: string; + toCoin: string; +} ⋮---- -// or -// import { RestClientV2 } from 'bitget-api'; +/** + * + * * Common | BGB Convert + * + */ ⋮---- -// Fetch the last 1000 1min candles for a symbol +export interface BGBConvertCoinV2 { + coin: string; + available: string; + bgbEstAmount: string; + precision: string; + feeDetail: { + feeRate: string; + fee: string; + }[]; + cTime: string; +} ⋮---- -const msPerCandle = 60 * 1000; // 60 seconds x 1000 - -================ -File: examples/V2/rest-public-spot.ts -================ -import { RestClientV2 } from '../../src/index'; +export interface ConvertBGBResponseV2 { + orderList: { + coin: string; + orderId: string; + }[]; +} ⋮---- -// or -// import { RestClientV2 } from 'bitget-api'; +export interface BGBConvertHistoryV2 { + orderId: string; + fromCoin: string; + fromAmount: string; + fromCoinPrice: string; + toCoin: string; + toAmount: string; + toCoinPrice: string; + feeDetail: { + feeCoin: string; + fee: string; + }[]; + status: string; + ctime: string; +} ================ -File: examples/V2/rest-trade-futures.ts +File: src/types/response/v2/copy-trading.ts ================ -import { - FuturesPlaceOrderRequestV2, - RestClientV2, - WebsocketClientV2, -} from '../../src'; -⋮---- -// or -// import { FuturesPlaceOrderRequestV2, RestClientV2, WebsocketClientV2 } from '../src'; -⋮---- -// read from environmental variables -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-futures.ts -⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed -⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', -⋮---- -function logWSEvent(type, data) -⋮---- -// simple sleep function -function promiseSleep(milliseconds) -⋮---- /** - * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). * - * It is designed to: - * - open a private websocket channel to log account events - * - check for any available USDT balance in the futures account - * - immediately open a minimum sized long position on BTCUSDT - * - check active positions - * - immediately send closing orders for any active futures positions - * - check positions again + * + * Copy Trading | Future copy trading | Trader Api + * * */ ⋮---- -// Add event listeners to log websocket events on account -⋮---- -// futures private -// : account updates -⋮---- -// : position updates -⋮---- -// : order updates -⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +export interface CTFuturesTraderCurrentOrderV2 { + trackingNo: string; + openOrderId: string; + symbol: string; + posSide: string; + openLeverage: string; + openPriceAvg: string; + openTime: string; + openSize: string; + presetStopSurplusPrice: string; + presetStopLossPrice: string; + openFee: string; + followCount: string; +} ⋮---- -// const balances = allBalances.filter((bal) => Number(bal.available) != 0); +export interface CTFuturesTraderCurrentOrdersV2 { + trackingList: CTFuturesTraderCurrentOrderV2[]; + endId: string; +} ⋮---- -// Loop through any active positions and send a closing market order on each position - -================ -File: examples/V2/rest-trade-spot.ts -================ -import { - RestClientV2, - SpotOrderRequestV2, - WebsocketClientV2, -} from '../../src/index'; -⋮---- -// import { RestClientV2, WebsocketClient } from '../src/index'; -⋮---- -// read from environmental variables +export interface CTFuturesTraderHistoryOrderV2 { + trackingNo: string; + symbol: string; + openOrderId: string; + closeOrderId: string; + productType: string; + posSide: string; + openLeverage: string; + openPriceAvg: string; + openTime: string; + openSize: string; + closeSize: string; + closeTime: string; + closePriceAvg: string; + stopType: string; + achievedPL: string; + openFee: string; + closeFee: string; + cTime: string; +} ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-spot.ts +export interface CTFuturesTraderHistoryOrderV2 { + trackingList: CTFuturesTraderHistoryOrderV2[]; + endId: string; +} ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +export interface CTRateCTimeV2 { + rate: string; + ctime: string; +} ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +export interface CTAmountCTimeV2 { + amount: string; + ctime: string; +} ⋮---- -function logWSEvent(type, data) +export interface CTFuturesTraderTotalOrderSummaryV2 { + roi: string; + tradingOrderNum: string; + totalFollowerNum: string; + currentFollowerNum: string; + totalpl: string; + gainNum: string; + lossNum: string; + winRate: string; + tradingPairsAvailableList: string[]; + lastWeekRoiList: CTRateCTimeV2[]; + lastWeekProfitList: CTAmountCTimeV2[]; + lastMonthRoiList: CTRateCTimeV2[]; + lastMonthProfitList: CTAmountCTimeV2[]; + totalEquity: string; +} ⋮---- -// simple sleep function -function promiseSleep(milliseconds) +export interface CTFuturesTraderProfitHistoryItemV2 { + coin: string; + profitCount: string; + lastProfitTime: string; +} ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ +export interface CTFuturesTraderHistoryProfitSummaryV2 { + profitSummary: { + yesterdayProfit: string; + sumProfit: string; + waitProfit: string; + yesterdayTime: string; + }; + profitHistoryList: CTFuturesTraderProfitHistoryItemV2[]; +} ⋮---- -// Add event listeners to log websocket events on account +export interface CTFuturesTraderProfitShare { + profitId: string; + coin: string; + profit: string; + nickName: string; + profitTime: string; +} ⋮---- -// Subscribe to private account topics -// spot private -// : account updates +export interface CTFuturesTraderProfitShareHistoryV2 { + profitList: CTFuturesTraderProfitShare[]; + endId: string; +} ⋮---- -// : order updates (note: symbol is required) +export interface CTFuturesTraderSymbolSettingsV2 { + symbol: string; + openTrader: string; + minOpenCount: string; + maxLeverage: string; + stopSurplusRatio: string; + stopLossRatio: string; +} ⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +export interface CTFuturesTraderMyFollowersV2 { + accountEquity: string; + isRemove: string; + followerHeadPic: string; + followerName: string; + followerUid: string; + followerTime: string; +} ⋮---- -// console.log('balance: ', JSON.stringify(balances, null, 2)); - -================ -File: examples/V2/ws-demo-trading.ts -================ -import { DefaultLogger, WebsocketClientV2 } from '../../src'; +/** + * + * + * Copy Trading | Future copy trading | Follower Api + * + * + */ ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +export interface CTFuturesFollowerCurrentOrdersV2 { + trackingNo: string; + traderName: string; + openOrderId: string; + closeOrderId: string; + traderId: string; + symbol: string; + posSide: string; + openLeverage: string; + openAvgPrice: string; + openTime: string; + openSize: string; + closeAvgPrice: string; + closeSize: string; + openMarginSz: string; + closeTime: string; +} ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +export interface CTFuturesFollowerHistoryOrderV2 { + trackingNo: string; + posSide: string; + openLeverage: string; + openSize: string; + closeSize: string; + openPriceAvg: string; + closePriceAvg: string; + achievedPL: string; + openFee: string; + closeFee: string; + symbol: string; + profitRate: string; + netProfit: string; + openOrderId: string; + closeOrderId: string; + openTime: string; + closeTime: string; + traderId: string; + productType: string; +} ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, +export interface CTFuturesFollowerHistoryOrdersV2 { + trackingList: CTFuturesFollowerHistoryOrderV2[]; + endId: string; +} ⋮---- -// Set demoTrading to true, to route all connections to the demo trading wss URLs: +export interface CTFuturesFollowerSettingV2 { + symbol: string; + productType: string; + marginType: string; + marginCoin: string; + leverType: string; + longLeverage: string; + shortLeverage: string; + traceType: string; +} ⋮---- -// If using private topics, make sure to include API keys +export interface CTFuturesFollowerSettingsV2 { + followerEnable: string; + detailList: CTFuturesFollowerSettingV2[]; +} ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +export interface CTFuturesFollowerMyTradersV2 { + certificationType: string; + traderId: string; + traderName: string; + maxFollowLimit: string; + followCount: string; + traceTotalMarginAmount: string; + traceTotalNetProfit: string; + traceTotalProfit: string; + currentTradingPairs: string[]; + followerTime: string; + bgbMaxFollowLimit: string; + bgbFollowCount: string; +} ⋮---- /** - * Public events - */ - -================ -File: examples/V2/ws-private.ts -================ -import { DefaultLogger, WebsocketClientV2 } from '../../src'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; + * + * + * Copy Trading | Spot copy trading | Trader api + * + * + */ ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +export interface CTSpotTraderProfitSummaryV2 { + profitSummarys: { + yesterdayProfit: string; + yesterdayTime: string; + sumProfit: string; + waitProfit: string; + }; + profitHistoryList: { + coin: string; + profitCount: string; + lastProfitTime: string; + historysByDateList: { + profit: string; + profitTime: string; + }[]; + }[]; +} ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +export interface CTSpotTraderHistoryProfitShareItemV2 { + profitId: string; + coin: string; + distributeRatio: string; + profit: string; + followerName: string; + profitTime: string; +} ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, -⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); -⋮---- -// auth happens async after the ws connection opens -⋮---- -// wsClient.subscribePublicSpotTickers(['BTCUSDT', 'LTCUSDT']); -⋮---- -/** - * Private account updates - */ -⋮---- -// spot private -// : account updates -⋮---- -// : order updates (note: symbol is required) -// wsClient.subscribeTopic('SPOT', 'orders', 'BTCUSDT'); -⋮---- -// futures private -// : account updates -⋮---- -// : position updates -// wsClient.subscribeTopic('USDT-FUTURES', 'positions'); -⋮---- -// : order updates -// wsClient.subscribeTopic('USDT-FUTURES', 'orders'); -⋮---- -// : plan order updates -// wsClient.subscribeTopic('USDT-FUTURES', 'orders-algo'); +export interface CTSpotTraderHistoryProfitSharingV2 { + endId: string; + profitList: CTSpotTraderHistoryProfitShareItemV2[]; +} ⋮---- -// wsClient -// .getWsStore() -// .getKeys() -// .forEach((wsKey) => { -// const state = wsClient.getWsStore().get(wsKey); -// console.log(`${wsKey} state: `, state.subscribedTopics.values()); -// }); +export interface CTSpotTraderUnrealizedProfitV2 { + distributeRatio: string; + coin: string; + profit: string; + followerName: string; +} ⋮---- -// setTimeout(() => { -// wsClient.unsubscribeTopic('USDT-FUTURES', 'account'); -// }, 1000 * 2); +export interface CTSpotTraderTotalOrderDetailV2 { + totalFollowerNum: string; + currentFollowerNum: string; + maxFollowerNum: string; + tradingOrderNum: string; + totalpl: string; + gainNum: string; + lossNum: string; + totalEquity: string; + winRate: string; + lastWeekRoiList: CTAmountCTimeV2[]; + lastMonthRoiList: CTRateCTimeV2[]; + lastWeekProfitList: CTAmountCTimeV2[]; + lastMonthProfitList: CTAmountCTimeV2[]; +} ⋮---- -// setTimeout(() => { -// wsClient -// .getWsStore() -// .getKeys() -// .forEach((wsKey) => { -// const state = wsClient.getWsStore().get(wsKey); -// console.log(`${wsKey} state: `, state.subscribedTopics.values()); -// }); -// }, 1000 * 5); - -================ -File: examples/V2/ws-public.ts -================ -import { DefaultLogger, WebsocketClientV2, WS_KEY_MAP } from '../../src'; +export interface CTSpotTraderHistoryOrderV2 { + trackingNo: string; + fillSize: string; + buyPrice: string; + sellPrice: string; + achievedPL: string; + buyTime: string; + sellTime: string; + buyFee: string; + sellFee: string; + achievedPLR: string; + symbol: string; + netProfit: string; + followCount: string; +} +export interface CTSpotTraderHistoryOrdersV2 { + endId: string; + trackingList: CTSpotTraderHistoryOrderV2[]; +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +export interface CTSpotTraderCurrentTrackingOrderV2 { + trackingNo: string; + orderId: string; + buyFillSize: string; + buyDelegateSize: string; + buyPrice: string; + unrealizedPL: string; + buyTime: string; + buyFee: string; + unrealizedPLR: string; + symbol: string; + stopLossPrice: string | null; + stopSurplusPrice: string | null; + followCount: string; +} ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, +export interface CTSpotTraderCurrentTrackingOrdersV2 { + endId: string; + trackingList: CTSpotTraderCurrentTrackingOrderV2[]; +} ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +export interface CTSpotTraderFollowerListV2 { + accountEquity: string; + isRemove: string; + followerHeadPic: string | null; + followerName: string; + followerUid: string; + followerTime: string; +} ⋮---- /** - * Public events - */ -⋮---- -// Spot public -⋮---- -// tickers -⋮---- -// candles -// wsClient.subscribeTopic('SPOT', 'candle1m', symbol); + * + * + * Copy Trading | Spot copy trading | Follower api + * + * + */ ⋮---- -// orderbook updates -// wsClient.subscribeTopic('SPOT', 'books', symbol); +export interface CTSpotFollowerMyTraderV2 { + certificationType: string; + traceTotalAmount: string; + traceTotalNetProfit: string; + traceTotalProfit: string; + traderName: string; + traderId: string; + maxFollowLimit: string; + bgbMaxFollowLimit: string; + followCount: string; + bgbFollowCount: string; + followerTime: string; +} ⋮---- -// trades -// wsClient.subscribeTopic('SPOT', 'trade', symbol); +export interface CTSpotFollowerMyTradersV2 { + resultList: CTSpotFollowerMyTraderV2[]; +} ⋮---- -// Futures public +export interface CTSpotFollowerTradeSettingV2 { + maxTraceAmount: string; + stopLossRation: string; + stopSurplusRation: string; + symbol: string; + traceType: string; +} ⋮---- -// tickers -// wsClient.subscribeTopic('USDT-FUTURES', 'ticker', symbol); +export interface CTSpotFollowerTradeSymbolSettingV2 { + maxStopLossRation: string; + maxStopSurplusRation: string; + maxTraceAmount: string; + maxTraceAmountSystem: string; + maxTraceSize: string; + maxTraceRation: string; + minStopLossRation: string; + minStopSurplusRation: string; + minTraceAmount: string; + minTraceSize: string; + minTraceRation: string; + sliderMaxStopLossRatio: string; + sliderMaxStopSurplusRatio: string; + symbol: string; +} ⋮---- -// candles -// wsClient.subscribeTopic('USDT-FUTURES', 'candle1m', symbol); +export interface CTSpotFollowerFollowConfigurationV2 { + enable: string; + profitRate: string; + settledInDays: string; + tradeSettingList: CTSpotFollowerTradeSettingV2[]; + tradeSymbolSettingList: CTSpotFollowerTradeSymbolSettingV2[]; + traderHeadPic: string; + traderName: string; +} ⋮---- -// orderbook updates -// wsClient.subscribeTopic('USDT-FUTURES', 'books', symbol); +export interface CTSpotFollowerHistoryOrderV2 { + trackingNo: string; + traderId: string; + fillSize: string; + buyPrice: string; + sellPrice: string; + buyFee: string; + sellFee: string; + achievedPL: string; + achievedPLR: string; + symbol: string; + buyTime: string; + sellTime: string; +} +export interface CTSpotFollowerHistoryOrdersV2 { + endId: string; + trackingList: CTSpotFollowerHistoryOrderV2[]; +} ⋮---- -// trades -// wsClient.subscribeTopic('USDT-FUTURES', 'trade', symbol); +export interface CTSpotFollowerCurrentOrderV2 { + trackingNo: string; + traderId: string; + buyFillSize: string; + buyDelegateSize: string; + buyPrice: string; + unrealizedPL: string; + buyTime: string; + buyFee: string; + unrealizedPLR: string; + symbol: string; + stopSurplusPrice: string | null; + stopLossPrice: string | null; +} ⋮---- -// Topics are tracked per websocket type -// Get a list of subscribed topics (e.g. all public topics) (after a 5 second delay) +export interface CTSpotFollowerCurrentOrdersV2 { + endId: string; + trackingList: CTSpotFollowerCurrentOrderV2[]; +} ================ -File: examples/V3/rest-private.ts +File: src/types/response/v2/earn.ts ================ -import { RestClientV3 } from '../../src/index'; +/** + * + * + * Earn | Savings + * + * + */ ⋮---- -// or -// import { RestClientV3 } from 'bitget-api'; -⋮---- -// read from environmental variables +export interface EarnSavingsProductsV2 { + productId: string; + coin: string; + periodType: string; + period: string; + apyType: string; + advanceRedeem: string; + settleMethod: string; + apyList: { + rateLevel: string; + minStepVal: string; + maxStepVal: string; + currentApy: string; + }[]; + status: string; + productLevel: string; +} ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-private-futures.ts +export interface EarnSavingsAccountV2 { + btcAmount: string; + usdtAmount: string; + btc24hEarning: string; + usdt24hEarning: string; + btcTotalEarning: string; + usdtTotalEarning: string; +} ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +export interface EarnSavingsAssetV2 { + productId: string; + orderId: string; + productCoin: string; + interestCoin: string; + periodType: string; + period: string; + holdAmount: string; + lastProfit: string; + totalProfit: string; + holdDays: string; + status: string; + allowRedemption: string; + productLevel: string; + apy: { + rateLevel: string; + minApy: string; + maxApy: string; + currentApy: string; + }[]; +} ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +export interface EarnSavingsAssetsV2 { + resultList: EarnSavingsAssetV2[]; + endId: string; +} ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check account assets for futures trading */ - -================ -File: examples/V3/rest-public-UTA-futures.ts -================ -import { RestClientV3 } from '../../src/index'; +export interface EarnSavingsRecordV2 { + orderId: string; + coinName: string; + settleCoinName: string; + productType: string; + period: string; + productLevel: string; + amount: string; + ts: string; + orderType: string; +} ⋮---- -// or -// import { RestClientV3 } from 'bitget-api'; - -================ -File: examples/V3/rest-public-UTA-spot.ts -================ -import { RestClientV3 } from '../../src/index'; +export interface EarnSavingsRecordsV2 { + resultList: EarnSavingsRecordV2[]; + endId: string; +} ⋮---- -// or -// import { RestClientV3 } from 'bitget-api'; - -================ -File: examples/V3/ws-api-client-trade.ts -================ -import { DefaultLogger } from '../../src'; -import { WebsocketAPIClient } from '../../src/websocket-api-client'; +export interface EarnSavingsSubscriptionDetailV2 { + singleMinAmount: string; + singleMaxAmount: string; + remainingAmount: string; + subscribePrecision: string; + profitPrecision: string; + subscribeTime: string; + interestTime: string; + settleTime: string; + expireTime: string; + redeemTime: string; + settleMethod: string; + apyList: { + rateLevel: string; + minStepVal: string; + maxStepVal: string; + currentApy: string; + }[]; + redeemDelay: string; +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketAPIClient } from 'bitget-api'; +/** + * + * + * Earn | Earn Account + * + * + */ ⋮---- -// function attachEventHandlers( -// wsClient: TWSClient, -// ): void { -// wsClient.on('update', (data) => { -// console.log('raw message received ', JSON.stringify(data)); -// }); -// wsClient.on('open', (data) => { -// console.log('ws connected', data.wsKey); -// }); -// wsClient.on('reconnect', ({ wsKey }) => { -// console.log('ws automatically reconnecting.... ', wsKey); -// }); -// wsClient.on('reconnected', (data) => { -// console.log('ws has reconnected ', data?.wsKey); -// }); -// wsClient.on('authenticated', (data) => { -// console.log('ws has authenticated ', data?.wsKey); -// }); -// } +/** + * + * + * Earn | Shark Fin + * + * + */ ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +export interface EarnSharkfinProductV2 { + productId: string; + productName: string; + productCoin: string; + subscribeCoin: string; + farmingStartTime: string; + farmingEndTime: string; + lowerRate: string; + defaultRate: string; + upperRate: string; + period: string; + interestStartTime: string; + status: string; + minAmount: string; + limitAmount: string; + soldAmount: string; + endTime: string; + startTime: string; +} ⋮---- -// Whether to use the demo trading wss connection -// demoTrading: true, +export interface EarnSharkfinProductsV2 { + resultList: EarnSharkfinProductV2[]; + endId: string; +} ⋮---- -// If you want your own event handlers instead of the default ones with logs, -// disable this setting and see the `attachEventHandlers` example below: -// attachEventListeners: false +export interface EarnSharkfinAccountV2 { + btcSubscribeAmount: string; + usdtSubscribeAmount: string; + btcHistoricalAmount: string; + usdtHistoricalAmount: string; + btcTotalEarning: string; + usdtTotalEarning: string; +} ⋮---- -logger, // Optional: inject a custom logger +export interface EarnSharkfinAssetV2 { + productId: string; + interestStartTime: string; + interestEndTime: string; + productCoin: string; + subscribeCoin: string; + trend: string; + settleTime: string; + interestAmount: string; + productStatus: string; +} ⋮---- -// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled -// attachEventHandlers(wsClient.getWSClient()); +export interface EarnSharkfinAssetsV2 { + resultList: EarnSharkfinAssetV2[]; + endId: string; +} ⋮---- -// Optional: prepare the WebSocket API connection in advance. -// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. +export interface EarnSharkfinRecordV2 { + orderId: string; + product: string; + period: string; + amount: string; + ts: string; + type: string; +} +export interface EarnSharkfinRecordsV2 { + resultList: EarnSharkfinRecordV2[]; + endId: string; +} ⋮---- -/** - * Bitget's WebSocket API be used like a REST API, through this SDK's WebsocketAPIClient. The WebsocketAPIClient is a utility class wrapped around WebsocketClientV3's sendWSAPIRequest() capabilities. - * - * Each request sent via the WebsocketAPIClient will automatically: - * - route via the active WS API connection - * - return a Promise, which automatically resolves/rejects when a matching response is received - * - * Note: this requires V3/UTA API keys! - */ +export interface EarnSharkfinSubscriptionDetailV2 { + productCoin: string; + subscribeCoin: string; + interestTime: string; + expirationTime: string; + minPrice: string; + currentPrice: string; + maxPrice: string; + minRate: string; + defaultRate: string; + maxRate: string; + period: string; + productMinAmount: string; + availableBalance: string; + userAmount: string; + remainingAmount: string; + profitPrecision: string; + subscribePrecision: string; +} ⋮---- /** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - */ + * + * + * Earn | Loan + * + * + */ ⋮---- -/** - const res = { - "event": "trade", - "id": "1750034396082", - "category": "spot", - "topic": "place-order", - "args": [ - { - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx", - "cTime": "1750034397008" - } - ], - "code": "0", - "msg": "success", - "ts": "1750034397076" - }; - */ -⋮---- -/** - * Batch Place Order Channel - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - */ +export interface EarnLoanCurrencyLoanInfoV2 { + coin: string; + hourRate7D: string; + rate7D: string; + hourRate30D: string; + rate30D: string; + minUsdt: string; + maxUsdt: string; + min: string; + max: string; +} +export interface EarnLoanCurrencyPledgeInfoV2 { + coin: string; + initRate: string; + supRate: string; + forceRate: string; + minUsdt: string; + maxUsdt: string; +} ⋮---- -/** - * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. - */ +export interface EarnLoanCurrenciesV2 { + loanInfos: EarnLoanCurrencyLoanInfoV2[]; + pledgeInfos: EarnLoanCurrencyPledgeInfoV2[]; +} ⋮---- -/** - const res = { - "event": "trade", - "id": "1750035029506", - "category": "spot", - "topic": "batch-place", - "args": [ - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - }, - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750035029925" - } - */ +export interface EarnLoanOrdersV2 { + orderId: string; + loanCoin: string; + loanAmount: string; + interestAmount: string; + hourInterestRate: string; + pledgeCoin: string; + pledgeAmount: string; + pledgeRate: string; + supRate: string; + forceRate: string; + borrowTime: string; + expireTime: string; +} ⋮---- -/** - * Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - */ +export interface EarnLoanRepayResponseV2 { + loanCoin: string; + pledgeCoin: string; + repayAmount: string; + payInterest: string; + repayLoanAmount: string; + repayUnlockAmount: string; +} ⋮---- -/** - const res = { - "event": "trade", - "id": "1750034870205", - "topic": "cancel-order", - "args": [ - { - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750034870597" - } - */ +export interface EarnLoanRepayHistoryV2 { + orderId: string; + loanCoin: string; + pledgeCoin: string; + repayAmount: string; + payInterest: string; + repayLoanAmount: string; + repayUnlockAmount: string; + repayTime: string; +} ⋮---- -/** - * Batch Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - */ +export interface EarnLoanPledgeRateHistoryV2 { + loanCoin: string; + pledgeCoin: string; + orderId: string; + reviseTime: string; + reviseSide: string; + reviseAmount: string; + afterPledgeRate: string; + beforePledgeRate: string; +} ⋮---- -/** - const res = { - "event": "trade", - "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", - "topic": "batch-cancel", - "args": [ - { - "code": "0", - "msg": "Success", - "orderId": "xxxxxxxxxxxxx" - }, - { - "code": "25204", - "msg": "Order does not exist", - "orderId": "xxxxxxxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1751980011084" - } - */ - -================ -File: examples/V3/ws-api-trade-raw.ts -================ -import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; +export interface EarnLoanHistoryV2 { + orderId: string; + loanCoin: string; + pledgeCoin: string; + initPledgeAmount: string; + initLoanAmount: string; + hourRate: string; + daily: string; + borrowTime: string; + status: string; +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV3 } from 'bitget-api'; +export interface EarnLoanDebtPledgeInfoV2 { + coin: string; + amount: string; + amountUsdt: string; +} ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +export interface EarnLoanDebtLoanInfoV2 { + coin: string; + amount: string; + amountUsdt: string; +} ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +export interface EarnLoanDebtsV2 { + pledgeInfos: EarnLoanDebtPledgeInfoV2[]; + loanInfos: EarnLoanDebtLoanInfoV2[]; +} ⋮---- +export interface EarnLoanLiquidationRecordsV2 { + orderId: string; + loanCoin: string; + pledgeCoin: string; + reduceTime: string; + pledgeRate: string; + pledgePrice: string; + status: string; + pledgeAmount: string; + reduceFee: string; + residueAmount: string; + runlockAmount: string; + repayLoanAmount: string; +} + +================ +File: src/types/response/v2/margin.ts +================ /** - * Bitget's WebSocket API can be used via the sendWSAPIRequest() method. - * - * Use the `WS_KEY_MAP.v3Private` connection key for any requests. - * - * Note: this requires V3/UTA API keys! - * Note: for a better user experience, it is recommended to use the WebsocketAPIClient. - */ + * + * * Margin | Common + * + */ ⋮---- -// Use the V3 private wss connection URL +export interface MarginCurrencyV2 { + symbol: string; + baseCoin: string; + quoteCoin: string; + maxCrossedLeverage: string; + maxIsolatedLeverage: string; + warningRiskRatio: string; + liquidationRiskRatio: string; + minTradeAmount: string; + maxTradeAmount: string; + takerFeeRate: string; + makerFeeRate: string; + pricePrecision: string; + quantityPrecision: string; + minTradeUSDT: string; + isBorrowable: boolean; + userMinBorrow: string; + status: string; + isIsolatedBaseBorrowable: boolean; + isIsolatedQuoteBorrowable: boolean; + isCrossBorrowable: boolean; +} ⋮---- /** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "1750034396082", - "category": "spot", - "topic": "place-order", - "args": [ - { - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx", - "cTime": "1750034397008" - } - ], - "code": "0", - "msg": "success", - "ts": "1750034397076" - }; - */ -⋮---- -/** - * Batch Place Order Channel - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - */ -⋮---- -/** - * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "1750035029506", - "category": "spot", - "topic": "batch-place", - "args": [ - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - }, - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750035029925" - } - */ -⋮---- -/** - * Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - */ + * + * * Margin | Cross/Isolated | Order Record + * + */ ⋮---- -/** - const res = { - "event": "trade", - "id": "1750034870205", - "topic": "cancel-order", - "args": [ - { - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750034870597" - } - */ +export interface MarginBorrowHistoryItemV2 { + loanId: string; + coin: string; + borrowAmount: string; + borrowType: string; + cTime: string; + uTime: string; +} ⋮---- -/** - * Batch Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - */ +export interface MarginRepaymentHistoryItemV2 { + repayId: string; + coin: string; + repayAmount: string; + repayType: string; + repayInterest: string; + repayPrincipal: string; + symbol: string; + cTime: string; + uTime: string; +} ⋮---- -/** - const res = { - "event": "trade", - "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", - "topic": "batch-cancel", - "args": [ - { - "code": "0", - "msg": "Success", - "orderId": "xxxxxxxxxxxxx" - }, - { - "code": "25204", - "msg": "Order does not exist", - "orderId": "xxxxxxxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1751980011084" - } - */ - -================ -File: examples/V3/ws-public.ts -================ -import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; +export interface MarginInterestHistoryItemV2 { + interestId: string; + interestCoin: string; + dailyInterestRate: string; + loanCoin: string; + interestAmount: string; + interstType: string; + symbol: string; + cTime: string; + uTime: string; +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +export interface MarginLiquidationHistoryItemV2 { + liqId: string; + symbol: string; + liqStartTime: string; + liqEndTime: string; + liqRiskRatio: string; + totalAssets: string; + totalDebt: string; + liqFee: string; + cTime: string; + uTime: string; +} ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +export interface MarginFinancialHistoryItemV2 { + coin: string; + symbol: string; + marginId: string; + amount: string; + balance: string; + fee: string; + marginType: string; + cTime: string; + uTime: string; +} ⋮---- /** - * Public events - */ -⋮---- -// You can subscribe to one topic at a time -⋮---- -WS_KEY_MAP.v3Public, // This parameter points to private or public -⋮---- -// Or multiple at once: -⋮---- -// Topics are tracked per websocket type -// The below example will pull a list of subscribed topics on that connection (e.g. all public topics), after a 5 second delay: - -================ -File: src/types/request/v1/futuresV1.ts -================ -import { OrderTimeInForce } from '../shared.js'; -⋮---- -export type FuturesProductType = - | 'umcbl' - | 'dmcbl' - | 'cmcbl' - | 'sumcbl' - | 'sdmcbl' - | 'scmcbl'; -⋮---- -export type FuturesKlineInterval = - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1H' - | '2H' - | '4H' - | '6H' - | '12H' - | '1D' - | '3D' - | '1W' - | '1M' - | '6Hutc' - | '12Hutc' - | '1Dutc' - | '3Dutc' - | '1Wutc' - | '1Mutc'; -⋮---- -export type FuturesHoldSide = 'long' | 'short'; -⋮---- -export type FuturesMarginMode = 'fixed' | 'crossed'; -⋮---- -export type FuturesHoldMode = 'double_hold' | 'single_hold'; + * + * * Margin | Cross/Isolated | Account + * + */ ⋮---- -export interface FuturesAccountBillRequest { +export interface MarginAccountAssetV2 { symbol: string; - marginCoin: string; - startTime: string; - endTime: string; - pageSize?: number; - lastEndId?: string; - next?: boolean; + coin: string; + totalAmount: string; + available: string; + frozen: string; + borrow: string; + interest: string; + net: string; + coupon: string; + cTime: string; + uTime: string; } ⋮---- -export interface FuturesBusinessBillRequest { - productType: FuturesProductType; - startTime: string; - endTime: string; - pageSize?: number; - lastEndId?: string; - next?: boolean; +export interface CrossMaxBorrowableResponseV2 { + coin: string; + maxBorrowableAmount: string; } ⋮---- -export type FuturesOrderType = 'limit' | 'market'; -export type FuturesOrderSide = - | 'open_long' - | 'open_short' - | 'close_long' - | 'close_short' - | 'buy_single' - | 'sell_single'; -⋮---- -export interface NewFuturesOrder { +export interface IsolatedMaxBorrowableResponseV2 { symbol: string; - productType: string; - marginCoin: string; - size?: string; - quantity?: string; - price?: string; - side: FuturesOrderSide; - orderType: FuturesOrderType; - timeInForceValue?: OrderTimeInForce; - clientOid?: string; - reduceOnly?: boolean; - reverse?: boolean; - presetTakeProfitPrice?: string; - presetStopLossPrice?: string; + baseCoin: string; + baseCoinMaxBorrowAmount: string; + quoteCoin: string; + quoteCoinMaxBorrowAmount: string; } ⋮---- -export interface NewBatchFuturesOrder { - size: string; - price?: string; - side: string; - orderType: string; - timeInForceValue?: string; - clientOid?: string; +export interface CrossMaxTransferableResponseV2 { + coin: string; + maxTransferOutAmount: string; } ⋮---- -export interface ModifyFuturesOrder { +export interface IsolatedMaxTransferableResponseV2 { + baseCoin: string; symbol: string; - orderId?: string; - clientOid?: string; - newClientOid?: string; - size?: string; - price?: string; - presetTakeProfitPrice?: string; - presetStopLossPrice?: string; -} -⋮---- -export interface FuturesHistoricPositions { - startTime: string; - endTime: string; - productType?: FuturesProductType; - symbol?: string; - pageSize?: number; - lastEndId?: string; + baseCoinMaxTransferOutAmount: string; + quoteCoin: string; + quoteCoinMaxTransferOutAmount: string; } ⋮---- -export interface FuturesPagination { - startTime?: string; - endTime?: string; - lastEndId?: string; +export interface CrossInterestRateAndLimitResponseV2 { + transferable: boolean; + leverage: string; + coin: string; + borrowable: boolean; + dailyInterestRate: string; + annualInterestRate: string; + maxBorrowableAmount: string; + vipList: { + level: string; + limit: string; + dailyInterestRate: string; + annualInterestRate: string; + discountRate: string; + }[]; } ⋮---- -export interface NewFuturesPlanOrder { +export interface IsolatedInterestRateAndLimitResponseV2 { symbol: string; - marginCoin: string; - size: string; - executePrice?: string; - triggerPrice: string; - triggerType: 'fill_price' | 'market_price'; - side: FuturesOrderSide; - orderType: FuturesOrderType; - clientOid?: string; - presetTakeProfitPrice?: string; - presetStopLossPrice?: string; - reduceOnly?: string; + leverage: string; + baseCoin: string; + baseTransferable: boolean; + baseBorrowable: boolean; + baseDailyInterestRate: string; + baseAnnuallyInterestRate: string; + baseMaxBorrowableAmount: string; + baseVipList: { + level: string; + dailyInterestRate: string; + limit: string; + annuallyInterestRate: string; + discountRate: string; + }[]; + quoteCoin: string; + quoteTransferable: boolean; + quoteBorrowable: boolean; + quoteDailyInterestRate: string; + quoteAnnuallyInterestRate: string; + quoteMaxBorrowableAmount: string; + quoteList: { + level: string; + dailyInterestRate: string; + limit: string; + annuallyInterestRate: string; + discountRate: string; + }[]; } ⋮---- -export interface ModifyFuturesPlanOrder { - orderId: string; - marginCoin: string; - symbol: string; - executePrice?: string; - triggerPrice: string; - triggerType: 'fill_price' | 'market_price'; - orderType: FuturesOrderType; +export interface CrossTierConfigurationResponseV2 { + tier: string; + leverage: string; + coin: string; + maxBorrowableAmount: string; + maintainMarginRate: string; } ⋮---- -export interface ModifyFuturesPlanOrderTPSL { - orderId?: string; - clientOid?: string; - marginCoin: string; +export interface IsolatedTierConfigurationResponseV2 { + tier: string; symbol: string; - presetTakeProfitPrice?: string; - presetStopLossPrice?: string; + leverage: string; + baseCoin: string; + quoteCoin: string; + baseMaxBorrowableAmount: string; + quoteMaxBorrowableAmount: string; + maintainMarginRate: string; + initRate: string; } ⋮---- -export type FuturesPlanType = - | 'profit_plan' - | 'loss_plan' - | 'normal_plan' - | 'pos_profit' - | 'pos_loss' - | 'moving_plan' - | 'track_plan'; -⋮---- -export interface NewFuturesPlanStopOrder { - symbol: string; - marginCoin: string; - planType: FuturesPlanType; - triggerPrice: string; - triggerType?: 'fill_price' | 'market_price'; - holdSide: FuturesHoldSide; - size?: string; - rangeRate?: string; - clientOid?: string; -} +/** + * + * * Margin | Cross/Isolated | Trade + * + */ ⋮---- -export interface NewFuturesPlanTrailingStopOrder { - symbol: string; - marginCoin: string; - triggerPrice: string; - triggerType?: 'fill_price' | 'market_price'; - size?: string; - side: FuturesOrderSide; - rangeRate?: string; - clientOid?: string; +export interface MarginBatchOrdersResponseV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + clientOid: string; + errorMsg: string; + }[]; } ⋮---- -export interface NewFuturesPlanPositionTPSL { +export interface MarginCurrentOrderV2 { + orderId: string; symbol: string; - marginCoin: string; - planType: FuturesPlanType; - triggerPrice: string; - triggerType?: 'fill_price' | 'market_price'; - holdSide: FuturesHoldSide; - clientOid?: string; + orderType: string; + enterPointSource: string; + clientOid: string; + loanType: string; + price: string; + side: string; + status: string; + baseSize: string; + quoteSize: string; + priceAvg: string; + size: string; + amount: string; + force: string; + cTime: string; + uTime: string; } ⋮---- -export interface ModifyFuturesPlanStopOrder { - orderId?: string; - clientOid?: string; - marginCoin: string; +export interface MarginHistoryOrderV2 { + orderId: string; symbol: string; - triggerPrice?: string; - planType: FuturesPlanType; + orderType: string; + enterPointSource: string; + clientOid: string; + loanType: string; + price: string; + side: string; + status: string; + baseSize: string; + quoteSize: string; + priceAvg: string; + size: string; + amount: string; + force: string; + cTime: string; + uTime: string; } ⋮---- -export interface CancelFuturesPlanTPSL { - orderId?: string; - clientOid?: string; - symbol: string; - marginCoin: string; - planType: FuturesPlanType; +export interface MarginOrderFillV2 { + orderId: string; + tradeId: string; + orderType: string; + side: string; + priceAvg: string; + size: string; + amount: string; + tradeScope: string; + feeDetail: { + deduction: string; + feeCoin: string; + totalDeductionFee: string; + totalFee: string; + }; + cTime: string; + uTime: string; } ⋮---- -export interface HistoricPlanOrderTPSLRequest { +export interface MarginLiquidationOrderV2 { symbol: string; - startTime: string; - endTime: string; - pageSize?: number; - isPre?: boolean; - isPlan?: string; + orderType: string; + side: string; + priceAvg: string; + price: string; + fillSize: string; + size: string; + amount: string; + orderId: string; + fromCoin: string; + toCoin: string; + fromSize: string; + toSize: string; + cTime: string; + uTime: string; } -⋮---- -/** - * @typedef {string[6]} FuturesCandleData - * @property {Array[0]} Timestamp in milliseconds - * @property {Array[1]} Opening price - * @property {Array[2]} Highest price - * @property {Array[3]} Lowest price - * @property {Array[4]} Closing price - Value of the latest candle stick might change - * @property {Array[5]} Base currency trading volume - * @property {Array[6]} Quote currency trading volume - */ -export type FuturesCandleData = string[6]; ================ -File: src/types/request/v1/spotV1.ts +File: src/types/response/v2/spot.ts ================ -import { OrderTimeInForce } from '../shared.js'; -⋮---- -export type WalletType = 'spot' | 'mix_usdt' | 'mix_usd'; +/** + * + * * Spot | Market + * + */ ⋮---- -export type SpotKlineInterval = - | '1min' - | '5min' - | '15min' - | '30min' - | '1h' - | '4h' - | '6h' - | '12h' - | '1day' - | '3day' - | '1week' - | '1M' - | '6Hutc' - | '12Hutc' - | '1Dutc' - | '3Dutc' - | '1Wutc' - | '1Mutc'; +export interface SpotCoinChainV2 { + chain: string; + needTag: boolean; + withdrawable: boolean; + rechargeable: boolean; + withdrawFee: string; + extraWithdrawFee: string; + depositConfirm: string; + withdrawConfirm: string; + minDepositAmount: string; + minWithdrawAmount: string; + browserUrl: string; + contractAddress: string; + withdrawStep: string; + withdrawMinScale: string; + congestion: string; +} ⋮---- -export interface NewWalletTransfer { - fromType: WalletType; - toType: WalletType; - amount: string; +export interface SpotCoinInfoV2 { + coinId: string; coin: string; - clientOid?: string; + transfer: boolean; + chains: SpotCoinChainV2[]; } ⋮---- -export interface NewSpotSubTransfer { - fromType: WalletType; - toType: WalletType; - amount: string; - coin: string; - clientOid: string; - fromUserId: string; - toUserId: string; -} -⋮---- -export interface NewSpotWithdraw { - coin: string; - address: string; - chain: string; - tag?: string; - amount: string; - remark?: string; - clientOid?: string; -} -⋮---- -export interface NewSpotOrder { +export interface SpotSymbolInfoV2 { symbol: string; - side: 'buy' | 'sell'; - orderType: 'limit' | 'market'; - force: OrderTimeInForce; - price?: string; - size?: string; - quantity?: string; - clientOrderId?: string; + baseCoin: string; + quoteCoin: string; + minTradeAmount: string; + maxTradeAmount: string; + takerFeeRate: string; + makerFeeRate: string; + pricePrecision: string; + quantityPrecision: string; + quotePrecision: string; + minTradeUSDT: string; + status: string; + buyLimitPriceRatio: string; + sellLimitPriceRatio: string; + orderQuantity: string; + areaSymbol: string; } ⋮---- -export type NewBatchSpotOrder = Omit; -⋮---- -export interface CancelSpotOrderV2 { - symbol: string; - orderId?: string; - clientOid?: string; +export interface SpotVipFeeRateV2 { + level: number; + dealAmount: string; + assetAmount: string; + takerFeeRate: string; + makerFeeRate: string; + btcWithdrawAmount: string; + usdtWithdrawAmount: string; } ⋮---- -export interface BatchCancelSpotOrderV2 { +export interface SpotTickerV2 { symbol: string; - orderIds?: string[]; - clientOids?: string[]; + high24h: string; + open: string; + low24h: string; + lastPr: string; + quoteVolume: string; + baseVolume: string; + usdtVolume: string; + bidPr: string; + askPr: string; + bidSz: string; + askSz: string; + openUtc: string; + ts: string; + changeUtc24h: string; + change24h: string; } ⋮---- -export interface NewSpotPlanOrder { - symbol: string; - side: 'buy' | 'sell'; - triggerPrice: number; - executePrice?: number; - size: number; - triggerType: 'fill_price' | 'market_price'; - orderType: 'limit' | 'market'; - clientOid?: string; - timeInForceValue?: string; +export interface SpotMergeDepthV2 { + asks: [string, string][]; + bids: [string, string][]; + ts: string; + scale: string; + precision: string; + isMaxPrecision: string; } ⋮---- -export interface ModifySpotPlanOrder { - orderId?: string; - clientOid?: string; - triggerPrice: number; - executePrice?: number; - size?: string; - orderType: 'limit' | 'market'; +export interface SpotOrderBookDepthV2 { + asks: [string, string][]; + bids: [string, string][]; + ts: string; } ⋮---- -export interface CancelSpotPlanOrderParams { - orderId?: string; - clientOid?: string; -} +export type SpotCandlestickV2 = [ + string, // timestamp + string, // open + string, // high + string, // low + string, // close + string, // baseVolume + string, // usdtVolume + string, // quoteVolume +]; ⋮---- -export interface GetSpotPlanOrdersParams { - symbol: string; - pageSize: string; - lastEndId?: string; -} +string, // timestamp +string, // open +string, // high +string, // low +string, // close +string, // baseVolume +string, // usdtVolume +string, // quoteVolume ⋮---- -export interface GetHistoricPlanOrdersParams { +export interface SpotTradeV2 { symbol: string; - pageSize: string; - lastEndId?: string; - startTime: string; - endTime: string; -} -⋮---- -export interface SpotCandleData { - open: string; - high: string; - low: string; - close: string; - quoteVol: string; - baseVol: string; - usdtVol: string; + tradeId: string; + side: string; + price: string; + size: string; ts: string; } - -================ -File: src/types/request/v2/common.ts -================ -import { FuturesProductTypeV2, MarginType } from '../shared.js'; ⋮---- /** * - * * Common | Notice + * * Spot | Trade * */ ⋮---- -export interface GetAnnouncementsRequestV2 { - annType?: string; - startTime?: string; - endTime?: string; - language: string; +export interface CancelAndSubmitSpotOrderResponseV2 { + orderId: string; + clientOid: string | null; + success: string; + msg: string | null; } ⋮---- -/** - * - * * Common | Public - * - */ +export interface SubmitSpotBatchOrdersResponseV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + orderId: string; + clientOid: string; + errorMsg: string; + errorCode?: string; + }[]; +} ⋮---- -export interface GetTradeRateRequestV2 { +export interface SpotOrderInfoV2 { + userId: string; symbol: string; - businessType: string; + orderId: string; + clientOid: string; + price: string; + size: string; + orderType: string; + side: string; + status: string; + priceAvg: string; + baseVolume: string; + quoteVolume: string; + enterPointSource: string; + feeDetail: { + BGB?: { + deduction: boolean; + feeCoinCode: string; + totalDeductionFee: string; + totalFee: string; + }; + newFees?: { + c: number; + d: number; + deduction: boolean; + r: string; + t: string; + totalDeductionFee: number; + }; + }; + orderSource: string; + cancelReason: string; + cTime: string; + uTime: string; +} +⋮---- +export interface SpotOpenOrderV2 { + userId: string; + symbol: string; + orderId: string; + clientOid: string; + priceAvg: string; + size: string; + orderType: string; + side: string; + status: string; + basePrice: string; + baseVolume: string; + quoteVolume: string; + enterPointSource: string; + orderSource?: string; + presetTakeProfitPrice: string; + executeTakeProfitPrice: string; + presetStopLossPrice: string; + executeStopLossPrice: string; + cTime: string; + uTime?: string; + tpslType: string; + triggerPrice: string | null; +} +⋮---- +export interface SpotFillV2 { + userId: string; + symbol: string; + orderId: string; + tradeId: string; + orderType: string; + side: string; + priceAvg: string; + size: string; + amount: string; + feeDetail: { + deduction: string; + feeCoin: string; + totalDeductionFee: string; + totalFee: string; + }; + tradeScope: string; + cTime: string; + uTime: string; } ⋮---- /** * - * * Common | Tax + * * Spot | Trigger Orders * */ ⋮---- -export interface GetSpotTransactionsRequestV2 { - coin?: string; - startTime: string; - endTime: string; - limit?: string; - idLessThan?: string; +export interface SpotCurrentPlanOrderV2 { + orderId: string; + clientOid: string; + symbol: string; + size: string; + executePrice: string; + triggerPrice: string; + status: string; + orderType: string; + side: string; + planType: string; + triggerType: string; + enterPointSource: string; + uTime: string; + cTime: string; } ⋮---- -export interface GetFuturesTransactionsRequestV2 { - productType?: FuturesProductTypeV2; - marginCoin?: string; - startTime: string; - endTime: string; - limit?: string; - idLessThan?: string; +export interface SpotHistoryPlanOrderV2 { + orderId: string; + clientOid: string; + symbol: string; + size: string; + executePrice: string; + triggerPrice: string; + status: string; + orderType: string; + side: string; + planType: string; + triggerType: string; + enterPointSource: string; + uTime: string; + cTime: string; } ⋮---- -export interface GetMarginTransactionsRequestV2 { - marginType?: MarginType; - coin?: string; - startTime: string; - endTime: string; - limit?: string; - idLessThan?: string; +export interface SpotPlanSubOrderV2 { + orderId: string; + price: string; + type: string; + status: string; } ⋮---- -export interface GetP2PTransactionsRequestV2 { - coin?: string; - startTime: string; - endTime: string; - limit?: string; - idLessThan?: string; +export interface SpotCancelPlanOrdersV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + orderId: string; + clientOid: string; + errorMsg: string; + }[]; } ⋮---- /** * - * * Common | P2P + * * Spot | Account * */ ⋮---- -export interface GetP2PMerchantsRequestV2 { - online?: 'yes' | 'no'; - idLessThan?: string; - limit?: string; +export interface SpotAccountInfoV2 { + userId: string; + inviterId: string; + ips: string; + authorities: string[]; + parentId: number; + traderType: string; + channelCode: string; + channel: string; + regisTime: string; } ⋮---- -export interface GetMerchantP2POrdersRequestV2 { - startTime: string; - endTime?: string; - idLessThan?: string; - limit?: string; - status?: string; - advNo: string; - side?: string; - coin?: string; - language: string; - fiat?: string; - orderNo?: string; +export interface SpotAccountAssetV2 { + coin: string; + available: string; + frozen: string; + locked: string; + limitAvailable: string; + uTime: string; } ⋮---- -export interface GetMerchantAdvertisementsRequestV2 { - startTime: string; - endTime?: string; - idLessThan?: string; - limit?: string; +export interface SpotSubAccountAssetV2 { + coin: string; + available: string; + limitAvailable: string; + frozen: string; + locked: string; + uTime: string; +} +export interface SpotSubAccountAssetsV2 { + userId: number; + assetsList: SpotSubAccountAssetV2[]; +} +⋮---- +export interface SpotAccountBillV2 { + cTime: string; + coin: string; + groupType: string; + businessType: string; + size: string; + balance: string; + fees: string; + billId: string; +} +⋮---- +export interface SpotMainSubTransferRecordV2 { + coin: string; status: string; - advNo?: string; - side: string; + toType: string; + fromType: string; + size: string; + ts: string; + clientOid: string; + transferId: string; + fromUserId: string; + toUserId: string; +} +⋮---- +export interface SpotTransferRecordV2 { coin: string; - language?: string; - fiat: string; - orderBy?: string; - payMethodId?: string; - sourceType?: string; + status: string; + toType: string; + toSymbol: string; + fromType: string; + fromSymbol: string; + size: string; + ts: string; + clientOid: string; + transferId: string; } ⋮---- -/** - * - * * Common | Virtual Subaccount - * - */ +export interface SpotDepositAddressV2 { + address: string; + chain: string; + coin: string; + tag: string; + url: string; +} ⋮---- -export interface ModifyVirtualSubRequestV2 { - subAccountUid: string; - permList: string[]; +export interface SpotSubAccountDepositRecordV2 { + orderId: string; + tradeId: string; + coin: string; + size: string; status: string; + toAddress: string; + dest: string; + chain: string; + fromAddress: string; + clientOid?: string; + confirm?: string; + tag?: string; + cTime: string; + uTime: string; } ⋮---- -export interface CreateVirtualSubRequestV2 { - subAccountName: string; - passphrase: string; - label: string; - ipList?: string[]; - permList?: string[]; +export interface SpotWithdrawalRecordV2 { + orderId: string; + tradeId: string; + coin: string; + dest: string; + clientOid: string; + type: string; + tag: string; + size: string; + fee: string; + status: string; + toAddress: string; + fromAddress: string; + confirm: string; + chain: string; + cTime: string; + uTime: string; } ⋮---- -export interface CreateVirtualSubApiKeyRequestV2 { - subAccountUid: string; - passphrase: string; +export interface SpotDepositRecordV2 { + orderId: string; + tradeId: string; + coin: string; + type: string; + size: string; + status: string; + toAddress: string; + dest: string; + chain: string; + fromAddress: string; + cTime: string; + uTime: string; +} + +================ +File: src/types/response/v3/broker.ts +================ +export interface CreateBrokerSubAccountResponseV3 { + subUid: string; + subaccountName: string; + subaccountEmail: string; + status: 'normal' | 'freeze'; + permList: string[]; label: string; - ipList?: string[]; - permList?: string[]; + cTime: string; } ⋮---- -export interface ModifyVirtualSubApiKeyRequestV2 { - subAccountUid: string; - subAccountApiKey: string; - passphrase: string; +export interface BrokerSubAccountV3 { + subUid: string; + subaccountName: string; + subaccountEmail: string | null; + status: 'normal' | 'freeze'; + permList: string[]; label: string; - ipList?: string[]; - permList?: string[]; + language: string; + cTime: string; + uTime: string; } ⋮---- -/** - * - * * Common | Convert - * - */ +export interface GetBrokerSubAccountListResponseV3 { + subList: BrokerSubAccountV3[]; +} ⋮---- -export interface ConvertQuoteRequestV2 { - fromCoin: string; - fromCoinSize?: string; - toCoin: string; - toCoinSize?: string; +export interface ModifyBrokerSubAccountResponseV3 { + subUid: string; + subaccountName: string; + status: 'normal' | 'freeze'; + permList: string[]; + label: string; + cTime: string; + uTime: string; } ⋮---- -export interface ConvertRequestV2 { - fromCoin: string; - fromCoinSize: string; - cnvtPrice: string; - toCoin: string; - toCoinSize: string; - traceId: string; +export interface BrokerSubWithdrawalResponseV3 { + orderId: string; + clientOid: string; } ⋮---- -export interface GetConvertHistoryRequestV2 { - startTime: string; - endTime: string; - limit?: string; - idLessThan?: string; +export interface BrokerSubDepositAddressV3 { + subUid: string; + coin: string; + address: string; + chain: string; + tag: string | null; + url: string; + cTime: string; } ⋮---- -/** - * - * * Common | BGB Convert - * - */ +export interface BrokerSubDepositWithdrawalRecordV3 { + uid: string; + txId: string; + type: 'deposit' | 'withdrawal'; + subType: 'onchain' | 'internal' | 'fast'; + coin: string; + amount: string; + status: 'pending' | 'fail' | 'success'; + ts: string; +} ⋮---- -export interface GetConvertBGBHistoryRequestV2 { - orderId?: string; - startTime: string; - endTime: string; - limit?: string; - idLessThan?: string; +export interface GetBrokerAllSubDepositWithdrawalResponseV3 { + list: BrokerSubDepositWithdrawalRecordV3[]; + endId: string; } - -================ -File: src/types/response/v1/futures.ts -================ -import { - FuturesHoldMode, - FuturesHoldSide, - FuturesMarginMode, -} from '../../request/v1/futuresV1.js'; ⋮---- -export interface FuturesMarketTrade { - tradeId: string; - price: string; - size: string; - side: 'buy' | 'sell'; - timestamp: string; +export interface BrokerCommissionRecordV3 { + uid: string; + coin: string; symbol: string; + dealtAmount: string; + totalFee: string; + deductedFee: string; + paidFee: string; + markUpFee: string; + totalCommission: string; } ⋮---- -export interface FuturesAccount { - marginCoin: string; - locked: number; - available: number; - crossMaxAvailable: number; - fixedMaxAvailable: number; - maxTransferOut: number; - equity: number; - usdtEquity: number; - btcEquity: number; - crossRiskRate: number; - crossMarginLeverage: number; - fixedLongLeverage: number; - fixedShortLeverage: number; - marginMode: string; - holdMode: string; +export interface CreateBrokerSubApiKeyResponseV3 { + subUid: string; + label: string; + apiKey: string; + secretKey: string; + permType: 'read_and_write' | 'readonly'; + permList: string[]; + ipList: string[] | null; } ⋮---- -export interface FuturesSymbolRule { - baseCoin: string; - buyLimitPriceRatio: string; - feeRateUpRatio: string; - limitOpenTime: string; - maintainTime: string; - makerFeeRate: string; - maxOrderNum: string; - maxPositionNum: string; - minTradeNum: string; - minTradeUSDT: string; - offTime: string; - openCostUpRatio: string; - priceEndStep: string; - pricePlace: string; - quoteCoin: string; - sellLimitPriceRatio: string; - sizeMultiplier: string; - supportMarginCoins: string[]; - symbol: string; - symbolName: string; - symbolStatus: string; - symbolType: string; - takerFeeRate: string; - volumePlace: string; +export interface ModifyBrokerSubApiKeyResponseV3 { + subUid: string; + label: string; + apiKey: string; + permType: 'read_and_write' | 'readonly'; + permList: string[]; + ipList: string[]; } ⋮---- -export interface FuturesPosition { - marginCoin: string; - symbol: string; - holdSide: FuturesHoldSide; - openDelegateCount: string; - margin: string; - available: string; - locked: string; - total: string; - leverage: number; - achievedProfits: string; - averageOpenPrice: string; - marginMode: FuturesMarginMode; - holdMode: FuturesHoldMode; - unrealizedPL: string; - liquidationPrice: string; - keepMarginRate: string; - marketPrice: string; - cTime: string; +export interface GetBrokerSubApiKeyResponseV3 { + subUid: string; + label: string; + apiKey: string; + secretKey: string; + permType: 'read_and_write' | 'readonly'; + permList: string[]; + ipList: string[] | null; } ================ -File: src/types/response/v3/public.ts +File: src/types/response/v3/strategy.ts ================ -export interface PublicFillV3 { - execId: string; - price: string; - size: string; - side: 'sell' | 'buy'; - ts: string; +export interface PlaceStrategyOrderResponseV3 { + orderId: string; + clientOid: string; } ⋮---- -export interface CandlestickV3 extends Array { - 0: string; // timestamp - 1: string; // open price - 2: string; // high price - 3: string; // low price - 4: string; // close price - 5: string; // volume - 6: string; // turnover +export interface ModifyStrategyOrderResponseV3 { + orderId: string; + clientOid: string; } ⋮---- -0: string; // timestamp -1: string; // open price -2: string; // high price -3: string; // low price -4: string; // close price -5: string; // volume -6: string; // turnover -⋮---- -export interface ContractOiV3 { +export interface StrategyOrderV3 { + orderId: string; + clientOid: string; + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; - notionalValue: string; - totalNotionalValue: string; + qty: string; + posSide: 'long' | 'short'; + tpTriggerBy: 'market' | 'mark'; + slTriggerBy: 'market' | 'mark'; + takeProfit: string; + stopLoss: string; + tpOrderType: 'limit' | 'market'; + slOrderType: 'limit' | 'market'; + tpLimitPrice: string; + slLimitPrice: string; + createdTime: string; + updatedTime: string; } -⋮---- -export interface CurrentFundingRateV3 { + +================ +File: src/types/websockets/ws-api-request.ts +================ +export interface WSAPIPlaceOrderRequestV3 { symbol: string; - fundingRate: string; - fundingRateInterval: string; - nextUpdate: string; - minFundingRate: string; - maxFundingRate: string; + orderType: 'limit' | 'market'; + qty: string; + price?: string; + side: 'buy' | 'sell'; + posSide?: 'long' | 'short'; + timeInForce?: 'gtc' | 'ioc' | 'fok' | 'post_only'; + reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. + clientOid?: string; + stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; + tpTriggerBy?: 'market' | 'mark'; + slTriggerBy?: 'market' | 'mark'; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: 'limit' | 'market'; + slOrderType?: 'limit' | 'market'; + tpLimitPrice?: string; + slLimitPrice?: string; } ⋮---- -export interface DiscountRateTierV3 { - tierStartValue: string; - discountRate: string; +reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. + +================ +File: src/types/websockets/ws-api-response.ts +================ +export interface WSAPIPlaceOrderResponseV3 { + symbol: string; + orderId: string; + clientOid: string; + cTime: string; } -⋮---- -export interface DiscountRateV3 { - coin: string; - list: DiscountRateTierV3[]; + +================ +File: src/types/websockets/ws-events.ts +================ +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; } ⋮---- -export interface HistoryFundingRateV3 { - symbol: string; - fundingRate: string; - fundingRateTimestamp: string; +export function isMessageEvent(msg: unknown): msg is MessageEventLike +⋮---- +export interface WsBaseEvent { + action: TAction; + arg: unknown; + data: TData[]; } ⋮---- -export interface MarginLoanV3 { - dailyInterest: string; - annualInterest: string; - limit: string; +export interface WsSnapshotChannelEvent extends WsBaseEvent<'snapshot'> { + arg: { + instType: string; + channel: string; + instId: string; + }; } ⋮---- -export interface OpenInterestItemV3 { - symbol: string; - openInterest: string; +export interface WsSnapshotAccountEvent extends WsBaseEvent<'snapshot'> { + arg: { + instType: string; + channel: 'account'; + instId: string; + }; } ⋮---- -export interface OpenInterestV3 { - list: OpenInterestItemV3[]; - ts: string; +export interface WsSnapshotPositionsEvent extends WsBaseEvent<'snapshot'> { + arg: { + instType: string; + channel: 'positions'; + instId: string; + }; } ⋮---- -export interface PositionTierV3 { - tier: string; - minTierValue: string; - maxTierValue: string; - leverage: string; - mmr: string; +export interface WsAccountSnapshotDataUMCBL { + marginCoin: string; + locked: string; + available: string; + maxOpenPosAvailable: string; + maxTransferOut: string; + equity: string; + usdtEquity: string; } ⋮---- -export interface RiskReserveRecordV3 { - balance: string; - amount: string; - ts: string; -} -⋮---- -export interface RiskReserveV3 { - coin: string; - riskReserveRecords: RiskReserveRecordV3[]; +export interface WsAccountSnapshotUMCBL extends WsBaseEvent<'snapshot'> { + arg: { + instType: 'umcbl'; + channel: 'account'; + instId: string; + }; + data: WsAccountSnapshotDataUMCBL[]; } ⋮---- -export interface InstrumentV3 { - symbol: string; - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - baseCoin: string; - quoteCoin: string; - buyLimitPriceRatio: string; - sellLimitPriceRatio: string; - feeRateUpRatio: string; - minOrderQty: string; - maxOrderQty: string; - maxMarketOrderQty: string; - pricePrecision: string; - quantityPrecision: string; - quotePrecision: string; - minOrderAmount: string; - maxSymbolOrderNum: string; - maxProductOrderNum: string; - status: - | 'listed' - | 'online' - | 'limit_open' - | 'limit_close' - | 'offline' - | 'restrictedAPI'; - offTime: string; - limitOpenTime: string; - maintainTime: string; - areaSymbol?: string; - - // Futures specific fields - makerFeeRate?: string; - takerFeeRate?: string; - openCostUpRatio?: string; - priceMultiplier?: string; - quantityMultiplier?: string; - symbolType?: 'perpetual' | 'delivery'; - maxPositionNum?: string; - deliveryTime?: string; - deliveryStartTime?: string; - deliveryPeriod?: string; - launchTime?: string; - fundInterval?: string; - minLeverage?: string; - maxLeverage?: string; - - // Margin specific fields - isIsolatedBaseBorrowable?: 'YES' | 'NO'; - isIsolatedQuotedBorrowable?: 'YES' | 'NO'; - warningRiskRatio?: string; - liquidationRiskRatio?: string; - maxCrossedLeverage?: string; - maxIsolatedLeverage?: string; - userMinBorrow?: string; +export interface WsPositionSnapshotDataUMCBL { + posId: string; + instId: string; + instName: string; + marginCoin: string; + margin: string; + marginMode: string; + holdSide: string; + holdMode: string; + total: string; + available: string; + locked: string; + averageOpenPrice: string; + leverage: number; + achievedProfits: string; + upl: string; + uplRate: string; + liqPx: string; + keepMarginRate: string; + marginRate: string; + cTime: string; + uTime: string; + markPrice: string; } ⋮---- -// Futures specific fields -⋮---- -// Margin specific fields -⋮---- -export interface OrderBookV3 { - a: string[][]; // asks - [price, size] - b: string[][]; // bids - [price, size] - ts: string; +export interface WSPositionSnapshotUMCBL extends WsBaseEvent<'snapshot'> { + arg: { + instType: 'umcbl'; + channel: 'positions'; + instId: string; + }; + data: WsPositionSnapshotDataUMCBL[]; } -⋮---- -a: string[][]; // asks - [price, size] -b: string[][]; // bids - [price, size] -⋮---- -export interface TickerV3 { - category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - lastPrice: string; - openPrice24h: string; - highPrice24h: string; - lowPrice24h: string; - ask1Price: string; - bid1Price: string; - bid1Size: string; - ask1Size: string; - price24hPcnt: string; - volume24h: string; - turnover24h: string; - // Futures specific fields - indexPrice?: string; - markPrice?: string; - fundingRate?: string; - openInterest?: string; - deliveryStartTime?: string; - deliveryTime?: string; - deliveryStatus?: string; -} -⋮---- -// Futures specific fields -⋮---- -export interface ProofOfReservesV3 { - merkleRootHash: string; - totalReserveRatio: string; - list: { - coin: string; - userAssets: string; - platformAssets: string; - reserveRatio: string; - }[]; +================ +File: .jshintrc +================ +{ + "esversion": 8, + "asi": true, + "laxbreak": true, + "predef": [ "-Promise" ] } ================ -File: src/types/response/v3/trade.ts +File: .nvmrc ================ -export interface BatchModifyOrderResponseV3 { - orderId: string; - clientOid: string; -} -⋮---- -export interface CancelAllOrdersResponseV3 { - list: { - orderId: string; - clientOid: string; - code: string; - msg: string; - }[]; -} -⋮---- -export interface CancelBatchOrdersResponseV3 { - orderId: string; - clientOid: string; - code?: string; - msg?: string; -} -⋮---- -export interface CloseAllPositionsResponseV3 { - list: { - orderId: string; - clientOid: string; - code: string; - msg: string; - }[]; -} -⋮---- -export interface CancelOrderResponseV3 { - orderId: string; - clientOid: string; -} -⋮---- -export interface GetMaxOpenAvailableResponseV3 { - available: string; - maxOpen: string; - buyOpenCost: string; - sellOpenCost: string; - maxBuyOpen: string; - maxSellOpen: string; -} -⋮---- -export interface FeeDetailV3 { - feeCoin: string; - fee: string; -} -⋮---- -export interface OrderInfoV3 { - orderId: string; - clientOid: string; - category: string; - symbol: string; - orderType: string; - side: string; - price: string; - qty: string; - amount: string; - cumExecQty: string; - cumExecValue: string; - avgPrice: string; - timeInForce: string; - orderStatus: string; - posSide: string; - holdMode: string; - reduceOnly: string; - feeDetail: FeeDetailV3[]; - cancelReason: string; - execType: string; - stpMode?: string; - createdTime: string; - updatedTime: string; +v22.17.1 + +================ +File: .prettierrc +================ +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" } -⋮---- -export interface FillV3 { - execId: string; - orderId: string; - category: string; - symbol: string; - orderType: string; - side: string; - execPrice: string; - execQty: string; - execValue: string; - tradeScope: string; - feeDetail: FeeDetailV3[]; - execPnl?: string; - tradeSide?: string; - createdTime: string; - updatedTime: string; + +================ +File: LICENSE.md +================ +Copyright 2022 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================ +File: examples/README.md +================ +# Examples + +These samples can be executed using `ts-node`: + +``` +ts-node ./examples/rest-spot-public.ts +``` + +Samples that require authentication can be edited directly but also support environmental variables. E.g. on mac/unix: + +``` +API_KEY_COM='yourkeyhere' API_SECRET_COM='yoursecrethere' API_PASS_COM='yourapipasshere' ts-node examples/rest-trade-futures.ts +``` + +They can also be converted to JavaScript by changing the imports to require & removing any type annotations. + +## V3 / Unified Trading Account (UTA) + +These newer examples are for Bitget's V3 APIs and WebSockets. They can be found in the examples/V3 folder. + +Refer to the V3 / UTA API documentation for more information on the V3 APIs: +https://www.bitget.com/api-doc/uta/intro + +These APIs require your account to be upgraded to the Unified Trading Account, if you plan on using the account-level REST APIs and WebSockets. Once upgraded, the V2 APIs are no longer available to you, unless you revert back to Classic Account mode. + +### WebSocket API (WS API) + +The V3/UTA API introduces order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API. + +There are two approaches to placing orders via the Bitget WebSocket APIs + +#### WebsocketAPIClient (recommended) + +This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types. + +This is the recommended approach to easily start sending orders via an automatically persisted WebSocket connection. A simple example is below, but for a more thorough example, check the example here: [./V3/ws-api-client-trade.ts](./V3/ws-api-client-trade.ts) + +```typescript +import { WebsocketAPIClient } from 'bitget-api'; +// or if you prefer require: +// const { WebsocketAPIClient } = require("bitget-api"); + +// Make an instance of the WS API Client class with your API keys +const wsClient = new WebsocketAPIClient({ + apiKey: API_KEY, + apiSecret: API_SECRET, + apiPass: API_PASS, + + // Whether to use the demo trading wss connection + // demoTrading: true, +}); + +async function start() { + // Start using it like a REST API. All actions are sent via a persisted WebSocket connection. + + /** + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ + try { + const res = await wsClient.submitNewOrder('spot', { + orderType: 'limit', + price: '100', + qty: '0.1', + side: 'buy', + symbol: 'BTCUSDT', + timeInForce: 'gtc', + }); + + console.log(new Date(), 'WS API "submitNewOrder()" result: ', res); + } catch (e) { + console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e); + } } + +start().catch((e) => console.error('Exception in example: '.e)); +``` + +#### ws.sendWSAPIRequest(wsKey, command, category, operation) + +This is the "raw" integration within the existing WebSocket client. It uses an automatically persisted & authenticated connection to send events through Bitget's WebSocket API. It automatically tracks and connects outgoing requests with incoming responses, and returns promises that resolve/reject when a matching response is received. + +Refer to [V3/ws-api-trade-raw.ts](./V3/ws-api-trade-raw.ts) to see an example. + +Note: The WebsocketClient is built around this. For a more user friendly experience, it is recommended to use the WebsocketClient for WS API requests. It uses this method but has the convenience of behaving similar to a REST API (while all communication automatically happens over a persisted WebSocket connection). + +## V2 + +These examples are for Bitget's V2 APIs and WebSockets. They can be found in the examples/V2 folder. + +Refer to the V2 API documentation for more information on the V2 APIs: +https://www.bitget.com/api-doc/common/intro + +================ +File: src/types/request/v2/common.ts +================ +import { FuturesProductTypeV2, MarginType } from '../shared.js'; ⋮---- -export interface UnfilledOrderV3 { - orderId: string; - clientOid: string; - category: string; - symbol: string; - orderType: string; - side: string; - price: string; - qty: string; - amount: string; - cumExecQty: string; - cumExecValue: string; - avgPrice: string; - timeInForce: string; - orderStatus: string; - posSide: string; - holdMode: string; - reduceOnly: string; - feeDetail: FeeDetailV3[]; - stpMode?: string; - createdTime: string; - updatedTime: string; -} +/** + * + * * Common | Notice + * + */ ⋮---- -export interface HistoryOrderV3 { - orderId: string; - clientOid: string; - category: string; - symbol: string; - orderType: string; - side: string; - price: string; - qty: string; - amount: string; - cumExecQty: string; - cumExecValue: string; - avgPrice: string; - timeInForce: string; - orderStatus: string; - posSide: string; - holdMode: string; - reduceOnly: string; - feeDetail: FeeDetailV3[]; - cancelReason: string; - execType: string; - stpMode?: string; - createdTime: string; - updatedTime: string; +export interface GetAnnouncementsRequestV2 { + annType?: string; + startTime?: string; + endTime?: string; + language: string; } ⋮---- -export interface PositionHistoryV3 { - positionId: string; - category: string; - symbol: string; - marginCoin: string; - holdMode: string; - posSide: string; - marginMode: string; - openPriceAvg: string; - closePriceAvg: string; - openTotalPos: string; - closeTotalPos: string; - cumRealisedPnl: string; - netProfit: string; - totalFunding: string; - openFeeTotal: string; - closeFeeTotal: string; - createdTime: string; - updatedTime: string; -} +/** + * + * * Common | Public + * + */ ⋮---- -export interface CurrentPositionV3 { - category: string; +export interface GetTradeRateRequestV2 { symbol: string; - marginCoin: string; - holdMode: string; - posSide: string; - marginMode: string; - positionBalance: string; - available: string; - frozen: string; - total: string; - leverage: string; - curRealisedPnl: string; - avgPrice: string; - positionStatus: string; - unrealisedPnl: string; - liquidationPrice: string; - mmr: string; - profitRate: string; - markPrice: string; - breakEvenPrice: string; - totalFunding: string; - openFeeTotal: string; - closeFeeTotal: string; - createdTime: string; - updatedTime: string; + businessType: string; } ⋮---- -export interface ModifyOrderResponseV3 { - orderId: string; - clientOid: string; -} +/** + * + * * Common | Tax + * + */ ⋮---- -export interface PlaceBatchOrdersResponseV3 { - orderId: string; - clientOid: string; - code?: string; - msg?: string; +export interface GetSpotTransactionsRequestV2 { + coin?: string; + startTime: string; + endTime: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface PlaceOrderResponseV3 { - orderId: string; - clientOid: string; +export interface GetFuturesTransactionsRequestV2 { + productType?: FuturesProductTypeV2; + marginCoin?: string; + startTime: string; + endTime: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface PositionAdlRankV3 { - symbol: string; - marginCoin: string; - adlRank: string; - holdSide: 'long' | 'short'; -} - -================ -File: src/types/websockets/ws-api-response.ts -================ -export interface WSAPIPlaceOrderResponseV3 { - symbol: string; - orderId: string; - clientOid: string; - cTime: string; +export interface GetMarginTransactionsRequestV2 { + marginType?: MarginType; + coin?: string; + startTime: string; + endTime: string; + limit?: string; + idLessThan?: string; } - -================ -File: src/types/shared.ts -================ -import { REST_CLIENT_TYPE_ENUM } from '../util/requestUtils.js'; -⋮---- -export type numberInString = string; ⋮---- -export type OrderSide = 'Buy' | 'Sell'; +export interface GetP2PTransactionsRequestV2 { + coin?: string; + startTime: string; + endTime: string; + limit?: string; + idLessThan?: string; +} ⋮---- /** - * @deprecated use SpotKlineInterval or FuturesKlineInterval, depending on which API group you're using + * + * * Common | P2P + * */ -export type KlineInterval = - | '1min' - | '5min' - | '15min' - | '30min' - | '1h' - | '4h' - | '6h' - | '12h' - | '1M' - | '1W' - | '1week' - | '6Hutc' - | '12Hutc' - | '1Dutc' - | '3Dutc' - | '1Wutc' - | '1Mutc'; ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; - -================ -File: src/broker-client.ts -================ -import { - BrokerProductType, - BrokerSubAPIKeyModifyRequest, - BrokerSubListRequest, - BrokerSubWithdrawalRequest, -} from './types/request/v1/brokerV1.js'; -import { APIResponse } from './types/response/v1/shared.js'; -import BaseRestClient from './util/BaseRestClient.js'; -import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; +export interface GetP2PMerchantsRequestV2 { + online?: 'yes' | 'no'; + idLessThan?: string; + limit?: string; +} +⋮---- +export interface GetMerchantP2POrdersRequestV2 { + startTime: string; + endTime?: string; + idLessThan?: string; + limit?: string; + status?: string; + advNo: string; + side?: string; + coin?: string; + language: string; + fiat?: string; + orderNo?: string; +} +⋮---- +export interface GetMerchantAdvertisementsRequestV2 { + startTime: string; + endTime?: string; + idLessThan?: string; + limit?: string; + status: string; + advNo?: string; + side: string; + coin: string; + language?: string; + fiat: string; + orderBy?: string; + payMethodId?: string; + sourceType?: string; +} ⋮---- /** - * REST API client for the V1 bitget Broker APIs. These are the previous generation of Bitget's APIs and should be considered deprecated. - * These will be removed in a future release, once Bitget formally deprecates them. * - * @deprecated use RestClientV2 instead + * * Common | Virtual Subaccount + * */ -export class BrokerClient extends BaseRestClient ⋮---- -getClientType() +export interface ModifyVirtualSubRequestV2 { + subAccountUid: string; + permList: string[]; + status: string; +} ⋮---- -/** - * - * Sub Account Interface - * - */ +export interface CreateVirtualSubRequestV2 { + subAccountName: string; + passphrase: string; + label: string; + ipList?: string[]; + permList?: string[]; +} ⋮---- -/** Get Broker Info */ -getBrokerInfo(): Promise> +export interface CreateVirtualSubApiKeyRequestV2 { + subAccountUid: string; + passphrase: string; + label: string; + ipList?: string[]; + permList?: string[]; +} ⋮---- -/** Create Sub Account */ -createSubAccount( - subName: string, - remark?: string, -): Promise> +export interface ModifyVirtualSubApiKeyRequestV2 { + subAccountUid: string; + subAccountApiKey: string; + passphrase: string; + label: string; + ipList?: string[]; + permList?: string[]; +} ⋮---- -/** Get Sub List */ -getSubAccounts(params?: BrokerSubListRequest): Promise> +/** + * + * * Common | Convert + * + */ ⋮---- -/** Modify Sub Account */ -modifySubAccount( - subUid: string, - perm: string, - status: 'normal' | 'freeze' | 'del', -): Promise> +export interface ConvertQuoteRequestV2 { + fromCoin: string; + fromCoinSize?: string; + toCoin: string; + toCoinSize?: string; +} ⋮---- -/** Modify Sub Email */ -modifySubEmail(subUid: string, subEmail: string): Promise> +export interface ConvertRequestV2 { + fromCoin: string; + fromCoinSize: string; + cnvtPrice: string; + toCoin: string; + toCoinSize: string; + traceId: string; +} ⋮---- -/** Get Sub Email */ -getSubEmail(subUid: string): Promise> +export interface GetConvertHistoryRequestV2 { + startTime: string; + endTime: string; + limit?: string; + idLessThan?: string; +} ⋮---- -/** Get Sub Spot Assets */ -getSubSpotAssets(subUid: string): Promise> +/** + * + * * Common | BGB Convert + * + */ ⋮---- -/** Get Sub Future Assets */ -getSubFutureAssets( - subUid: string, - productType: BrokerProductType, -): Promise> +export interface GetConvertBGBHistoryRequestV2 { + orderId?: string; + startTime: string; + endTime: string; + limit?: string; + idLessThan?: string; +} + +================ +File: src/types/response/v3/loan.ts +================ +export interface LoanTransfersV3 { + coin: string; + transfered: string; + userId: string; +} ⋮---- -/** Get Sub Deposit Address (Only Broker) */ -getSubDepositAddress( - subUid: string, - coin: string, - chain?: string, -): Promise> +export interface LoanSymbolSettingV3 { + symbol: string; + leverage: string; +} ⋮---- -/** Sub Withdrawal (Only Broker) */ -subWithdrawal(params: BrokerSubWithdrawalRequest): Promise> +export interface LoanSymbolsV3 { + productId: string; + spotSymbols: string[]; + marginLeverage: string; + usdtContractLeverage: string; + coinContractLeverage: string; + usdcContractLeverage: string; + usdtContractSymbols: LoanSymbolSettingV3[]; + coinContractSymbols: LoanSymbolSettingV3[]; + usdcContractSymbols: LoanSymbolSettingV3[]; +} ⋮---- -/** Sub Deposit Auto Transfer (Only Broker) */ -setSubDepositAutoTransfer( - subUid: string, - coin: string, - toAccountType: 'spot' | 'mix_usdt' | 'mix_usd' | 'mix_usdc', -): Promise> +export interface RepaidHistoryItemV3 { + repayOrderId: string; + businessType: 'normal' | 'liquidation'; + repayType: 'all' | 'part'; + repaidTime: string; + coin: string; + repayAmount: string; + repayInterest: string; +} ⋮---- -/** - * - * Sub API Interface - * - */ +export interface LoanProductInfoV3 { + productId: string; + leverage: string; + supportUsdtContract: 'YES' | 'NO'; + supportCoinContract: 'YES' | 'NO'; + supportUsdcContract: 'YES' | 'NO'; + transferLine: string; + spotBuyLine: string; + usdtContractOpenLine: string; + coinContractOpenLine: string; + usdcContractOpenLine: string; + liquidationLine: string; + stopLiquidationLine: string; +} ⋮---- -/** Create Sub ApiKey (Only Broker) */ -createSubAPIKey( - subUid: string, - passphrase: string, - remark: string, - ip: string, - perm?: string, -): Promise> +export interface LoanOrderV3 { + orderId: string; + orderProductId: string; + uid: string; + loanTime: string; + loanCoin: string; + loanAmount: string; + unpaidAmount: string; + unpaidInterest: string; + repaidAmount: string; + repaidInterest: string; + reserve: string; + status: 'not_paid_off' | 'paid_off'; +} ⋮---- -/** Get Sub ApiKey List */ -getSubAPIKeys(subUid: string): Promise> +export interface CoinInfoV3 { + coin: string; + convertRatio: string; + maxConvertValue: string; +} ⋮---- -/** Modify Sub ApiKey (Only Broker) */ -modifySubAPIKey( - params: BrokerSubAPIKeyModifyRequest, -): Promise> +export interface BindUidResponseV3 { + riskUnitId: string; + uid: string; + operate: 'bind' | 'unbind'; +} ⋮---- -/** - * Undocumented endpoints - */ -⋮---- -getAgentCommissionDetail(params?: { - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -}): Promise> -⋮---- -/** Get Agent Customer List */ -getAgentCustomerList(params?: { - startTime?: string; - endTime?: string; - pageNo?: string; - pageSize?: string; - uid?: string; - referralCode?: string; -}): Promise> -⋮---- -/** - * Get Agent Customer Deposit List - * Includes both on-chain deposits and internal transfers - * Note: Can only query data within the last 90 days - */ -getAgentCustomerDepositList(params?: { - startTime?: string; - endTime?: string; - pageNo?: string; - pageSize?: string; - uid?: string; -}): Promise> -⋮---- -/** - * Get Agent Customer Trade Volume List - * Includes trading volume for both spot and futures - * Note: Data updates every 10 minutes and can only query last 90 days - */ -getAgentCustomerTradeVolumeList(params?: { - startTime?: string; - endTime?: string; - pageNo?: string; - pageSize?: string; - uid?: string; -}): Promise> -⋮---- -/** - * Get Agent Customer Assets List - * Returns account balances for customer accounts - * Note: Data updates every 10 minutes - */ -getAgentCustomerAssetsList(params?: { - pageNo?: string; - pageSize?: string; - uid?: string; -}): Promise> +export interface UnpaidInfoV3 { + coin: string; + unpaidQty: string; + unpaidInterest: string; +} ⋮---- -/** - * Get Agent Direct Commissions - * Returns commission data for direct customers - * Note: Data updates on T+1 (UTC+8) basis and can only query last 90 days - */ -getAgentCustomerCommissions(params?: { - startTime?: string; - endTime?: string; - idLessThan?: string; - limit?: string; - uid?: string; - coin?: string; - symbol?: string; -}): Promise> +export interface BalanceInfoV3 { + coin: string; + price: string; + amount: string; + convertedUsdtAmount: string; +} ⋮---- -/** - * Get Agent Customer KYC Result - * Returns KYC verification status for customers - */ -getAgentCustomerKycResult(params?: { - startTime?: string; - endTime?: string; - pageNo?: string; - pageSize?: string; - uid?: string; -}): Promise> +export interface LTVConvertResponseV3 { + ltv: string; + subAccountUids: string[]; + unpaidUsdtAmount: string; + usdtBalance: string; + unpaidInfo: UnpaidInfoV3[]; + balanceInfo: BalanceInfoV3[]; +} ================ -File: src/futures-client.ts +File: src/types/response/v3/trade.ts ================ -import { GetHistoricTradesParams } from './types/request/shared.js'; -import { - CancelFuturesPlanTPSL, - FuturesAccountBillRequest, - FuturesBusinessBillRequest, - FuturesCandleData, - FuturesHistoricPositions, - FuturesKlineInterval, - FuturesMarginMode, - FuturesPagination, - FuturesPlanType, - FuturesProductType, - HistoricPlanOrderTPSLRequest, - ModifyFuturesOrder, - ModifyFuturesPlanOrder, - ModifyFuturesPlanOrderTPSL, - ModifyFuturesPlanStopOrder, - NewBatchFuturesOrder, - NewFuturesOrder, - NewFuturesPlanOrder, - NewFuturesPlanPositionTPSL, - NewFuturesPlanStopOrder, - NewFuturesPlanTrailingStopOrder, -} from './types/request/v1/futuresV1.js'; -import { - FuturesAccount, - FuturesMarketTrade, - FuturesPosition, - FuturesSymbolRule, -} from './types/response/v1/futures.js'; -import { APIResponse, VIPFeeRate } from './types/response/v1/shared.js'; -import BaseRestClient from './util/BaseRestClient.js'; -import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; -⋮---- -/** - * REST API client for the V1 bitget Futures APIs. These are the previous generation of Bitget's APIs and should be considered deprecated. - * These will be removed in a future release, once Bitget formally deprecates them. - * - * @deprecated use RestClientV2 instead - */ -export class FuturesClient extends BaseRestClient -⋮---- -getClientType() -⋮---- -/** - * - * Market - * - */ -⋮---- -/** Get Symbols : Get basic configuration information of all trading pairs (including rules) */ -getSymbols( - productType: FuturesProductType, -): Promise> -⋮---- -/** Get Depth */ -getDepth(symbol: string, limit?: string): Promise> -⋮---- -/** Get Single Symbol Ticker */ -getTicker(symbol: string): Promise> -⋮---- -/** Get All Tickers */ -getAllTickers(productType: FuturesProductType): Promise> -⋮---- -/** Get VIP fee rates */ -getVIPFeeRates(): Promise> -⋮---- -/** Get most recent trades (up to 500, 100 by default) */ -getRecentTrades( - symbol: string, - limit?: string, -): Promise> -⋮---- -/** Get historic trades, up to 30 days at a time. Same-parameter responses are cached for 10 minutes. */ -getHistoricTrades( - params: GetHistoricTradesParams, -): Promise> -⋮---- -/** - * @deprecated use getRecentTrades() instead. This method will be removed soon. - */ -getMarketTrades( - symbol: string, - limit?: string, -): Promise> -⋮---- -/** Get Candle Data */ -getCandles( - symbol: string, - granularity: FuturesKlineInterval, - startTime: string, - endTime: string, - limit?: string, - kLineType?: 'market' | 'mark' | 'index', -): Promise> -⋮---- -/** Get symbol index price */ -getIndexPrice(symbol: string): Promise> -⋮---- -/** Get symbol next funding time */ -getNextFundingTime(symbol: string): Promise> -⋮---- -/** Get Withdraw List */ -getHistoricFundingRate( - symbol: string, - pageSize?: string, - pageNo?: string, - nextPage?: boolean, -): Promise> +export interface BatchModifyOrderResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -/** Get symbol current funding time */ -getCurrentFundingRate(symbol: string): Promise> +export interface CancelAllOrdersResponseV3 { + list: { + orderId: string; + clientOid: string; + code: string; + msg: string; + }[]; +} ⋮---- -/** Get symbol open interest */ -getOpenInterest(symbol: string): Promise> +export interface CancelBatchOrdersResponseV3 { + orderId: string; + clientOid: string; + code?: string; + msg?: string; +} ⋮---- -/** Get symbol mark price */ -getMarkPrice(symbol: string): Promise> +export interface CloseAllPositionsResponseV3 { + list: { + orderId: string; + clientOid: string; + code: string; + msg: string; + }[]; +} ⋮---- -/** Get symbol min/max leverage rules */ -getLeverageMinMax(symbol: string): Promise> +export interface CancelOrderResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -/** Get Position Tier */ -getPositionTier( - symbol: string, - productType: FuturesProductType, -): Promise> +export interface GetMaxOpenAvailableResponseV3 { + available: string; + maxOpen: string; + buyOpenCost: string; + sellOpenCost: string; + maxBuyOpen: string; + maxSellOpen: string; +} ⋮---- -/** - * - * Account Endpoints - * - */ +export interface FeeDetailV3 { + feeCoin: string; + fee: string; +} ⋮---- -/** Get Single Account */ -getAccount( - symbol: string, - marginCoin: string, -): Promise> +export interface OrderInfoV3 { + orderId: string; + clientOid: string; + category: string; + symbol: string; + orderType: string; + side: string; + price: string; + qty: string; + amount: string; + cumExecQty: string; + cumExecValue: string; + avgPrice: string; + timeInForce: string; + orderStatus: string; + posSide: string; + holdMode: string; + reduceOnly: string; + feeDetail: FeeDetailV3[]; + cancelReason: string; + execType: string; + stpMode?: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** Get Account List */ -getAccounts(productType: FuturesProductType): Promise> +export interface FillV3 { + execId: string; + orderId: string; + category: string; + symbol: string; + orderType: string; + side: string; + execPrice: string; + execQty: string; + execValue: string; + tradeScope: string; + feeDetail: FeeDetailV3[]; + execPnl?: string; + tradeSide?: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** Get Sub Account Contract Assets */ -getSubAccountContractAssets( - productType: FuturesProductType, -): Promise> +export interface UnfilledOrderV3 { + orderId: string; + clientOid: string; + category: string; + symbol: string; + orderType: string; + side: string; + price: string; + qty: string; + amount: string; + cumExecQty: string; + cumExecValue: string; + avgPrice: string; + timeInForce: string; + orderStatus: string; + posSide: string; + holdMode: string; + delegateType?: string; + reduceOnly: string; + feeDetail: FeeDetailV3[]; + stpMode?: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** - * This interface is only used to calculate the maximum number of positions that can be opened when the user does not hold a position by default. - * The result does not represent the actual number of positions opened. - */ -getOpenCount( - symbol: string, - marginCoin: string, - openPrice: number, - openAmount: number, - leverage?: number, -): Promise> +export interface HistoryOrderV3 { + orderId: string; + clientOid: string; + category: string; + symbol: string; + orderType: string; + side: string; + price: string; + qty: string; + amount: string; + cumExecQty: string; + cumExecValue: string; + avgPrice: string; + timeInForce: string; + orderStatus: string; + posSide: string; + holdMode: string; + delegateType?: string; + reduceOnly: string; + feeDetail: FeeDetailV3[]; + cancelReason: string; + execType: string; + stpMode?: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** Change Leverage */ -setLeverage( - symbol: string, - marginCoin: string, - leverage: string, - holdSide?: string, -): Promise> +export interface PositionHistoryV3 { + positionId: string; + category: string; + symbol: string; + marginCoin: string; + holdMode: string; + posSide: string; + marginMode: string; + openPriceAvg: string; + closePriceAvg: string; + openTotalPos: string; + closeTotalPos: string; + cumRealisedPnl: string; + netProfit: string; + totalFunding: string; + openFeeTotal: string; + closeFeeTotal: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** Change Margin */ -setMargin( - symbol: string, - marginCoin: string, - amount: string, - holdSide?: string, -): Promise> -⋮---- -/** Change Margin Mode */ -setMarginMode( - symbol: string, - marginCoin: string, - marginMode: FuturesMarginMode, -): Promise> -⋮---- -/** Change Hold Mode */ -setHoldMode( - productType: FuturesProductType, - holdMode: 'single_hold' | 'double_hold', -): Promise> -⋮---- -/** Get Symbol Position */ -getPosition( - symbol: string, - marginCoin?: string, -): Promise> -⋮---- -/** Get Symbol Position V2 */ -getPositionV2( - symbol: string, - marginCoin: string, -): Promise> -⋮---- -/** Get All Position */ -getPositions( - productType: FuturesProductType, - marginCoin?: string, -): Promise> -⋮---- -/** Get All Position V2 */ -getPositionsV2( - productType: FuturesProductType, - marginCoin?: string, -): Promise> -⋮---- -/** Get All historic positions, only supports Query within 3 months */ -getHistoryPositions( - params: FuturesHistoricPositions, -): Promise> -⋮---- -/** Get Account Bill */ -getAccountBill(params: FuturesAccountBillRequest): Promise> -⋮---- -/** Get Business Account Bill */ -getBusinessBill( - params: FuturesBusinessBillRequest, -): Promise> +export interface CurrentPositionV3 { + category: string; + symbol: string; + marginCoin: string; + holdMode: string; + posSide: string; + marginMode: string; + positionBalance: string; + available: string; + frozen: string; + total: string; + leverage: string; + curRealisedPnl: string; + avgPrice: string; + positionStatus: string; + unrealisedPnl: string; + liquidationPrice: string; + mmr: string; + profitRate: string; + markPrice: string; + breakEvenPrice: string; + totalFunding: string; + openFeeTotal: string; + closeFeeTotal: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** - * - * Trade Endpoints - * - */ +export interface ModifyOrderResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -/** Place Order */ -submitOrder(params: NewFuturesOrder): Promise> +export interface PlaceBatchOrdersResponseV3 { + orderId: string; + clientOid: string; + code?: string; + msg?: string; +} ⋮---- -/** Batch Order */ -batchSubmitOrder( - symbol: string, - marginCoin: string, - orders: NewBatchFuturesOrder[], -): Promise> +export interface PlaceOrderResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -/** Cancel Order */ -cancelOrder( - symbol: string, - marginCoin: string, - orderId?: string, - clientOid?: string, -): Promise> +export interface PositionAdlRankV3 { + symbol: string; + marginCoin: string; + adlRank: string; + holdSide: 'long' | 'short'; +} + +================ +File: src/types/websockets/ws-api.ts +================ +import { WS_KEY_MAP } from '../../util/websocket-util.js'; +import { CancelOrderRequestV3 } from '../request/v3/trade.js'; +import { CancelOrderResponseV3 } from '../response/v3/trade.js'; +import { WSAPIPlaceOrderRequestV3 } from './ws-api-request.js'; +import { WSAPIPlaceOrderResponseV3 } from './ws-api-response.js'; +import { BitgetInstTypeV3, WsKey } from './ws-general.js'; ⋮---- -/** Batch Cancel Order */ -batchCancelOrder( - symbol: string, - marginCoin: string, - orderIds: string[], -): Promise> +export type WSOperation = 'subscribe' | 'unsubscribe' | 'login'; ⋮---- -/** Modify Order */ -modifyOrder(params: ModifyFuturesOrder): Promise> +// When new WS API operations are added, make sure to also update WS_API_Operations[] below +export type WSAPIOperation = + | 'place-order' + | 'batch-place' + | 'cancel-order' + | 'batch-cancel'; ⋮---- -/** - * Cancel all futures orders for a symbol - */ -cancelSymbolOrders( - symbol: string, - marginCoin: string, -): Promise> +export interface WSOperationLoginParams { + apiKey: string; + passphrase: string; + timestamp: number; + sign: string; +} ⋮---- -/** Cancel All Order */ -cancelAllOrders( - productType: FuturesProductType, - marginCoin: string, -): Promise> +export interface WSAPIRequestBitgetV3 { + op: 'trade'; + id: string; + category: BitgetInstTypeV3; + topic: WSAPIOperation; + args: TWSParams | TWSParams[]; +} ⋮---- -/** Get Open Order */ -getOpenSymbolOrders(symbol: string): Promise> +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; +} ⋮---- -/** Get All Open Order */ -getOpenOrders( - productType: FuturesProductType, - marginCoin: string, -): Promise> +/** If true, will skip auth requirement for WS API connection */ ⋮---- -/** Get History Orders */ -getOrderHistory( - symbol: string, - startTime: string, - endTime: string, - pageSize: string, - lastEndId?: string, - isPre?: boolean, - clientOid?: string, -): Promise> +export type Exact = { + // This part says: if there's any key that's not in T, it's an error + [K: string]: never; +} & { + [K in keyof T]: T[K]; +}; ⋮---- -/** Get ProductType History Orders */ -getProductTypeOrderHistory( - productType: FuturesProductType, - startTime: string, - endTime: string, - pageSize: string, - lastEndId?: string, - isPre?: boolean, - clientOid?: string, -): Promise> +// This part says: if there's any key that's not in T, it's an error ⋮---- -/** Get order details */ -getOrder( - symbol: string, - orderId?: string, - clientOid?: string, -): Promise> +/** + +/** + * V2 request looks like this: +{ + "op":"subscribe", + "args":[ + { + "instType":"SPOT", + "channel":"ticker", + "instId":"BTCUSDT" + }, + { + "instType":"SPOT", + "channel":"candle5m", + "instId":"BTCUSDT" + } + ] +} + */ +export interface WsRequestOperationBitget { + op: WSOperation; + args?: (TWSRequestArg | string | number)[]; +} +export interface WSAPIResponse< + TResponseData extends object = object, + TOperation extends WSAPIOperation = WSAPIOperation, +> { + wsKey: WsKey; + /** Auto-generated */ + id: string; + event: 'trade'; + category: BitgetInstTypeV3; + topic: TOperation; + args: TResponseData; + code: '0' | string; + msg: 'success' | string; + ts: string; +} ⋮---- -/** Get transaction details / history (fills) */ -getOrderFills( - symbol: string, - orderId?: string, - pagination?: FuturesPagination, -): Promise> +/** Auto-generated */ ⋮---- -/** Get ProductType Order fill detail */ -getProductTypeOrderFills( - productType: FuturesProductType, - pagination?: FuturesPagination, -): Promise> +/** + * List of operations supported for this WsKey (connection) + */ +export interface WsAPIWsKeyTopicMap { + [WS_KEY_MAP.v3Private]: WSAPIOperation; +} ⋮---- -/** Place Plan order */ -submitPlanOrder(params: NewFuturesPlanOrder): Promise> +/** + * Request parameters expected per operation + */ +export interface WsAPITopicRequestParamMap { + // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + 'place-order': WSAPIPlaceOrderRequestV3; + // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + 'batch-place': WSAPIPlaceOrderRequestV3[]; + // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + 'cancel-order': CancelOrderRequestV3; + // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + 'batch-cancel': CancelOrderRequestV3[]; +} ⋮---- -/** Modify Plan Order */ -modifyPlanOrder(params: ModifyFuturesPlanOrder): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters ⋮---- -/** Modify Plan Order TPSL */ -modifyPlanOrderTPSL( - params: ModifyFuturesPlanOrderTPSL, -): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel ⋮---- -/** Place Stop order */ -submitStopOrder(params: NewFuturesPlanStopOrder): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel ⋮---- -/** Place Trailing Stop order */ -submitTrailingStopOrder( - params: NewFuturesPlanTrailingStopOrder, -): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel ⋮---- -/** Place Position TPSL */ -submitPositionTPSL( - params: NewFuturesPlanPositionTPSL, -): Promise> +/** + * Response structure expected for each operation + */ +export interface WsAPIOperationResponseMap { + // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + 'place-order': WSAPIResponse<[WSAPIPlaceOrderResponseV3], 'place-order'>; + // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + 'batch-place': WSAPIResponse; + // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + 'cancel-order': WSAPIResponse<[CancelOrderResponseV3], 'cancel-order'>; + // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + 'batch-cancel': WSAPIResponse; +} ⋮---- -/** Modify Stop Order */ -modifyStopOrder( - params: ModifyFuturesPlanStopOrder, -): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters ⋮---- -/** Cancel Plan Order (TPSL) */ -cancelPlanOrderTPSL( - params: CancelFuturesPlanTPSL, -): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel ⋮---- -/** Cancel Symbol Plan Order (TPSL) */ -cancelSymbolPlanOrders( - symbol: string, - planType: FuturesPlanType, -): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel ⋮---- -/** Cancel All Trigger Order (TPSL) */ -cancelAllPlanOrders( - productType: FuturesProductType, - planType: FuturesPlanType, -): Promise> +// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + +================ +File: src/websocket-client-v2.ts +================ +import { + WSOperation, + WSOperationLoginParams, + WsRequestOperationBitget, +} from './types/websockets/ws-api.js'; +import { MessageEventLike } from './types/websockets/ws-events.js'; +import { + BitgetInstTypeV2, + WsKey, + WsTopicV2, +} from './types/websockets/ws-general.js'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient.js'; +import { isWsPong } from './util/requestUtils.js'; +import { + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './util/webCryptoAPI.js'; +import { + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getWsUrl, + isPrivateChannel, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WsTopicRequest, +} from './util/websocket-util.js'; +import { WSConnectedResult } from './util/WsStore.types.js'; ⋮---- -/** Get Plan Order (TPSL) List */ -getPlanOrderTPSLs( - symbol: string, - isPlan?: string, - productType?: FuturesProductType, -): Promise> +export class WebsocketClientV2 extends BaseWebsocketClient< ⋮---- -/** Get History Plan Orders (TPSL) */ -getHistoricPlanOrdersTPSL( - params: HistoricPlanOrderTPSLRequest, -): Promise> +WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within ⋮---- /** - * - * Copy Trade Endpoints - * + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ +public connectAll(): Promise[] ⋮---- -/** Get Trader Open order */ -getCopyTraderOpenOrder( - symbol: string, - productType: FuturesProductType, - pageSize: number, - pageNo: number, -): Promise> -⋮---- -/** Get Followers Open Order */ -getCopyFollowersOpenOrder( - symbol: string, - productType: FuturesProductType, - pageSize: number, - pageNo: number, -): Promise> -⋮---- -/** Trader Close Position */ -closeCopyTraderPosition( - symbol: string, - trackingNo: string, -): Promise> -⋮---- -/** Trader Modify TPSL */ -modifyCopyTraderTPSL( - symbol: string, - trackingNo: string, - changes?: { - stopProfitPrice?: number; - stopLossPrice?: number; - }, -): Promise> -⋮---- -/** Get Traders History Orders */ -getCopyTraderOrderHistory( - startTime: string, - endTime: string, - pageSize: number, - pageNo: number, -): Promise> -⋮---- -/** Get Trader Profit Summary */ -getCopyTraderProfitSummary(): Promise> -⋮---- -/** Get Trader History Profit Summary (according to settlement currency) */ -getCopyTraderHistoricProfitSummary(): Promise> -⋮---- -/** Get Trader History Profit Summary (according to settlement currency and date) */ -getCopyTraderHistoricProfitSummaryByDate( - marginCoin: string, - dateMs: string, - pageSize: number, - pageNo: number, -): Promise> -⋮---- -/** Get Trader Histroy Profit Detail */ -getCopyTraderHistoricProfitDetail( - marginCoin: string, - dateMs: string, - pageSize: number, - pageNo: number, -): Promise> -⋮---- -/** Get Trader Profits Details */ -getCopyTraderProfitDetails( - pageSize: number, - pageNo: number, -): Promise> -⋮---- -/** Get CopyTrade Symbols */ -getCopyTraderSymbols(): Promise> -⋮---- -/** Trader Change CopyTrade symbol */ -setCopyTraderSymbols( - symbol: string, - operation: 'add' | 'delete', -): Promise> - -================ -File: src/spot-client.ts -================ -import { GetHistoricTradesParams, Pagination } from './types/request/shared.js'; -import { - BatchCancelSpotOrderV2, - CancelSpotOrderV2, - CancelSpotPlanOrderParams, - GetHistoricPlanOrdersParams, - GetSpotPlanOrdersParams, - ModifySpotPlanOrder, - NewBatchSpotOrder, - NewSpotOrder, - NewSpotPlanOrder, - NewSpotSubTransfer, - NewSpotWithdraw, - NewWalletTransfer, - SpotCandleData, - SpotKlineInterval, -} from './types/request/v1/spotV1.js'; -import { APIResponse, VIPFeeRate } from './types/response/v1/shared.js'; -import { - CoinBalance, - SpotMarketTrade, - SpotOrderResult, - SpotPlanOrder, - SymbolRules, -} from './types/response/v1/spot.js'; -import BaseRestClient from './util/BaseRestClient.js'; -import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; +/** Some private channels use `coin` instead of `instId`. This method handles building the sub/unsub request */ +private getSubRequest( + instType: BitgetInstTypeV2, + topic: WsTopicV2, + coin: string = 'default', +): WsTopicRequest ⋮---- /** - * REST API client for the V1 bitget Spot APIs. These are the previous generation of Bitget's APIs and should be considered deprecated. - * These will be removed in a future release, once Bitget formally deprecates them. - * - * @deprecated use RestClientV2 instead - */ -export class SpotClient extends BaseRestClient -⋮---- -getClientType() -⋮---- -async fetchServerTime(): Promise + * Subscribe to a topic + * @param instType instrument type (refer to API docs). + * @param topic topic name (e.g. "ticker"). + * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics. + */ +public subscribeTopic( + instType: BitgetInstTypeV2, + topic: WsTopicV2, + coin: string = 'default', +) ⋮---- /** - * - * Public - * + * Unsubscribe from a topic + * @param instType instrument type (refer to API docs). + * @param topic topic name (e.g. "ticker"). + * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics to get all symbols. */ -/** Get Server Time */ -getServerTime(): Promise> -⋮---- -/** Get Coin List : Get all coins information on the platform */ -getCoins(): Promise> -⋮---- -/** Get Symbols : Get basic configuration information of all trading pairs (including rules) */ -getSymbols(): Promise> -⋮---- -/** Get Single Symbol : Get basic configuration information for one symbol */ -getSymbol(symbol: string): Promise> +public unsubscribeTopic( + instType: BitgetInstTypeV2, + topic: WsTopicV2, + coin: string = 'default', +) ⋮---- /** + * Request subscription to one or more topics. Pass topics as either an array of strings, + * or array of objects (if the topic has parameters). + * + * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. * - * Market + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. * + * Call `unsubscribe(topics)` to remove topics */ -⋮---- -/** Get Single Ticker */ -getTicker(symbol: string): Promise> -⋮---- -/** Get All Tickers */ -getAllTickers(): Promise> -⋮---- -/** Get most recent trades (up to 500, 100 by default) */ -getRecentTrades( - symbol: string, - limit?: string, -): Promise> -⋮---- -/** Get historic trades, up to 30 days at a time. Same-parameter responses are cached for 10 minutes. */ -getHistoricTrades( - params: GetHistoricTradesParams, -): Promise> +public subscribe( + requests: + | (WsTopicRequest | WsTopicV2) + | (WsTopicRequest | WsTopicV2)[], + wsKey: WsKey, +): Promise ⋮---- /** - * @deprecated use getRecentTrades() instead. This method will be removed soon. + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * + * - Requests are automatically routed to the correct websocket connection. + * - These topics will be removed from the topic cache, so they won't be subscribed to again. */ -getMarketTrades( - symbol: string, - limit?: string, -): Promise> -⋮---- -/** Get Candle Data */ -getCandles( - symbol: string, - period: SpotKlineInterval, - pagination?: Pagination, -): Promise> -⋮---- -/** Get Depth */ -getDepth( - symbol: string, - type: 'step0' | 'step1' | 'step2' | 'step3' | 'step4' | 'step5', - limit?: string, -): Promise> -⋮---- -/** Get VIP fee rates */ -getVIPFeeRates(): Promise> +public unsubscribe( + requests: + | (WsTopicRequest | WsTopicV2) + | (WsTopicRequest | WsTopicV2)[], + wsKey: WsKey, +) ⋮---- /** * - * Wallet Endpoints + * + * Internal methods required to integrate with the BaseWSClient + * * */ ⋮---- -/** Initiate wallet transfer */ -transfer(params: NewWalletTransfer): Promise> -⋮---- -/** Initiate wallet transfer (v2 endpoint) */ -transferV2(params: NewWalletTransfer): Promise> +protected sendPingEvent(wsKey: WsKey): void ⋮---- -/** - * Transfer main-sub, sub-sub or sub-main - */ -subTransfer(params: NewSpotSubTransfer): Promise> +protected sendPongEvent(wsKey: WsKey): void ⋮---- -/** Get Coin Address */ -getDepositAddress(coin: string, chain?: string): Promise> +protected isWsPing(data: any): boolean ⋮---- -/** Withdraw Coins On Chain */ -withdraw(params: NewSpotWithdraw): Promise> +protected isWsPong(data: any): boolean ⋮---- -/** Withdraw Coins On Chain (v2 endpoint) */ -withdrawV2(params: NewSpotWithdraw): Promise> +protected isPrivateTopicRequest( + _request: WsTopicRequest, + wsKey: WsKey, +): boolean ⋮---- -/** Inner Withdraw : Internal withdrawal means that both users are on the Bitget platform */ -innerWithdraw( - coin: string, - toUid: string, - amount: string, - clientOid?: string, -): Promise> +protected getPrivateWSKeys(): WsKey[] ⋮---- -/** Inner Withdraw (v2 endpoint) : Internal withdrawal means that both users are on the Bitget platform */ -innerWithdrawV2( - coin: string, - toUid: string, - amount: string, - clientOid?: string, -): Promise> +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -/** Get Withdraw List */ -getWithdrawals( - coin: string, - startTime: string, - endTime: string, - pageSize?: string, - pageNo?: string, - clientOid?: string, -): Promise> +protected async getWsUrl(wsKey: WsKey): Promise ⋮---- -/** Get Deposit List */ -getDeposits( - coin: string, - startTime: string, - endTime: string, - pageSize?: string, - pageNo?: string, -): Promise> +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** - * - * Account Endpoints - * + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ +protected async getWsRequestEvents( + operation: WSOperation, + requests: WsTopicRequest[], +): Promise>[]> ⋮---- -/** Get ApiKey Info */ -getApiKeyInfo(): Promise> -⋮---- -/** Get Account : get account assets */ -getBalance(coin?: string): Promise> -⋮---- -/** Get sub Account Spot Asset */ -getSubAccountSpotAssets(): Promise> -⋮---- -/** Get Bills : get transaction detail flow */ -getTransactionHistory(params?: { - coinId?: number; - groupType?: string; - bizType?: string; - after?: string; - before?: string; - limit?: number; -}): Promise> -⋮---- -/** Get Transfer List */ -getTransferHistory(params?: { - coinId?: number; - fromType?: string; - after?: string; - before?: string; - limit?: number; - clientOid?: string; -}): Promise> +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- /** - * - * Trade Endpoints - * - */ + { + "op":"subscribe", + "args":[ + { + "instType":"SPOT", + "channel":"ticker", + "instId":"BTCUSDT" + }, + { + "instType":"SPOT", + "channel":"candle5m", + "instId":"BTCUSDT" + } + ] + } + */ ⋮---- -/** Place order */ -submitOrder(params: NewSpotOrder): Promise> +// const request = { +// topic: 'ticker', +// payload: { instType: 'SPOT', instId: 'BTCUSDT' }, +// }; +// becomes: +// const request = { +// channel: 'ticker', +// instType: 'SPOT', +// instId: 'BTCUSDT', +// }; ⋮---- -/** Place orders in batches, up to 50 at a time */ -batchSubmitOrder( - symbol: string, - orderList: NewBatchSpotOrder[], -): Promise> +private async getWsAuthSignature( + wsKey: WsKey, +): Promise< ⋮---- -/** Cancel order */ -cancelOrder(symbol: string, orderId: string): Promise> +private async signMessage( + paramsStr: string, + secret: string, + method: SignEncodeMethod, + algorithm: SignAlgorithm, +): Promise ⋮---- -/** Cancel order (v2 endpoint - supports orderId or clientOid) */ -cancelOrderV2(params?: CancelSpotOrderV2): Promise> +protected async getWsAuthRequestEvent( + wsKey: WsKey, +): Promise> ⋮---- /** - * Cancel all spot orders for a symbol + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ -cancelSymbolOrders(symbol: string): Promise> -⋮---- -/** Cancel order in batch (per symbol) */ -batchCancelOrder( - symbol: string, - orderIds: string[], -): Promise> -⋮---- -/** Cancel order in batch (per symbol). V2 endpoint, supports orderIds or clientOids. */ -batchCancelOrderV2( - params: BatchCancelSpotOrderV2, -): Promise> -⋮---- -/** Get order details */ -getOrder( - symbol: string, - orderId: string, - clientOrderId?: string, -): Promise> -⋮---- -/** Get order list (open orders) */ -getOpenOrders(symbol?: string): Promise> -⋮---- -/** Get order history for a symbol */ -getOrderHistory( - symbol: string, - pagination?: Pagination, -): Promise> +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] ⋮---- -/** Get transaction details / history (fills) for an order */ -getOrderFills( - symbol: string, - orderId: string, - pagination?: Pagination, -): Promise> +// v2 event processing ⋮---- -/** Place plan order */ -submitPlanOrder( - params: NewSpotPlanOrder, -): Promise> +// v2 authentication event ⋮---- -/** Modify plan order */ -modifyPlanOrder( - params: ModifySpotPlanOrder, -): Promise> +// messageType: typeof msg, +// messageString: JSON.stringify(msg), ⋮---- -/** Cancel plan order */ -cancelPlanOrder( - params: CancelSpotPlanOrderParams, -): Promise> +// messageType: typeof msg, +// messageString: JSON.stringify(msg), ⋮---- -/** Get current plan orders */ -getCurrentPlanOrders(params: GetSpotPlanOrdersParams): Promise< - APIResponse<{ - nextFlag: boolean; - endId: number; - orderList: SpotPlanOrder[]; - }> - > { - return this.postPrivate('/api/spot/v1/plan/currentPlan', params); +// fallback emit anyway ⋮---- -/** Get history plan orders */ -getHistoricPlanOrders(params: GetHistoricPlanOrdersParams): Promise< - APIResponse<{ - nextFlag: boolean; - endId: number; - orderList: SpotPlanOrder[]; - }> - > { - return this.postPrivate('/api/spot/v1/plan/historyPlan', params); +/** + * @deprecrated not supported by Bitget's V2 API offering + */ +async sendWSAPIRequest(): Promise ================ -File: webpack/webpack.config.js +File: src/websocket-client-v3.ts ================ -function generateConfig(name) -⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. -⋮---- -// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. +import { + WsAPIOperationResponseMap, + WSAPIRequestBitgetV3, + WSAPIRequestFlags, + WsAPITopicRequestParamMap, + WsAPIWsKeyTopicMap, + WSOperation, + WSOperationLoginParams, + WsRequestOperationBitget, +} from './types/websockets/ws-api.js'; +import { MessageEventLike } from './types/websockets/ws-events.js'; +import { + BitgetInstTypeV3, + WsKey, + WsTopicV3, +} from './types/websockets/ws-general.js'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient.js'; +import { isWsPong } from './util/requestUtils.js'; +import { isWSAPIResponse } from './util/type-guards.js'; +import { SignAlgorithm, signMessage } from './util/webCryptoAPI.js'; +import { + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getPromiseRefForWSAPIRequest, + getWsUrl, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WS_LOGGER_CATEGORY, + WsTopicRequest, +} from './util/websocket-util.js'; +import { WSConnectedResult } from './util/WsStore.types.js'; ⋮---- -// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. - -================ -File: .nvmrc -================ -v22.17.1 - -================ -File: jest.config.ts -================ /** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration + * WebSocket client dedicated to the unified account (V3) WebSockets. + * + * Your Bitget account needs to be upgraded to unified account mode, to use the account-level WebSocket topics. */ +export class WebsocketClientV3 extends BaseWebsocketClient< ⋮---- -import type { Config } from 'jest'; +WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +public connectAll(): Promise[] +⋮---- +/** + * Ensures the WS API connection is active and ready. + * + * You do not need to call this, but if you call this before making any WS API requests, + * it can accelerate the first request (by preparing the connection in advance). + */ +public connectWSAPI(): Promise +⋮---- +/** This call automatically ensures the connection is active AND authenticated before resolving */ +⋮---- +/** + * Request subscription to one or more topics. Pass topics as either an array of strings, + * or array of objects (if the topic has parameters). + * + * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. + * + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. + * + * Call `unsubscribe(topics)` to remove topics + */ +public subscribe( + requests: + | (WsTopicRequest | WsTopicV3) + | (WsTopicRequest | WsTopicV3)[], + wsKey: WsKey, +): Promise +⋮---- +/** + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * + * - Requests are automatically routed to the correct websocket connection. + * - These topics will be removed from the topic cache, so they won't be subscribed to again. + */ +public unsubscribe( + requests: + | (WsTopicRequest | WsTopicV3) + | (WsTopicRequest | WsTopicV3)[], + wsKey: WsKey, +) +⋮---- +/** + * + * + * Internal methods required to integrate with the BaseWSClient + * + * + */ +⋮---- +protected sendPingEvent(wsKey: WsKey): void +⋮---- +protected sendPongEvent(wsKey: WsKey): void +⋮---- +protected isWsPing(data: any): boolean +⋮---- +protected isWsPong(data: any): boolean +⋮---- +protected isPrivateTopicRequest( + _request: WsTopicRequest, + wsKey: WsKey, +): boolean +⋮---- +protected getPrivateWSKeys(): WsKey[] +⋮---- +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +⋮---- +protected async getWsUrl(wsKey: WsKey): Promise +⋮---- +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +⋮---- +/** + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + */ +protected async getWsRequestEvents( + operation: WSOperation, + requests: WsTopicRequest[], +): Promise>[]> +⋮---- +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +⋮---- +/** + { + "op":"subscribe", + "args":[ + { + "instType":"spot", + "topic":"ticker", + "symbol":"BTCUSDT" + }, + { + "instType":"spot", + "topic":"candle5m", + "symbol":"BTCUSDT" + } + ] + } + */ +⋮---- +// const request = { +// topic: 'ticker', +// payload: { instType: 'spot', symbol: 'BTCUSDT' }, +// }; +// becomes: +// const request = { +// topic: 'ticker', +// instType: 'spot', +// symbol: 'BTCUSDT', +// }; +⋮---- +private async getWsAuthSignature( + wsKey: WsKey, +): Promise< +⋮---- +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise +⋮---- +protected async getWsAuthRequestEvent( + wsKey: WsKey, +): Promise> +⋮---- +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] +⋮---- +/** + * WS API response handling + */ +⋮---- +// const eg1 = { +// event: 'error', +// id: '1', +// code: '43012', +// msg: 'Insufficient balance', +// }; +⋮---- +// WS API Success +⋮---- +/** + * V3 event handling for consumers - behaves the same as V2 + */ +⋮---- +// v2 authentication event +⋮---- +// messageType: typeof msg, +// messageString: JSON.stringify(msg), +⋮---- +// messageType: typeof msg, +// messageString: JSON.stringify(msg), +⋮---- +// fallback emit anyway +⋮---- +/** + * V3/UTA supports order placement via WebSockets. This is the WS API: + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel + * + * @returns a promise that resolves/rejects when a matching response arrives + */ +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends WsAPITopicRequestParamMap[TWSOperation], + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: WsKey, + operation: TWSOperation, + category: BitgetInstTypeV3, + params: TWSParams & { signRequest?: boolean }, + requestFlags?: WSAPIRequestFlags, +): Promise +⋮---- +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +⋮---- +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +⋮---- +// Ensure "args" is always wrapped as array +⋮---- +// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +// Enrich returned promise with request context for easier debugging +⋮---- +// throw e; +⋮---- +// Send event +⋮---- +// Return deferred promise, so caller can await this call + +================ +File: webpack/webpack.config.cjs +================ +function generateConfig(name) +⋮---- +// Add '.ts' and '.tsx' as resolvable extensions. +⋮---- +// Node.js core modules not available in browsers +// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers +⋮---- +// Code is already transpiled from TypeScript, no additional loaders needed + +================ +File: jest.config.ts +================ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ +⋮---- +import type { Config } from 'jest'; +⋮---- +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- // Stop running tests after `n` failures // bail: 0, @@ -7204,169 +6234,12 @@ File: tsconfig.linting.json } ================ -File: examples/deprecated-V1-Websockets/ws-private.ts +File: src/constants/enum.ts ================ -import { DefaultLogger, WebsocketClientLegacyV1 } from '../../src'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bitget-api'; -⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, -⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); -⋮---- -// auth happens async after the ws connection opens -⋮---- -// wsClient.subscribePublicSpotTickers(['BTCUSDT', 'LTCUSDT']); -⋮---- -/** - * Private account updates - */ -⋮---- -// spot private -// : account updates -⋮---- -// : order updates -// wsClient.subscribeTopic('SPBL', 'orders'); -⋮---- -// futures private -// : account updates -// wsClient.subscribeTopic('UMCBL', 'account'); -// // : position updates -// wsClient.subscribeTopic('UMCBL', 'positions'); -// // : order updates -// wsClient.subscribeTopic('UMCBL', 'orders'); -// // : plan order updates -// wsClient.subscribeTopic('UMCBL', 'ordersAlgo'); +/** Parameter verification exception margin mode == FIXED */ ================ -File: examples/V3/rest-trade-UTA-futures.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - PlaceOrderRequestV3, - RestClientV3, - WebsocketClientV3, -} from '../../src'; -⋮---- -// or -// import { PlaceOrderRequestV3, RestClientV3, WebsocketClientV3 } from '../src'; -⋮---- -// read from environmental variables -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-futures.ts -⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed -⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', -⋮---- -function logWSEvent(type, data) -⋮---- -// simple sleep function -function promiseSleep(milliseconds) -⋮---- -/** - * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). - * - * It is designed to: - * - open a private websocket channel to log account events - * - check for any available USDT balance in the account - * - immediately open a minimum sized long position on BTCUSDT - * - check active positions - * - immediately send closing orders for any active futures positions - * - check positions again - * - */ -⋮---- -// Add event listeners to log websocket events on account -⋮---- -// Subscribe to private topics for UTA account -⋮---- -// Subscribe to position updates -⋮---- -// Subscribe to order updates -⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) -⋮---- -// Loop through any active positions and send a closing market order on each position - -================ -File: examples/V3/rest-trade-UTA-spot.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - PlaceOrderRequestV3, - RestClientV3, - WebsocketClientV3, -} from '../../src/index'; -⋮---- -// import { RestClientV3, WebsocketClientV3 } from '../src/index'; -⋮---- -// read from environmental variables -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-spot.ts -⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed -⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', -⋮---- -function logWSEvent(type, data) -⋮---- -// simple sleep function -function promiseSleep(milliseconds) -⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ -⋮---- -// Add event listeners to log websocket events on account -⋮---- -// Subscribe to private account topics -// Account updates for UTA (unified trading account) -⋮---- -// Order updates for spot -⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) - -================ -File: examples/V3/ws-private.ts -================ -import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts -⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); -⋮---- -// You can subscribe to one topic at a time -⋮---- -instType: 'UTA', // Note: all account events go on the UTA instType -⋮---- -WS_KEY_MAP.v3Private, // This parameter points to private or public -⋮---- -// Note: all account events go on the UTA instType -⋮---- -// Or multiple at once: -⋮---- -// Topics are tracked per websocket type -// The below example will pull a list of subscribed topics on that connection (e.g. all private topics), after a 5 second delay: - -================ -File: src/constants/enum.ts -================ -/** Parameter verification exception margin mode == FIXED */ - -================ -File: src/types/request/v2/broker.ts +File: src/types/request/v2/broker.ts ================ /** * @@ -7565,510 +6438,224 @@ export interface GetBrokerRebateInfoRequestV2 { } ================ -File: src/types/request/v3/account.ts +File: src/types/response/v2/broker.ts ================ -// Account Management Request Types -⋮---- -export interface SetLeverageRequestV3 { - category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - leverage: string; - coin?: string; - posSide?: 'long' | 'short'; -} -⋮---- -export interface GetConvertRecordsRequestV3 { - fromCoin: string; - toCoin: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetFinancialRecordsRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - coin?: string; - type?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +/** + * + * * Broker | Subaccount + * + */ ⋮---- -export interface RepayRequestV3 { - repayableCoinList: string[]; - paymentCoinList: string[]; +export interface CreateSubaccountResponseV2 { + subUid: string; + subaccountName: string; + status: string; + permList: string[]; + label: string; + cTime: string; } ⋮---- -// Sub-account Management Request Types -⋮---- -export interface CreateSubAccountApiKeyRequestV3 { +export interface BrokerSubaccountV2 { subUid: string; - note: string; - type: 'read_write' | 'read_only'; - passphrase: string; - permissions: string[]; - ips: string[]; + subaccountName: string; + status: string; + permList: string[]; + label: string; + language: string; + cTime: string; + uTime: string; } ⋮---- -export interface DeleteSubAccountApiKeyRequestV3 { - apiKey: string; +export interface ModifySubaccountResponseV2 { + subUid: string; + subaccountName: string; + status: string; + permList: string[]; + label: string; + language: string; + cTime: string; + uTime: string; } ⋮---- -export interface GetSubAccountApiKeysRequestV3 { +export interface SubaccountEmailV2 { subUid: string; - limit?: string; - cursor?: string; + subaccountName: string; + subaccountEmail: string; + cTime: string; + uTime: string; } ⋮---- -export interface UpdateSubAccountApiKeyRequestV3 { - apiKey: string; - passphrase: string; - type?: 'read_write' | 'read_only'; - permissions?: string[]; - ips?: string[]; +export interface BrokerSubaccountSpotAssetV2 { + coin: string; + available: string; + frozen: string; + locked: string; + uTime: string; } ⋮---- -export interface CreateSubAccountRequestV3 { - username: string; - accountMode?: 'classic' | 'unified'; - note?: string; +export interface BrokerSubaccountFutureAssetV2 { + marginCoin: string; + available: string; + frozen: string; + locked: string; + crossedMaxAvailable: string; + isolatedMaxAvailable: string; + maxTransferOut: string; + accountEquity: string; + usdtEquity: string; + btcEquity: string; + uTime: string; } ⋮---- -export interface FreezeSubAccountRequestV3 { +export interface CreateSubaccountDepositAddressV2 { subUid: string; - operation: 'freeze' | 'unfreeze'; -} -⋮---- -export interface GetSubAccountListRequestV3 { - limit?: string; - cursor?: string; + coin: string; + address: string; + chain: string; + tag: string; + url: string; + cTime: string; } ⋮---- -// Transfer Request Types -⋮---- -export interface TransferRequestV3 { - fromType: - | 'spot' - | 'p2p' - | 'coin-futures' - | 'usdt-futures' - | 'usdc-futures' - | 'crossed-margin' - | 'isolated-margin' - | 'uta'; - toType: - | 'spot' - | 'p2p' - | 'coin-futures' - | 'usdt-futures' - | 'usdc-futures' - | 'crossed-margin' - | 'isolated-margin' - | 'uta'; - amount: string; +export interface SubaccountDepositV2 { + orderId: string; + txId: string; coin: string; - symbol?: string; -} -⋮---- -export interface GetTransferableCoinsRequestV3 { - fromType: - | 'spot' - | 'p2p' - | 'coin-futures' - | 'usdt-futures' - | 'usdc-futures' - | 'crossed-margin' - | 'isolated-margin' - | 'uta'; - toType: - | 'spot' - | 'p2p' - | 'coin-futures' - | 'usdt-futures' - | 'usdc-futures' - | 'crossed-margin' - | 'isolated-margin' - | 'uta'; -} -⋮---- -export interface GetSubTransferRecordsRequestV3 { - subUid?: string; - role?: 'initiator' | 'receiver'; - coin?: string; - startTime?: string; - endTime?: string; - clientOid?: string; - limit?: string; - cursor?: string; + type: string; + dest: string; + amount: string; + status: string; + fromAddress: string; + toAddress: string; + fee: string; + chain: string; + confirm: string; + tag: string; + cTime: string; + uTime: string; } ⋮---- -export interface SubAccountTransferRequestV3 { - fromType: - | 'spot' - | 'p2p' - | 'usdt_futures' - | 'coin_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'uta'; - toType: - | 'spot' - | 'p2p' - | 'usdt_futures' - | 'coin_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'uta'; - amount: string; +export interface BrokerSubaccountWithdrawalV2 { + orderId: string; + txId: string; coin: string; - fromUserId: string; - toUserId: string; - clientOid: string; + type: string; + dest: string; + amount: string; + status: string; + fromAddress: string; + toAddress: string; + fee: string; + chain: string; + confirm: string; + tag: string; + userId: string; + cTime: string; + uTime: string; } ⋮---- -export interface GetSubUnifiedAssetsRequestV3 { - subUid?: string; - cursor?: string; - limit?: string; -} +/** + * + * Broker | Api Key + * + */ ⋮---- -export interface GetFeeRateRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; +export interface CreateSubaccountApiKeyResponseV2 { + subUid: string; + apiKey: string; + secretKey: string; + label: string; + ipList: string[]; + permType: string; + permList: string[]; } ⋮---- -export interface GetFundingAssetsRequestV3 { - coin?: string; +export interface SubaccountApiKeyV2 { + subUid: string; + label: string; + apiKey: string; + secretKey: string; + permType: string; + permList: string[]; + ipList: string[]; } ⋮---- -export interface SwitchDeductRequestV3 { - deduct: 'on' | 'off'; +export interface ModifySubaccountApiKeyResponseV2 { + subUid: string; + apiKey: string; + label: string; + ipList: string[]; + permType: string; + permList: string[]; } ⋮---- -// Deposit Request Types -⋮---- -export interface GetDepositAddressRequestV3 { - coin: string; - chain?: string; - size?: string; -} +/** + * + * * Broker | All Sub-accounts Deposit and Withdrawal Records + * + */ ⋮---- -export interface GetSubDepositAddressRequestV3 { - subUid: string; +export interface AllSubDepositWithdrawalRecordV2 { + uid: string; + txId: string; + type: 'deposit' | 'withdrawal'; + subType: 'onchain' | 'internal' | 'fast'; coin: string; - chain?: string; - size?: string; + amount: string; + status: 'pending' | 'fail' | 'success'; + ts: string; } ⋮---- -export interface GetDepositRecordsRequestV3 { - coin?: string; - orderId?: string; - startTime: string; - endTime: string; - limit?: string; - cursor?: string; -} +/** + * + * * Broker | Subaccounts + * + */ ⋮---- -export interface GetSubDepositRecordsRequestV3 { - coin?: string; - subUid: string; - startTime: string; - endTime: string; - limit?: string; - cursor?: string; +export interface BrokerSubaccountInfoV2 { + uid: string; + asset: string; + firstTimeDeposit: string; + firstTimeTrade: string; + registerTime: string; } ⋮---- -// Withdraw Request Types +/** + * + * * Broker | Commissions + * + */ ⋮---- -export interface WithdrawRequestV3 { +export interface BrokerCommissionV2 { + uid: string; coin: string; - chain?: string; - transferType: 'on_chain' | 'internal_transfer'; - address: string; - innerToType?: 'uid' | 'email' | 'mobile'; - areaCode?: string; - tag?: string; - size: string; - remark?: string; - clientOid?: string; - memberCode?: 'bithumb' | 'korbit' | 'coinone'; - identityType?: 'company' | 'user'; - companyName?: string; - firstName?: string; - lastName?: string; + symbol: string; + dealtAmount: string; + totalFee: string; + deductedFee: string; + paidFee: string; + markUpFee: string; + totalCommission: string; } ⋮---- -export interface GetWithdrawRecordsRequestV3 { - coin?: string; - orderId?: string; - clientOid?: string; - startTime: string; - endTime: string; - limit?: string; - cursor?: string; -} +/** + * + * * Broker | Trade Volume + * + */ ⋮---- -export interface SetDepositAccountRequestV3 { - coin: string; - accountType: 'funding' | 'unified' | 'otc'; +export interface BrokerTradeVolumeV2 { + uid: string; + volume: string; + spotVolume: string; + futureVolume: string; } ⋮---- -export interface GetMaxTransferableRequestV3 { - coin: string; -} -⋮---- -export interface GetOpenInterestLimitRequestV3 { - symbol: string; - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; -} -⋮---- -export interface GetTaxRecordsRequestV3 { - bizType: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES' - | 'OTHER'; - marginType?: 'isolated' | 'crossed'; - coin?: string; - startTime: string; - endTime: string; - limit?: string; - cursor?: string; -} - -================ -File: src/types/response/v2/broker.ts -================ -/** - * - * * Broker | Subaccount - * - */ -⋮---- -export interface CreateSubaccountResponseV2 { - subUid: string; - subaccountName: string; - status: string; - permList: string[]; - label: string; - cTime: string; -} -⋮---- -export interface BrokerSubaccountV2 { - subUid: string; - subaccountName: string; - status: string; - permList: string[]; - label: string; - language: string; - cTime: string; - uTime: string; -} -⋮---- -export interface ModifySubaccountResponseV2 { - subUid: string; - subaccountName: string; - status: string; - permList: string[]; - label: string; - language: string; - cTime: string; - uTime: string; -} -⋮---- -export interface SubaccountEmailV2 { - subUid: string; - subaccountName: string; - subaccountEmail: string; - cTime: string; - uTime: string; -} -⋮---- -export interface BrokerSubaccountSpotAssetV2 { - coin: string; - available: string; - frozen: string; - locked: string; - uTime: string; -} -⋮---- -export interface BrokerSubaccountFutureAssetV2 { - marginCoin: string; - available: string; - frozen: string; - locked: string; - crossedMaxAvailable: string; - isolatedMaxAvailable: string; - maxTransferOut: string; - accountEquity: string; - usdtEquity: string; - btcEquity: string; - uTime: string; -} -⋮---- -export interface CreateSubaccountDepositAddressV2 { - subUid: string; - coin: string; - address: string; - chain: string; - tag: string; - url: string; - cTime: string; -} -⋮---- -export interface SubaccountDepositV2 { - orderId: string; - txId: string; - coin: string; - type: string; - dest: string; - amount: string; - status: string; - fromAddress: string; - toAddress: string; - fee: string; - chain: string; - confirm: string; - tag: string; - cTime: string; - uTime: string; -} -⋮---- -export interface BrokerSubaccountWithdrawalV2 { - orderId: string; - txId: string; - coin: string; - type: string; - dest: string; - amount: string; - status: string; - fromAddress: string; - toAddress: string; - fee: string; - chain: string; - confirm: string; - tag: string; - userId: string; - cTime: string; - uTime: string; -} -⋮---- -/** - * - * Broker | Api Key - * - */ -⋮---- -export interface CreateSubaccountApiKeyResponseV2 { - subUid: string; - apiKey: string; - secretKey: string; - label: string; - ipList: string[]; - permType: string; - permList: string[]; -} -⋮---- -export interface SubaccountApiKeyV2 { - subUid: string; - label: string; - apiKey: string; - secretKey: string; - permType: string; - permList: string[]; - ipList: string[]; -} -⋮---- -export interface ModifySubaccountApiKeyResponseV2 { - subUid: string; - apiKey: string; - label: string; - ipList: string[]; - permType: string; - permList: string[]; -} -⋮---- -/** - * - * * Broker | All Sub-accounts Deposit and Withdrawal Records - * - */ -⋮---- -export interface AllSubDepositWithdrawalRecordV2 { - uid: string; - txId: string; - type: 'deposit' | 'withdrawal'; - subType: 'onchain' | 'internal' | 'fast'; - coin: string; - amount: string; - status: 'pending' | 'fail' | 'success'; - ts: string; -} -⋮---- -/** - * - * * Broker | Subaccounts - * - */ -⋮---- -export interface BrokerSubaccountInfoV2 { - uid: string; - asset: string; - firstTimeDeposit: string; - firstTimeTrade: string; - registerTime: string; -} -⋮---- -/** - * - * * Broker | Commissions - * - */ -⋮---- -export interface BrokerCommissionV2 { - uid: string; - coin: string; - symbol: string; - dealtAmount: string; - totalFee: string; - deductedFee: string; - paidFee: string; - markUpFee: string; - totalCommission: string; -} -⋮---- -/** - * - * * Broker | Trade Volume - * - */ -⋮---- -export interface BrokerTradeVolumeV2 { - uid: string; - volume: string; - spotVolume: string; - futureVolume: string; -} -⋮---- -/** - * - * * Broker | Total Commission - * - */ +/** + * + * * Broker | Total Commission + * + */ ⋮---- export interface BrokerTotalCommissionV2 { date: string; @@ -8133,1263 +6720,1184 @@ export interface BrokerRebateInfoV2 { } ================ -File: src/types/response/v2/futures.ts +File: src/types/response/v3/public.ts ================ -/** - * - * * Futures | Market - * - */ +export interface PublicFillV3 { + execId: string; + price: string; + size: string; + side: 'sell' | 'buy'; + ts: string; +} ⋮---- -export interface FuturesVipFeeRateV2 { - level: string; - dealAmount: string; - assetAmount: string; - takerFeeRate: string; - makerFeeRate: string; - btcWithdrawAmount: string; - usdtWithdrawAmount: string; +export interface CandlestickV3 extends Array { + 0: string; // timestamp + 1: string; // open price + 2: string; // high price + 3: string; // low price + 4: string; // close price + 5: string; // volume + 6: string; // turnover } ⋮---- -export interface FuturesHistoryInterestRateV2 { - ts: string; - annualInterestRate: string; - dailyInterestRate: string; +0: string; // timestamp +1: string; // open price +2: string; // high price +3: string; // low price +4: string; // close price +5: string; // volume +6: string; // turnover +⋮---- +export interface ContractOiV3 { + symbol: string; + notionalValue: string; + totalNotionalValue: string; } ⋮---- -export interface FuturesInterestExchangeRateV2 { - tier: string; - minAmount: string; - maxAmount: string; - exchangeRate: string; +export interface CurrentFundingRateV3 { + symbol: string; + fundingRate: string; + fundingRateInterval: string; + nextUpdate: string; + minFundingRate: string; + maxFundingRate: string; } ⋮---- -export interface FuturesDiscountRateV2 { - tier: string; - minAmount: string; - maxAmount: string; +export interface DiscountRateTierV3 { + tierStartValue: string; discountRate: string; } ⋮---- -export interface FuturesDiscountRatesV2 { +export interface DiscountRateV3 { coin: string; - userLimit: string; - totalLimit: string; - discountRateList: FuturesDiscountRateV2[]; -} -⋮---- -export interface FuturesMergeDepthV2 { - asks: [number, number][]; - bids: [number, number][]; - ts: string; - scale: string; - precision: string; - isMaxPrecision: string; + list: DiscountRateTierV3[]; } ⋮---- -export interface FuturesTickerV2 { +export interface HistoryFundingRateV3 { symbol: string; - lastPr: string; - askPr: string; - bidPr: string; - bidSz: string; - askSz: string; - high24h: string; - low24h: string; - ts: string; - change24h: string; - baseVolume: string; - quoteVolume: string; - usdtVolume: string; - openUtc: string; - changeUtc24h: string; - indexPrice: string; fundingRate: string; - holdingAmount: string; - deliveryStartTime: string; - deliveryTime: string; - deliveryStatus: string; - open24h: string; - markPrice: string; + fundingRateTimestamp: string; } ⋮---- -export interface FuturesFillV2 { - tradeId: string; - price: string; - size: string; - side: string; - ts: string; - symbol: string; +export interface MarginLoanV3 { + dailyInterest: string; + annualInterest: string; + limit: string; } ⋮---- -export type FuturesCandlestickV2 = [ - string, // timestamp - string, // open - string, // high - string, // low - string, // close - string, // baseVolume - string, // usdtVolume - string, // quoteVolume -]; -⋮---- -string, // timestamp -string, // open -string, // high -string, // low -string, // close -string, // baseVolume -string, // usdtVolume -string, // quoteVolume -⋮---- -export interface FuturesOpenInterestV2 { +export interface OpenInterestItemV3 { symbol: string; - size: string; + openInterest: string; } ⋮---- -export interface FuturesFundingTimeV2 { - symbol: string; - nextFundingTime: string; - ratePeriod: string; +export interface OpenInterestV3 { + list: OpenInterestItemV3[]; + ts: string; } ⋮---- -export interface FuturesSymbolPriceV2 { - symbol: string; - price: string; - indexPrice: string; - markPrice: string; +export interface PositionTierV3 { + tier: string; + minTierValue: string; + maxTierValue: string; + leverage: string; + mmr: string; +} +⋮---- +export interface RiskReserveRecordV3 { + balance: string; + amount: string; ts: string; } ⋮---- -export interface FuturesHistoricalFundingRateV2 { - symbol: string; - fundingRate: string; - fundingTime: string; +export interface RiskReserveV3 { + coin: string; + riskReserveRecords: RiskReserveRecordV3[]; } ⋮---- -export interface FuturesContractConfigV2 { +export interface InstrumentV3 { symbol: string; + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; baseCoin: string; quoteCoin: string; buyLimitPriceRatio: string; sellLimitPriceRatio: string; feeRateUpRatio: string; - makerFeeRate: string; - takerFeeRate: string; - openCostUpRatio: string; - supportMarginCoins: string[]; - minTradeNum: string; - priceEndStep: string; - volumePlace: string; - pricePlace: string; - sizeMultiplier: string; - symbolType: string; - minTradeUSDT: string; + minOrderQty: string; + maxOrderQty: string; + maxMarketOrderQty: string; + pricePrecision: string; + quantityPrecision: string; + quotePrecision: string; + minOrderAmount: string; maxSymbolOrderNum: string; maxProductOrderNum: string; - maxPositionNum: string; - symbolStatus: string; + status: + | 'listed' + | 'online' + | 'limit_open' + | 'limit_close' + | 'offline' + | 'restrictedAPI'; offTime: string; limitOpenTime: string; - deliveryTime: string; - deliveryStartTime: string; - launchTime: string; - fundInterval: string; - minLever: string; - maxLever: string; - posLimit: string; maintainTime: string; - isRwa: string; + areaSymbol?: string; + + // Futures specific fields + makerFeeRate?: string; + takerFeeRate?: string; + openCostUpRatio?: string; + priceMultiplier?: string; + quantityMultiplier?: string; + symbolType?: 'perpetual' | 'delivery'; + maxPositionNum?: string; + deliveryTime?: string; + deliveryStartTime?: string; + deliveryPeriod?: string; + launchTime?: string; + fundInterval?: string; + minLeverage?: string; + maxLeverage?: string; + + // Margin specific fields + isIsolatedBaseBorrowable?: 'YES' | 'NO'; + isIsolatedQuotedBorrowable?: 'YES' | 'NO'; + warningRiskRatio?: string; + liquidationRiskRatio?: string; + maxCrossedLeverage?: string; + maxIsolatedLeverage?: string; + userMinBorrow?: string; } ⋮---- -/** - * - * * Futures | Account - * - */ +// Futures specific fields ⋮---- -export interface FuturesAccountV2 { - marginCoin: string; - locked: string; - available: string; - crossedMaxAvailable: string; - isolatedMaxAvailable: string; - maxTransferOut: string; - accountEquity: string; - usdtEquity: string; - btcEquity: string; - crossedRiskRate: string; - crossedMarginLeverage: string; - isolatedLongLever: string; - isolatedShortLever: string; - marginMode: string; - posMode: string; - unrealizedPL: string; - coupon: string; - crossedUnrealizedPL: string; - isolatedUnrealizedPL: string; - assetMode: string; +// Margin specific fields +⋮---- +export interface OrderBookV3 { + a: string[][]; // asks - [price, size] + b: string[][]; // bids - [price, size] + ts: string; } ⋮---- -export interface FuturesAccountsV2 { - marginCoin: string; - locked: string; - available: string; - crossedMaxAvailable: string; - isolatedMaxAvailable: string; - maxTransferOut: string; - accountEquity: string; - usdtEquity: string; - btcEquity: string; - crossedRiskRate: string; - unrealizedPL: string; - coupon: string; - unionTotalMagin: string; - unionAvailable: string; - unionMm: string; - assetList: { - coin: string; - balance: string; - }[]; - isolatedMargin: string; - crossedMargin: string; - crossedUnrealizedPL: string; - isolatedUnrealizedPL: string; - assetMode: string; -} +a: string[][]; // asks - [price, size] +b: string[][]; // bids - [price, size] ⋮---- -export interface FuturesSubAccountAssetV2 { - marginCoin: string; - locked: string; - available: string; - crossedMaxAvailable: string; - isolatedMaxAvailable: string; - maxTransferOut: string; - accountEquity: string; - usdtEquity: string; - btcEquity: string; - unrealizedPL: string; - coupon: string; +export interface TickerV3 { + category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; + lastPrice: string; + openPrice24h: string; + highPrice24h: string; + lowPrice24h: string; + ask1Price: string; + bid1Price: string; + bid1Size: string; + ask1Size: string; + price24hPcnt: string; + volume24h: string; + turnover24h: string; + + // Futures specific fields + indexPrice?: string; + markPrice?: string; + fundingRate?: string; + openInterest?: string; + deliveryStartTime?: string; + deliveryTime?: string; + deliveryStatus?: string; } ⋮---- -export interface FuturesInterestV2 { - coin: string; - liability: string; - interestFreeLimit: string; - interestLimit: string; - hourInterestRate: string; - interest: string; - cTime: string; -} -export interface FuturesInterestHistoryV2 { - nextSettleTime: string; - borrowAmount: string; - borrowLimit: string; - interestList: FuturesInterestV2[]; - endId: string; -} +// Futures specific fields ⋮---- -export interface SetLeverageResponseV2 { - symbol: string; - marginCoin: string; - longLeverage: string; - shortLeverage: string; - crossMarginLeverage: string; - marginMode: string; +export interface ProofOfReservesV3 { + merkleRootHash: string; + totalReserveRatio: string; + list: { + coin: string; + userAssets: string; + platformAssets: string; + reserveRatio: string; + }[]; } ⋮---- -export interface SetMarginModeResponseV2 { - symbol: string; - marginCoin: string; - longLeverage: string; - shortLeverage: string; - marginMode: string; +export interface IndexComponentV3 { + exchange: string; + spotPair: string; + equivalentPrice: string; + weight: string; } ⋮---- -export interface FuturesAccountBillV2 { - billId: string; +export interface IndexPriceComponentsV3 { symbol: string; - amount: string; - fee: string; - feeByCoupon: string; - businessType: string; - coin: string; - balance: string; - cTime: string; + componentList: IndexComponentV3[]; } + +================ +File: src/types/shared.ts +================ +import { REST_CLIENT_TYPE_ENUM } from '../util/requestUtils.js'; +⋮---- +export type numberInString = string; +⋮---- +export type OrderSide = 'Buy' | 'Sell'; ⋮---- /** - * - * * Futures | Position - * + * @deprecated use SpotKlineInterval or FuturesKlineInterval, depending on which API group you're using */ +export type KlineInterval = + | '1min' + | '5min' + | '15min' + | '30min' + | '1h' + | '4h' + | '6h' + | '12h' + | '1M' + | '1W' + | '1week' + | '6Hutc' + | '12Hutc' + | '1Dutc' + | '3Dutc' + | '1Wutc' + | '1Mutc'; ⋮---- -export interface FuturesPositionTierV2 { - symbol: string; - level: string; - startUnit: string; - endUnit: string; - leverage: string; - keepMarginRate: string; +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +⋮---- +export interface APIResponse { + code: string; + requestTime: number; + msg: 'success' | string; + data: T; } + +================ +File: .gitignore +================ +!.gitkeep +.DS_STORE +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json +pids +*.pid +*.seed +*.pid.lock +node_modules/ +.npm +.eslintcache +.node_repl_history +*.tgz +.yarn-integrity +.env +.env.test +.cache +lib +bundleReport.html +.history/ +tiagoSpot.ts +restClientRegex.ts +localtest.sh +privaterepotracker +testfile.ts +dist +repomix.sh +coverage + +================ +File: src/types/request/v3/account.ts +================ +// Account Management Request Types ⋮---- -export interface FuturesPositionV2 { - marginCoin: string; - symbol: string; - holdSide: string; - openDelegateSize: string; - marginSize: string; - available: string; - locked: string; - total: string; +export interface SetLeverageRequestV3 { + category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; leverage: string; - achievedProfits: string; - openPriceAvg: string; - marginMode: string; - posMode: string; - unrealizedPL: string; - liquidationPrice: string; - keepMarginRate: string; - markPrice: string; - breakEvenPrice: string; - totalFee: string; - deductedFee: string; - marginRatio: string; - assetMode: string; - uTime: string; - autoMargin: string; - cTime: string; + coin?: string; + posSide?: 'long' | 'short'; } ⋮---- -export interface FuturesHistoryPositionV2 { - positionId: string; - marginCoin: string; - symbol: string; - holdSide: string; - openAvgPrice: string; - closeAvgPrice: string; - marginMode: string; - openTotalPos: string; - closeTotalPos: string; - pnl: string; - netProfit: string; - totalFunding: string; - openFee: string; - closeFee: string; - cTime: string; - uTime: string; +export interface GetConvertRecordsRequestV3 { + fromCoin: string; + toCoin: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ⋮---- -/** - * - * * Futures | Trade - * - */ -⋮---- -export interface FuturesBatchOrderResponseV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - orderId: string; - clientOid: string; - errorMsg: string; - errorCode: string; - }[]; +export interface GetFinancialRecordsRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + coin?: string; + type?: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface FuturesClosePositionResponseV2 { - successList: { - orderId: string; - clientOid: string; - symbol: string; - }[]; - failureList: { - orderId: string; - clientOid: string; - symbol: string; - errorMsg: string; - errorCode: string; - }[]; +export interface RepayRequestV3 { + repayableCoinList: string[]; + paymentCoinList: string[]; } ⋮---- -export interface FuturesOrderDetailV2 { - symbol: string; - size: string; - orderId: string; - clientOid: string; - baseVolume: string; - priceAvg: string; - fee: string; - price: string; - state: string; - side: string; - force: string; - totalProfits: string; - posSide: string; - marginCoin: string; - presetStopSurplusPrice: string; - presetStopLossPrice: string; - quoteVolume: string; - orderType: string; - leverage: string; - marginMode: string; - reduceOnly: string; - enterPointSource: string; - tradeSide: string; - posMode: string; - orderSource: string; - cancelReason: string; - cTime: string; - uTime: string; -} +// Sub-account Management Request Types ⋮---- -export interface FuturesOrderFillV2 { - tradeId: string; - symbol: string; - orderId: string; - price: string; - baseVolume: string; - feeDetail: { - deduction: string; - feeCoin: string; - totalDeductionFee: string; - totalFee: string; - }[]; - side: string; - quoteVolume: string; - profit: string; - enterPointSource: string; - tradeSide: string; - posMode: string; - tradeScope: string; - cTime: string; +export interface CreateSubAccountApiKeyRequestV3 { + subUid: string; + note: string; + type: 'read_write' | 'read_only'; + passphrase: string; + permissions: string[]; + ips: string[]; } ⋮---- -export interface FuturesOpenOrderV2 { - symbol: string; - size: string; - orderId: string; - clientOid: string; - baseVolume: string; - fee: string; - price: string; - priceAvg: string; - status: string; - side: string; - force: string; - totalProfits: string; - posSide: string; - marginCoin: string; - quoteVolume: string; - leverage: string; - marginMode: string; - enterPointSource: string; - tradeSide: string; - posMode: string; - orderType: string; - orderSource: string; - cTime: string; - uTime: string; - presetStopSurplusPrice: string; - presetStopSurplusType: string; - presetStopSurplusExecutePrice: string; - presetStopLossPrice: string; - presetStopLossType: string; - presetStopLossExecutePrice: string; +export interface DeleteSubAccountApiKeyRequestV3 { + apiKey: string; } ⋮---- -export interface FuturesHistoryOrderV2 { - symbol: string; - size: string; - orderId: string; - clientOid: string; - baseVolume: string; - fee: string; - price: string; - priceAvg: string; - status: string; - side: string; - force: string; - totalProfits: string; - posSide: string; - marginCoin: string; - quoteVolume: string; - leverage: string; - marginMode: string; - enterPointSource: string; - tradeSide: string; - posMode: string; - orderType: string; - orderSource: string; - cTime: string; - uTime: string; - presetStopSurplusPrice: string; - presetStopLossPrice: string; - liqPrice: string; +export interface GetSubAccountApiKeysRequestV3 { + subUid: string; + limit?: string; + cursor?: string; } ⋮---- -export interface FuturesCancelAllOrdersV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - orderId: string; - clientOid: string; - errorMsg: string; - errorCode: string; - }[]; +export interface UpdateSubAccountApiKeyRequestV3 { + apiKey: string; + passphrase: string; + type?: 'read_write' | 'read_only'; + permissions?: string[]; + ips?: string[]; } ⋮---- -/** - * - * * Futures | Trigger Orders - * - */ -⋮---- -export interface FuturesTriggerSubOrderV2 { - orderId: string; - price: string; - type: string; - status: string; +export interface CreateSubAccountRequestV3 { + username: string; + accountMode?: 'classic' | 'unified'; + note?: string; } ⋮---- -export interface FuturesPendingPlanOrderV2 { - planType: string; - symbol: string; - size: string; - orderId: string; - clientOid: string; - price: string; - executePrice: string; - callbackRatio: string; - triggerPrice: string; - triggerType: string; - planStatus: string; - side: string; - posSide: string; - marginCoin: string; - marginMode: string; - enterPointSource: string; - tradeSide: string; - posMode: string; - orderType: string; - orderSource: string; - cTime: string; - uTime: string; - stopSurplusExecutePrice: string; - stopSurplusTriggerPrice: string; - stopSurplusTriggerType: string; - stopLossExecutePrice: string; - stopLossTriggerPrice: string; - stopLossTriggerType: string; +export interface FreezeSubAccountRequestV3 { + subUid: string; + operation: 'freeze' | 'unfreeze'; } ⋮---- -export interface FuturesCancelPlanOrderV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - orderId: string; - clientOid: string; - errorMsg: string; - }[]; +export interface GetSubAccountListRequestV3 { + limit?: string; + cursor?: string; } ⋮---- -export interface FuturesHistoryPlanOrderV2 { - planType: string; - symbol: string; - size: string; - orderId: string; - executeOrderId: string; - clientOid: string; - planStatus: string; - price: string; - executePrice: string; - priceAvg: string; - baseVolume: string; - callbackRatio: string; - triggerPrice: string; - triggerType: string; - side: string; - posSide: string; - marginCoin: string; - marginMode: string; - enterPointSource: string; - tradeSide: string; - posMode: string; - orderType: string; - cTime: string; - uTime: string; - stopSurplusExecutePrice: string; - stopSurplusTriggerPrice: string; - stopSurplusTriggerType: string; - stopLossExecutePrice: string; - stopLossTriggerPrice: string; - stopLossTriggerType: string; +// Transfer Request Types +⋮---- +export interface TransferRequestV3 { + fromType: + | 'spot' + | 'p2p' + | 'coin-futures' + | 'usdt-futures' + | 'usdc-futures' + | 'crossed-margin' + | 'isolated-margin' + | 'uta'; + toType: + | 'spot' + | 'p2p' + | 'coin-futures' + | 'usdt-futures' + | 'usdc-futures' + | 'crossed-margin' + | 'isolated-margin' + | 'uta'; + amount: string; + coin: string; + symbol?: string; } ⋮---- -/** - * - * * Futures | Union Margin - * - */ +export interface GetTransferableCoinsRequestV3 { + fromType: + | 'spot' + | 'p2p' + | 'coin-futures' + | 'usdt-futures' + | 'usdc-futures' + | 'crossed-margin' + | 'isolated-margin' + | 'uta'; + toType: + | 'spot' + | 'p2p' + | 'coin-futures' + | 'usdt-futures' + | 'usdc-futures' + | 'crossed-margin' + | 'isolated-margin' + | 'uta'; +} ⋮---- -export interface UnionTransferLimitsV2 { +export interface GetSubTransferRecordsRequestV3 { + subUid?: string; + role?: 'initiator' | 'receiver'; + coin?: string; + startTime?: string; + endTime?: string; + clientOid?: string; + limit?: string; + cursor?: string; +} +⋮---- +export interface SubAccountTransferRequestV3 { + fromType: + | 'spot' + | 'p2p' + | 'usdt_futures' + | 'coin_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'uta'; + toType: + | 'spot' + | 'p2p' + | 'usdt_futures' + | 'coin_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'uta'; + amount: string; coin: string; - maxTransferIn: string; + fromUserId: string; + toUserId: string; + clientOid: string; } ⋮---- -export interface UnionConfigV2 { - imr: string; - mmr: string; - individualLimit: string; - individualLimitRatio: string; +export interface GetSubUnifiedAssetsRequestV3 { + subUid?: string; + cursor?: string; + limit?: string; } ⋮---- -export interface UnionSwitchUsdtV2 { - usdtAmount: string; +export interface GetFeeRateRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; } ⋮---- -export interface UnionConvertV2 { - usdtAmount: string; +export interface GetFundingAssetsRequestV3 { + coin?: string; } ⋮---- -/** - * - * * Futures | Account | Max Openable Quantity - * - */ +export interface SwitchDeductRequestV3 { + deduct: 'on' | 'off'; +} ⋮---- -export interface FuturesMaxOpenV2 { - maxOpen: string; +// Deposit Request Types +⋮---- +export interface GetDepositAddressRequestV3 { + coin: string; + chain?: string; + size?: string; } ⋮---- -/** - * - * * Futures | Account | Liquidation Price - * - */ +export interface GetSubDepositAddressRequestV3 { + subUid: string; + coin: string; + chain?: string; + size?: string; +} ⋮---- -export interface FuturesLiquidationPriceV2 { - liqPrice: string; +export interface GetDepositRecordsRequestV3 { + coin?: string; + orderId?: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; } ⋮---- -/** - * - * * Futures | Account | Isolated Symbols - * - */ +export interface GetSubDepositRecordsRequestV3 { + coin?: string; + subUid: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; +} ⋮---- -export interface FuturesIsolatedSymbolV2 { - symbol: string; - marginMode: 'isolated'; +// Withdraw Request Types +⋮---- +export interface WithdrawRequestV3 { + coin: string; + chain?: string; + transferType: 'on_chain' | 'internal_transfer'; + address: string; + innerToType?: 'uid' | 'email' | 'mobile'; + areaCode?: string; + tag?: string; + size: string; + remark?: string; + clientOid?: string; + memberCode?: 'bithumb' | 'korbit' | 'coinone'; + identityType?: 'company' | 'user'; + companyName?: string; + firstName?: string; + lastName?: string; } - -================ -File: src/types/websockets/ws-api-request.ts -================ -export interface WSAPIPlaceOrderRequestV3 { - symbol: string; - orderType: 'limit' | 'market'; - qty: string; - price?: string; - side: 'buy' | 'sell'; - posSide?: 'long' | 'short'; - timeInForce?: 'gtc' | 'ioc' | 'fok' | 'post_only'; - reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. +⋮---- +export interface GetWithdrawRecordsRequestV3 { + coin?: string; + orderId?: string; clientOid?: string; - stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; - tpTriggerBy?: 'market' | 'mark'; - slTriggerBy?: 'market' | 'mark'; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: 'limit' | 'market'; - slOrderType?: 'limit' | 'market'; - tpLimitPrice?: string; - slLimitPrice?: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; } ⋮---- -reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. +export interface SetDepositAccountRequestV3 { + coin: string; + accountType: 'funding' | 'unified' | 'otc'; +} +⋮---- +export interface GetMaxTransferableRequestV3 { + coin: string; +} +⋮---- +export interface GetOpenInterestLimitRequestV3 { + symbol: string; + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; +} +⋮---- +export interface GetTaxRecordsRequestV3 { + bizType: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES' + | 'OTHER'; + marginType?: 'isolated' | 'crossed'; + coin?: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; +} ================ -File: .gitignore +File: src/types/response/v2/futures.ts ================ -!.gitkeep -.DS_STORE -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json -pids -*.pid -*.seed -*.pid.lock -node_modules/ -.npm -.eslintcache -.node_repl_history -*.tgz -.yarn-integrity -.env -.env.test -.cache -lib -bundleReport.html -.history/ -tiagoSpot.ts -restClientRegex.ts -localtest.sh -privaterepotracker -testfile.ts -dist -repomix.sh -coverage - -================ -File: examples/README.md -================ -# Examples - -These samples can be executed using `ts-node`: - -``` -ts-node ./examples/rest-spot-public.ts -``` - -Samples that require authentication can be edited directly but also support environmental variables. E.g. on mac/unix: - -``` -API_KEY_COM='yourkeyhere' API_SECRET_COM='yoursecrethere' API_PASS_COM='yourapipasshere' ts-node examples/rest-trade-futures.ts -``` - -They can also be converted to JavaScript by changing the imports to require & removing any type annotations. - -## V3 / Unified Trading Account (UTA) - -These newer examples are for Bitget's V3 APIs and WebSockets. They can be found in the examples/V3 folder. - -Refer to the V3 / UTA API documentation for more information on the V3 APIs: -https://www.bitget.com/api-doc/uta/intro - -These APIs require your account to be upgraded to the Unified Trading Account, if you plan on using the account-level REST APIs and WebSockets. Once upgraded, the V2 APIs are no longer available to you, unless you revert back to Classic Account mode. - -### WebSocket API (WS API) - -The V3/UTA API introduces order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API. - -There are two approaches to placing orders via the Bitget WebSocket APIs - -#### WebsocketAPIClient (recommended) - -This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types. - -This is the recommended approach to easily start sending orders via an automatically persisted WebSocket connection. A simple example is below, but for a more thorough example, check the example here: [./V3/ws-api-client-trade.ts](./V3/ws-api-client-trade.ts) - -```typescript -import { WebsocketAPIClient } from 'bitget-api'; -// or if you prefer require: -// const { WebsocketAPIClient } = require("bitget-api"); - -// Make an instance of the WS API Client class with your API keys -const wsClient = new WebsocketAPIClient({ - apiKey: API_KEY, - apiSecret: API_SECRET, - apiPass: API_PASS, - - // Whether to use the demo trading wss connection - // demoTrading: true, -}); - -async function start() { - // Start using it like a REST API. All actions are sent via a persisted WebSocket connection. - - /** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - */ - try { - const res = await wsClient.submitNewOrder('spot', { - orderType: 'limit', - price: '100', - qty: '0.1', - side: 'buy', - symbol: 'BTCUSDT', - timeInForce: 'gtc', - }); - - console.log(new Date(), 'WS API "submitNewOrder()" result: ', res); - } catch (e) { - console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e); - } -} - -start().catch((e) => console.error('Exception in example: '.e)); -``` - -#### ws.sendWSAPIRequest(wsKey, command, category, operation) - -This is the "raw" integration within the existing WebSocket client. It uses an automatically persisted & authenticated connection to send events through Bitget's WebSocket API. It automatically tracks and connects outgoing requests with incoming responses, and returns promises that resolve/reject when a matching response is received. - -Refer to [V3/ws-api-trade-raw.ts](./V3/ws-api-trade-raw.ts) to see an example. - -Note: The WebsocketClient is built around this. For a more user friendly experience, it is recommended to use the WebsocketClient for WS API requests. It uses this method but has the convenience of behaving similar to a REST API (while all communication automatically happens over a persisted WebSocket connection). - -## V2 - -These examples are for Bitget's V2 APIs and WebSockets. They can be found in the examples/V2 folder. - -Refer to the V2 API documentation for more information on the V2 APIs: -https://www.bitget.com/api-doc/common/intro - -================ -File: src/types/request/v2/futures.ts -================ -import { FuturesPlanTypeV2, FuturesProductTypeV2 } from '../shared.js'; -import { FuturesKlineInterval } from '../v1/futuresV1.js'; -⋮---- -export type FuturesKlineTypeV2 = 'MARKET' | 'MARK' | 'INDEX'; -⋮---- -export interface FuturesAccountBillRequestV2 { - productType: FuturesProductTypeV2; - symbol?: string; - coin?: string; - businessType?: string; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} -⋮---- /** * * * Futures | Market * */ ⋮---- -export interface FuturesMergeDepthRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - precision?: 'scale0' | 'scale1' | 'scale2' | 'scale3'; - limit?: '1' | '5' | '15' | '50' | 'max'; +export interface FuturesVipFeeRateV2 { + level: string; + dealAmount: string; + assetAmount: string; + takerFeeRate: string; + makerFeeRate: string; + btcWithdrawAmount: string; + usdtWithdrawAmount: string; } ⋮---- -export interface FuturesRecentTradesRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - limit?: string; +export interface FuturesHistoryInterestRateV2 { + ts: string; + annualInterestRate: string; + dailyInterestRate: string; } ⋮---- -export interface FuturesHistoricTradesRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - limit?: string; - idLessThan?: string; - startTime?: string; - endTime?: string; +export interface FuturesInterestExchangeRateV2 { + tier: string; + minAmount: string; + maxAmount: string; + exchangeRate: string; } ⋮---- -export interface FuturesCandlesRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - granularity: FuturesKlineInterval; - startTime?: string; - endTime?: string; - kLineType?: FuturesKlineTypeV2; - limit?: string; +export interface FuturesDiscountRateV2 { + tier: string; + minAmount: string; + maxAmount: string; + discountRate: string; } ⋮---- -/** - * - * * Futures | Account - * - */ -⋮---- -export interface FuturesSingleAccountRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; +export interface FuturesDiscountRatesV2 { + coin: string; + userLimit: string; + totalLimit: string; + discountRateList: FuturesDiscountRateV2[]; } ⋮---- -export interface FuturesInterestHistoryRequestV2 { - productType: 'USDT-FUTURES' | 'SUSDT-FUTURES'; - coin?: string; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; +export interface FuturesMergeDepthV2 { + asks: [number, number][]; + bids: [number, number][]; + ts: string; + scale: string; + precision: string; + isMaxPrecision: string; } ⋮---- -export interface FuturesOpenCountRequestV2 { +export interface FuturesTickerV2 { symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; - openAmount: string; - openPrice: string; - leverage?: string; + lastPr: string; + askPr: string; + bidPr: string; + bidSz: string; + askSz: string; + high24h: string; + low24h: string; + ts: string; + change24h: string; + baseVolume: string; + quoteVolume: string; + usdtVolume: string; + openUtc: string; + changeUtc24h: string; + indexPrice: string; + fundingRate: string; + holdingAmount: string; + deliveryStartTime: string; + deliveryTime: string; + deliveryStatus: string; + open24h: string; + markPrice: string; } ⋮---- -export interface FuturesSetAutoMarginRequestV2 { +export interface FuturesFillV2 { + tradeId: string; + price: string; + size: string; + side: string; + ts: string; symbol: string; - autoMargin: 'on' | 'off'; - marginCoin: string; - amount: string; - holdSide?: 'long' | 'short'; } ⋮---- -export interface FuturesSetLeverageRequestV2 { +export type FuturesCandlestickV2 = [ + string, // timestamp + string, // open + string, // high + string, // low + string, // close + string, // baseVolume + string, // usdtVolume + string, // quoteVolume +]; +⋮---- +string, // timestamp +string, // open +string, // high +string, // low +string, // close +string, // baseVolume +string, // usdtVolume +string, // quoteVolume +⋮---- +export interface FuturesOpenInterestV2 { symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; - leverage: string; - holdSide?: 'long' | 'short'; + size: string; } ⋮---- -export interface FuturesSetPositionMarginRequestV2 { +export interface FuturesFundingTimeV2 { symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; - holdSide: 'long' | 'short'; - amount: string; + nextFundingTime: string; + ratePeriod: string; } ⋮---- -export interface FuturesSetMarginModeRequestV2 { +export interface FuturesSymbolPriceV2 { symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; - marginMode: 'isolated' | 'crossed'; + price: string; + indexPrice: string; + markPrice: string; + ts: string; } ⋮---- -/** - * - * * Futures | Position - * - */ +export interface FuturesHistoricalFundingRateV2 { + symbol: string; + fundingRate: string; + fundingTime: string; +} ⋮---- -export interface FuturesHistoricalPositionsRequestV2 { - symbol?: string; - productType?: FuturesProductTypeV2; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; +export interface FuturesContractConfigV2 { + symbol: string; + baseCoin: string; + quoteCoin: string; + buyLimitPriceRatio: string; + sellLimitPriceRatio: string; + feeRateUpRatio: string; + makerFeeRate: string; + takerFeeRate: string; + openCostUpRatio: string; + supportMarginCoins: string[]; + minTradeNum: string; + priceEndStep: string; + volumePlace: string; + pricePlace: string; + sizeMultiplier: string; + symbolType: string; + minTradeUSDT: string; + maxSymbolOrderNum: string; + maxProductOrderNum: string; + maxPositionNum: string; + symbolStatus: string; + offTime: string; + limitOpenTime: string; + deliveryTime: string; + deliveryStartTime: string; + launchTime: string; + fundInterval: string; + minLever: string; + maxLever: string; + posLimit: string; + maintainTime: string; + isRwa: string; } ⋮---- /** * - * * Futures | Trade + * * Futures | Account * */ ⋮---- -export interface FuturesPlaceOrderRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - marginMode: 'isolated' | 'crossed'; +export interface FuturesAccountV2 { marginCoin: string; - size: string; - price?: string; - side: 'buy' | 'sell'; - tradeSide?: 'open' | 'close'; - orderType: 'limit' | 'market'; - force?: 'ioc' | 'fok' | 'gtc' | 'post_only'; - clientOid?: string; - reduceOnly?: 'YES' | 'NO'; - presetStopSurplusPrice?: string; - presetStopLossPrice?: string; - stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; + locked: string; + available: string; + crossedMaxAvailable: string; + isolatedMaxAvailable: string; + maxTransferOut: string; + accountEquity: string; + usdtEquity: string; + btcEquity: string; + crossedRiskRate: string; + crossedMarginLeverage: string; + isolatedLongLever: string; + isolatedShortLever: string; + marginMode: string; + posMode: string; + unrealizedPL: string; + coupon: string; + crossedUnrealizedPL: string; + isolatedUnrealizedPL: string; + assetMode: string; } ⋮---- -export interface FuturesReversalOrderRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; +export interface FuturesAccountsV2 { marginCoin: string; - size: string; - side?: 'buy' | 'sell'; - tradeSide?: 'open' | 'close'; - clientOid?: string; + locked: string; + available: string; + crossedMaxAvailable: string; + isolatedMaxAvailable: string; + maxTransferOut: string; + accountEquity: string; + usdtEquity: string; + btcEquity: string; + crossedRiskRate: string; + unrealizedPL: string; + coupon: string; + unionTotalMagin: string; + unionAvailable: string; + unionMm: string; + assetList: { + coin: string; + balance: string; + }[]; + isolatedMargin: string; + crossedMargin: string; + crossedUnrealizedPL: string; + isolatedUnrealizedPL: string; + assetMode: string; } ⋮---- -interface FuturesBatchOrderItem { - size: string; - price?: string; - side: 'buy' | 'sell'; - tradeSide?: 'open' | 'close'; - orderType: 'limit' | 'market'; - force?: 'ioc' | 'fok' | 'gtc' | 'post_only'; - clientOid?: string; - reduceOnly?: 'YES' | 'NO'; - presetStopSurplusPrice?: string; - presetStopLossPrice?: string; - stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; +export interface FuturesSubAccountAssetV2 { + marginCoin: string; + locked: string; + available: string; + crossedMaxAvailable: string; + isolatedMaxAvailable: string; + maxTransferOut: string; + accountEquity: string; + usdtEquity: string; + btcEquity: string; + unrealizedPL: string; + coupon: string; } ⋮---- -export interface FuturesBatchOrderRequestV2 { +export interface FuturesInterestV2 { + coin: string; + liability: string; + interestFreeLimit: string; + interestLimit: string; + hourInterestRate: string; + interest: string; + cTime: string; +} +export interface FuturesInterestHistoryV2 { + nextSettleTime: string; + borrowAmount: string; + borrowLimit: string; + interestList: FuturesInterestV2[]; + endId: string; +} +⋮---- +export interface SetLeverageResponseV2 { symbol: string; - productType: FuturesProductTypeV2; marginCoin: string; - marginMode: 'isolated' | 'crossed'; - orderList: FuturesBatchOrderItem[]; + longLeverage: string; + shortLeverage: string; + crossMarginLeverage: string; + marginMode: string; } ⋮---- -export interface FuturesModifyOrderRequestV2 { - orderId?: string; - clientOid?: string; +export interface SetMarginModeResponseV2 { symbol: string; - productType: FuturesProductTypeV2; - newClientOid: string; - newSize?: string; - newPrice?: string; - newPresetStopSurplusPrice?: string; - newPresetStopLossPrice?: string; + marginCoin: string; + longLeverage: string; + shortLeverage: string; + marginMode: string; } ⋮---- -export interface FuturesCancelOrderRequestV2 { +export interface FuturesAccountBillV2 { + billId: string; symbol: string; - productType: FuturesProductTypeV2; - marginCoin?: string; - orderId?: string; - clientOid?: string; + amount: string; + fee: string; + feeByCoupon: string; + businessType: string; + coin: string; + balance: string; + cTime: string; } ⋮---- -interface FuturesBatchCancelOrderItem { - orderId?: string; - clientOid?: string; +/** + * + * * Futures | Position + * + */ +⋮---- +export interface FuturesPositionTierV2 { + symbol: string; + level: string; + startUnit: string; + endUnit: string; + leverage: string; + keepMarginRate: string; } ⋮---- -export interface FuturesBatchCancelOrderRequestV2 { - orderIdList?: FuturesBatchCancelOrderItem[]; - symbol?: string; - productType: FuturesProductTypeV2; - marginCoin?: string; -} -⋮---- -export interface FuturesFlashClosePositionsRequestV2 { - symbol?: string; - productType: FuturesProductTypeV2; - holdSide?: 'long' | 'short'; -} -⋮---- -export interface FuturesGetOrderRequestV2 { +export interface FuturesPositionV2 { + marginCoin: string; symbol: string; - productType: FuturesProductTypeV2; - orderId?: string; - clientOid?: string; -} -⋮---- -export interface FuturesGetOrderFillsRequestV2 { - orderId?: string; - symbol?: string; - productType: FuturesProductTypeV2; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} -⋮---- -export interface FuturesGetHistoricalFillsRequestV2 { - orderId?: string; - symbol?: string; - productType: FuturesProductTypeV2; - startTime?: string; - endTime?: string; - idLessThan?: string; - limit?: string; -} -⋮---- -export interface FuturesGetOpenOrdersRequestV2 { - orderId?: string; - clientOid?: string; - symbol?: string; - productType: FuturesProductTypeV2; - status?: 'live' | 'partially_filled'; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} -⋮---- -export type FuturesOrderSourceV2 = - | 'normal' - | 'market' - | 'profit_market' - | 'loss_market' - | 'Trader_delegate' - | 'trader_profit' - | 'trader_loss' - | 'reverse' - | 'trader_reverse' - | 'profit_limit' - | 'loss_limit' - | 'liquidation' - | 'delivery_close_long' - | 'delivery_close_short' - | 'pos_profit_limit' - | 'pos_profit_market' - | 'pos_loss_limit' - | 'pos_loss_market'; -⋮---- -export interface FuturesGetHistoryOrdersRequestV2 { - orderId?: string; - clientOid?: string; - symbol?: string; - productType: FuturesProductTypeV2; - idLessThan?: string; - orderSource?: FuturesOrderSourceV2; - startTime?: string; - endTime?: string; - limit?: string; + holdSide: string; + openDelegateSize: string; + marginSize: string; + available: string; + locked: string; + total: string; + leverage: string; + achievedProfits: string; + openPriceAvg: string; + marginMode: string; + posMode: string; + unrealizedPL: string; + liquidationPrice: string; + keepMarginRate: string; + markPrice: string; + breakEvenPrice: string; + totalFee: string; + deductedFee: string; + marginRatio: string; + assetMode: string; + uTime: string; + autoMargin: string; + cTime: string; } ⋮---- -export interface FuturesCancelAllOrdersRequestV2 { - symbol?: string; - productType: FuturesProductTypeV2; - marginCoin?: string; - requestTime?: string; - receiveWindow?: string; +export interface FuturesHistoryPositionV2 { + positionId: string; + marginCoin: string; + symbol: string; + holdSide: string; + openAvgPrice: string; + closeAvgPrice: string; + marginMode: string; + openTotalPos: string; + closeTotalPos: string; + pnl: string; + netProfit: string; + totalFunding: string; + openFee: string; + closeFee: string; + cTime: string; + uTime: string; } ⋮---- /** * - * * Futures | Trigger Orders + * * Futures | Trade * */ ⋮---- -export type FuturesTriggerTypeV2 = 'fill_price' | 'mark_price'; +export interface FuturesBatchOrderResponseV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + orderId: string; + clientOid: string; + errorMsg: string; + errorCode: string; + }[]; +} ⋮---- -export type FuturesStpModeV2 = - | 'none' - | 'cancel_taker' - | 'cancel_maker' - | 'cancel_both'; +export interface FuturesClosePositionResponseV2 { + successList: { + orderId: string; + clientOid: string; + symbol: string; + }[]; + failureList: { + orderId: string; + clientOid: string; + symbol: string; + errorMsg: string; + errorCode: string; + }[]; +} ⋮---- -export interface FuturesTPSLOrderRequestV2 { - marginCoin: string; - productType: FuturesProductTypeV2; +export interface FuturesOrderDetailV2 { symbol: string; - planType: FuturesPlanTypeV2; - triggerPrice: string; - triggerType?: FuturesTriggerTypeV2; - executePrice?: string; - holdSide: 'long' | 'short' | 'buy' | 'sell'; size: string; - rangeRate?: string; - clientOid?: string; - stpMode?: FuturesStpModeV2; + orderId: string; + clientOid: string; + baseVolume: string; + priceAvg: string; + fee: string; + price: string; + state: string; + side: string; + force: string; + totalProfits: string; + posSide: string; + marginCoin: string; + presetStopSurplusPrice: string; + presetStopLossPrice: string; + quoteVolume: string; + orderType: string; + leverage: string; + marginMode: string; + reduceOnly: string; + enterPointSource: string; + tradeSide: string; + posMode: string; + orderSource: string; + cancelReason: string; + cTime: string; + uTime: string; } ⋮---- -export type FuturesTriggerPriceTypeV2 = - | 'fill_price' - | 'mark_price' - | 'index_price'; -⋮---- -export interface FuturesPlanOrderRequestV2 { - planType: 'normal_plan' | 'track_plan'; +export interface FuturesOrderFillV2 { + tradeId: string; symbol: string; - productType: FuturesProductTypeV2; - marginMode: 'isolated' | 'crossed'; - marginCoin: string; - size: string; - price?: string; - callbackRatio?: string; - triggerPrice: string; - triggerType: 'mark_price' | 'fill_price'; - side: 'buy' | 'sell'; - tradeSide?: 'open' | 'close'; - orderType: 'limit' | 'market'; - clientOid?: string; - reduceOnly?: 'YES' | 'NO'; - stopSurplusTriggerPrice?: string; - stopSurplusExecutePrice?: string; - stopSurplusTriggerType?: FuturesTriggerPriceTypeV2; - stopLossTriggerPrice?: string; - stopLossExecutePrice?: string; - stopLossTriggerType?: FuturesTriggerPriceTypeV2; - stpMode?: FuturesStpModeV2; + orderId: string; + price: string; + baseVolume: string; + feeDetail: { + deduction: string; + feeCoin: string; + totalDeductionFee: string; + totalFee: string; + }[]; + side: string; + quoteVolume: string; + profit: string; + enterPointSource: string; + tradeSide: string; + posMode: string; + tradeScope: string; + cTime: string; } ⋮---- -export interface FuturesModifyTPSLOrderRequestV2 { - orderId?: string; - clientOid?: string; - marginCoin: string; - productType: FuturesProductTypeV2; +export interface FuturesOpenOrderV2 { symbol: string; - triggerPrice: string; - triggerType?: 'fill_price' | 'mark_price'; - executePrice?: string; size: string; - rangeRate?: string; + orderId: string; + clientOid: string; + baseVolume: string; + fee: string; + price: string; + priceAvg: string; + status: string; + side: string; + force: string; + totalProfits: string; + posSide: string; + marginCoin: string; + quoteVolume: string; + leverage: string; + marginMode: string; + enterPointSource: string; + tradeSide: string; + posMode: string; + orderType: string; + orderSource: string; + cTime: string; + uTime: string; + presetStopSurplusPrice: string; + presetStopSurplusType: string; + presetStopSurplusExecutePrice: string; + presetStopLossPrice: string; + presetStopLossType: string; + presetStopLossExecutePrice: string; } ⋮---- -export interface FuturesModifyPlanOrderRequestV2 { - planType: 'normal_plan' | 'track_plan'; - orderId?: string; - clientOid?: string; +export interface FuturesHistoryOrderV2 { symbol: string; - productType: FuturesProductTypeV2; - newSize?: string; - newPrice?: string; - newCallbackRatio?: string; - newTriggerPrice?: string; - newTriggerType?: 'fill_price' | 'mark_price'; - newStopSurplusTriggerPrice?: string; - newStopSurplusExecutePrice?: string; - newStopSurplusTriggerType?: FuturesTriggerPriceTypeV2; - newStopLossTriggerPrice?: string; - newStopLossExecutePrice?: string; - newStopLossTriggerType?: FuturesTriggerPriceTypeV2; + size: string; + orderId: string; + clientOid: string; + baseVolume: string; + fee: string; + price: string; + priceAvg: string; + status: string; + side: string; + force: string; + totalProfits: string; + posSide: string; + marginCoin: string; + quoteVolume: string; + leverage: string; + marginMode: string; + enterPointSource: string; + tradeSide: string; + posMode: string; + orderType: string; + orderSource: string; + cTime: string; + uTime: string; + presetStopSurplusPrice: string; + presetStopLossPrice: string; + liqPrice: string; } ⋮---- -export interface FuturesGetPlanOrdersRequestV2 { - orderId?: string; - clientOid?: string; - symbol?: string; - planType: 'normal_plan' | 'track_plan' | 'profit_loss'; - productType: FuturesProductTypeV2; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; +export interface FuturesCancelAllOrdersV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + orderId: string; + clientOid: string; + errorMsg: string; + errorCode: string; + }[]; } ⋮---- -interface FuturesCancelPlanOrderItemV2 { - orderId?: string; - clientOid?: string; -} +/** + * + * * Futures | Trigger Orders + * + */ ⋮---- -export type FuturesPlanOrderTypeV2 = - | 'normal_plan' - | 'profit_plan' - | 'loss_plan' - | 'pos_profit' - | 'pos_loss' - | 'moving_plan'; +export interface FuturesTriggerSubOrderV2 { + orderId: string; + price: string; + type: string; + status: string; +} ⋮---- -export interface FuturesCancelPlanOrderRequestV2 { - orderIdList?: FuturesCancelPlanOrderItemV2[]; - symbol?: string; - productType: FuturesProductTypeV2; - marginCoin?: string; - planType?: FuturesPlanOrderTypeV2; +export interface FuturesPendingPlanOrderV2 { + planType: string; + symbol: string; + size: string; + orderId: string; + clientOid: string; + price: string; + executePrice: string; + callbackRatio: string; + triggerPrice: string; + triggerType: string; + planStatus: string; + side: string; + posSide: string; + marginCoin: string; + marginMode: string; + enterPointSource: string; + tradeSide: string; + posMode: string; + orderType: string; + orderSource: string; + cTime: string; + uTime: string; + stopSurplusExecutePrice: string; + stopSurplusTriggerPrice: string; + stopSurplusTriggerType: string; + stopLossExecutePrice: string; + stopLossTriggerPrice: string; + stopLossTriggerType: string; } ⋮---- -export type FuturesPlanStatusV2 = 'executed' | 'fail_trigger' | 'cancelled'; +export interface FuturesCancelPlanOrderV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + orderId: string; + clientOid: string; + errorMsg: string; + }[]; +} ⋮---- -export interface FuturesGetHistoryPlanOrdersRequestV2 { - orderId?: string; - clientOid?: string; - planType: 'normal_plan' | 'track_plan' | 'profit_loss'; - planStatus?: FuturesPlanStatusV2; - symbol?: string; - productType: FuturesProductTypeV2; - idLessThan?: string; - startTime?: string; - endTime?: string; - limit?: string; +export interface FuturesHistoryPlanOrderV2 { + planType: string; + symbol: string; + size: string; + orderId: string; + executeOrderId: string; + clientOid: string; + planStatus: string; + price: string; + executePrice: string; + priceAvg: string; + baseVolume: string; + callbackRatio: string; + triggerPrice: string; + triggerType: string; + side: string; + posSide: string; + marginCoin: string; + marginMode: string; + enterPointSource: string; + tradeSide: string; + posMode: string; + orderType: string; + cTime: string; + uTime: string; + stopSurplusExecutePrice: string; + stopSurplusTriggerPrice: string; + stopSurplusTriggerType: string; + stopLossExecutePrice: string; + stopLossTriggerPrice: string; + stopLossTriggerType: string; } ⋮---- /** @@ -9398,13 +7906,24 @@ export interface FuturesGetHistoryPlanOrdersRequestV2 { * */ ⋮---- -export interface GetUnionTransferLimitsRequestV2 { +export interface UnionTransferLimitsV2 { coin: string; + maxTransferIn: string; } ⋮---- -export interface UnionConvertRequestV2 { - coin: string; - amount: string; +export interface UnionConfigV2 { + imr: string; + mmr: string; + individualLimit: string; + individualLimitRatio: string; +} +⋮---- +export interface UnionSwitchUsdtV2 { + usdtAmount: string; +} +⋮---- +export interface UnionConvertV2 { + usdtAmount: string; } ⋮---- /** @@ -9413,13 +7932,8 @@ export interface UnionConvertRequestV2 { * */ ⋮---- -export interface FuturesMaxOpenRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; - posSide: 'long' | 'short'; - orderType: 'limit' | 'market'; - openPrice?: string; +export interface FuturesMaxOpenV2 { + maxOpen: string; } ⋮---- /** @@ -9428,14 +7942,8 @@ export interface FuturesMaxOpenRequestV2 { * */ ⋮---- -export interface FuturesLiquidationPriceRequestV2 { - symbol: string; - productType: FuturesProductTypeV2; - marginCoin: string; - posSide: 'long' | 'short'; - orderType: 'limit' | 'market'; - openAmount: string; - openPrice?: string; +export interface FuturesLiquidationPriceV2 { + liqPrice: string; } ⋮---- /** @@ -9444,1106 +7952,1247 @@ export interface FuturesLiquidationPriceRequestV2 { * */ ⋮---- -export interface FuturesIsolatedSymbolsRequestV2 { - productType: FuturesProductTypeV2; +export interface FuturesIsolatedSymbolV2 { + symbol: string; + marginMode: 'isolated'; } ================ -File: src/types/response/v3/account.ts +File: src/websocket-api-client.ts ================ -// Account Management Response Types -export interface AccountSymbolConfigV3 { - category: string; - symbol: string; - marginMode: string; - leverage: string; -} -⋮---- -export interface AccountCoinConfigV3 { - coin: string; - leverage: string; -} +import { CancelOrderRequestV3 } from './types/request/v3/trade.js'; +import { CancelOrderResponseV3 } from './types/response/v3/trade.js'; +import { WSAPIResponse } from './types/websockets/ws-api.js'; +import { WSAPIPlaceOrderRequestV3 } from './types/websockets/ws-api-request.js'; +import { WSAPIPlaceOrderResponseV3 } from './types/websockets/ws-api-response.js'; +import { + BitgetInstTypeV3, + WSClientConfigurableOptions, +} from './types/websockets/ws-general.js'; +import { DefaultLogger } from './util/logger.js'; +import { WS_KEY_MAP } from './util/websocket-util.js'; +import { WebsocketClientV3 } from './websocket-client-v3.js'; ⋮---- -export interface AccountSettingsV3 { - assetMode: string; - holdMode: string; - symbolConfigList: AccountSymbolConfigV3[]; - coinConfigList: AccountCoinConfigV3[]; +/** + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ + attachEventListeners: boolean; } ⋮---- -export interface AccountAssetV3 { - coin: string; - equity: string; - usdValue: string; - balance: string; - available: string; - debt: string; - locked: string; -} +/** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ ⋮---- -export interface AccountAssetsV3 { - accountEquity: string; - usdtEquity: string; - btcEquity: string; - unrealisedPnl: string; - usdtUnrealisedPnl: string; - btcUnrealizedPnl: string; - effEquity: string; - mmr: string; - imr: string; - mgnRatio: string; - positionMgnRatio: string; - assets: AccountAssetV3[]; -} +/** + * This is a minimal Websocket API wrapper around the WebsocketClient. + * + * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some + * may find the below methods slightly more intuitive. + * + * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: + * https://github.com/tiagosiebler/bitget-api/blob/master/examples/V3/ws-api-trade-raw.ts + */ +export class WebsocketAPIClient ⋮---- -export interface ConvertRecordV3 { - fromCoin: string; - fromCoinSize: string; - toCoin: string; - toCoinSize: string; - price: string; - ts: string; -} +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -export interface FinancialRecordV3 { - category: string; - id: string; - symbol: string; - coin: string; - type: string; - amount: string; - fee: string; - balance: string; - ts: string; -} +public getWSClient(): WebsocketClientV3 ⋮---- -export interface PaymentCoinV3 { - coin: string; - size: string; - amount: string; -} +public setTimeOffsetMs(newOffset: number): void ⋮---- -export interface RepayableCoinV3 { - coin: string; - size: string; - amount: string; -} +/* + * Bitget WebSocket API Methods + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel + */ ⋮---- -export interface RepayResponseV3 { - result: string; - repayAmount: string; -} +/** + * Submit a new order + * + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel + * + * @returns + */ +submitNewOrder( + category: BitgetInstTypeV3, + params: WSAPIPlaceOrderRequestV3, +): Promise> ⋮---- -// Sub-account Management Response Types +/** + * Submit a new order + * + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + * + * @returns + */ +placeBatchOrders( + category: BitgetInstTypeV3, + params: WSAPIPlaceOrderRequestV3[], +): Promise> ⋮---- -export interface CreateSubAccountApiKeyResponseV3 { - note: string; - apiKey: string; - secret: string; - type: string; - permissions: string[]; - ips: string[]; -} -export interface SubAccountApiKeyV3 { - apiKey: string; - note: string; - type: string; - permissions: string[]; - ips: string[]; - ts?: string; -} +/* + * Bitget WebSocket API Methods + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel + */ ⋮---- -export interface UpdateSubAccountApiKeyResponseV3 { - note: string; - apiKey: string; - type: string; - permissions: string[]; - ips: string[]; -} +/** + * Cancel Order + * + * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + * + * @returns + */ +cancelOrder( + category: BitgetInstTypeV3, + params: CancelOrderRequestV3, +): Promise> ⋮---- -export interface CreateSubAccountResponseV3 { - username: string; - subUid: string; - status: string; - note: string; - createdTime: string; - updatedTime: string; -} +/** + * Batch Cancel Order + * + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + * + * @returns + */ +cancelBatchOrders( + category: BitgetInstTypeV3, + params: CancelOrderRequestV3[], +): Promise> ⋮---- -export interface SubAccountV3 { - subUid: string; - username: string; - status: string; - accountMode: string; - type: string; - note: string; - createdTime: string; - updatedTime: string; -} +/** + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * + */ ⋮---- -// Transfer Response Types +private setupDefaultEventListeners() ⋮---- -export interface TransferResponseV3 { - transferId: string; -} +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -export interface SubTransferRecordV3 { - transferId: string; - oldTransferId?: string; - fromType: string; - toType: string; - amount: string; - coin: string; - fromUserId: string; - toUserId: string; - status: string; - clientOid: string; - createdTime: string; - updatedTime: string; -} +// Blind JSON.stringify can fail on circular references ⋮---- -export interface SubUnifiedAssetV3 { - coin: string; - equity: string; - usdValue: string; - balance: string; - available: string; - debt: string; - locked: string; +// JSON.stringify({ ...data, target: 'WebSocket' }), + +================ +File: .eslintrc.cjs +================ +// 'no-unused-vars': ['warn'], + +================ +File: tsconfig.json +================ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "baseUrl": ".", + "noEmitOnError": true, + "declaration": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": false, + "inlineSourceMap": false, + "lib": ["esnext", "DOM"], + "listEmittedFiles": false, + "listFiles": false, + "moduleResolution": "node", + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noUnusedParameters": true, + "pretty": true, + "removeComments": false, + "resolveJsonModule": true, + "skipLibCheck": false, + "sourceMap": true, + "strict": true, + "strictNullChecks": true, + "types": ["node", "jest"], + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext" + }, + "compileOnSave": true, + "exclude": ["node_modules", "dist"], + "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] } + +================ +File: src/types/request/v2/futures.ts +================ +import { FuturesPlanTypeV2, FuturesProductTypeV2 } from '../shared.js'; ⋮---- -export interface SubUnifiedAssetV3 { - subUid: string; - cursor: string; - assets: SubUnifiedAssetV3[]; -} +export type FuturesKlineInterval = + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1H' + | '2H' + | '4H' + | '6H' + | '12H' + | '1D' + | '3D' + | '1W' + | '1M' + | '6Hutc' + | '12Hutc' + | '1Dutc' + | '3Dutc' + | '1Wutc' + | '1Mutc'; ⋮---- -export interface GetFeeRateResponseV3 { - makerFeeRate: string; - takerFeeRate: string; -} +export type FuturesKlineTypeV2 = 'MARKET' | 'MARK' | 'INDEX'; ⋮---- -export interface FundingAssetV3 { - coin: string; - available: string; - frozen: string; - balance: string; +export interface FuturesAccountBillRequestV2 { + productType: FuturesProductTypeV2; + symbol?: string; + coin?: string; + businessType?: string; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -// Deposit Response Types +/** + * + * * Futures | Market + * + */ ⋮---- -export interface DepositAddressV3 { - address: string; - chain: string; - coin: string; - tag: string; - url: string; +export interface FuturesMergeDepthRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + precision?: 'scale0' | 'scale1' | 'scale2' | 'scale3'; + limit?: '1' | '5' | '15' | '50' | 'max'; } ⋮---- -export interface DepositRecordV3 { - orderId: string; - recordId: string; - coin: string; - type: 'deposit'; - dest: 'on_chain' | 'internal_transfer'; - size: string; - status: 'pending' | 'success' | 'fail'; - fromAddress: string; - toAddress: string; - chain: string; - createdTime: string; - updatedTime: string; +export interface FuturesRecentTradesRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + limit?: string; } ⋮---- -// Withdraw Response Types +export interface FuturesHistoricTradesRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + limit?: string; + idLessThan?: string; + startTime?: string; + endTime?: string; +} ⋮---- -export interface WithdrawResponseV3 { - orderId: string; - clientOid: string; +export interface FuturesCandlesRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + granularity: FuturesKlineInterval; + startTime?: string; + endTime?: string; + kLineType?: FuturesKlineTypeV2; + limit?: string; } ⋮---- -export interface WithdrawRecordV3 { - orderId: string; - clientOid: string; - recordId: string; - coin: string; - type: 'withdraw'; - dest: 'on_chain' | 'internal_transfer'; - size: string; - status: 'pending' | 'success' | 'fail'; - fromAddress: string; - toAddress: string; - chain: string; - fee: string; - confirm: string; - tag: string; - createdTime: string; - updatedTime: string; +/** + * + * * Futures | Account + * + */ +⋮---- +export interface FuturesSingleAccountRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; } ⋮---- -export interface MaxTransferableV3 { - coin: string; - maxTransfer: string; - borrowMaxTransfer: string; +export interface FuturesInterestHistoryRequestV2 { + productType: 'USDT-FUTURES' | 'SUSDT-FUTURES'; + coin?: string; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface OpenInterestLimitV3 { +export interface FuturesOpenCountRequestV2 { symbol: string; - singleUserLimit: string; - masterSubLimit: string; - marketMakerLimit: string; + productType: FuturesProductTypeV2; + marginCoin: string; + openAmount: string; + openPrice: string; + leverage?: string; } ⋮---- -export interface TaxRecordV3 { - id: string; - coin: string; - type: string; +export interface FuturesSetAutoMarginRequestV2 { + symbol: string; + autoMargin: 'on' | 'off'; + marginCoin: string; amount: string; - fee: string; - balance: string; - ts: string; + holdSide?: 'long' | 'short'; } - -================ -File: src/websocket-client-legacy-v1.ts -================ -/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ -import { EventEmitter } from 'events'; -import WebSocket from 'isomorphic-ws'; -⋮---- -import { - BitgetInstType, - WebsocketClientOptions, - WSClientConfigurableOptions, - WsKey, - WsTopic, - WsTopicSubscribeEventArgs, -} from './types/websockets/ws-general.js'; -import { DefaultLogger } from './util/logger.js'; -import { isWsPong } from './util/requestUtils.js'; -import { signMessage } from './util/webCryptoAPI.js'; -import { - getMaxTopicsPerSubscribeEvent, - getWsKeyForTopicV1, - isPrivateChannel, - neverGuard, - safeTerminateWs, - WS_AUTH_ON_CONNECT_KEYS, - WS_BASE_URL_MAP, - WS_KEY_MAP, -} from './util/websocket-util.js'; -import WsStore from './util/WsStore.js'; -import { WsConnectionStateEnum } from './util/WsStore.types.js'; ⋮---- -export type WsClientEvent = - | 'open' - | 'update' - | 'close' - | 'exception' - | 'reconnect' - | 'reconnected' - | 'response'; -⋮---- -interface WebsocketClientEvents { - /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ - open: (evt: { wsKey: WsKey; event: any }) => void; - /** Reconnecting a dropped connection */ - reconnect: (evt: { wsKey: WsKey; event: any }) => void; - /** Successfully reconnected a connection that dropped */ - reconnected: (evt: { wsKey: WsKey; event: any }) => void; - /** Connection closed */ - close: (evt: { wsKey: WsKey; event: any }) => void; - /** Received reply to websocket command (e.g. after subscribing to topics) */ - response: (response: any & { wsKey: WsKey }) => void; - /** Received data for topic */ - update: (response: any & { wsKey: WsKey }) => void; - /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ - exception: (response: any & { wsKey: WsKey }) => void; - /** Confirmation that a connection successfully authenticated */ - authenticated: (event: { wsKey: WsKey; event: any }) => void; +export interface FuturesSetLeverageRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + leverage: string; + holdSide?: 'long' | 'short'; } ⋮---- -/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ -⋮---- -/** Reconnecting a dropped connection */ -⋮---- -/** Successfully reconnected a connection that dropped */ -⋮---- -/** Connection closed */ -⋮---- -/** Received reply to websocket command (e.g. after subscribing to topics) */ -⋮---- -/** Received data for topic */ -⋮---- -/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ -⋮---- -/** Confirmation that a connection successfully authenticated */ -⋮---- -// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 -export declare interface WebsocketClientLegacyV1 { - on( - event: U, - listener: WebsocketClientEvents[U], - ): this; - - emit( - event: U, - ...args: Parameters - ): boolean; +export interface FuturesSetPositionMarginRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + holdSide: 'long' | 'short'; + amount: string; } ⋮---- -on( - event: U, - listener: WebsocketClientEvents[U], - ): this; -⋮---- -emit( - event: U, - ...args: Parameters - ): boolean; +export interface FuturesSetMarginModeRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + marginMode: 'isolated' | 'crossed'; +} ⋮---- /** - * @deprecated use WebsocketClientV2 instead - */ -export class WebsocketClientLegacyV1 extends EventEmitter -⋮---- -constructor( - options: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, -) -⋮---- -/** - * Subscribe to topics & track/persist them. They will be automatically resubscribed to if the connection drops/reconnects. - * @param wsTopics topic or list of topics - * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet) - */ -public subscribe( - wsTopics: WsTopicSubscribeEventArgs[] | WsTopicSubscribeEventArgs, - isPrivateTopic?: boolean, -) -⋮---- -// Persist this topic to the expected topics list -⋮---- -// if connected, send subscription request -⋮---- -// if not authenticated, dont sub to private topics yet. -// This'll happen automatically once authenticated + * + * * Futures | Position + * + */ ⋮---- -// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +export interface FuturesHistoricalPositionsRequestV2 { + symbol?: string; + productType?: FuturesProductTypeV2; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; +} ⋮---- /** - * Unsubscribe from topics & remove them from memory. They won't be re-subscribed to if the connection reconnects. - * @param wsTopics topic or list of topics - * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet) - */ -public unsubscribe( - wsTopics: WsTopicSubscribeEventArgs[] | WsTopicSubscribeEventArgs, - isPrivateTopic?: boolean, -) -⋮---- -// unsubscribe request only necessary if active connection exists + * + * * Futures | Trade + * + */ ⋮---- -/** Get the WsStore that tracks websockets & topics */ -public getWsStore(): typeof this.wsStore +export interface FuturesPlaceOrderRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginMode: 'isolated' | 'crossed'; + marginCoin: string; + size: string; + price?: string; + side: 'buy' | 'sell'; + tradeSide?: 'open' | 'close'; + orderType: 'limit' | 'market'; + force?: 'ioc' | 'fok' | 'gtc' | 'post_only'; + clientOid?: string; + reduceOnly?: 'YES' | 'NO'; + presetStopSurplusPrice?: string; + presetStopLossPrice?: string; + stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; +} ⋮---- -public close(wsKey: WsKey, force?: boolean) +export interface FuturesReversalOrderRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + size: string; + side?: 'buy' | 'sell'; + tradeSide?: 'open' | 'close'; + clientOid?: string; +} ⋮---- -public closeAll(force?: boolean) +interface FuturesBatchOrderItem { + size: string; + price?: string; + side: 'buy' | 'sell'; + tradeSide?: 'open' | 'close'; + orderType: 'limit' | 'market'; + force?: 'ioc' | 'fok' | 'gtc' | 'post_only'; + clientOid?: string; + reduceOnly?: 'YES' | 'NO'; + presetStopSurplusPrice?: string; + presetStopLossPrice?: string; + stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; +} ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -public connectAll(): Promise[] +export interface FuturesBatchOrderRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + marginMode: 'isolated' | 'crossed'; + orderList: FuturesBatchOrderItem[]; +} ⋮---- -/** - * Request connection to a specific websocket, instead of waiting for automatic connection. - */ -private async connect(wsKey: WsKey): Promise +export interface FuturesModifyOrderRequestV2 { + orderId?: string; + clientOid?: string; + symbol: string; + productType: FuturesProductTypeV2; + newClientOid: string; + newSize?: string; + newPrice?: string; + newPresetStopSurplusPrice?: string; + newPresetStopLossPrice?: string; +} ⋮---- -const url = this.getWsUrl(wsKey); // + authParams; +export interface FuturesCancelOrderRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin?: string; + orderId?: string; + clientOid?: string; +} ⋮---- -private parseWsError(context: string, error: any, wsKey: WsKey) +interface FuturesBatchCancelOrderItem { + orderId?: string; + clientOid?: string; +} ⋮---- -private async getWsAuthSignature( - apiKey: string | undefined, - apiSecret: string | undefined, - apiPass: string | undefined, - recvWindow: number = 0, -): Promise< +export interface FuturesBatchCancelOrderRequestV2 { + orderIdList?: FuturesBatchCancelOrderItem[]; + symbol?: string; + productType: FuturesProductTypeV2; + marginCoin?: string; +} ⋮---- -/** Get a signature, build the auth request and send it */ -private async sendAuthRequest(wsKey: WsKey): Promise +export interface FuturesFlashClosePositionsRequestV2 { + symbol?: string; + productType: FuturesProductTypeV2; + holdSide?: 'long' | 'short'; +} ⋮---- -// console.log('ws auth req', request); +export interface FuturesGetOrderRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + orderId?: string; + clientOid?: string; +} ⋮---- -private reconnectWithDelay(wsKey: WsKey, connectionDelayMs: number) +export interface FuturesGetOrderFillsRequestV2 { + orderId?: string; + symbol?: string; + productType: FuturesProductTypeV2; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; +} ⋮---- -private ping(wsKey: WsKey) +export interface FuturesGetHistoricalFillsRequestV2 { + orderId?: string; + symbol?: string; + productType: FuturesProductTypeV2; + startTime?: string; + endTime?: string; + idLessThan?: string; + limit?: string; +} ⋮---- -private clearTimers(wsKey: WsKey) +export interface FuturesGetOpenOrdersRequestV2 { + orderId?: string; + clientOid?: string; + symbol?: string; + productType: FuturesProductTypeV2; + status?: 'live' | 'partially_filled'; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; +} ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: WsKey) +export type FuturesOrderSourceV2 = + | 'normal' + | 'market' + | 'profit_market' + | 'loss_market' + | 'Trader_delegate' + | 'trader_profit' + | 'trader_loss' + | 'reverse' + | 'trader_reverse' + | 'profit_limit' + | 'loss_limit' + | 'liquidation' + | 'delivery_close_long' + | 'delivery_close_short' + | 'pos_profit_limit' + | 'pos_profit_market' + | 'pos_loss_limit' + | 'pos_loss_market'; ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: WsKey) +export interface FuturesGetHistoryOrdersRequestV2 { + orderId?: string; + clientOid?: string; + symbol?: string; + productType: FuturesProductTypeV2; + idLessThan?: string; + orderSource?: FuturesOrderSourceV2; + startTime?: string; + endTime?: string; + limit?: string; +} ⋮---- -/** - * @private Use the `subscribe(topics)` method to subscribe to topics. Send WS message to subscribe to topics. - */ -private requestSubscribeTopics( - wsKey: WsKey, - topics: WsTopicSubscribeEventArgs[], -) +export interface FuturesCancelAllOrdersRequestV2 { + symbol?: string; + productType: FuturesProductTypeV2; + marginCoin?: string; + requestTime?: string; + receiveWindow?: string; +} ⋮---- /** - * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. - */ -private requestUnsubscribeTopics( - wsKey: WsKey, - topics: WsTopicSubscribeEventArgs[], -) -⋮---- -public tryWsSend(wsKey: WsKey, wsMessage: string) -⋮---- -private connectToWsUrl(url: string, wsKey: WsKey): WebSocket -⋮---- -private async onWsOpen(event: WebSocket.Event, wsKey: WsKey) -⋮---- -// Some websockets require an auth packet to be sent after opening the connection + * + * * Futures | Trigger Orders + * + */ ⋮---- -// Reconnect to topics known before it connected -// Private topics will be resubscribed to once reconnected +export type FuturesTriggerTypeV2 = 'fill_price' | 'mark_price'; ⋮---- -/** Handle subscription to private topics _after_ authentication successfully completes asynchronously */ -private onWsAuthenticated(wsKey: WsKey) +export type FuturesStpModeV2 = + | 'none' + | 'cancel_taker' + | 'cancel_maker' + | 'cancel_both'; ⋮---- -private onWsMessage(event: unknown, wsKey: WsKey) +export interface FuturesTPSLOrderRequestV2 { + marginCoin: string; + productType: FuturesProductTypeV2; + symbol: string; + planType: FuturesPlanTypeV2; + triggerPrice: string; + triggerType?: FuturesTriggerTypeV2; + executePrice?: string; + holdSide: 'long' | 'short' | 'buy' | 'sell'; + size: string; + rangeRate?: string; + clientOid?: string; + stpMode?: FuturesStpModeV2; +} ⋮---- -// any message can clear the pong timer - wouldn't get a message if the ws wasn't working +export type FuturesTriggerPriceTypeV2 = + | 'fill_price' + | 'mark_price' + | 'index_price'; ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface FuturesPlanOrderRequestV2 { + planType: 'normal_plan' | 'track_plan'; + symbol: string; + productType: FuturesProductTypeV2; + marginMode: 'isolated' | 'crossed'; + marginCoin: string; + size: string; + price?: string; + callbackRatio?: string; + triggerPrice: string; + triggerType: 'mark_price' | 'fill_price'; + side: 'buy' | 'sell'; + tradeSide?: 'open' | 'close'; + orderType: 'limit' | 'market'; + clientOid?: string; + reduceOnly?: 'YES' | 'NO'; + stopSurplusTriggerPrice?: string; + stopSurplusExecutePrice?: string; + stopSurplusTriggerType?: FuturesTriggerPriceTypeV2; + stopLossTriggerPrice?: string; + stopLossExecutePrice?: string; + stopLossTriggerType?: FuturesTriggerPriceTypeV2; + stpMode?: FuturesStpModeV2; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface FuturesModifyTPSLOrderRequestV2 { + orderId?: string; + clientOid?: string; + marginCoin: string; + productType: FuturesProductTypeV2; + symbol: string; + triggerPrice: string; + triggerType?: 'fill_price' | 'mark_price'; + executePrice?: string; + size: string; + rangeRate?: string; +} ⋮---- -// fallback emit anyway +export interface FuturesModifyPlanOrderRequestV2 { + planType: 'normal_plan' | 'track_plan'; + orderId?: string; + clientOid?: string; + symbol: string; + productType: FuturesProductTypeV2; + newSize?: string; + newPrice?: string; + newCallbackRatio?: string; + newTriggerPrice?: string; + newTriggerType?: 'fill_price' | 'mark_price'; + newStopSurplusTriggerPrice?: string; + newStopSurplusExecutePrice?: string; + newStopSurplusTriggerType?: FuturesTriggerPriceTypeV2; + newStopLossTriggerPrice?: string; + newStopLossExecutePrice?: string; + newStopLossTriggerType?: FuturesTriggerPriceTypeV2; +} ⋮---- -private onWsClose(event: unknown, wsKey: WsKey) +export interface FuturesGetPlanOrdersRequestV2 { + orderId?: string; + clientOid?: string; + symbol?: string; + planType: 'normal_plan' | 'track_plan' | 'profit_loss'; + productType: FuturesProductTypeV2; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; +} ⋮---- -private getWs(wsKey: WsKey) +interface FuturesCancelPlanOrderItemV2 { + orderId?: string; + clientOid?: string; +} ⋮---- -private setWsState(wsKey: WsKey, state: WsConnectionStateEnum) +export type FuturesPlanOrderTypeV2 = + | 'normal_plan' + | 'profit_plan' + | 'loss_plan' + | 'pos_profit' + | 'pos_loss' + | 'moving_plan'; ⋮---- -private getWsUrl(wsKey: WsKey): string +export interface FuturesCancelPlanOrderRequestV2 { + orderIdList?: FuturesCancelPlanOrderItemV2[]; + symbol?: string; + productType: FuturesProductTypeV2; + marginCoin?: string; + planType?: FuturesPlanOrderTypeV2; +} ⋮---- -/** - * Subscribe to a topic - * @param instType instrument type (refer to API docs). - * @param topic topic name (e.g. "ticker"). - * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics. - * - * @deprecated use WebsocketClientV2 instead - */ -public subscribeTopic( - instType: BitgetInstType, - topic: WsTopic, - instId: string = 'default', -) +export type FuturesPlanStatusV2 = 'executed' | 'fail_trigger' | 'cancelled'; ⋮---- -/** - * Unsubscribe from a topic - * @param instType instrument type (refer to API docs). - * @param topic topic name (e.g. "ticker"). - * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics to get all symbols. - * - * @deprecated use WebsocketClientV2 instead - */ -public unsubscribeTopic( - instType: BitgetInstType, - topic: WsTopic, - instId: string = 'default', -) - -================ -File: src/websocket-client-v3.ts -================ -import { - WsAPIOperationResponseMap, - WSAPIRequestBitgetV3, - WSAPIRequestFlags, - WsAPITopicRequestParamMap, - WsAPIWsKeyTopicMap, - WSOperation, - WSOperationLoginParams, - WsRequestOperationBitget, -} from './types/websockets/ws-api.js'; -import { MessageEventLike } from './types/websockets/ws-events.js'; -import { - BitgetInstTypeV3, - WsKey, - WsTopicV3, -} from './types/websockets/ws-general.js'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient.js'; -import { isWsPong } from './util/requestUtils.js'; -import { isWSAPIResponse } from './util/type-guards.js'; -import { SignAlgorithm, signMessage } from './util/webCryptoAPI.js'; -import { - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getPromiseRefForWSAPIRequest, - getWsUrl, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WS_LOGGER_CATEGORY, - WsTopicRequest, -} from './util/websocket-util.js'; -import { WSConnectedResult } from './util/WsStore.types.js'; +export interface FuturesGetHistoryPlanOrdersRequestV2 { + orderId?: string; + clientOid?: string; + planType: 'normal_plan' | 'track_plan' | 'profit_loss'; + planStatus?: FuturesPlanStatusV2; + symbol?: string; + productType: FuturesProductTypeV2; + idLessThan?: string; + startTime?: string; + endTime?: string; + limit?: string; +} ⋮---- /** - * WebSocket client dedicated to the unified account (V3) WebSockets. * - * Your Bitget account needs to be upgraded to unified account mode, to use the account-level WebSocket topics. + * * Futures | Union Margin + * */ -export class WebsocketClientV3 extends BaseWebsocketClient< ⋮---- -WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within +export interface GetUnionTransferLimitsRequestV2 { + coin: string; +} ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -public connectAll(): Promise[] +export interface UnionConvertRequestV2 { + coin: string; + amount: string; +} ⋮---- /** - * Ensures the WS API connection is active and ready. - * - * You do not need to call this, but if you call this before making any WS API requests, - * it can accelerate the first request (by preparing the connection in advance). - */ -public connectWSAPI(): Promise + * + * * Futures | Account | Max Openable Quantity + * + */ ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +export interface FuturesMaxOpenRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + posSide: 'long' | 'short'; + orderType: 'limit' | 'market'; + openPrice?: string; +} ⋮---- /** - * Request subscription to one or more topics. Pass topics as either an array of strings, - * or array of objects (if the topic has parameters). - * - * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics - */ -public subscribe( - requests: - | (WsTopicRequest | WsTopicV3) - | (WsTopicRequest | WsTopicV3)[], - wsKey: WsKey, -): Promise + * + * * Futures | Account | Liquidation Price + * + */ ⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopicV3) - | (WsTopicRequest | WsTopicV3)[], - wsKey: WsKey, -) +export interface FuturesLiquidationPriceRequestV2 { + symbol: string; + productType: FuturesProductTypeV2; + marginCoin: string; + posSide: 'long' | 'short'; + orderType: 'limit' | 'market'; + openAmount: string; + openPrice?: string; +} ⋮---- /** - * - * - * Internal methods required to integrate with the BaseWSClient - * - * - */ + * + * * Futures | Account | Isolated Symbols + * + */ ⋮---- -protected sendPingEvent(wsKey: WsKey): void +export interface FuturesIsolatedSymbolsRequestV2 { + productType: FuturesProductTypeV2; +} + +================ +File: src/types/response/v3/account.ts +================ +// Account Management Response Types +export interface AccountSymbolConfigV3 { + category: string; + symbol: string; + marginMode: string; + leverage: string; +} ⋮---- -protected sendPongEvent(wsKey: WsKey): void +export interface AccountCoinConfigV3 { + coin: string; + leverage: string; +} ⋮---- -protected isWsPing(data: any): boolean +export interface AccountSettingsV3 { + assetMode: string; + holdMode: string; + symbolConfigList: AccountSymbolConfigV3[]; + coinConfigList: AccountCoinConfigV3[]; +} ⋮---- -protected isWsPong(data: any): boolean +export interface AccountAssetV3 { + coin: string; + equity: string; + usdValue: string; + balance: string; + available: string; + debt: string; + locked: string; +} ⋮---- -protected isPrivateTopicRequest( - _request: WsTopicRequest, - wsKey: WsKey, -): boolean -⋮---- -protected getPrivateWSKeys(): WsKey[] +export interface AccountAssetsV3 { + accountEquity: string; + usdtEquity: string; + btcEquity: string; + unrealisedPnl: string; + usdtUnrealisedPnl: string; + btcUnrealizedPnl: string; + effEquity: string; + mmr: string; + imr: string; + mgnRatio: string; + positionMgnRatio: string; + assets: AccountAssetV3[]; +} ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +export interface ConvertRecordV3 { + fromCoin: string; + fromCoinSize: string; + toCoin: string; + toCoinSize: string; + price: string; + ts: string; +} ⋮---- -protected async getWsUrl(wsKey: WsKey): Promise +export interface FinancialRecordV3 { + category: string; + id: string; + symbol: string; + coin: string; + type: string; + amount: string; + fee: string; + balance: string; + ts: string; +} ⋮---- -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface PaymentCoinV3 { + coin: string; + size: string; + amount: string; +} ⋮---- -/** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected async getWsRequestEvents( - operation: WSOperation, - requests: WsTopicRequest[], -): Promise>[]> +export interface RepayableCoinV3 { + coin: string; + size: string; + amount: string; +} ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +export interface RepayResponseV3 { + result: string; + repayAmount: string; +} ⋮---- -/** - { - "op":"subscribe", - "args":[ - { - "instType":"spot", - "topic":"ticker", - "symbol":"BTCUSDT" - }, - { - "instType":"spot", - "topic":"candle5m", - "symbol":"BTCUSDT" - } - ] - } - */ +// Sub-account Management Response Types ⋮---- -// const request = { -// topic: 'ticker', -// payload: { instType: 'spot', symbol: 'BTCUSDT' }, -// }; -// becomes: -// const request = { -// topic: 'ticker', -// instType: 'spot', -// symbol: 'BTCUSDT', -// }; +export interface CreateSubAccountApiKeyResponseV3 { + note: string; + apiKey: string; + secret: string; + type: string; + permissions: string[]; + ips: string[]; +} +export interface SubAccountApiKeyV3 { + apiKey: string; + note: string; + type: string; + permissions: string[]; + ips: string[]; + ts?: string; +} ⋮---- -private async getWsAuthSignature( - wsKey: WsKey, -): Promise< +export interface UpdateSubAccountApiKeyResponseV3 { + note: string; + apiKey: string; + type: string; + permissions: string[]; + ips: string[]; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +export interface CreateSubAccountResponseV3 { + username: string; + subUid: string; + status: string; + note: string; + createdTime: string; + updatedTime: string; +} ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, -): Promise> +export interface SubAccountV3 { + subUid: string; + username: string; + status: string; + accountMode: string; + type: string; + note: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] +// Transfer Response Types ⋮---- -/** - * WS API response handling - */ +export interface TransferResponseV3 { + transferId: string; +} ⋮---- -// const eg1 = { -// event: 'error', -// id: '1', -// code: '43012', -// msg: 'Insufficient balance', -// }; +export interface SubTransferRecordV3 { + transferId: string; + oldTransferId?: string; + fromType: string; + toType: string; + amount: string; + coin: string; + fromUserId: string; + toUserId: string; + status: string; + clientOid: string; + createdTime: string; + updatedTime: string; +} ⋮---- -// WS API Success +export interface SubUnifiedAssetV3 { + coin: string; + equity: string; + usdValue: string; + balance: string; + available: string; + debt: string; + locked: string; +} ⋮---- -/** - * V3 event handling for consumers - behaves the same as V2 - */ +export interface SubUnifiedAssetV3 { + subUid: string; + cursor: string; + assets: SubUnifiedAssetV3[]; +} ⋮---- -// v2 authentication event +export interface GetFeeRateResponseV3 { + makerFeeRate: string; + takerFeeRate: string; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface FundingAssetV3 { + coin: string; + available: string; + frozen: string; + balance: string; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +// Deposit Response Types ⋮---- -// fallback emit anyway +export interface DepositAddressV3 { + address: string; + chain: string; + coin: string; + tag: string; + url: string; +} ⋮---- -/** - * V3/UTA supports order placement via WebSockets. This is the WS API: - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - * - * @returns a promise that resolves/rejects when a matching response arrives - */ -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends WsAPITopicRequestParamMap[TWSOperation], - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( - wsKey: WsKey, - operation: TWSOperation, - category: BitgetInstTypeV3, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, -): Promise +export interface DepositRecordV3 { + orderId: string; + recordId: string; + coin: string; + type: 'deposit'; + dest: 'on_chain' | 'internal_transfer'; + size: string; + status: 'pending' | 'success' | 'fail'; + fromAddress: string; + toAddress: string; + chain: string; + createdTime: string; + updatedTime: string; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +// Withdraw Response Types ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); -⋮---- -// Ensure "args" is always wrapped as array -⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface WithdrawResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -// Enrich returned promise with request context for easier debugging +export interface WithdrawRecordV3 { + orderId: string; + clientOid: string; + recordId: string; + coin: string; + type: 'withdraw'; + dest: 'on_chain' | 'internal_transfer'; + size: string; + status: 'pending' | 'success' | 'fail'; + fromAddress: string; + toAddress: string; + chain: string; + fee: string; + confirm: string; + tag: string; + createdTime: string; + updatedTime: string; +} ⋮---- -// throw e; +export interface MaxTransferableV3 { + coin: string; + maxTransfer: string; + borrowMaxTransfer: string; +} ⋮---- -// Send event +export interface OpenInterestLimitV3 { + symbol: string; + singleUserLimit: string; + masterSubLimit: string; + marketMakerLimit: string; +} ⋮---- -// Return deferred promise, so caller can await this call - -================ -File: tsconfig.json -================ -{ - "compilerOptions": { - "allowSyntheticDefaultImports": true, - "baseUrl": ".", - "noEmitOnError": true, - "declaration": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": false, - "inlineSourceMap": false, - "lib": ["esnext", "DOM"], - "listEmittedFiles": false, - "listFiles": false, - "moduleResolution": "node", - "noFallthroughCasesInSwitch": true, - "noImplicitAny": true, - "noUnusedParameters": true, - "pretty": true, - "removeComments": false, - "resolveJsonModule": true, - "skipLibCheck": false, - "sourceMap": true, - "strict": true, - "strictNullChecks": true, - "types": ["node", "jest"], - "module": "commonjs", - "outDir": "dist/cjs", - "target": "esnext" - }, - "compileOnSave": true, - "exclude": ["node_modules", "dist"], - "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] +export interface TaxRecordV3 { + id: string; + coin: string; + type: string; + amount: string; + fee: string; + balance: string; + ts: string; } ================ -File: src/websocket-api-client.ts +File: src/types/websockets/ws-general.ts ================ -import { CancelOrderRequestV3 } from './types/request/v3/trade.js'; -import { CancelOrderResponseV3 } from './types/response/v3/trade.js'; -import { WSAPIResponse } from './types/websockets/ws-api.js'; -import { WSAPIPlaceOrderRequestV3 } from './types/websockets/ws-api-request.js'; -import { WSAPIPlaceOrderResponseV3 } from './types/websockets/ws-api-response.js'; -import { - BitgetInstTypeV3, - WSClientConfigurableOptions, -} from './types/websockets/ws-general.js'; -import { DefaultLogger } from './util/logger.js'; -import { WS_KEY_MAP } from './util/websocket-util.js'; -import { WebsocketClientV3 } from './websocket-client-v3.js'; +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; ⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ - attachEventListeners: boolean; -} +import { RestClientOptions } from '../../util/requestUtils.js'; +import { WS_KEY_MAP } from '../../util/websocket-util.js'; +import { FuturesProductTypeV2 } from '../request/shared.js'; ⋮---- -/** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ +export type BitgetInstType = 'SP' | 'SPBL' | 'MC' | 'UMCBL' | 'DMCBL'; +export type BitgetInstTypeV2 = 'SPOT' | FuturesProductTypeV2; +export type BitgetInstTypeV3 = + | 'UTA' // for account-level topics + | 'spot' + | 'usdt-futures' + | 'coin-futures' + | 'usdc-futures'; +⋮---- +| 'UTA' // for account-level topics ⋮---- /** - * This is a minimal Websocket API wrapper around the WebsocketClient. * - * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some - * may find the below methods slightly more intuitive. + * V1 list of topics for WebSocket consumers * - * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: - * https://github.com/tiagosiebler/bitget-api/blob/master/examples/V3/ws-api-trade-raw.ts */ -export class WebsocketAPIClient ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +export type WsPublicSpotTopic = + | 'ticker' + | 'candle1W' + | 'candle1D' + | 'candle12H' + | 'candle4H' + | 'candle1H' + | 'candle30m' + | 'candle15m' + | 'candle5m' + | 'candle1m' + | 'books' + | 'books5' + | 'trade'; ⋮---- -public getWSClient(): WebsocketClientV3 +// Futures currently has the same public topics as spot +export type WsPublicFuturesTopic = WsPublicSpotTopic; +export type WsPrivateSpotTopic = 'account' | 'orders'; ⋮---- -public setTimeOffsetMs(newOffset: number): void +export type WsPrivateFuturesTopic = + | 'account' + | 'positions' + | 'orders' + | 'ordersAlgo'; ⋮---- -/* - * Bitget WebSocket API Methods - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - */ +export type WsPublicTopic = WsPublicSpotTopic | WsPublicFuturesTopic; ⋮---- -/** - * Submit a new order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - * - * @returns - */ -submitNewOrder( - category: BitgetInstTypeV3, - params: WSAPIPlaceOrderRequestV3, -): Promise> +export type WsPrivateTopic = WsPrivateSpotTopic | WsPrivateFuturesTopic; +export type WsTopic = WsPublicTopic | WsPrivateTopic; ⋮---- /** - * Submit a new order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - * - * @returns - */ -placeBatchOrders( - category: BitgetInstTypeV3, - params: WSAPIPlaceOrderRequestV3[], -): Promise> + * + * V2 list of topics for WebSocket consumers + * + */ ⋮---- -/* - * Bitget WebSocket API Methods - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - */ +export type WsPublicTopicV2 = + | 'index-price' // margin only + | 'ticker' + | 'candle1m' + | 'candle5m' + | 'candle15m' + | 'candle30m' + | 'candle1H' + | 'candle4H' + | 'candle6H' + | 'candle12H' + | 'candle1D' + | 'candle3D' + | 'candle1W' + | 'candle1M' + | 'candle6Hutc' + | 'candle12Hutc' + | 'candle1Dutc' + | 'candle3Dutc' + | 'candle1Wutc' + | 'candle1Mutc' + | 'trade' + | 'books' + | 'books1' + | 'books5' + | 'books15'; ⋮---- -/** - * Cancel Order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - * - * @returns - */ -cancelOrder( - category: BitgetInstTypeV3, - params: CancelOrderRequestV3, -): Promise> +| 'index-price' // margin only ⋮---- -/** - * Batch Cancel Order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - * - * @returns - */ -cancelBatchOrders( - category: BitgetInstTypeV3, - params: CancelOrderRequestV3[], -): Promise> +// Also update PRIVATE_TOPICS_V2 if this is updated +export type WSPrivateTopicFuturesV2 = + | 'positions' + | 'orders-algo' + | 'positions-history'; ⋮---- -/** - * - * - * - * - * - * - * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * - * - */ +// Also update PRIVATE_TOPICS_V2 if this is updated +export type WSPrivateTopicMarginV2 = + | 'orders-crossed' + | 'account-crossed' + | 'account-isolated' + | 'orders-isolated'; ⋮---- -private setupDefaultEventListeners() +// Also update PRIVATE_TOPICS_V2 if this is updated +export type WsPrivateTopicV2 = + | 'account' + | 'orders' + | WSPrivateTopicFuturesV2 + | WSPrivateTopicMarginV2; +⋮---- +export type WsTopicV2 = WsPublicTopicV2 | WsPrivateTopicV2; ⋮---- /** - * General event handlers for monitoring the WebsocketClient - */ + * + * V3 / UTA list of topics for WebSocket consumers + * + */ +export type WsPublicTopicV3 = 'ticker' | 'kline' | 'books' | 'publicTrade'; +// Also update PRIVATE_TOPICS_V3 if this is updated +export type WsPrivateTopicV3 = 'account' | 'position' | 'fill' | 'order'; +export type WsTopicV3 = WsPublicTopicV3 | WsPrivateTopicV3; ⋮---- -// Blind JSON.stringify can fail on circular references +/** This is used to differentiate between each of the available websocket streams */ +export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; ⋮---- -// JSON.stringify({ ...data, target: 'WebSocket' }), - -================ -File: src/types/websockets/ws-api.ts -================ -import { WS_KEY_MAP } from '../../util/websocket-util.js'; -import { CancelOrderRequestV3 } from '../request/v3/trade.js'; -import { CancelOrderResponseV3 } from '../response/v3/trade.js'; -import { WSAPIPlaceOrderRequestV3 } from './ws-api-request.js'; -import { WSAPIPlaceOrderResponseV3 } from './ws-api-response.js'; -import { BitgetInstTypeV3, WsKey } from './ws-general.js'; +/** + * Event args for subscribing/unsubscribing + */ ⋮---- -export type WSOperation = 'subscribe' | 'unsubscribe' | 'login'; +export interface WsTopicSubscribeEventArgs { + instType: BitgetInstType; + channel: WsTopic; + instId?: string; +} ⋮---- -// When new WS API operations are added, make sure to also update WS_API_Operations[] below -export type WSAPIOperation = - | 'place-order' - | 'batch-place' - | 'cancel-order' - | 'batch-cancel'; +export type WsTopicSubscribePublicArgsV2 = { + instType: BitgetInstTypeV2; + channel: WsPublicTopicV2; + /** The symbol, e.g. "BTCUSDT" */ + instId: string; +}; ⋮---- -export interface WSOperationLoginParams { - apiKey: string; - passphrase: string; - timestamp: number; - sign: string; -} +/** The symbol, e.g. "BTCUSDT" */ ⋮---- -export interface WSAPIRequestBitgetV3 { - op: 'trade'; - id: string; - category: BitgetInstTypeV3; - topic: WSAPIOperation; - args: TWSParams | TWSParams[]; -} +export type WsInstIdChannelsV2 = + | 'orders' + | WSPrivateTopicFuturesV2 + | 'orders-crossed' + | 'orders-isolated'; ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} +export type WsTopicSubscribePrivateInstIdArgsV2 = { + instType: BitgetInstTypeV2; + channel: WsInstIdChannelsV2; + /** The symbol, e.g. "BTCUSDT" */ + instId?: string; +}; ⋮---- -/** If true, will skip auth requirement for WS API connection */ +/** The symbol, e.g. "BTCUSDT" */ ⋮---- -export type Exact = { - // This part says: if there's any key that's not in T, it's an error - [K: string]: never; -} & { - [K in keyof T]: T[K]; +export type WsCoinChannelsV2 = + | 'account' + | 'account-crossed' + | 'account-isolated'; +⋮---- +export type WsTopicSubscribePrivateCoinArgsV2 = { + instType: BitgetInstTypeV2; + channel: WsCoinChannelsV2; + coin: 'default' | string; }; ⋮---- -// This part says: if there's any key that's not in T, it's an error +export type WsTopicSubscribePrivateArgsV2 = + | WsTopicSubscribePrivateInstIdArgsV2 + | WsTopicSubscribePrivateCoinArgsV2; ⋮---- -/** +export type WsTopicSubscribeEventArgsV2 = + | WsTopicSubscribePublicArgsV2 + | WsTopicSubscribePrivateArgsV2; +⋮---- +/** General configuration for the WebsocketClient */ +export interface WSClientConfigurableOptions { + /** Your API key */ + apiKey?: string; -/** - * V2 request looks like this: -{ - "op":"subscribe", - "args":[ - { - "instType":"SPOT", - "channel":"ticker", - "instId":"BTCUSDT" - }, - { - "instType":"SPOT", - "channel":"candle5m", - "instId":"BTCUSDT" - } - ] -} - */ -export interface WsRequestOperationBitget { - op: WSOperation; - args?: (TWSRequestArg | string | number)[]; -} -export interface WSAPIResponse< - TResponseData extends object = object, - TOperation extends WSAPIOperation = WSAPIOperation, -> { - wsKey: WsKey; - /** Auto-generated */ - id: string; - event: 'trade'; - category: BitgetInstTypeV3; - topic: TOperation; - args: TResponseData; - code: '0' | string; - msg: 'success' | string; - ts: string; + /** Your API secret */ + apiSecret?: string; + + /** The passphrase you set when creating the API Key (NOT your account password) */ + apiPass?: string; + + /** + * Set to `true` to connect to Bitget's demo trading WebSockets: + * + * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket + * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading + */ + demoTrading?: boolean; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; + + // Disable ping/pong ws heartbeat mechanism (not recommended) + disableHeartbeat?: boolean; + + /** How often to check if the connection is alive */ + pingInterval?: number; + + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; + + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; + + requestOptions?: RestClientOptions; + + wsOptions?: { + protocols?: string[]; + agent?: any; + } & Partial; + + wsUrl?: string; + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ + customSignMessageFn?: (message: string, secret: string) => Promise; } ⋮---- -/** Auto-generated */ +/** Your API key */ ⋮---- -/** - * List of operations supported for this WsKey (connection) - */ -export interface WsAPIWsKeyTopicMap { - [WS_KEY_MAP.v3Private]: WSAPIOperation; -} +/** Your API secret */ +⋮---- +/** The passphrase you set when creating the API Key (NOT your account password) */ ⋮---- /** - * Request parameters expected per operation - */ -export interface WsAPITopicRequestParamMap { - // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - 'place-order': WSAPIPlaceOrderRequestV3; - // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - 'batch-place': WSAPIPlaceOrderRequestV3[]; - // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - 'cancel-order': CancelOrderRequestV3; - // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - 'batch-cancel': CancelOrderRequestV3[]; -} + * Set to `true` to connect to Bitget's demo trading WebSockets: + * + * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket + * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading + */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel +// Disable ping/pong ws heartbeat mechanism (not recommended) ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel +/** How often to check if the connection is alive */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel -⋮---- -/** - * Response structure expected for each operation - */ -export interface WsAPIOperationResponseMap { - // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - 'place-order': WSAPIResponse<[WSAPIPlaceOrderResponseV3], 'place-order'>; - // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - 'batch-place': WSAPIResponse; - // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - 'cancel-order': WSAPIResponse<[CancelOrderResponseV3], 'cancel-order'>; - // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - 'batch-cancel': WSAPIResponse; -} -⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel +/** Delay in milliseconds before respawning the connection */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + pingInterval: number; + pongTimeout: number; + reconnectTimeout: number; + recvWindow: number; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequests: boolean; +} ================ File: src/index.ts @@ -10551,4532 +9200,4201 @@ File: src/index.ts ================ -File: .eslintrc.cjs -================ -// 'no-unused-vars': ['warn'], - -================ -File: src/types/websockets/ws-general.ts +File: README.md ================ -import { RestClientOptions } from '../../util/requestUtils.js'; -import { WS_KEY_MAP } from '../../util/websocket-util.js'; -import { FuturesProductTypeV2 } from '../request/shared.js'; -⋮---- -export type BitgetInstType = 'SP' | 'SPBL' | 'MC' | 'UMCBL' | 'DMCBL'; -export type BitgetInstTypeV2 = 'SPOT' | FuturesProductTypeV2; -export type BitgetInstTypeV3 = - | 'UTA' // for account-level topics - | 'spot' - | 'usdt-futures' - | 'coin-futures' - | 'usdc-futures'; -⋮---- -| 'UTA' // for account-level topics -⋮---- -/** - * - * V1 list of topics for WebSocket consumers - * - */ -⋮---- -export type WsPublicSpotTopic = - | 'ticker' - | 'candle1W' - | 'candle1D' - | 'candle12H' - | 'candle4H' - | 'candle1H' - | 'candle30m' - | 'candle15m' - | 'candle5m' - | 'candle1m' - | 'books' - | 'books5' - | 'trade'; -⋮---- -// Futures currently has the same public topics as spot -export type WsPublicFuturesTopic = WsPublicSpotTopic; -export type WsPrivateSpotTopic = 'account' | 'orders'; -⋮---- -export type WsPrivateFuturesTopic = - | 'account' - | 'positions' - | 'orders' - | 'ordersAlgo'; -⋮---- -export type WsPublicTopic = WsPublicSpotTopic | WsPublicFuturesTopic; -⋮---- -export type WsPrivateTopic = WsPrivateSpotTopic | WsPrivateFuturesTopic; -export type WsTopic = WsPublicTopic | WsPrivateTopic; -⋮---- -/** - * - * V2 list of topics for WebSocket consumers - * - */ -⋮---- -export type WsPublicTopicV2 = - | 'index-price' // margin only - | 'ticker' - | 'candle1m' - | 'candle5m' - | 'candle15m' - | 'candle30m' - | 'candle1H' - | 'candle4H' - | 'candle6H' - | 'candle12H' - | 'candle1D' - | 'candle3D' - | 'candle1W' - | 'candle1M' - | 'candle6Hutc' - | 'candle12Hutc' - | 'candle1Dutc' - | 'candle3Dutc' - | 'candle1Wutc' - | 'candle1Mutc' - | 'trade' - | 'books' - | 'books1' - | 'books5' - | 'books15'; -⋮---- -| 'index-price' // margin only -⋮---- -// Also update PRIVATE_TOPICS_V2 if this is updated -export type WSPrivateTopicFuturesV2 = - | 'positions' - | 'orders-algo' - | 'positions-history'; -⋮---- -// Also update PRIVATE_TOPICS_V2 if this is updated -export type WSPrivateTopicMarginV2 = - | 'orders-crossed' - | 'account-crossed' - | 'account-isolated' - | 'orders-isolated'; -⋮---- -// Also update PRIVATE_TOPICS_V2 if this is updated -export type WsPrivateTopicV2 = - | 'account' - | 'orders' - | WSPrivateTopicFuturesV2 - | WSPrivateTopicMarginV2; -⋮---- -export type WsTopicV2 = WsPublicTopicV2 | WsPrivateTopicV2; -⋮---- -/** - * - * V3 / UTA list of topics for WebSocket consumers - * - */ -export type WsPublicTopicV3 = 'ticker' | 'kline' | 'books' | 'publicTrade'; -// Also update PRIVATE_TOPICS_V3 if this is updated -export type WsPrivateTopicV3 = 'account' | 'position' | 'fill' | 'order'; -export type WsTopicV3 = WsPublicTopicV3 | WsPrivateTopicV3; -⋮---- -/** This is used to differentiate between each of the available websocket streams */ -export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; -⋮---- -/** - * Event args for subscribing/unsubscribing - */ -⋮---- -export interface WsTopicSubscribeEventArgs { - instType: BitgetInstType; - channel: WsTopic; - instId?: string; -} -⋮---- -export type WsTopicSubscribePublicArgsV2 = { - instType: BitgetInstTypeV2; - channel: WsPublicTopicV2; - /** The symbol, e.g. "BTCUSDT" */ - instId: string; -}; -⋮---- -/** The symbol, e.g. "BTCUSDT" */ -⋮---- -export type WsInstIdChannelsV2 = - | 'orders' - | WSPrivateTopicFuturesV2 - | 'orders-crossed' - | 'orders-isolated'; -⋮---- -export type WsTopicSubscribePrivateInstIdArgsV2 = { - instType: BitgetInstTypeV2; - channel: WsInstIdChannelsV2; - /** The symbol, e.g. "BTCUSDT" */ - instId?: string; -}; -⋮---- -/** The symbol, e.g. "BTCUSDT" */ -⋮---- -export type WsCoinChannelsV2 = - | 'account' - | 'account-crossed' - | 'account-isolated'; -⋮---- -export type WsTopicSubscribePrivateCoinArgsV2 = { - instType: BitgetInstTypeV2; - channel: WsCoinChannelsV2; - coin: 'default' | string; -}; -⋮---- -export type WsTopicSubscribePrivateArgsV2 = - | WsTopicSubscribePrivateInstIdArgsV2 - | WsTopicSubscribePrivateCoinArgsV2; -⋮---- -export type WsTopicSubscribeEventArgsV2 = - | WsTopicSubscribePublicArgsV2 - | WsTopicSubscribePrivateArgsV2; -⋮---- -/** General configuration for the WebsocketClient */ -export interface WSClientConfigurableOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; +# Node.js & Typescript Bitget API SDK - /** The passphrase you set when creating the API Key (NOT your account password) */ - apiPass?: string; +[![Build & Test](https://github.com/tiagosiebler/bitget-api/actions/workflows/e2etests.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/bitget-api/actions/workflows/e2etests.yml) +[![npm version](https://img.shields.io/npm/v/bitget-api)][1] +[![npm size](https://img.shields.io/bundlephobia/min/bitget-api/latest)][1] +[![npm downloads](https://img.shields.io/npm/dt/bitget-api)][1] +[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/bitget-api)][1] +[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/bitget-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/bitget-api) +[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) - /** - * Set to `true` to connect to Bitget's demo trading WebSockets: - * - * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket - * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading - */ - demoTrading?: boolean; +

+ + + + SDK Logo + + +

- /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; +[1]: https://www.npmjs.com/package/bitget-api - // Disable ping/pong ws heartbeat mechanism (not recommended) - disableHeartbeat?: boolean; +Updated & performant JavaScript & Node.js SDK for the Bitget V2 REST APIs and WebSockets: - /** How often to check if the connection is alive */ - pingInterval?: number; +- Professional, robust & performant Bitget SDK with extensive production use in live trading environments. +- Complete integration with all Bitget APIs. + - [x] Supports V2 REST APIs & WebSockets + - [x] Supports V3/UTA REST APIs & WebSockets (latest) + - [x] Supports order placement via V3 WebSocket API +- Complete TypeScript support (with type declarations for all API requests & responses). + - Strongly typed requests and responses. + - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. +- Actively maintained with a modern, promise-driven interface. +- Over 100 integration tests making real API calls & WebSocket connections, validating any changes before they reach npm. +- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. + - Event driven messaging. + - Smart WebSocket persistence with automatic reconnection handling. + - Emit `reconnected` event when dropped connection is restored. + - Optional beautification of WebSocket events for improved readability. +- Officially listed Node.js SDK in [Bitget API docs](https://bitgetlimited.github.io/apidoc/en/spot/#sdk-code-example). +- Browser support (via webpack bundle - see "Browser Usage" below). +- Support all authentication methods supported by Bitget: + - [x] HMAC + - [x] RSA +- Heavy automated end-to-end testing with real API calls. + - End-to-end testing before any release. + - Real API calls in e2e tests. +- Proxy support via axios integration. +- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; +## Table of Contents - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; +- [Installation](#installation) +- [Examples](#examples) +- [Issues & Discussion](#issues--discussion) +- [Related Projects](#related-projects) +- [Documentation](#documentation) +- [Structure](#structure) +- [Usage](#usage) + - [REST API Clients](#rest-api-clients) + - [V3 REST APIs (Unified Trading Account)](#v3-rest-apis) + - [V2 REST APIs](#v2-rest-apis) + - [WebSockets](#websockets) + - [V3 Unified Trading Account](#v3-unified-trading-account) + - [Sending Orders via WebSockets](#sending-orders-via-websockets) + - [Receiving Realtime Data](#receiving-realtime-data) + - [V2 WebSockets](#v2-websockets) + - [Customise Logging](#logging) + - [Custom Logger](#customise-logging) + - [Debug HTTP Requests](#debug-http-requests) + - [Frontend Usage](#browser-usage) + - [Import](#import) + - [Webpack](#webpack) +- [LLMs & AI](#use-with-llms--ai) +- [Used By](#used-by) +- [Contributions & Thanks](#contributions--thanks) - requestOptions?: RestClientOptions; +## Installation - wsOptions?: { - protocols?: string[]; - agent?: any; - }; +`npm install --save bitget-api` - wsUrl?: string; +## Examples - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ - customSignMessageFn?: (message: string, secret: string) => Promise; -} -⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- -/** The passphrase you set when creating the API Key (NOT your account password) */ -⋮---- -/** - * Set to `true` to connect to Bitget's demo trading WebSockets: - * - * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket - * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading - */ -⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ -⋮---- -// Disable ping/pong ws heartbeat mechanism (not recommended) -⋮---- -/** How often to check if the connection is alive */ -⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ -⋮---- -/** Delay in milliseconds before respawning the connection */ -⋮---- -/** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ -⋮---- -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - pingInterval: number; - pongTimeout: number; - reconnectTimeout: number; - recvWindow: number; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequests: boolean; -} +Refer to the [examples](./examples) folder for implementation demos. -================ -File: src/websocket-client-v2.ts -================ -import { - WSOperation, - WSOperationLoginParams, - WsRequestOperationBitget, -} from './types/websockets/ws-api.js'; -import { MessageEventLike } from './types/websockets/ws-events.js'; -import { - BitgetInstTypeV2, - WsKey, - WsTopicV2, -} from './types/websockets/ws-general.js'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient.js'; -import { isWsPong } from './util/requestUtils.js'; -import { - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './util/webCryptoAPI.js'; -import { - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getWsUrl, - isPrivateChannel, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WsTopicRequest, -} from './util/websocket-util.js'; -import { WSConnectedResult } from './util/WsStore.types.js'; -⋮---- -export class WebsocketClientV2 extends BaseWebsocketClient< -⋮---- -WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within -⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -public connectAll(): Promise[] -⋮---- -/** Some private channels use `coin` instead of `instId`. This method handles building the sub/unsub request */ -private getSubRequest( - instType: BitgetInstTypeV2, - topic: WsTopicV2, - coin: string = 'default', -): WsTopicRequest -⋮---- -/** - * Subscribe to a topic - * @param instType instrument type (refer to API docs). - * @param topic topic name (e.g. "ticker"). - * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics. - */ -public subscribeTopic( - instType: BitgetInstTypeV2, - topic: WsTopicV2, - coin: string = 'default', -) -⋮---- -/** - * Unsubscribe from a topic - * @param instType instrument type (refer to API docs). - * @param topic topic name (e.g. "ticker"). - * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics to get all symbols. - */ -public unsubscribeTopic( - instType: BitgetInstTypeV2, - topic: WsTopicV2, - coin: string = 'default', -) -⋮---- -/** - * Request subscription to one or more topics. Pass topics as either an array of strings, - * or array of objects (if the topic has parameters). - * - * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics - */ -public subscribe( - requests: - | (WsTopicRequest | WsTopicV2) - | (WsTopicRequest | WsTopicV2)[], - wsKey: WsKey, -): Promise -⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopicV2) - | (WsTopicRequest | WsTopicV2)[], - wsKey: WsKey, -) -⋮---- -/** - * - * - * Internal methods required to integrate with the BaseWSClient - * - * - */ -⋮---- -protected sendPingEvent(wsKey: WsKey): void -⋮---- -protected sendPongEvent(wsKey: WsKey): void -⋮---- -protected isWsPing(data: any): boolean -⋮---- -protected isWsPong(data: any): boolean -⋮---- -protected isPrivateTopicRequest( - _request: WsTopicRequest, - wsKey: WsKey, -): boolean -⋮---- -protected getPrivateWSKeys(): WsKey[] -⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean -⋮---- -protected async getWsUrl(wsKey: WsKey): Promise -⋮---- -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null -⋮---- -/** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected async getWsRequestEvents( - operation: WSOperation, - requests: WsTopicRequest[], -): Promise>[]> -⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values -⋮---- -/** - { - "op":"subscribe", - "args":[ - { - "instType":"SPOT", - "channel":"ticker", - "instId":"BTCUSDT" - }, - { - "instType":"SPOT", - "channel":"candle5m", - "instId":"BTCUSDT" - } - ] - } - */ -⋮---- -// const request = { -// topic: 'ticker', -// payload: { instType: 'SPOT', instId: 'BTCUSDT' }, -// }; -// becomes: -// const request = { -// channel: 'ticker', -// instType: 'SPOT', -// instId: 'BTCUSDT', -// }; -⋮---- -private async getWsAuthSignature( - wsKey: WsKey, -): Promise< -⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: SignEncodeMethod, - algorithm: SignAlgorithm, -): Promise -⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, -): Promise> -⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] -⋮---- -// v2 event processing -⋮---- -// v2 authentication event -⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), -⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), -⋮---- -// fallback emit anyway -⋮---- -/** - * @deprecrated not supported by Bitget's V2 API offering - */ -async sendWSAPIRequest(): Promise +## Issues & Discussion -================ -File: src/rest-client-v2.ts -================ -import { FuturesProductTypeV2, MarginType } from './types/request/shared.js'; -import { - CreateSubAccountApiKeyRequestV2, - GetAllSubDepositWithdrawalRequestV2, - GetBrokerCommissionsRequestV2, - GetBrokerOrderCommissionRequestV2, - GetBrokerRebateInfoRequestV2, - GetBrokerSubaccountsRequestV2, - GetBrokerTotalCommissionRequestV2, - GetBrokerTradeVolumeRequestV2, - GetSubAccountsRequestV2, - ModifySubAccountApiKeyRequestV2, - ModifySubRequestV2, - SubDepositRecordsRequestV2, - SubWithdrawalRecordsRequestV2, - SubWithdrawalRequestV2, -} from './types/request/v2/broker.js'; -import { - ConvertQuoteRequestV2, - ConvertRequestV2, - CreateVirtualSubApiKeyRequestV2, - CreateVirtualSubRequestV2, - GetAnnouncementsRequestV2, - GetConvertBGBHistoryRequestV2, - GetConvertHistoryRequestV2, - GetFuturesTransactionsRequestV2, - GetMarginTransactionsRequestV2, - GetMerchantAdvertisementsRequestV2, - GetMerchantP2POrdersRequestV2, - GetP2PMerchantsRequestV2, - GetP2PTransactionsRequestV2, - GetSpotTransactionsRequestV2, - GetTradeRateRequestV2, - ModifyVirtualSubApiKeyRequestV2, - ModifyVirtualSubRequestV2, -} from './types/request/v2/common.js'; -import { - CloseFuturesFollowerPositionsRequestV2, - CopyTradingProductTypeV2, - FuturesTraderSymbolSettingRequestV2, - GetFollowerFuturesCurrentTrackingOrdersRequestV2, - GetFollowerFuturesHistoryTrackingOrdersRequestV2, - GetFuturesFollowerTradersRequestV2, - GetFuturesTraderCurrentOrdersRequestV2, - GetFuturesTraderFollowersRequestV2, - GetFuturesTraderHistoryOrdersRequestV2, - GetFuturesTraderProfitShareDetailRequestV2, - GetSpotFollowerHistoryOrdersRequestV2, - GetSpotFollowerOpenOrdersRequestV2, - GetSpotTraderCurrentOrdersRequestV2, - GetSpotTraderFollowersRequestV2, - GetSpotTraderHistoryOrdersRequestV2, - GetSpotTraderHistoryProfitRequestV2, - ModifyFuturesTraderOrderTPSLRequestV2, - SpotFollowerCopyTradeSettingV2, - UpdateFuturesFollowerSettingsRequestV2, - UpdateFuturesFollowerTPSLRequestV2, -} from './types/request/v2/copytrading.js'; -import { - BorrowLoanRequestV2, - GetEarnSavingsAssetsRequestV2, - GetEarnSavingsRecordsRequestV2, - GetLiquidationRecordsRequestV2, - GetLoanEstInterestAndBorrowableRequestV2, - GetLoanHistoryRequestV2, - GetLoanPledgeRateHistoryRequestV2, - GetLoanRepayHistoryRequestV2, - GetSharkfinAssetsRequestV2, - GetSharkfinRecordsRequestV2, - ModifyLoanPledgeRateRequestV2, - RedeemSavingsRequestV2, - RepayLoanRequestV2, -} from './types/request/v2/earn.js'; -import { - FuturesAccountBillRequestV2, - FuturesBatchCancelOrderRequestV2, - FuturesBatchOrderRequestV2, - FuturesCancelAllOrdersRequestV2, - FuturesCancelOrderRequestV2, - FuturesCancelPlanOrderRequestV2, - FuturesCandlesRequestV2, - FuturesFlashClosePositionsRequestV2, - FuturesGetHistoricalFillsRequestV2, - FuturesGetHistoryOrdersRequestV2, - FuturesGetHistoryPlanOrdersRequestV2, - FuturesGetOpenOrdersRequestV2, - FuturesGetOrderFillsRequestV2, - FuturesGetOrderRequestV2, - FuturesGetPlanOrdersRequestV2, - FuturesHistoricalPositionsRequestV2, - FuturesHistoricTradesRequestV2, - FuturesInterestHistoryRequestV2, - FuturesIsolatedSymbolsRequestV2, - FuturesLiquidationPriceRequestV2, - FuturesMaxOpenRequestV2, - FuturesMergeDepthRequestV2, - FuturesModifyOrderRequestV2, - FuturesModifyPlanOrderRequestV2, - FuturesModifyTPSLOrderRequestV2, - FuturesOpenCountRequestV2, - FuturesPlaceOrderRequestV2, - FuturesPlanOrderRequestV2, - FuturesRecentTradesRequestV2, - FuturesReversalOrderRequestV2, - FuturesSetAutoMarginRequestV2, - FuturesSetLeverageRequestV2, - FuturesSetMarginModeRequestV2, - FuturesSetPositionMarginRequestV2, - FuturesSingleAccountRequestV2, - FuturesTPSLOrderRequestV2, - GetUnionTransferLimitsRequestV2, - UnionConvertRequestV2, -} from './types/request/v2/futures.js'; -import { - GetBorrowHistoryRequestV2, - GetFinancialHistoryRequestV2, - GetHistoryOrdersRequestV2, - GetInterestHistoryRequestV2, - GetLiquidationHistoryRequestV2, - GetMarginCurrentOrdersRequestV2, - GetMarginLiquidationOrdersRequestV2, - GetMarginOrderFillsRequestV2, - GetRepayHistoryRequestV2, - MarginBatchOrdersRequestV2, - MarginPlaceOrderRequestV2, -} from './types/request/v2/margin.js'; -import { - GetSpotAccountBillsRequestV2, - GetSpotCurrentPlanOrdersRequestV2, - GetSpotDepositRecordRequestV2, - GetSpotFillsRequestV2, - GetSpotHistoryOrdersRequestV2, - GetSpotHistoryPlanOrdersRequestV2, - GetSpotOpenOrdersRequestV2, - GetSpotOrderInfoRequestV2, - GetSpotSubAccountDepositRecordRequestV2, - GetSpotTransferRecordRequestV2, - GetSpotWithdrawalRecordRequestV2, - SpotAccountTypeV2, - SpotBatchCancelOrderRequestV2, - SpotBatchOrderRequestV2, - SpotCancelandSubmitOrderRequestV2, - SpotCancelOrderRequestV2, - SpotCandlesRequestV2, - SpotHistoricCandlesRequestV2, - SpotHistoricTradesRequestV2, - SpotMainSubTransferRecordRequestV2, - SpotModifyPlanOrderRequestV2, - SpotOrderRequestV2, - SpotPlanOrderRequestV2, - SpotSubAccountTransferRequestV2, - SpotTransferRequestV2, - SpotWithdrawalRequestV2, -} from './types/request/v2/spot.js'; -import { APIResponse } from './types/response/v1/shared.js'; -import { - AllSubDepositWithdrawalRecordV2, - BrokerCommissionV2, - BrokerOrderCommissionV2, - BrokerRebateInfoV2, - BrokerSubaccountFutureAssetV2, - BrokerSubaccountInfoV2, - BrokerSubaccountSpotAssetV2, - BrokerSubaccountV2, - BrokerSubaccountWithdrawalV2, - BrokerTotalCommissionV2, - BrokerTradeVolumeV2, - CreateSubaccountApiKeyResponseV2, - CreateSubaccountDepositAddressV2, - CreateSubaccountResponseV2, - ModifySubaccountApiKeyResponseV2, - ModifySubaccountResponseV2, - SubaccountApiKeyV2, - SubaccountDepositV2, - SubaccountEmailV2, -} from './types/response/v2/broker.js'; -import { - AnnouncementV2, - BGBConvertCoinV2, - BGBConvertHistoryV2, - BotAssetV2, - ConvertBGBResponseV2, - ConvertCurrencyV2, - ConvertQuotedPriceV2, - ConvertRecordV2, - ConvertTradeResponseV2, - CreateVirtualSubAccountAndApiKeyV2, - CreateVirtualSubAccountApiKeyV2, - CreateVirtualSubAccountV2, - FundingAssetV2, - FuturesActiveBuySellVolumeV2, - FuturesActiveLongShortAccountV2, - FuturesActiveLongShortPositionV2, - FuturesLongShortRatioV2, - FuturesTransactionRecordV2, - IsolatedMarginBorrowingRatioV2, - LeveragedLongShortRatioV2, - MarginLoanGrowthRateV2, - MarginTransactionRecordV2, - ModifyVirtualSubAccountApiKeyV2, - P2PMerchantAdvertismentV2, - P2PMerchantInfoV2, - P2PMerchantOrdersV2, - P2PMerchantOrderV2, - P2PMerchantV2, - SpotFundFlowV2, - SpotTransactionRecordV2, - SpotWhaleNetFlowV2, - SubAccountApiKeyItemV2, - VirtualSubAccountV2, -} from './types/response/v2/common.js'; -import { - CTFuturesFollowerCurrentOrdersV2, - CTFuturesFollowerHistoryOrdersV2, - CTFuturesFollowerMyTradersV2, - CTFuturesFollowerSettingsV2, - CTFuturesTraderCurrentOrdersV2, - CTFuturesTraderHistoryOrderV2, - CTFuturesTraderHistoryProfitSummaryV2, - CTFuturesTraderMyFollowersV2, - CTFuturesTraderProfitShareHistoryV2, - CTFuturesTraderSymbolSettingsV2, - CTFuturesTraderTotalOrderSummaryV2, - CTSpotFollowerCurrentOrdersV2, - CTSpotFollowerFollowConfigurationV2, - CTSpotFollowerHistoryOrdersV2, - CTSpotFollowerMyTradersV2, - CTSpotTraderCurrentTrackingOrdersV2, - CTSpotTraderFollowerListV2, - CTSpotTraderHistoryOrdersV2, - CTSpotTraderHistoryProfitSharingV2, - CTSpotTraderProfitSummaryV2, - CTSpotTraderTotalOrderDetailV2, - CTSpotTraderUnrealizedProfitV2, -} from './types/response/v2/copy-trading.js'; -import { - EarnLoanCurrenciesV2, - EarnLoanDebtsV2, - EarnLoanHistoryV2, - EarnLoanLiquidationRecordsV2, - EarnLoanOrdersV2, - EarnLoanPledgeRateHistoryV2, - EarnLoanRepayHistoryV2, - EarnLoanRepayResponseV2, - EarnSavingsAccountV2, - EarnSavingsAssetsV2, - EarnSavingsProductsV2, - EarnSavingsRecordsV2, - EarnSavingsSubscriptionDetailV2, - EarnSharkfinAccountV2, - EarnSharkfinAssetsV2, - EarnSharkfinProductsV2, - EarnSharkfinRecordsV2, - EarnSharkfinSubscriptionDetailV2, -} from './types/response/v2/earn.js'; -import { - FuturesAccountBillV2, - FuturesAccountsV2, - FuturesAccountV2, - FuturesBatchOrderResponseV2, - FuturesCancelAllOrdersV2, - FuturesCancelPlanOrderV2, - FuturesCandlestickV2, - FuturesClosePositionResponseV2, - FuturesContractConfigV2, - FuturesDiscountRatesV2, - FuturesFillV2, - FuturesFundingTimeV2, - FuturesHistoricalFundingRateV2, - FuturesHistoryInterestRateV2, - FuturesHistoryOrderV2, - FuturesHistoryPlanOrderV2, - FuturesHistoryPositionV2, - FuturesInterestExchangeRateV2, - FuturesInterestHistoryV2, - FuturesIsolatedSymbolV2, - FuturesLiquidationPriceV2, - FuturesMaxOpenV2, - FuturesMergeDepthV2, - FuturesOpenInterestV2, - FuturesOpenOrderV2, - FuturesOrderDetailV2, - FuturesOrderFillV2, - FuturesPendingPlanOrderV2, - FuturesPositionTierV2, - FuturesPositionV2, - FuturesSubAccountAssetV2, - FuturesSymbolPriceV2, - FuturesTickerV2, - FuturesTriggerSubOrderV2, - FuturesVipFeeRateV2, - SetLeverageResponseV2, - SetMarginModeResponseV2, - UnionConfigV2, - UnionConvertV2, - UnionSwitchUsdtV2, - UnionTransferLimitsV2, -} from './types/response/v2/futures.js'; -import { - CrossInterestRateAndLimitResponseV2, - CrossMaxBorrowableResponseV2, - CrossMaxTransferableResponseV2, - CrossTierConfigurationResponseV2, - IsolatedInterestRateAndLimitResponseV2, - IsolatedMaxBorrowableResponseV2, - IsolatedMaxTransferableResponseV2, - IsolatedTierConfigurationResponseV2, - MarginAccountAssetV2, - MarginBatchOrdersResponseV2, - MarginBorrowHistoryItemV2, - MarginCurrencyV2, - MarginCurrentOrderV2, - MarginFinancialHistoryItemV2, - MarginHistoryOrderV2, - MarginInterestHistoryItemV2, - MarginLiquidationHistoryItemV2, - MarginLiquidationOrderV2, - MarginOrderFillV2, - MarginRepaymentHistoryItemV2, -} from './types/response/v2/margin.js'; -import { - CancelAndSubmitSpotOrderResponseV2, - SpotAccountAssetV2, - SpotAccountBillV2, - SpotAccountInfoV2, - SpotCancelPlanOrdersV2, - SpotCandlestickV2, - SpotCoinInfoV2, - SpotCurrentPlanOrderV2, - SpotDepositAddressV2, - SpotDepositRecordV2, - SpotFillV2, - SpotHistoryPlanOrderV2, - SpotMainSubTransferRecordV2, - SpotMergeDepthV2, - SpotOpenOrderV2, - SpotOrderBookDepthV2, - SpotOrderInfoV2, - SpotPlanSubOrderV2, - SpotSubAccountAssetsV2, - SpotSubAccountDepositRecordV2, - SpotSymbolInfoV2, - SpotTickerV2, - SpotTradeV2, - SpotTransferRecordV2, - SpotVipFeeRateV2, - SpotWithdrawalRecordV2, - SubmitSpotBatchOrdersResponseV2, -} from './types/response/v2/spot.js'; -import BaseRestClient from './util/BaseRestClient.js'; -import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; -import { assertMarginType } from './util/type-guards.js'; -⋮---- -/** - * REST API client for all V2 endpoints - */ -export class RestClientV2 extends BaseRestClient -⋮---- -getClientType() -⋮---- -/** - * - * Custom SDK functions - * - */ -⋮---- -/** - * 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 -⋮---- -// Adjust server time by adding estimated one-way latency -⋮---- -// Calculate time difference between adjusted server time and local time -⋮---- -async fetchServerTime(): Promise -⋮---- -/** - * - * Bitget misc functions - * - */ -⋮---- -/** - * - * - * Common - * - * - */ -⋮---- -/** - * - * * Common | Notice - * - */ -⋮---- -getAnnouncements( - params?: GetAnnouncementsRequestV2, -): Promise> -⋮---- -/** - * - * * Common | Public - * - */ -⋮---- -getServerTime(): Promise< - APIResponse<{ - serverTime: string; - }> - > { - return this.get('/api/v2/public/time'); -⋮---- -getTradeRate(params: GetTradeRateRequestV2): Promise< - APIResponse<{ - makerFeeRate: string; - takerFeeRate: string; - }> - > { - return this.getPrivate('/api/v2/common/trade-rate', params); -⋮---- -/** - * - * * Common | Tax - * - */ -⋮---- -getSpotTransactionRecords( - params: GetSpotTransactionsRequestV2, -): Promise> -⋮---- -getFuturesTransactionRecords( - params: GetFuturesTransactionsRequestV2, -): Promise> -⋮---- -getMarginTransactionRecords( - params: GetMarginTransactionsRequestV2, -): Promise> -⋮---- -getP2PTransactionRecords( - params: GetP2PTransactionsRequestV2, -): Promise> -⋮---- -/** - * - * * Common | P2P - * - */ -⋮---- -getP2PMerchantList(params?: GetP2PMerchantsRequestV2): Promise< - APIResponse<{ - merchantList: P2PMerchantV2[]; - minMerchantId: string; - }> - > { - return this.getPrivate('/api/v2/p2p/merchantList', params); -⋮---- -getP2PMerchantInfo(): Promise> -⋮---- -getP2PMerchantOrders(params: GetMerchantP2POrdersRequestV2): Promise< - APIResponse<{ - orderList: P2PMerchantOrderV2[]; - minOrderId: string; - }> - > { - return this.getPrivate('/api/v2/p2p/orderList', params); -⋮---- -getP2PMerchantAdvertisementList( - params: GetMerchantAdvertisementsRequestV2, - ): Promise< - APIResponse<{ - advList: P2PMerchantAdvertismentV2[]; - minAdvId: string; - }> - > { - return this.getPrivate('/api/v2/p2p/advList', params); -⋮---- -/** - * - * * Common | Trading insights - * - */ -⋮---- -getSpotWhaleNetFlowData(params: { - symbol: string; -}): Promise> -⋮---- -getFuturesActiveTakerBuySellVolumeData(params: { - symbol: string; - period?: string; -}): Promise> -⋮---- -getFuturesActiveLongShortPositionData(params: { - symbol: string; - period?: string; -}): Promise> -⋮---- -getFuturesLongShortRatio(params: { - symbol: string; - period?: string; - coin?: string; -}): Promise> -⋮---- -getMarginLoanGrowthRate(params: { - symbol: string; - period?: string; - coin?: string; -}): Promise> -⋮---- -getIsolatedMarginBorrowingRatio(params: { - symbol: string; - period?: string; -}): Promise> -⋮---- -getFuturesActiveBuySellVolumeData(params: { - symbol: string; - period?: string; -}): Promise> -⋮---- -getSpotFundFlow(params: { - symbol: string; - period?: string; -}): Promise> -⋮---- -getTradeDataSupportSymbols(): Promise< - APIResponse<{ - spotList: string[]; - futureList: string[]; - }> - > { - return this.get('/api/v2/spot/market/support-symbols'); -⋮---- -getSpotFundNetFlowData(params: { symbol: string }): Promise< - APIResponse< - { - netFlow: string; - ts: string; - }[] - > - > { - return this.get('/api/v2/spot/market/fund-net-flow', params); -⋮---- -getFuturesActiveLongShortAccountData(params: { - symbol: string; - period?: string; -}): Promise> -⋮---- -/** - * - * * Common | Virtual Subaccount - * - */ -⋮---- -createVirtualSubaccount(params: { - subAccountList: string[]; -}): Promise> -⋮---- -modifyVirtualSubaccount(params: ModifyVirtualSubRequestV2): Promise< - APIResponse<{ - result: string; - }> - > { - return this.postPrivate('/api/v2/user/modify-virtual-subaccount', params); -⋮---- -batchCreateVirtualSubaccountAndAPIKey( - params: CreateVirtualSubRequestV2, -): Promise> -⋮---- -getVirtualSubaccounts(params?: { - limit?: string; - idLessThan?: string; - status?: 'normal' | 'freeze'; - }): Promise< - APIResponse<{ - endId: string; - subAccountList: VirtualSubAccountV2[]; - }> - > { - return this.getPrivate('/api/v2/user/virtual-subaccount-list', params); -⋮---- -createVirtualSubaccountAPIKey( - params: CreateVirtualSubApiKeyRequestV2, -): Promise> -⋮---- -modifyVirtualSubaccountAPIKey( - params: ModifyVirtualSubApiKeyRequestV2, -): Promise> -⋮---- -getVirtualSubaccountAPIKeys(params: { - subAccountUid: string; -}): Promise> -⋮---- -/** - * - * * Common | Assets - * - */ -getFundingAssets(params?: { - coin?: string; -}): Promise> -⋮---- -getBotAccount(params?: { - accountType?: string; -}): Promise> -⋮---- -/** Get assets overview */ -getBalances(): Promise< - APIResponse< - { - accountType: string; - usdtBalance: string; - }[] - > - > { - return this.getPrivate('/api/v2/account/all-account-balance'); -⋮---- -/** - * - * * Common | Convert - * - */ -⋮---- -getConvertCoins(): Promise> -⋮---- -getConvertQuotedPrice( - params: ConvertQuoteRequestV2, -): Promise> -⋮---- -convert( - params: ConvertRequestV2, -): Promise> -⋮---- -getConvertHistory(params: GetConvertHistoryRequestV2): Promise< - APIResponse<{ - dataList: ConvertRecordV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/convert/convert-record', params); -⋮---- -/** - * - * * Common | BGB Convert - * - */ -⋮---- -getConvertBGBCoins(): Promise< - APIResponse<{ - coinList: BGBConvertCoinV2[]; - }> - > { - return this.getPrivate('/api/v2/convert/bgb-convert-coin-list'); -⋮---- -convertBGB(params: { - coinList: string; -}): Promise> -⋮---- -getConvertBGBHistory( - params: GetConvertBGBHistoryRequestV2, -): Promise> -⋮---- -/** - * - * - * Spot - * - * - */ -⋮---- -/** - * - * * Spot | Market - * - */ -⋮---- -getSpotCoinInfo(params?: { - coin?: string; -}): Promise> -⋮---- -getSpotSymbolInfo(params?: { - symbol?: string; -}): Promise> -⋮---- -getSpotVIPFeeRate(): Promise> -⋮---- -getSpotTicker(params?: { - symbol?: string; -}): Promise> -⋮---- -getSpotMergeDepth(params: { - symbol: string; - precision?: string; - limit?: string; -}): Promise> -⋮---- -getSpotOrderBookDepth(params: { - symbol: string; - type?: string; - limit?: string; -}): Promise> -⋮---- -getSpotCandles( - params: SpotCandlesRequestV2, -): Promise> -⋮---- -getSpotHistoricCandles( - params: SpotHistoricCandlesRequestV2, -): Promise> -⋮---- -getSpotRecentTrades(params: { - symbol: string; - limit?: string; -}): Promise> -⋮---- -getSpotHistoricTrades( - params: SpotHistoricTradesRequestV2, -): Promise> -⋮---- -/** - * - * * Spot | Trade - * - */ -⋮---- -spotSubmitOrder(params: SpotOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/trade/place-order', params); -⋮---- -spotCancelandSubmitOrder( - params: SpotCancelandSubmitOrderRequestV2, -): Promise> -⋮---- -spotBatchCancelandSubmitOrder(params: { - orderList: SpotCancelandSubmitOrderRequestV2[]; -}): Promise> -⋮---- -spotCancelOrder(params: SpotCancelOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/trade/cancel-order', params); -⋮---- -spotBatchSubmitOrders( - params: SpotBatchOrderRequestV2, -): Promise> -⋮---- -spotBatchCancelOrders( - params: SpotBatchCancelOrderRequestV2, -): Promise> -⋮---- -spotCancelSymbolOrder(params: { symbol: string }): Promise< - APIResponse<{ - symbol: string; - }> - > { - return this.postPrivate('/api/v2/spot/trade/cancel-symbol-order', params); -⋮---- -getSpotOrder( - params?: GetSpotOrderInfoRequestV2, -): Promise> -⋮---- -getSpotOpenOrders( - params?: GetSpotOpenOrdersRequestV2, -): Promise> -⋮---- -getSpotHistoricOrders( - params?: GetSpotHistoryOrdersRequestV2, -): Promise> -⋮---- -getSpotFills( - params: GetSpotFillsRequestV2, -): Promise> -⋮---- -/** - * - * * Spot | Trigger Orders - * - */ -⋮---- -spotSubmitPlanOrder(params: SpotPlanOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/trade/place-plan-order', params); -⋮---- -spotModifyPlanOrder(params: SpotModifyPlanOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/trade/modify-plan-order', params); -⋮---- -spotCancelPlanOrder(params: { - clientOid?: string; - orderId?: string; - }): Promise< - APIResponse<{ - result: string; - }> - > { - return this.postPrivate('/api/v2/spot/trade/cancel-plan-order', params); -⋮---- -getSpotCurrentPlanOrders(params: GetSpotCurrentPlanOrdersRequestV2): Promise< - APIResponse<{ - nextFlag: boolean; - idLessThan: string; - orderList: SpotCurrentPlanOrderV2[]; - }> - > { - return this.getPrivate('/api/v2/spot/trade/current-plan-order', params); -⋮---- -getSpotPlanSubOrder(params: { - planOrderId: string; -}): Promise> -⋮---- -getSpotHistoricPlanOrders(params: GetSpotHistoryPlanOrdersRequestV2): Promise< - APIResponse<{ - nextFlag: boolean; - idLessThan: string; - orderList: SpotHistoryPlanOrderV2[]; - }> - > { - return this.getPrivate('/api/v2/spot/trade/history-plan-order', params); -⋮---- -spotCancelPlanOrders(params?: { - symbolList?: string[]; -}): Promise> -⋮---- -/** - * - * * Spot | Account - * - */ -⋮---- -getSpotAccount(): Promise> -⋮---- -getSpotAccountAssets(params?: { - coin?: string; - assetType?: string; -}): Promise> -⋮---- -getSpotSubAccountAssets(): Promise> -⋮---- -spotModifyDepositAccount(params: { - accountType: string; - coin: string; -}): Promise> -⋮---- -getSpotAccountBills( - params?: GetSpotAccountBillsRequestV2, -): Promise> -⋮---- -spotTransfer(params: SpotTransferRequestV2): Promise< - APIResponse<{ - transferId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/wallet/transfer', params); -⋮---- -getSpotTransferableCoins(params: { - fromType: SpotAccountTypeV2; - toType: SpotAccountTypeV2; -}): Promise> -⋮---- -spotSubTransfer(params: SpotSubAccountTransferRequestV2): Promise< - APIResponse<{ - transferId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/wallet/subaccount-transfer', params); -⋮---- -spotWithdraw(params: SpotWithdrawalRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/spot/wallet/withdrawal', params); -⋮---- -getSpotMainSubTransferRecord( - params: SpotMainSubTransferRecordRequestV2, -): Promise> -⋮---- -getSpotTransferHistory( - params: GetSpotTransferRecordRequestV2, -): Promise> -⋮---- -spotSwitchBGBDeduct(params: { - deduct: boolean; -}): Promise> -⋮---- -getSpotDepositAddress(params: { - coin: string; - chain?: string; - size: string; -}): Promise> -⋮---- -getSpotSubDepositAddress(params: { - subUid: string; - coin: string; - chain?: string; - size: string; -}): Promise> -⋮---- -getSpotBGBDeductInfo(): Promise< - APIResponse<{ - deduct: string; - }> - > { - return this.getPrivate('/api/v2/spot/account/deduct-info'); -⋮---- -spotCancelWithdrawal(params: { - orderId: string; -}): Promise> -⋮---- -getSubAccountDepositRecords( - params: GetSpotSubAccountDepositRecordRequestV2, -): Promise> -⋮---- -getSpotWithdrawalHistory( - params: GetSpotWithdrawalRecordRequestV2, -): Promise> -⋮---- -getSpotDepositHistory( - params: GetSpotDepositRecordRequestV2, -): Promise> -⋮---- -/** - * Upgrade Account - Upgrade to unified account mode - * No account type restrictions; both parent and sub-accounts are supported. - * This interface is only used for upgrading to the unified account mode. - * Please note that as the account upgrade process takes approximately 1 minute, - * the successful response you receive only indicates that the request has been received, - * and does not mean that the account has been successfully upgraded to a unified account. - * Please use the query upgrade status interface to confirm whether the account upgrade is successful. - */ -upgradeToUnifiedAccount(params?: { - subUid?: string; -}): Promise> -⋮---- -/** - * Get Upgrade Status - Get account upgrade status - * No account type restrictions; both parent and sub-accounts are supported. - */ -getUnifiedAccountSwitchStatus(params?: { subUid?: string }): Promise< - APIResponse<{ - status: 'processProcessing' | 'successSuccess' | 'failFailed'; - }> - > { - return this.getPrivate('/api/v2/spot/account/upgrade-status', params); -⋮---- -/** - * - * - * Futures - * - * - */ -⋮---- -/** - * - * * Futures | Market - * - */ -⋮---- -getFuturesVIPFeeRate(): Promise> -⋮---- -getFuturesInterestRateHistory(params: { coin: string }): Promise< - APIResponse<{ - coin: string; - historyInterestRateList: FuturesHistoryInterestRateV2[]; - }> - > { - return this.get('/api/v2/mix/market/union-interest-rate-history', params); -⋮---- -getFuturesInterestExchangeRate(): Promise< - APIResponse< - { - coin: string; - exchangeRateList: FuturesInterestExchangeRateV2[]; - }[] - > - > { - return this.get('/api/v2/mix/market/exchange-rate'); -⋮---- -getFuturesDiscountRate(): Promise> -⋮---- -getFuturesMergeDepth( - params: FuturesMergeDepthRequestV2, -): Promise> -⋮---- -getFuturesTicker(params: { - symbol: string; - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -getFuturesAllTickers(params: { - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -getFuturesRecentTrades( - params: FuturesRecentTradesRequestV2, -): Promise> -⋮---- -getFuturesHistoricTrades( - params: FuturesHistoricTradesRequestV2, -): Promise> -⋮---- -getFuturesCandles( - params: FuturesCandlesRequestV2, -): Promise> -⋮---- -getFuturesHistoricCandles( - params: FuturesCandlesRequestV2, -): Promise> -⋮---- -getFuturesHistoricIndexPriceCandles( - params: FuturesCandlesRequestV2, -): Promise> -⋮---- -getFuturesHistoricMarkPriceCandles( - params: FuturesCandlesRequestV2, -): Promise> -⋮---- -getFuturesOpenInterest(params: { - symbol: string; - productType: FuturesProductTypeV2; - }): Promise< - APIResponse<{ - openInterestList: FuturesOpenInterestV2[]; - ts: string; - }> - > { - return this.get('/api/v2/mix/market/open-interest', params); -⋮---- -getFuturesNextFundingTime(params: { - symbol: string; - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -getFuturesSymbolPrice(params: { - symbol: string; - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -getFuturesHistoricFundingRates(params: { - symbol: string; - productType: FuturesProductTypeV2; - pageSize?: string; - pageNo?: string; -}): Promise> -⋮---- -getFuturesCurrentFundingRate(params: { - symbol?: string; - productType: FuturesProductTypeV2; - }): Promise< - APIResponse< - { - symbol: string; - fundingRate: string; // '0.0001'; - fundingRateInterval: string; // hours, example: '1' | '2' | '4' | '8'; - nextUpdate: string; // timestamp in milliseconds - minFundingRate: string; - maxFundingRate: string; - }[] - > - > { - return this.get('/api/v2/mix/market/current-fund-rate', params); -⋮---- -fundingRate: string; // '0.0001'; -fundingRateInterval: string; // hours, example: '1' | '2' | '4' | '8'; -nextUpdate: string; // timestamp in milliseconds -⋮---- -getFuturesContractConfig(params: { - symbol?: string; - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -/** - * - * * Futures | Account - * - */ -⋮---- -getFuturesAccountAsset( - params: FuturesSingleAccountRequestV2, -): Promise> -⋮---- -getFuturesAccountAssets(params: { - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -getFuturesSubAccountAssets(params: { - productType: FuturesProductTypeV2; - }): Promise< - APIResponse< - { - userId: number; - assetList: FuturesSubAccountAssetV2[]; - }[] - > - > { - return this.getPrivate('/api/v2/mix/account/sub-account-assets', params); -⋮---- -getFuturesInterestHistory( - params: FuturesInterestHistoryRequestV2, -): Promise> -⋮---- -getFuturesOpenCount(params: FuturesOpenCountRequestV2): Promise< - APIResponse<{ - size: string; - }> - > { - return this.getPrivate('/api/v2/mix/account/open-count', params); -⋮---- -setFuturesPositionAutoMargin( - params: FuturesSetAutoMarginRequestV2, -): Promise> -⋮---- -setFuturesLeverage( - params: FuturesSetLeverageRequestV2, -): Promise> -⋮---- -setFuturesPositionMargin( - params: FuturesSetPositionMarginRequestV2, -): Promise> -⋮---- -setFuturesAssetMode(params: { - productType: 'USDT-FUTURES' | 'SUSDT-FUTURES'; - assetMode: 'single' | 'union'; -}): Promise> -⋮---- -setFuturesMarginMode( - params: FuturesSetMarginModeRequestV2, -): Promise> -⋮---- -setFuturesPositionMode(params: { - productType: FuturesProductTypeV2; - posMode: 'one_way_mode' | 'hedge_mode'; - }): Promise< - APIResponse<{ - posMode: 'one_way_mode' | 'hedge_mode'; - }> - > { - return this.postPrivate('/api/v2/mix/account/set-position-mode', params); -⋮---- -getFuturesAccountBills(params: FuturesAccountBillRequestV2): Promise< - APIResponse<{ - bills: FuturesAccountBillV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/account/bill', params); -⋮---- -/** - * Get Union Transfer Limits - * - * - Rate limit: 1 time/1s (uid) - * - Get union margin currency transfer limits - */ -getUnionTransferLimits( - params: GetUnionTransferLimitsRequestV2, -): Promise> -⋮---- -/** - * Get Union Config - * - * - Rate limit: 1 time/1s (uid) - * - Get API for union margin configuration parameters (Liability Initial Margin Rate, Liability Maintenance Margin Rate, Personal Liability Limit, Personal Liability Limit Ratio) - */ -getUnionConfig(): Promise> -⋮---- -/** - * Get Switch Union USDT - * - * - Rate limit: 1 time/1s (uid) - * - Get USDT quota for switching from union margin to single margin - */ -getSwitchUnionUsdt(): Promise> -⋮---- -/** - * Union Convert - * - * - Rate limit: 1 time/1s (uid) - * - Union margin exchange - */ -unionConvert( - params: UnionConvertRequestV2, -): Promise> -⋮---- -/** - * Get Max Openable Quantity - * - * - Rate limit: 20 req/sec/UID - * - Get Max Openable Quantity - */ -getFuturesMaxOpenableQuantity( - params: FuturesMaxOpenRequestV2, -): Promise> -⋮---- -/** - * Get Liquidation Price - * - * - Rate limit: 20 req/sec/UID - * - Get Liquidation Price - */ -getFuturesLiquidationPrice( - params: FuturesLiquidationPriceRequestV2, -): Promise> -⋮---- -/** - * Get Isolated Symbols - * - * - Rate limits: 10 time/1s (uid) - * - Retrieve trading pairs with isolated margin mode under the account. - */ -getFuturesIsolatedSymbols( - params: FuturesIsolatedSymbolsRequestV2, -): Promise> -⋮---- -/** - * - * * Futures | Position - * - */ -⋮---- -getFuturesPositionTier(params: { - productType: FuturesProductTypeV2; - symbol: string; -}): Promise> -⋮---- -getFuturesPosition(params: { - productType: FuturesProductTypeV2; - symbol: string; - marginCoin: string; -}): Promise> -⋮---- -getFuturesPositions(params: { - productType: FuturesProductTypeV2; - marginCoin?: string; -}): Promise> -⋮---- -getFuturesHistoricPositions( - params?: FuturesHistoricalPositionsRequestV2, - ): Promise< - APIResponse<{ - list: FuturesHistoryPositionV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/position/history-position', params); -⋮---- -/** - * - * * Futures | Trade - * - */ -⋮---- -futuresSubmitOrder(params: FuturesPlaceOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/place-order', params); -⋮---- -futuresSubmitReversal(params: FuturesReversalOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/click-backhand', params); -⋮---- -futuresBatchSubmitOrders( - params: FuturesBatchOrderRequestV2, -): Promise> -⋮---- -futuresModifyOrder(params: FuturesModifyOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/modify-order', params); -⋮---- -futuresCancelOrder(params: FuturesCancelOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/cancel-order', params); -⋮---- -futuresBatchCancelOrders( - params: FuturesBatchCancelOrderRequestV2, -): Promise> -⋮---- -futuresFlashClosePositions( - params: FuturesFlashClosePositionsRequestV2, -): Promise> -⋮---- -getFuturesOrder( - params: FuturesGetOrderRequestV2, -): Promise> -⋮---- -getFuturesFills(params: FuturesGetOrderFillsRequestV2): Promise< - APIResponse<{ - fillList: FuturesOrderFillV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/order/fills', params); -⋮---- -getFuturesHistoricOrderFills( - params: FuturesGetHistoricalFillsRequestV2, - ): Promise< - APIResponse<{ - fillList: FuturesOrderFillV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/order/fill-history', params); -⋮---- -getFuturesOpenOrders(params: FuturesGetOpenOrdersRequestV2): Promise< - APIResponse<{ - entrustedList: FuturesOpenOrderV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/order/orders-pending', params); -⋮---- -getFuturesHistoricOrders(params: FuturesGetHistoryOrdersRequestV2): Promise< - APIResponse<{ - entrustedList: FuturesHistoryOrderV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/order/orders-history', params); -⋮---- -futuresCancelAllOrders( - params: FuturesCancelAllOrdersRequestV2, -): Promise> -⋮---- -/** - * - * * Futures | Trigger Orders - * - */ -⋮---- -getFuturesTriggerSubOrder(params: { - planType: 'normal_plan' | 'track_plan'; - planOrderId: string; - productType: FuturesProductTypeV2; -}): Promise> -⋮---- -futuresSubmitTPSLOrder(params: FuturesTPSLOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/place-tpsl-order', params); -⋮---- -futuresSubmitPlanOrder(params: FuturesPlanOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/place-plan-order', params); -⋮---- -futuresModifyTPSLPOrder(params: FuturesModifyTPSLOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/modify-tpsl-order', params); -⋮---- -futuresModifyPlanOrder(params: FuturesModifyPlanOrderRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v2/mix/order/modify-plan-order', params); -⋮---- -getFuturesPlanOrders(params: FuturesGetPlanOrdersRequestV2): Promise< - APIResponse<{ - entrustedList: FuturesPendingPlanOrderV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/order/orders-plan-pending', params); -⋮---- -futuresCancelPlanOrder( - params: FuturesCancelPlanOrderRequestV2, -): Promise> -⋮---- -getFuturesHistoricPlanOrders( - params: FuturesGetHistoryPlanOrdersRequestV2, - ): Promise< - APIResponse<{ - entrustedList: FuturesHistoryPlanOrderV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/mix/order/orders-plan-history', params); -⋮---- -/** - * - * - * Broker - * - * - */ -⋮---- -/** - * - * * Broker | Subaccount - * - */ -⋮---- -modifySubaccountEmail(params: { - subUid: string; - subaccountEmail: string; -}): Promise> -⋮---- -getBrokerInfo(): Promise< - APIResponse<{ - subAccountSize: string; - maxSubAccountSize: string; - uTime: string; - }> - > { - return this.getPrivate('/api/v2/broker/account/info'); -⋮---- -createSubaccount(params: { - subaccountName: string; - label: string; -}): Promise> -⋮---- -getSubaccounts(params?: GetSubAccountsRequestV2): Promise< - APIResponse<{ - hasNextPage: boolean; - idLessThan: number; - subList: BrokerSubaccountV2[]; - }> - > { - return this.getPrivate('/api/v2/broker/account/subaccount-list', params); -⋮---- -modifySubaccount( - params: ModifySubRequestV2, -): Promise> -⋮---- -getSubaccountEmail(params: { - subUid: string; -}): Promise> -⋮---- -getSubaccountSpotAssets(params: { - subUid: string; - coin?: string; - assetType?: 'hold_only' | 'all'; - }): Promise< - APIResponse<{ - assetsList: BrokerSubaccountSpotAssetV2[]; - }> - > { - return this.getPrivate( - '/api/v2/broker/account/subaccount-spot-assets', - params, - ); -⋮---- -getSubaccountFuturesAssets(params: { - subUid: string; - productType: FuturesProductTypeV2; - }): Promise< - APIResponse<{ - assetsList: BrokerSubaccountFutureAssetV2[]; - }> - > { - return this.getPrivate( - '/api/v2/broker/account/subaccount-future-assets', - params, - ); -⋮---- -createSubaccountDepositAddress(params: { - subUid: string; - coin: string; - chain?: string; -}): Promise> -⋮---- -subaccountWithdrawal(params: SubWithdrawalRequestV2): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - return this.postPrivate( - '/api/v2/broker/account/subaccount-withdrawal', - params, - ); -⋮---- -subaccountSetAutoTransfer(params: { - subUid: string; - coin: string; - toAccountType: string; -}): Promise> -⋮---- -/** - * Sub Deposit Records - * - * - Only applicable for ND broker main-account to get ND sub-accounts deposit record - */ -subaccountDepositRecords( - params: SubDepositRecordsRequestV2, -): Promise> -⋮---- -/** - * Sub Withdrawal Records - * - * - Only applicable for ND broker main-account - */ -subaccountWithdrawalRecords(params: SubWithdrawalRecordsRequestV2): Promise< - APIResponse<{ - resultList: BrokerSubaccountWithdrawalV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/broker/subaccount-withdrawal', params); -⋮---- -/** - * - * Broker | Api Key - * - */ -⋮---- -createSubaccountApiKey( - params: CreateSubAccountApiKeyRequestV2, -): Promise> -⋮---- -getSubaccountApiKey(params: { - subUid: string; -}): Promise> -⋮---- -modifySubaccountApiKey( - params: ModifySubAccountApiKeyRequestV2, -): Promise> -⋮---- -/** - * Get All Sub-accounts Deposit and Withdrawal Records - * - * - Only applicable for ND broker main-account - * - Rate limit: 5 req/sec/UID - * - Able to get ND sub-accounts deposit and withdrawal records within 90 days - */ -getAllSubDepositWithdrawalRecords( - params?: GetAllSubDepositWithdrawalRequestV2, - ): Promise< - APIResponse<{ - list: AllSubDepositWithdrawalRecordV2[]; - endId: string; - }> - > { - return this.getPrivate('/api/v2/broker/all-sub-deposit-withdrawal', params); -⋮---- -/** - * Get Broker Subaccounts - * - * - Rate limit: 5 req/sec/UID - * - Please contact your BD or RM to apply for access permissions - */ -getBrokerSubaccounts( - params?: GetBrokerSubaccountsRequestV2, -): Promise> -⋮---- -/** - * Get Broker Subaccounts Commissions - * - * - Rate limit: 5 req/sec/UID - * - Please contact your BD or RM to apply for access permissions - */ -getBrokerCommissions( - params?: GetBrokerCommissionsRequestV2, -): Promise> -⋮---- -/** - * Get Broker Trade Volume - * - * - Rate limit: 5 req/sec/UID - * - Please contact your BD or RM to apply for access permissions - */ -getBrokerTradeVolume( - params?: GetBrokerTradeVolumeRequestV2, -): Promise> -⋮---- -/** - * Get Total Commission - * - * - Rate limit: 20 req/sec/UID - * - Data retention: 365 days - * - Historical data available from: 2025/6/1 - * - Data granularity: daily - * - Data update granularity: daily, previous day's data is updated on the current day - * - Time zone: UTC+8 - * - startTime and endTime should either both be set or both left unset - * - This API supports retrieving data within the past 365 days (data is available starting from 2025/6/1 at the earliest) - * - If startTime and endTime are not set in the request, the default returned information will be for yesterday (00:00-23:59 UTC+8) - * - Data update frequency: T+1 (UTC+8) - */ -getBrokerTotalCommission( - params?: GetBrokerTotalCommissionRequestV2, -): Promise> -⋮---- -/** - * Get Order Commission - * - * - Rate limit: 20 req/sec/UID - * - Data storage: 30 days - * - Historical data backtracking: 2025/9/1 - * - Data granularity: daily - * - Data update frequency: daily, previous day's data is updated on the current day - * - Time zone: UTC+8 - * - startTime and endTime should either both be set or both not set - * - The maximum time span supported for startTime and endTime is 30 days - * - This API supports retrieving data within the past 30 days - * - If startTime and endTime are not set in the request, the default return will be information for yesterday (00:00-23:59 UTC+8) - * - This API data is updated on a T+1 basis - * - Transaction details only show those marked with broker channel id - */ -getBrokerOrderCommission( - params?: GetBrokerOrderCommissionRequestV2, -): Promise> -⋮---- -/** - * Get Rebate Info - * - * - Rate limit: 20 req/sec/UID - * - Data retention: 30 days - * - Real-time data - */ -getBrokerRebateInfo( - params: GetBrokerRebateInfoRequestV2, -): Promise> -⋮---- -/** - * - * - * Margin - * - * - */ -⋮---- -/** - * - * * Margin | Common - * - */ -⋮---- -getMarginCurrencies(): Promise> -⋮---- -/** - * - * * Margin | Cross/Isolated | Order Record - * - */ -⋮---- -getMarginBorrowHistory( - marginType: MarginType, - params: GetBorrowHistoryRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginBorrowHistoryItemV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginRepayHistory( - marginType: MarginType, - params: GetRepayHistoryRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginRepaymentHistoryItemV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginInterestHistory( - marginType: MarginType, - params: GetInterestHistoryRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginInterestHistoryItemV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginLiquidationHistory( - marginType: MarginType, - params: GetLiquidationHistoryRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginLiquidationHistoryItemV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginFinancialHistory( - marginType: MarginType, - params: GetFinancialHistoryRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginFinancialHistoryItemV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -/** - * - * * Margin | Cross/Isolated | Account - * - */ -⋮---- -getMarginAccountAssets( - marginType: MarginType, - params?: { coin?: string }, -): Promise> -⋮---- -marginBorrow( - marginType: MarginType, - params: { - loanId: string; - symbol: string; - coin: string; - borrowAmount: string; - }, - ): Promise< - APIResponse<{ - loanId: string; - symbol: string; - coin: string; - borrowAmount: string; - }> - > { - assertMarginType(marginType); -⋮---- -marginRepay( - marginType: MarginType, - params: { - remainDebtAmount: string; - symbol: string; - repayId: string; - coin: string; - repayAmount: string; - }, - ): Promise< - APIResponse<{ - symbol: string; - coin: string; - repayId: string; - remainDebtAmount: string; - repayAmount: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginRiskRate(marginType: MarginType): Promise< - APIResponse< - { - symbol: string; - riskRateRatio: string; - }[] - > - > { - assertMarginType(marginType); -⋮---- -getMarginMaxBorrowable( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse - > { - assertMarginType(marginType); -⋮---- -getMarginMaxTransferable( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse< - CrossMaxTransferableResponseV2 | IsolatedMaxTransferableResponseV2 - > - > { - assertMarginType(marginType); -⋮---- -getMarginInterestRateAndMaxBorrowable( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse< - | IsolatedInterestRateAndLimitResponseV2[] - | CrossInterestRateAndLimitResponseV2[] - > - > { - assertMarginType(marginType); -⋮---- -getMarginTierConfiguration( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse< - CrossTierConfigurationResponseV2[] | IsolatedTierConfigurationResponseV2[] - > - > { - assertMarginType(marginType); -⋮---- -marginFlashRepay( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse<{ - repayId: string; - coin?: string; - symbol?: string; - result?: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginFlashRepayResult( - marginType: MarginType, - params: { idList: string }, - ): Promise< - APIResponse< - { - repayId: string; - status: string; - }[] - > - > { - assertMarginType(marginType); -⋮---- -/** - * - * * Margin | Cross/Isolated | Trade - * - */ -⋮---- -marginSubmitOrder( - marginType: MarginType, - params: MarginPlaceOrderRequestV2, - ): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - assertMarginType(marginType); -⋮---- -marginBatchSubmitOrders( - marginType: MarginType, - params: MarginBatchOrdersRequestV2, -): Promise> -⋮---- -marginCancelOrder( - marginType: MarginType, - params: { - symbol: string; - orderId?: string; - clientOid?: string; - }, - ): Promise< - APIResponse<{ - orderId: string; - clientOid: string; - }> - > { - assertMarginType(marginType); -⋮---- -marginBatchCancelOrders( - marginType: MarginType, - params: { - symbol: string; - orderIdList: string[]; - }, -): Promise> -⋮---- -getMarginOpenOrders( - marginType: MarginType, - params: GetMarginCurrentOrdersRequestV2, - ): Promise< - APIResponse<{ - orderList: MarginCurrentOrderV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginHistoricOrders( - marginType: MarginType, - params: GetHistoryOrdersRequestV2, - ): Promise< - APIResponse<{ - orderList: MarginHistoryOrderV2[]; - maxId: string; - minId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginHistoricOrderFills( - marginType: MarginType, - params: GetMarginOrderFillsRequestV2, - ): Promise< - APIResponse<{ - fills: MarginOrderFillV2[]; - minId: string; - maxId: string; - }> - > { - assertMarginType(marginType); -⋮---- -getMarginLiquidationOrders( - marginType: MarginType, - params: GetMarginLiquidationOrdersRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginLiquidationOrderV2[]; - idLessThan: string; - }> - > { - assertMarginType(marginType); -⋮---- -/** - * - * - * Copy Trading - * - * - */ -⋮---- -/** - * - * - * Copy Trading | Future copy trading | Trader Api - * - * - */ -⋮---- -getFuturesTraderCurrentOrder( - params: GetFuturesTraderCurrentOrdersRequestV2, -): Promise> -⋮---- -getFuturesTraderHistoryOrders( - params: GetFuturesTraderHistoryOrdersRequestV2, -): Promise> -⋮---- -modifyFuturesTraderOrderTPSL( - params: ModifyFuturesTraderOrderTPSLRequestV2, -): Promise> -⋮---- -getFuturesTraderOrder(): Promise< - APIResponse - > { - return this.getPrivate('/api/v2/copy/mix-trader/order-total-detail'); -⋮---- -getFuturesTraderProfitHistory(): Promise< - APIResponse - > { - return this.getPrivate('/api/v2/copy/mix-trader/profit-history-summarys'); -⋮---- -getFuturesTraderProfitShareHistory( - params: GetFuturesTraderProfitShareDetailRequestV2, -): Promise> -⋮---- -closeFuturesTraderOrder(params: { - trackingNo: string; - symbol: string; - productType: CopyTradingProductTypeV2; - }): Promise< - APIResponse< - { - trackingNo: string; - symbol: string; - productType: string; - }[] - > - > { - return this.postPrivate( - '/api/v2/copy/mix-trader/order-close-positions', - params, - ); -⋮---- -getFuturesTraderProfitShare(params?: { - coin?: string; - pageSize?: string; - pageNo?: string; - }): Promise< - APIResponse< - { - coin: string; - profit: string; - nickName: string; - }[] - > - > { - return this.getPrivate('/api/v2/copy/mix-trader/profit-details', params); -⋮---- -getFuturesTraderProfitShareGroup(params?: { - pageSize?: string; - pageNo?: string; - }): Promise< - APIResponse< - { - coin: string; - profit: string; - profitTime: string; - }[] - > - > { - return this.getPrivate( - '/api/v2/copy/mix-trader/profits-group-coin-date', - params, - ); -⋮---- -getFuturesTraderSymbolSettings(params: { - productType: CopyTradingProductTypeV2; -}): Promise> -⋮---- -updateFuturesTraderSymbolSettings(params: { - settingList: FuturesTraderSymbolSettingRequestV2[]; -}): Promise> -⋮---- -updateFuturesTraderGlobalSettings(params?: { - enable?: 'YES' | 'NO'; - showTotalEquity?: 'YES' | 'NO'; - showTpsl?: 'YES' | 'NO'; -}): Promise> -⋮---- -getFuturesTraderFollowers( - params?: GetFuturesTraderFollowersRequestV2, -): Promise> -⋮---- -removeFuturesTraderFollower(params: { - followerUid: string; -}): Promise> -⋮---- -/** - * - * - * Copy Trading | Future copy trading | Follower Api - * - * - */ -⋮---- -getFuturesFollowerCurrentOrders( - params: GetFollowerFuturesCurrentTrackingOrdersRequestV2, -): Promise> -⋮---- -getFuturesFollowerHistoryOrders( - params: GetFollowerFuturesHistoryTrackingOrdersRequestV2, -): Promise> -⋮---- -updateFuturesFollowerTPSL( - params: UpdateFuturesFollowerTPSLRequestV2, -): Promise> -⋮---- -updateFuturesFollowerSettings( - params: UpdateFuturesFollowerSettingsRequestV2, -): Promise> -⋮---- -getFuturesFollowerSettings(params: { - traderId: string; -}): Promise> -⋮---- -closeFuturesFollowerPositions( - params: CloseFuturesFollowerPositionsRequestV2, - ): Promise< - APIResponse<{ - orderIdList: string[]; - }> - > { - return this.postPrivate( - '/api/v2/copy/mix-follower/close-positions', - params, - ); -⋮---- -getFuturesFollowerTraders( - params: GetFuturesFollowerTradersRequestV2, -): Promise> -⋮---- -getFuturesFollowerFollowLimit(params: { - symbol: string; - productType: CopyTradingProductTypeV2; - }): Promise< - APIResponse< - { - maxFollowSize: string; - minFollowSize: string; - symbol: string; - }[] - > - > { - return this.getPrivate( - '/api/v2/copy/mix-follower/query-quantity-limit', - params, - ); -⋮---- -unfollowFuturesTrader(params: { - traderId: string; -}): Promise> -⋮---- -/** - * - * - * Copy Trading | Future copy trading | Broker api - * - * - */ -⋮---- -getBrokerTraders(params: object): Promise> -⋮---- -getBrokerTradersHistoricalOrders(params: object): Promise> -⋮---- -getBrokerTradersPendingOrders(params: object): Promise> -⋮---- -/** - * - * - * Copy Trading | Spot copy trading | Trader api - * - * - */ -⋮---- -getSpotTraderProfit(): Promise> -⋮---- -getSpotTraderHistoryProfit( - params: GetSpotTraderHistoryProfitRequestV2, -): Promise> -⋮---- -getSpotTraderUnrealizedProfit(params?: { - coin?: string; - pageNo?: string; - pageSize?: string; -}): Promise> -⋮---- -getSpotTraderOrder(): Promise> -⋮---- -modifySpotTraderOrderTPSL(params: { - trackingNo: string; - stopSurplusPrice?: string; - stopLossPrice?: string; -}): Promise> -⋮---- -getSpotTraderHistoryOrders( - params: GetSpotTraderHistoryOrdersRequestV2, -): Promise> -⋮---- -getSpotTraderCurrentOrders( - params: GetSpotTraderCurrentOrdersRequestV2, -): Promise> -⋮---- -sellSpotTrader(params: { - trackingNoList: string[]; - symbol: string; -}): Promise> -⋮---- -getSpotTraderSymbolSettings(params: { - symbolList: string[]; - settingType: 'add' | 'delete'; -}): Promise> -⋮---- -removeSpotTraderFollowers(params: { - followerUid: string; -}): Promise> -⋮---- -getSpotTraderConfiguration(): Promise> -⋮---- -getSpotTraderFollowers( - params: GetSpotTraderFollowersRequestV2, -): Promise> -⋮---- -/** - * - * - * Copy Trading | Spot copy trading | Follower api - * - * - */ -⋮---- -cancelSpotFollowerOrder(params: { - trackingNoList: string[]; -}): Promise> -⋮---- -updateSpotFollowerSettings(params: { - traderId: string; - autoCopy?: 'on' | 'off'; - mode?: 'basic' | 'advanced'; - settings: SpotFollowerCopyTradeSettingV2[]; -}): Promise> -⋮---- -updateSpotFollowerTPSL(params: { - trackingNo: string; - stopSurplusPrice?: string; - stopLossPrice?: string; -}): Promise> -⋮---- -getSpotFollowerTraders(params?: { - pageNo?: string; - pageSize?: string; - startTime?: string; - endTime?: string; -}): Promise> -⋮---- -getSpotFollowerCurrentTraderSymbols(params: { traderId: string }): Promise< - APIResponse<{ - currentTradingList: string[]; - }> - > { - return this.getPrivate( - '/api/v2/copy/spot-follower/query-trader-symbols', - params, - ); -⋮---- -getSpotFollowerSettings(params: { - traderId: string; -}): Promise> -⋮---- -getSpotFollowerHistoryOrders( - params: GetSpotFollowerHistoryOrdersRequestV2, -): Promise> -⋮---- -getSpotFollowerOpenOrders( - params: GetSpotFollowerOpenOrdersRequestV2, -): Promise> -⋮---- -sellSpotFollower(params: { - trackingNoList: string[]; - symbol: string; -}): Promise> -⋮---- -unfollowSpotTrader(params: { - traderId: string; -}): Promise> -⋮---- -/** - * - * - * Earn | Savings - * - * - */ -⋮---- -getEarnSavingsProducts(params?: { - coin?: string; - filter?: string; -}): Promise> -⋮---- -getEarnSavingsAccount(): Promise> -⋮---- -getEarnSavingsAssets( - params: GetEarnSavingsAssetsRequestV2, -): Promise> -⋮---- -getEarnSavingsRecords( - params: GetEarnSavingsRecordsRequestV2, -): Promise> -⋮---- -getEarnSavingsSubscription(params: { - productId: string; - periodType: string; -}): Promise> -⋮---- -earnSubscribeSavings(params: { - productId: string; - periodType: string; - amount: string; - }): Promise< - APIResponse<{ - orderId: string; - status: string; - }> - > { - return this.postPrivate('/api/v2/earn/savings/subscribe', params); -⋮---- -getEarnSavingsSubscriptionResult(params: { - productId: string; - periodType: string; - }): Promise< - APIResponse<{ - result: 'success' | 'fail'; - msg: string; - }> - > { - return this.getPrivate('/api/v2/earn/savings/subscribe-result', params); -⋮---- -earnRedeemSavings(params: RedeemSavingsRequestV2): Promise< - APIResponse<{ - orderId: string; - status: string; - }> - > { - return this.postPrivate('/api/v2/earn/savings/redeem', params); -⋮---- -getEarnSavingsRedemptionResult(params: { - orderId: string; - periodType: string; - }): Promise< - APIResponse<{ - result: 'success' | 'fail'; - msg: string; - }> - > { - return this.getPrivate('/api/v2/earn/savings/redeem-result', params); -⋮---- -/** - * - * - * Earn | Earn Account - * - * - */ -⋮---- -getEarnAccount(params?: { coin?: string }): Promise< - APIResponse< - { - coin: string; - amount: string; - }[] - > - > { - return this.getPrivate('/api/v2/earn/account/assets', params); -⋮---- -/** - * - * - * Earn | Shark Fin - * - * - */ -⋮---- -getSharkfinProducts(params: { - coin: string; - limit?: string; - idLessThan?: string; -}): Promise> -⋮---- -getSharkfinAccount(): Promise> -⋮---- -getSharkfinAssets( - params: GetSharkfinAssetsRequestV2, -): Promise> -⋮---- -getSharkfinRecords( - params: GetSharkfinRecordsRequestV2, -): Promise> -⋮---- -getSharkfinSubscription(params: { - productId: string; -}): Promise> -⋮---- -subscribeSharkfin(params: { productId: string; amount: string }): Promise< - APIResponse<{ - orderId: string; - status: string; - }> - > { - return this.postPrivate('/api/v2/earn/sharkfin/subscribe', params); -⋮---- -getSharkfinSubscriptionResult(params: { orderId: string }): Promise< - APIResponse<{ - result: 'success' | 'fail'; - msg: string; - }> - > { - return this.getPrivate('/api/v2/earn/sharkfin/subscribe-result', params); -⋮---- -/** - * - * - * Earn | Loan - * - * - */ -⋮---- -getLoanCurrencies(params?: { - coin?: string; -}): Promise> -⋮---- -getLoanEstInterestAndBorrowable( - params: GetLoanEstInterestAndBorrowableRequestV2, - ): Promise< - APIResponse<{ - hourInterest: string; - loanAmount: string; - }> - > { - return this.get('/api/v2/earn/loan/public/hour-interest', params); -⋮---- -borrowLoan(params: BorrowLoanRequestV2): Promise< - APIResponse<{ - orderId: string; - }> - > { - return this.postPrivate('/api/v2/earn/loan/borrow', params); -⋮---- -getOngoingLoanOrders(params?: { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; -}): Promise> -⋮---- -repayLoan( - params: RepayLoanRequestV2, -): Promise> -⋮---- -getRepayHistory( - params: GetLoanRepayHistoryRequestV2, -): Promise> -⋮---- -updateLoanPledgeRate(params: ModifyLoanPledgeRateRequestV2): Promise< - APIResponse<{ - loanCoin: string; - pledgeCoin: string; - afterPledgeRate: string; - }> - > { - return this.postPrivate('/api/v2/earn/loan/revise-pledge', params); -⋮---- -getLoanPledgeRateHistory( - params: GetLoanPledgeRateHistoryRequestV2, -): Promise> -⋮---- -getLoanHistory( - params: GetLoanHistoryRequestV2, -): Promise> -⋮---- -getLoanDebts(): Promise> -⋮---- -getLoanLiquidationRecords( - params: GetLiquidationRecordsRequestV2, -): Promise> - -================ -File: src/rest-client-v3.ts -================ -import { - CreateSubAccountApiKeyRequestV3, - CreateSubAccountRequestV3, - DeleteSubAccountApiKeyRequestV3, - FreezeSubAccountRequestV3, - GetConvertRecordsRequestV3, - GetDepositAddressRequestV3, - GetDepositRecordsRequestV3, - GetFeeRateRequestV3, - GetFinancialRecordsRequestV3, - GetFundingAssetsRequestV3, - GetMaxTransferableRequestV3, - GetOpenInterestLimitRequestV3, - GetSubAccountApiKeysRequestV3, - GetSubAccountListRequestV3, - GetSubDepositAddressRequestV3, - GetSubDepositRecordsRequestV3, - GetSubTransferRecordsRequestV3, - GetSubUnifiedAssetsRequestV3, - GetTaxRecordsRequestV3, - GetTransferableCoinsRequestV3, - GetWithdrawRecordsRequestV3, - RepayRequestV3, - SetDepositAccountRequestV3, - SetLeverageRequestV3, - SubAccountTransferRequestV3, - SwitchDeductRequestV3, - TransferRequestV3, - UpdateSubAccountApiKeyRequestV3, - WithdrawRequestV3, -} from './types/request/v3/account.js'; -import { - BindUidRequestV3, - GetEnsureCoinsRequestV3, - GetLoanOrderRequestV3, - GetLTVConvertRequestV3, - GetProductInfosRequestV3, - GetRepaidHistoryRequestV3, - GetSymbolsRequestV3, - GetTransferedRequestV3, -} from './types/request/v3/loan.js'; -import { - GetCandlesRequestV3, - GetContractsOiRequestV3, - GetCurrentFundingRateRequestV3, - GetHistoryCandlesRequestV3, - GetHistoryFundingRateRequestV3, - GetInstrumentsRequestV3, - GetMarginLoansRequestV3, - GetOpenInterestRequestV3, - GetOrderBookRequestV3, - GetPositionTierRequestV3, - GetPublicFillsRequestV3, - GetRiskReserveRequestV3, - GetTickersRequestV3, -} from './types/request/v3/public.js'; -import { - CancelStrategyOrderRequestV3, - GetHistoryStrategyOrdersRequestV3, - GetUnfilledStrategyOrdersRequestV3, - ModifyStrategyOrderRequestV3, - PlaceStrategyOrderRequestV3, -} from './types/request/v3/strategy.js'; -import { - BatchModifyOrderRequestV3, - CancelAllOrdersRequestV3, - CancelBatchOrdersRequestV3, - CancelOrderRequestV3, - CloseAllPositionsRequestV3, - CountdownCancelAllRequestV3, - GetCurrentPositionRequestV3, - GetFillsRequestV3, - GetHistoryOrdersRequestV3, - GetMaxOpenAvailableRequestV3, - GetOrderInfoRequestV3, - GetPositionHistoryRequestV3, - GetUnfilledOrdersRequestV3, - ModifyOrderRequestV3, - PlaceBatchOrdersRequestV3, - PlaceOrderRequestV3, -} from './types/request/v3/trade.js'; -import { APIResponse } from './types/response/v1/shared.js'; -import { - AccountAssetsV3, - AccountSettingsV3, - ConvertRecordV3, - CreateSubAccountApiKeyResponseV3, - CreateSubAccountResponseV3, - DepositAddressV3, - DepositRecordV3, - FinancialRecordV3, - FundingAssetV3, - MaxTransferableV3, - OpenInterestLimitV3, - PaymentCoinV3, - RepayableCoinV3, - RepayResponseV3, - SubAccountApiKeyV3, - SubAccountV3, - SubTransferRecordV3, - SubUnifiedAssetV3, - TaxRecordV3, - TransferResponseV3, - UpdateSubAccountApiKeyResponseV3, - WithdrawRecordV3, - WithdrawResponseV3, -} from './types/response/v3/account.js'; -import { - BindUidResponseV3, - CoinInfoV3, - LoanOrderV3, - LoanProductInfoV3, - LoanSymbolsV3, - LoanTransfersV3, - LTVConvertResponseV3, - RepaidHistoryItemV3, -} from './types/response/v3/loan.js'; -import { - CandlestickV3, - ContractOiV3, - CurrentFundingRateV3, - DiscountRateV3, - HistoryFundingRateV3, - InstrumentV3, - MarginLoanV3, - OpenInterestV3, - OrderBookV3, - PositionTierV3, - ProofOfReservesV3, - PublicFillV3, - RiskReserveV3, - TickerV3, -} from './types/response/v3/public.js'; -import { - ModifyStrategyOrderResponseV3, - PlaceStrategyOrderResponseV3, - StrategyOrderV3, -} from './types/response/v3/strategy.js'; -import { - BatchModifyOrderResponseV3, - CancelAllOrdersResponseV3, - CancelBatchOrdersResponseV3, - CancelOrderResponseV3, - CloseAllPositionsResponseV3, - CurrentPositionV3, - FillV3, - GetMaxOpenAvailableResponseV3, - HistoryOrderV3, - ModifyOrderResponseV3, - OrderInfoV3, - PlaceBatchOrdersResponseV3, - PlaceOrderResponseV3, - PositionAdlRankV3, - PositionHistoryV3, - UnfilledOrderV3, -} from './types/response/v3/trade.js'; -import BaseRestClient from './util/BaseRestClient.js'; -import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; -⋮---- -/** - * REST API client for all V3 endpoints - */ -export class RestClientV3 extends BaseRestClient -⋮---- -getClientType() -⋮---- -/** - * - * Custom SDK functions - * - */ -⋮---- -/** - * 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 -⋮---- -// Adjust server time by adding estimated one-way latency -⋮---- -// Calculate time difference between adjusted server time and local time -⋮---- -async fetchServerTime(): Promise -⋮---- -/** - * - * Public endpoints - * - */ -⋮---- -getServerTime(): Promise< - APIResponse<{ - serverTime: string; - }> - > { - return this.get('/api/v3/public/time'); -⋮---- -/** - * - * =====Market======= endpoints - * - */ -⋮---- -/** - * Get Instruments - */ -getInstruments( - params: GetInstrumentsRequestV3, -): Promise> -⋮---- -/** - * Get Tickers - */ -getTickers(params: GetTickersRequestV3): Promise> -⋮---- -/** - * Get OrderBook - */ -getOrderBook( - params: GetOrderBookRequestV3, -): Promise> -⋮---- -/** - * Get Recent Public Fills - */ -getFills( - params: GetPublicFillsRequestV3, -): Promise> -⋮---- -/** - * Get Proof Of Reserves - */ -getProofOfReserves(): Promise> -⋮---- -/** - * Get Open Interest - */ -getOpenInterest( - params: GetOpenInterestRequestV3, -): Promise> -⋮---- -/** - * Get Kline/Candlestick - * Maximum number of returned entries: 1,000 - */ -getCandles( - params: GetCandlesRequestV3, -): Promise> -⋮---- -/** - * Get Kline/Candlestick History - */ -getHistoryCandles( - params: GetHistoryCandlesRequestV3, -): Promise> -⋮---- -/** - * Get Current Funding Rate - */ -getCurrentFundingRate( - params: GetCurrentFundingRateRequestV3, -): Promise> -⋮---- -/** - * Get Funding Rate History - */ -getHistoryFundingRate( - params: GetHistoryFundingRateRequestV3, -): Promise> -⋮---- -/** - * Get Risk Reserve - */ -getRiskReserve( - params: GetRiskReserveRequestV3, -): Promise> -⋮---- -/** - * Get Discount Rate - */ -getDiscountRate(): Promise> -⋮---- -/** - * Get Margin Loan - */ -getMarginLoans( - params: GetMarginLoansRequestV3, -): Promise> -⋮---- -/** - * Get Position Tier - */ -getPositionTier( - params: GetPositionTierRequestV3, -): Promise> -⋮---- -/** - * Get Open Interest Limit - */ -getContractsOi( - params: GetContractsOiRequestV3, -): Promise> -⋮---- -/** - * - * =====Account======= endpoints - * - */ -⋮---- -/** - * Get Account Assets - */ -getBalances(): Promise> -⋮---- -/** - * Get Fund Account Assets - */ -getFundingAssets( - params?: GetFundingAssetsRequestV3, -): Promise> -⋮---- -/** - * Get Account Info - */ -getAccountSettings(): Promise> -⋮---- -/** - * Set Leverage - */ -setLeverage(params: SetLeverageRequestV3): Promise> -⋮---- -/** - * Set Holding Mode - */ -setHoldMode(params: { - holdMode: 'one_way_mode' | 'hedge_mode'; -}): Promise> -⋮---- -/** - * Get Financial Records - */ -getFinancialRecords(params: GetFinancialRecordsRequestV3): Promise< - APIResponse<{ - list: FinancialRecordV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/account/financial-records', params); -⋮---- -/** - * Get Repayable Coins - */ -getRepayableCoins(): Promise< - APIResponse<{ - repayableCoinList: RepayableCoinV3[]; - maxSelection: string; - }> - > { - return this.getPrivate('/api/v3/account/repayable-coins'); -⋮---- -/** - * Get Payment Coins - */ -getPaymentCoins(): Promise< - APIResponse<{ - paymentCoinList: PaymentCoinV3[]; - maxSelection: string; - }> - > { - return this.getPrivate('/api/v3/account/payment-coins'); -⋮---- -/** - * Repay - */ -submitRepay(params: RepayRequestV3): Promise> -⋮---- -/** - * Get Convert Records - */ -getConvertRecords(params: GetConvertRecordsRequestV3): Promise< - APIResponse<{ - list: ConvertRecordV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/account/convert-records', params); -⋮---- -/** - * Set up deposit account - Configure default recharge account for a certain symbol - * This configuration item remains valid for a long time. That is, once a user sets a default - * recharge account for a certain symbol, it will be retained permanently, and there is no need to reconfigure it. - * Permission: UTA mgt. (read & write) - */ -setDepositAccount( - params: SetDepositAccountRequestV3, -): Promise> -⋮---- -/** - * Switch Deduct - Set BGB deduction - */ -switchDeduct(params: SwitchDeductRequestV3): Promise> -⋮---- -/** - * Get Deduct Info - Get BGB deduction status - */ -getDeductInfo(): Promise< - APIResponse<{ - deduct: 'on' | 'off'; - }> - > { - return this.getPrivate('/api/v3/account/deduct-info'); -⋮---- -/** - * Get Trading Fee Rate - */ -getFeeRate(params: GetFeeRateRequestV3): Promise< - APIResponse<{ - makerFeeRate: string; - takerFeeRate: string; - }> - > { - return this.getPrivate('/api/v3/account/fee-rate', params); -⋮---- -/** - * Get Max Transferable - * - * - Rate limit: 3 req/sec/UID - * - Permission: UTA mgt. (read) - * - Get the maximum transferable amount for the unified account. - */ -getMaxTransferable( - params: GetMaxTransferableRequestV3, -): Promise> -⋮---- -/** - * Get Open Interest Limit - * - * - Rate limit: 5/sec/UID - * - Get open interest limit for a symbol - */ -getOpenInterestLimit( - params: GetOpenInterestLimitRequestV3, -): Promise> -⋮---- -/** - * Switch Account - Switch to classic account mode - * Only supports parent accounts. - * This endpoint is only used for switching to classic account mode. - * Please note that since the account switching process takes approximately 1 minute, - * the successful response you receive only indicates that the request has been received, - * and does not mean that the account has been successfully switched to the classic account. - * Please use the query switching status interface to confirm whether the account switching is successful. - */ -downgradeAccountToClassic(): Promise> -⋮---- -/** - * Get Switch Status - Get account switching status - * Only supports parent accounts. - */ -getUnifiedAccountSwitchStatus(): Promise< - APIResponse<{ - status: 'processProcessing' | 'successSuccess' | 'failFailed'; - }> - > { - return this.getPrivate('/api/v3/account/switch-status'); -⋮---- -/** - * Get Tax Records - * - * - Rate limit: 1/sec/UID - * - Data query range: 366 days - * - Please use the tax API Key to request Creation Portal - * - Get Unified Account Tax Records - */ -getTaxRecords( - params: GetTaxRecordsRequestV3, -): Promise> -⋮---- -/** - * - * =====SubAccount======= endpoints - * - */ -⋮---- -/** - * Create Sub-account - */ -createSubAccount( - params: CreateSubAccountRequestV3, -): Promise> -⋮---- -/** - * Freeze/Unfreeze Sub-account - */ -freezeSubAccount( - params: FreezeSubAccountRequestV3, -): Promise> -⋮---- -/** - * Get Sub-account Unified Account Assets - */ -getSubUnifiedAssets( - params?: GetSubUnifiedAssetsRequestV3, -): Promise> -⋮---- -/** - * Get Sub-account List - */ -getSubAccountList(params?: GetSubAccountListRequestV3): Promise< - APIResponse<{ - list: SubAccountV3[]; - hasNext: boolean; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/user/sub-list', params); -⋮---- -/** - * Create Sub-account API Key - */ -createSubAccountApiKey( - params: CreateSubAccountApiKeyRequestV3, -): Promise> -⋮---- -/** - * Modify Sub-account API Key - */ -updateSubAccountApiKey( - params: UpdateSubAccountApiKeyRequestV3, -): Promise> -⋮---- -/** - * Delete Sub-account API Key - */ -deleteSubAccountApiKey( - params: DeleteSubAccountApiKeyRequestV3, -): Promise> -⋮---- -/** - * Get Sub-account API Keys - */ -getSubAccountApiKeys(params: GetSubAccountApiKeysRequestV3): Promise< - APIResponse<{ - items: SubAccountApiKeyV3[]; - hasNext: boolean; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/user/sub-api-list', params); -⋮---- -/** - * - * =====Transfer======= endpoints - * - */ -⋮---- -/** - * Get Transferable Coins - */ -getTransferableCoins( - params: GetTransferableCoinsRequestV3, -): Promise> -⋮---- -/** - * Transfer - */ -submitTransfer( - params: TransferRequestV3, -): Promise> -⋮---- -/** - * Main-Sub Account Transfer - */ -subAccountTransfer(params: SubAccountTransferRequestV3): Promise< - APIResponse<{ - transferId: string; - clientOid: string; - }> - > { - return this.postPrivate('/api/v3/account/sub-transfer', params); -⋮---- -/** - * Get Main-Sub Transfer Records - */ -getSubTransferRecords(params?: GetSubTransferRecordsRequestV3): Promise< - APIResponse<{ - items: SubTransferRecordV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/account/sub-transfer-record', params); -⋮---- -/** - * - * =====Deposit======= endpoints - * - */ -⋮---- -/** - * Get Deposit Address - */ -getDepositAddress( - params: GetDepositAddressRequestV3, -): Promise> -⋮---- -/** - * Get Sub Deposit Address - */ -getSubDepositAddress( - params: GetSubDepositAddressRequestV3, -): Promise> -⋮---- -/** - * Get Deposit Records - */ -getDepositRecords( - params: GetDepositRecordsRequestV3, -): Promise> -⋮---- -/** - * Get Sub Deposit Records - */ -getSubDepositRecords( - params: GetSubDepositRecordsRequestV3, -): Promise> -⋮---- -/** - * - * =====Withdraw======= endpoints - * - */ -⋮---- -/** - * Withdraw - Includes on-chain withdrawals and internal transfers - */ -submitWithdraw( - params: WithdrawRequestV3, -): Promise> -⋮---- -/** - * Get Withdraw Records - */ -getWithdrawRecords( - params: GetWithdrawRecordsRequestV3, -): Promise> -⋮---- -/** - * - * =====Trade======= endpoints - * - */ -⋮---- -/** - * Place Order - */ -submitNewOrder( - params: PlaceOrderRequestV3, -): Promise> -⋮---- -/** - * Modify Order - */ -modifyOrder( - params: ModifyOrderRequestV3, -): Promise> -⋮---- -/** - * Cancel Order - */ -cancelOrder( - params: CancelOrderRequestV3, -): Promise> -⋮---- -/** - * Batch Order - */ -placeBatchOrders( - params: PlaceBatchOrdersRequestV3[], -): Promise> -⋮---- -/** - * Batch Modify Orders - */ -batchModifyOrders( - params: BatchModifyOrderRequestV3[], -): Promise> -⋮---- -/** - * Batch Cancel - */ -cancelBatchOrders( - params: CancelBatchOrdersRequestV3[], -): Promise> -⋮---- -/** - * Cancel All Orders - */ -cancelAllOrders( - params: CancelAllOrdersRequestV3, -): Promise> -⋮---- -/** - * Close All Positions - */ -closeAllPositions( - params: CloseAllPositionsRequestV3, -): Promise> -⋮---- -/** - * Get Order Details - */ -getOrderInfo( - params: GetOrderInfoRequestV3, -): Promise> -⋮---- -/** - * Get Open Orders - */ -getUnfilledOrders(params?: GetUnfilledOrdersRequestV3): Promise< - APIResponse<{ - list: UnfilledOrderV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/trade/unfilled-orders', params); -⋮---- -/** - * Get Order History - */ -getHistoryOrders(params: GetHistoryOrdersRequestV3): Promise< - APIResponse<{ - list: HistoryOrderV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/trade/history-orders', params); -⋮---- -/** - * Get Fill History - */ -getTradeFills(params?: GetFillsRequestV3): Promise< - APIResponse<{ - list: FillV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/trade/fills', params); -⋮---- -/** - * Get Position Info - */ -getCurrentPosition(params: GetCurrentPositionRequestV3): Promise< - APIResponse<{ - list: CurrentPositionV3[]; - }> - > { - return this.getPrivate('/api/v3/position/current-position', params); -⋮---- -/** - * Get Positions History - */ -getPositionHistory(params: GetPositionHistoryRequestV3): Promise< - APIResponse<{ - list: PositionHistoryV3[]; - cursor: string; - }> - > { - return this.getPrivate('/api/v3/position/history-position', params); -⋮---- -/** - * Get Max Open Available - */ -getMaxOpenAvailable( - params: GetMaxOpenAvailableRequestV3, -): Promise> -⋮---- -/** - * Get Position ADL Rank - Get position auto-deleveraging ranking - */ -getPositionAdlRank(): Promise> -⋮---- -/** - * CountDown Cancel All - */ -countdownCancelAll( - params: CountdownCancelAllRequestV3, -): Promise> -⋮---- -/** - * - * =====Inst Loan======= endpoints - * - */ -⋮---- -/** - * Get Transferred Quantity - */ -getLoanTransfered( - params: GetTransferedRequestV3, -): Promise> -⋮---- -/** - * Get Trade Symbols - */ -getLoanSymbols( - params: GetSymbolsRequestV3, -): Promise> -⋮---- -/** - * Get Risk Unit - */ -getLoanRiskUnit(): Promise< - APIResponse<{ - riskUnitId: string[]; - }> - > { - return this.getPrivate('/api/v3/ins-loan/risk-unit'); -⋮---- -/** - * Get Repayment Orders - */ -getLoanRepaidHistory( - params?: GetRepaidHistoryRequestV3, -): Promise> -⋮---- -/** - * Get Product Info - */ -getLoanProductInfo( - params: GetProductInfosRequestV3, -): Promise> -⋮---- -/** - * Get Loan Orders - */ -getLoanOrder( - params?: GetLoanOrderRequestV3, -): Promise> -⋮---- -/** - * Get LTV - */ -getLoanLTVConvert( - params?: GetLTVConvertRequestV3, -): Promise> -⋮---- -/** - * Get Margin Coin Info - */ -getLoanMarginCoinInfo(params: GetEnsureCoinsRequestV3): Promise< - APIResponse<{ - productId: string; - coinInfo: CoinInfoV3[]; - }> - > { - return this.getPrivate('/api/v3/ins-loan/ensure-coins-convert', params); -⋮---- -/** - * Bind/Unbind UID to Risk Unit - */ -bindLoanUid( - params: BindUidRequestV3, -): Promise> -⋮---- -/** - * - * =====Strategy======= endpoints - * - */ -⋮---- -/** - * Place Strategy Order - */ -submitStrategyOrder( - params: PlaceStrategyOrderRequestV3, -): Promise> -⋮---- -/** - * Modify Strategy Order - */ -modifyStrategyOrder( - params: ModifyStrategyOrderRequestV3, -): Promise> -⋮---- -/** - * Cancel Strategy Order - */ -cancelStrategyOrder( - params: CancelStrategyOrderRequestV3, -): Promise> -⋮---- -/** - * Get Unfilled Strategy Orders - */ -getUnfilledStrategyOrders( - params: GetUnfilledStrategyOrdersRequestV3, -): Promise> -⋮---- -/** - * Get Strategy Order History - */ -getHistoryStrategyOrders(params: GetHistoryStrategyOrdersRequestV3): Promise< - APIResponse<{ - list: StrategyOrderV3[]; - cursor?: string; - }> - > { - return this.getPrivate('/api/v3/trade/history-strategy-orders', params); +- Issues? Check the [issues tab](https://github.com/tiagosiebler/bitget-api/issues). +- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. +- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) + + + +## Related Projects + +Check out our JavaScript/TypeScript/Node.js SDKs & Projects: + +- Visit our website: [https://Siebly.io](https://siebly.io/?ref=gh) +- Try our REST API & WebSocket SDKs published on npmjs: + - [Bybit Node.js SDK: bybit-api](https://www.npmjs.com/package/bybit-api) + - [Kraken Node.js SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) + - [OKX Node.js SDK: okx-api](https://www.npmjs.com/package/okx-api) + - [Binance Node.js SDK: binance](https://www.npmjs.com/package/binance) + - [Gate (gate.com) Node.js SDK: gateio-api](https://www.npmjs.com/package/gateio-api) + - [Bitget Node.js SDK: bitget-api](https://www.npmjs.com/package/bitget-api) + - [Kucoin Node.js SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) + - [Coinbase Node.js SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) + - [Bitmart Node.js SDK: bitmart-api](https://www.npmjs.com/package/bitmart-api) +- Try my misc utilities: + - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) + - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) +- Check out my examples: + - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) + + +## Documentation + +Most methods accept JS objects. These can be populated using parameters specified by Bitget's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class). + +- Bitget API Documentation + - [V3/UTA API Documentation](https://www.bitget.com/api-doc/uta/intro) (Latest - Unified Trading Account) + - [V2 API Documentation](https://www.bitget.com/api-doc/common/intro) +- [REST Endpoint Function List](./docs/endpointFunctionList.md) +- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/bitget-api) + +## Structure + +This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using `npm run build`, which is also the version published to [npm](https://www.npmjs.com/package/bitget-api). + +The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended). + +- [src](./src) - the whole connector written in TypeScript +- [lib](./lib) - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release. +- [dist](./dist) - the webpack bundle of the project for use in browser environments (see guidance on webpack below). +- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! + +--- + +# Usage + +Create API credentials at Bitget: + +- [Livenet API Management](https://www.bitget.com/en/support/articles/360011132814-How-to-create-API) +- [Demo Trading Environment](https://www.bitget.com/en/demo-trading) + +## REST API Clients + +Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups: +| Class | Description | +|:------------------------------------: |:---------------------------------------------------------------------------------------------: | +| [RestClientV3](src/rest-client-v3.ts) | [V3/UTA REST APIs for Bitget's Unified Trading Account](https://www.bitget.com/api-doc/uta/intro) | +| [WebsocketClientV3](src/websocket-client-v3.ts) | Universal WS client for Bitget's V3/UTA WebSockets | +| [WebsocketAPIClient](src/websocket-api-client.ts) | Websocket API Client, for RESTlike order placement via Bitget's V3/UTA WebSocket API | +| [RestClientV2](src/rest-client-v2.ts) | [V2 REST APIs](https://www.bitget.com/api-doc/common/intro) | +| [WebsocketClientV2](src/websocket-client-v2.ts) | Universal WS client for all Bitget's V2 WebSockets | + +Examples for using each client can be found in: + +- the [examples](./examples) folder. +- the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository. + +If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler). + +### Getting Started + +All REST APIs are integrated in each dedicated Rest Client class. See the above table for which REST client to use. If you've upgraded to the Unified Trading Account, you should use the V3 REST APIs and WebSockets. + +There are several REST API modules as there are some differences in each API group: + +1. `RestClientV3` for the latest V3/UTA APIs (Unified Trading Account) - recommended for new projects. +2. `RestClientV2` for V2 APIs - use if you haven't upgraded to UTA yet. + +More Node.js & JavaScript examples for Bitget's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. + +#### V3 REST APIs + +These are only available if you have upgraded to the Unified Trading Account. If not, use the V2 APIs instead. + +```javascript +import { RestClientV3 } from 'bitget-api'; +// or if you prefer require: +// const { RestClientV3 } = require('bitget-api'); + +// note the single quotes, preventing special characters such as $ from being incorrectly passed +const client = new RestClientV3({ + apiKey: process.env.API_KEY_COM || 'insert_api_key_here', + apiSecret: process.env.API_SECRET_COM || 'insert_api_secret_here', + apiPass: process.env.API_PASS_COM || 'insert_api_pass_here', +}); -================ -File: README.md -================ -# Node.js & Typescript Bitget API SDK +(async () => { + try { + console.log(await client.getBalances()); -[![Build & Test](https://github.com/tiagosiebler/bitget-api/actions/workflows/e2etests.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/bitget-api/actions/workflows/e2etests.yml) -[![npm version](https://img.shields.io/npm/v/bitget-api)][1] -[![npm size](https://img.shields.io/bundlephobia/min/bitget-api/latest)][1] -[![npm downloads](https://img.shields.io/npm/dt/bitget-api)][1] -[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/bitget-api)][1] -[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/bitget-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/bitget-api) -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) + const newOrder = await client.submitNewOrder({ + category: 'USDT-FUTURES', + orderType: 'market', + side: 'buy', + qty: '0.001', + symbol: 'BTCUSDT', + }); -

- - - - SDK Logo - - -

+ console.log('Order submitted: ', newOrder); + } catch (e) { + console.error('request failed: ', e); + } +})(); +``` -[1]: https://www.npmjs.com/package/bitget-api +#### V2 REST APIs -Updated & performant JavaScript & Node.js SDK for the Bitget V2 REST APIs and WebSockets: +Not sure which function to call or which parameters to use? Click the class name in the table above to look at all the function names (they are in the same order as the official API docs), and check the API docs for a list of endpoints/parameters/responses. -- Professional, robust & performant Bitget SDK with extensive production use in live trading environments. -- Complete integration with all Bitget APIs. - - [x] Supports V1 REST APIs & WebSockets (legacy) - - [x] Supports V2 REST APIs & WebSockets - - [x] Supports V3/UTA REST APIs & WebSockets (latest) - - [x] Supports order placement via V3 WebSocket API -- Complete TypeScript support (with type declarations for all API requests & responses). - - Strongly typed requests and responses. - - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. -- Actively maintained with a modern, promise-driven interface. -- Over 100 integration tests making real API calls & WebSocket connections, validating any changes before they reach npm. -- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. - - Event driven messaging. - - Smart WebSocket persistence with automatic reconnection handling. - - Emit `reconnected` event when dropped connection is restored. - - Optional beautification of WebSocket events for improved readability. -- Officially listed Node.js SDK in [Bitget API docs](https://bitgetlimited.github.io/apidoc/en/spot/#sdk-code-example). -- Browser support (via webpack bundle - see "Browser Usage" below). -- Support all authentication methods supported by Bitget: - - [x] HMAC - - [x] RSA -- Heavy automated end-to-end testing with real API calls. - - End-to-end testing before any release. - - Real API calls in e2e tests. -- Proxy support via axios integration. -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). +If you found the method you're looking for in the API docs, you can also search for the endpoint in the [RestClientV2](src/rest-client-v2.ts) class. This class has all V2 endpoints available. -## Table of Contents +```javascript +import { RestClientV2 } from 'bitget-api'; +// or if you prefer require: +// const { RestClientV2 } = require('bitget-api'); -- [Installation](#installation) -- [Examples](#examples) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation](#documentation) -- [Structure](#structure) -- [Usage](#usage) - - [REST API Clients](#rest-api-clients) - - [V3 REST APIs (Unified Trading Account)](#v3-rest-apis) - - [V2 REST APIs](#v2-rest-apis) - - [WebSockets](#websockets) - - [V3 Unified Trading Account](#v3-unified-trading-account) - - [Sending Orders via WebSockets](#sending-orders-via-websockets) - - [Receiving Realtime Data](#receiving-realtime-data) - - [V2 WebSockets](#v2-websockets) - - [Customise Logging](#logging) - - [Custom Logger](#customise-logging) - - [Debug HTTP Requests](#debug-http-requests) - - [Frontend Usage](#browser-usage) - - [Import](#import) - - [Webpack](#webpack) -- [LLMs & AI](#use-with-llms--ai) -- [Used By](#used-by) -- [Contributions & Thanks](#contributions--thanks) +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; +const API_PASS = 'zzz'; -## Installation +const client = new RestClientV2({ + apiKey: API_KEY, + apiSecret: API_SECRET, + apiPass: API_PASS, +}); -`npm install --save bitget-api` +// For public-only API calls, simply don't provide a key & secret or set them to undefined +// const client = new RestClientV2(); -## Examples +client + .getSpotAccount() + .then((result) => { + console.log('getSpotAccount result: ', result); + }) + .catch((err) => { + console.error('getSpotAccount error: ', err); + }); -Refer to the [examples](./examples) folder for implementation demos. +client + .getSpotCandles({ + symbol: 'BTCUSDT', + granularity: '1min', + limit: '1000', + }) + .then((result) => { + console.log('getCandles result: ', result); + }) + .catch((err) => { + console.error('getCandles error: ', err); + }); +``` -## Issues & Discussion +## WebSockets -- Issues? Check the [issues tab](https://github.com/tiagosiebler/bitget-api/issues). -- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. -- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) +All WebSocket functionality is supported via the WebsocketClient. Since there are currently 2 generations of Bitget's API, there are 2 WebsocketClient classes in this Node.js, JavaScript & TypeScript SDK for Bitget. - +Use the following guidance to decide which one to use: -## Related projects +- **Unified Trading Account / V3** (latest generation): + - For receiving data, use the [WebsocketClientV3](./src/websocket-client-v3.ts). + - For sending orders via WebSockets, use the [WebsocketAPIClient](./src/websocket-api-client.ts). +- **V2** (not upgraded to Unified Trading Account yet) + - Use the [WebsocketClientV2](./src/websocket-client-v2.ts). -Check out my related JavaScript/TypeScript/Node.js projects: +All WebSocket clients support: -- Try my REST API & WebSocket SDKs: - - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) -- Try my misc utilities: - - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) -- Check out my examples: - - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) - +- Event driven messaging +- Smart WebSocket persistence with automatic reconnection +- Heartbeat mechanisms to detect disconnections +- Automatic resubscription after reconnection +- Error handling and connection monitoring +- Optional data beautification -## Documentation +Higher level examples below, while more thorough examples can be found in the examples folder on GitHub. -Most methods accept JS objects. These can be populated using parameters specified by Bitget's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class). +##### V3 Unified Trading Account -- Bitget API Documentation - - [V3/UTA API Documentation](https://www.bitget.com/api-doc/uta/intro) (Latest - Unified Trading Account) - - [V2 API Documentation](https://www.bitget.com/api-doc/common/intro) - - [Legacy V1 API Documentation](https://bitgetlimited.github.io/apidoc/en/spot/#introduction) (deprecated) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) -- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/bitget-api) +###### Sending orders via WebSockets + +The V3 / Unified Trading Account APIs introduce order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API. + +There are two approaches to placing orders via the Bitget WebSocket APIs. The recommended route is to use the dedicated WebsocketAPIClient class, included with this SDK. + +This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types. + +A simple example is below, but for a more thorough example, check the example here: [./examples/V3/ws-api-client-trade.ts](./examples/V3/ws-api-client-trade.ts) + +```typescript +import { WebsocketAPIClient } from 'bitget-api'; +// or if you prefer require: +// const { WebsocketAPIClient } = require("bitget-api"); + +// Make an instance of the WS API Client class with your API keys +const wsClient = new WebsocketAPIClient({ + apiKey: API_KEY, + apiSecret: API_SECRET, + apiPass: API_PASS, + + // Whether to use the demo trading wss connection + // demoTrading: true, +}); + +async function start() { + // Start using it like a REST API. All actions are sent via a persisted WebSocket connection. + + /** + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ + try { + const res = await wsClient.submitNewOrder('spot', { + orderType: 'limit', + price: '100', + qty: '0.1', + side: 'buy', + symbol: 'BTCUSDT', + timeInForce: 'gtc', + }); + + console.log(new Date(), 'WS API "submitNewOrder()" result: ', res); + } catch (e) { + console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e); + } +} + +start().catch((e) => console.error('Exception in example: '.e)); +``` + +###### Receiving realtime data + +Use the WebsocketClientV3 to receive data via the V3 WebSockets + +```typescript +import { WebsocketClientV3 } from "bitget-api"; +// or if you prefer require: +// const { WebsocketClientV3 } = require("bitget-api"); + +const API_KEY = "yourAPIKeyHere"; +const API_SECRET = "yourAPISecretHere; +const API_PASS = "yourAPIPassHere"; + +const wsClient = new WebsocketClientV3( + { + // Only necessary if you plan on using private/account websocket topics + apiKey: API_KEY, + apiSecret: API_SECRET, + apiPass: API_PASS, + } +); + +// Connect event handlers to process incoming events +wsClient.on('update', (data) => { + console.log('WS raw message received ', data); + // console.log('WS raw message received ', JSON.stringify(data, null, 2)); +}); + +wsClient.on('open', (data) => { + console.log('WS connection opened:', data.wsKey); +}); +wsClient.on('response', (data) => { + console.log('WS response: ', JSON.stringify(data, null, 2)); +}); +wsClient.on('reconnect', ({ wsKey }) => { + console.log('WS automatically reconnecting.... ', wsKey); +}); +wsClient.on('reconnected', (data) => { + console.log('WS reconnected ', data?.wsKey); +}); +wsClient.on('exception', (data) => { + console.log('WS error', data); +}); -## Structure +/** + * Subscribe to topics as you wish + */ -This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using `npm run build`, which is also the version published to [npm](https://www.npmjs.com/package/bitget-api). +// You can subscribe to one topic at a time +wsClient.subscribe( + { + topic: 'account', + payload: { + instType: 'UTA', // Note: all account events go on the UTA instType + }, + }, + WS_KEY_MAP.v3Private, // This parameter points to private or public +); -The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended). +// Note: all account events go on the UTA instType +const ACCOUNT_INST_TYPE = 'UTA'; +const ACCOUNT_WS_KEY = WS_KEY_MAP.v3Private; -- [src](./src) - the whole connector written in TypeScript -- [lib](./lib) - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release. -- [dist](./dist) - the webpack bundle of the project for use in browser environments (see guidance on webpack below). -- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! +// Or multiple at once: +wsClient.subscribe( + [ + { + topic: 'account', + payload: { + instType: ACCOUNT_INST_TYPE, + }, + }, + { + topic: 'position', + payload: { + instType: ACCOUNT_INST_TYPE, + }, + }, + { + topic: 'fill', + payload: { + instType: ACCOUNT_INST_TYPE, + }, + }, + { + topic: 'order', + payload: { + instType: ACCOUNT_INST_TYPE, + }, + }, + ], + ACCOUNT_WS_KEY, +); ---- +// Example public events +wsClient.subscribe( + [ + { + topic: 'ticker', + payload: { + instType: 'spot', + symbol: 'BTCUSDT', + }, + }, + { + topic: 'ticker', + payload: { + instType: 'spot', + symbol: 'ETHUSDT', + }, + }, + { + topic: 'ticker', + payload: { + instType: 'spot', + symbol: 'XRPUSDT', + }, + }, + { + topic: 'ticker', + payload: { + instType: 'usdt-futures', + symbol: 'BTCUSDT', + }, + }, + { + topic: 'ticker', + payload: { + instType: 'usdt-futures', + symbol: 'BTCUSDT', + }, + }, + ], + WS_KEY_MAP.v3Public, +); +``` -# Usage +For more examples, including how to use websockets with Bitget, check the [examples](./examples/) and [test](./test/) folders. -Create API credentials at Bitget: +### V2 WebSockets -- [Livenet API Management](https://www.bitget.com/en/support/articles/360011132814-How-to-create-API) -- [Demo Trading Environment](https://www.bitget.com/en/demo-trading) +If you haven't upgraded to the Unified Trading Account, use the V2 WebSocket client: -## REST API Clients +```javascript +import { WebsocketClientV2 } from 'bitget-api'; +// or if you prefer require: +// const { WebsocketClientV2 } = require('bitget-api'); -Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups: -| Class | Description | -|:------------------------------------: |:---------------------------------------------------------------------------------------------: | -| [RestClientV3](src/rest-client-v3.ts) | [V3/UTA REST APIs for Bitget's Unified Trading Account](https://www.bitget.com/api-doc/uta/intro) | -| [WebsocketClientV3](src/websocket-client-v3.ts) | Universal WS client for Bitget's V3/UTA WebSockets | -| [WebsocketAPIClient](src/websocket-api-client.ts) | Websocket API Client, for RESTlike order placement via Bitget's V3/UTA WebSocket API | -| [RestClientV2](src/rest-client-v2.ts) | [V2 REST APIs](https://www.bitget.com/api-doc/common/intro) | -| [WebsocketClientV2](src/websocket-client-v2.ts) | Universal WS client for all Bitget's V2 WebSockets | -| [~~SpotClient~~ (deprecated, use RestClientV2)](src/spot-client.ts) | [~~Spot APIs~~](https://bitgetlimited.github.io/apidoc/en/spot/#introduction) | -| [~~FuturesClient~~ (deprecated, use RestClientV2)](src/futures-client.ts) | [~~Futures APIs~~](https://bitgetlimited.github.io/apidoc/en/mix/#introduction) | -| [~~BrokerClient~~ (deprecated, use RestClientV2)](src/broker-client.ts) | [~~Broker APIs~~](https://bitgetlimited.github.io/apidoc/en/broker/#introduction) | -| [~~WebsocketClient~~ (deprecated, use WebsocketClientV2)](src/websocket-client.ts) | ~~Universal client for all Bitget's V1 WebSockets~~ | +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; +const API_PASS = 'zzz'; -Examples for using each client can be found in: +const wsClient = new WebsocketClientV2({ + apiKey: API_KEY, + apiSecret: API_SECRET, + apiPass: API_PASS, + // Optional: connect to demo trading environment + // demoTrading: true, +}); -- the [examples](./examples) folder. -- the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository. +// Handle incoming messages +wsClient.on('update', (data) => { + console.log('WS update received: ', data); +}); -If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler). +wsClient.on('open', (data) => { + console.log('WS connection opened: ', data.wsKey); +}); -### Getting Started +wsClient.on('reconnected', (data) => { + console.log('WS reconnected: ', data?.wsKey); +}); -All REST APIs are integrated in each dedicated Rest Client class. See the above table for which REST client to use. If you've upgraded to the Unified Trading Account, you should use the V3 REST APIs and WebSockets. +wsClient.on('exception', (data) => { + console.log('WS error: ', data); +}); -There are several REST API modules as there are some differences in each API group: +// Subscribe to public data streams +wsClient.subscribeTopic('SPOT', 'ticker', symbol); -1. `RestClientV3` for the latest V3/UTA APIs (Unified Trading Account) - recommended for new projects. -2. `RestClientV2` for V2 APIs - use if you haven't upgraded to UTA yet. -3. Legacy V1 clients (`SpotClient`, `FuturesClient`, `BrokerClient`) - deprecated, migrate to V2 or V3. +// Subscribe to private data streams (requires authentication) +wsClient.subscribeTopic('SPOT', 'account'); +``` -More Node.js & JavaScript examples for Bitget's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. +--- -#### V3 REST APIs +## Logging -These are only available if you have upgraded to the Unified Trading Account. If not, use the V2 APIs instead. +### Customise logging + +Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. ```javascript -import { RestClientV3 } from 'bitget-api'; +import { WebsocketClientV2, DefaultLogger } from 'bitget-api'; // or if you prefer require: -// const { RestClientV3 } = require('bitget-api'); - -// note the single quotes, preventing special characters such as $ from being incorrectly passed -const client = new RestClientV3({ - apiKey: process.env.API_KEY_COM || 'insert_api_key_here', - apiSecret: process.env.API_SECRET_COM || 'insert_api_secret_here', - apiPass: process.env.API_PASS_COM || 'insert_api_pass_here', -}); - -(async () => { - try { - console.log(await client.getBalances()); +// const { WebsocketClientV2, DefaultLogger } = require('bitget-api'); - const newOrder = await client.submitNewOrder({ - category: 'USDT-FUTURES', - orderType: 'market', - side: 'buy', - qty: '0.001', - symbol: 'BTCUSDT', - }); +// Disable all logging on the trace level (less console logs) +const customLogger = { + ...DefaultLogger, + trace: () => {}, +}; - console.log('Order submitted: ', newOrder); - } catch (e) { - console.error('request failed: ', e); - } -})(); +const ws = new WebsocketClientV2( + { + apiKey: 'API_KEY', + apiSecret: 'API_SECRET', + apiPass: 'API_PASS', + }, + customLogger, +); ``` -#### V2 REST APIs +### Debug HTTP requests -Not sure which function to call or which parameters to use? Click the class name in the table above to look at all the function names (they are in the same order as the official API docs), and check the API docs for a list of endpoints/parameters/responses. +In rare situations, you may want to see the raw HTTP requets being built as well as the API response. These can be enabled by setting the `BITGETTRACE` env var to `true`. -If you found the method you're looking for in the API docs, you can also search for the endpoint in the [RestClientV2](src/rest-client-v2.ts) class. This class has all V2 endpoints available. +## Browser Usage -```javascript -import { RestClientV2 } from 'bitget-api'; -// or if you prefer require: -// const { RestClientV2 } = require('bitget-api'); +### Import -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; -const API_PASS = 'zzz'; +This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. -const client = new RestClientV2({ - apiKey: API_KEY, - apiSecret: API_SECRET, - apiPass: API_PASS, -}); +1. Install these dependencies + ```sh + npm install crypto-browserify stream-browserify + ``` +2. Add this to your `tsconfig.json` + ```json + { + "compilerOptions": { + "paths": { + "crypto": [ + "./node_modules/crypto-browserify" + ], + "stream": [ + "./node_modules/stream-browserify" + ] + } + ``` +3. Declare this in the global context of your application (ex: in polyfills for angular) + ```js + (window as any).global = window; + ``` -// For public-only API calls, simply don't provide a key & secret or set them to undefined -// const client = new RestClientV2(); +### Webpack -client - .getSpotAccount() - .then((result) => { - console.log('getSpotAccount result: ', result); - }) - .catch((err) => { - console.error('getSpotAccount error: ', err); - }); +This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. + +Build a bundle using webpack: -client - .getSpotCandles({ - symbol: 'BTCUSDT', - granularity: '1min', - limit: '1000', - }) - .then((result) => { - console.log('getCandles result: ', result); - }) - .catch((err) => { - console.error('getCandles error: ', err); - }); -``` +- `npm install` +- `npm build` +- `npm pack` -## WebSockets +The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO - contributions welcome. -All WebSocket functionality is supported via the WebsocketClient. Since there are currently 3 generations of Bitget's API, there are 3 WebsocketClient classes in this Node.js, JavaScript & TypeScript SDK for Bitget. +## Use with LLMs & AI -Use the following guidance to decide which one to use: +This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. -- **Unified Trading Account / V3** (latest generation): - - For receiving data, use the [WebsocketClientV3](./src/websocket-client-v3.ts). - - For sending orders via WebSockets, use the [WebsocketAPIClient](./src/websocket-api-client.ts). -- **V2** (not upgraded to Unified Trading Account yet) - - Use the [WebsocketClientV2](./src/websocket-client-v2.ts). -- **V1** (deprecated) - - This is the oldest API group supported by Bitget. You should migrate to V3 or V2 as soon as possible. - - If you're not ready to migrate, you can use the [WebsocketClientLegacyV1](./src/websocket-client-legacy-v1.ts) class in the meantime. +This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. -All WebSocket clients support: +--- -- Event driven messaging -- Smart WebSocket persistence with automatic reconnection -- Heartbeat mechanisms to detect disconnections -- Automatic resubscription after reconnection -- Error handling and connection monitoring -- Optional data beautification +## Used By -Higher level examples below, while more thorough examples can be found in the examples folder on GitHub. +[![Repository Users Preview Image](https://dependents.info/tiagosiebler/bitget-api/image)](https://github.com/tiagosiebler/bitget-api/network/dependents) -##### V3 Unified Trading Account +--- -###### Sending orders via WebSockets + -The V3 / Unified Trading Account APIs introduce order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API. +### Contributions & Thanks -There are two approaches to placing orders via the Bitget WebSocket APIs. The recommended route is to use the dedicated WebsocketAPIClient class, included with this SDK. +Have my projects helped you? Share the love, there are many ways you can show your thanks: -This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types. +- Star & share my projects. +- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler +- Have an interesting project? Get in touch & invite me to it. +- Or buy me all the coffee: + - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` +- Sign up with my referral links: + - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 + - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ + - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SDK + - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 -A simple example is below, but for a more thorough example, check the example here: [./examples/V3/ws-api-client-trade.ts](./examples/V3/ws-api-client-trade.ts) + + -// Make an instance of the WS API Client class with your API keys -const wsClient = new WebsocketAPIClient({ - apiKey: API_KEY, - apiSecret: API_SECRET, - apiPass: API_PASS, +### Contributions & Pull Requests - // Whether to use the demo trading wss connection - // demoTrading: true, -}); +Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. -async function start() { - // Start using it like a REST API. All actions are sent via a persisted WebSocket connection. + - /** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) + + + +================ +File: src/rest-client-v2.ts +================ +import { FuturesProductTypeV2, MarginType } from './types/request/shared.js'; +import { + CreateSubAccountApiKeyRequestV2, + GetAllSubDepositWithdrawalRequestV2, + GetBrokerCommissionsRequestV2, + GetBrokerOrderCommissionRequestV2, + GetBrokerRebateInfoRequestV2, + GetBrokerSubaccountsRequestV2, + GetBrokerTotalCommissionRequestV2, + GetBrokerTradeVolumeRequestV2, + GetSubAccountsRequestV2, + ModifySubAccountApiKeyRequestV2, + ModifySubRequestV2, + SubDepositRecordsRequestV2, + SubWithdrawalRecordsRequestV2, + SubWithdrawalRequestV2, +} from './types/request/v2/broker.js'; +import { + ConvertQuoteRequestV2, + ConvertRequestV2, + CreateVirtualSubApiKeyRequestV2, + CreateVirtualSubRequestV2, + GetAnnouncementsRequestV2, + GetConvertBGBHistoryRequestV2, + GetConvertHistoryRequestV2, + GetFuturesTransactionsRequestV2, + GetMarginTransactionsRequestV2, + GetMerchantAdvertisementsRequestV2, + GetMerchantP2POrdersRequestV2, + GetP2PMerchantsRequestV2, + GetP2PTransactionsRequestV2, + GetSpotTransactionsRequestV2, + GetTradeRateRequestV2, + ModifyVirtualSubApiKeyRequestV2, + ModifyVirtualSubRequestV2, +} from './types/request/v2/common.js'; +import { + CloseFuturesFollowerPositionsRequestV2, + CopyTradingProductTypeV2, + FuturesTraderSymbolSettingRequestV2, + GetFollowerFuturesCurrentTrackingOrdersRequestV2, + GetFollowerFuturesHistoryTrackingOrdersRequestV2, + GetFuturesFollowerTradersRequestV2, + GetFuturesTraderCurrentOrdersRequestV2, + GetFuturesTraderFollowersRequestV2, + GetFuturesTraderHistoryOrdersRequestV2, + GetFuturesTraderProfitShareDetailRequestV2, + GetSpotFollowerHistoryOrdersRequestV2, + GetSpotFollowerOpenOrdersRequestV2, + GetSpotTraderCurrentOrdersRequestV2, + GetSpotTraderFollowersRequestV2, + GetSpotTraderHistoryOrdersRequestV2, + GetSpotTraderHistoryProfitRequestV2, + ModifyFuturesTraderOrderTPSLRequestV2, + SpotFollowerCopyTradeSettingV2, + UpdateFuturesFollowerSettingsRequestV2, + UpdateFuturesFollowerTPSLRequestV2, +} from './types/request/v2/copytrading.js'; +import { + BorrowLoanRequestV2, + GetEarnSavingsAssetsRequestV2, + GetEarnSavingsRecordsRequestV2, + GetLiquidationRecordsRequestV2, + GetLoanEstInterestAndBorrowableRequestV2, + GetLoanHistoryRequestV2, + GetLoanPledgeRateHistoryRequestV2, + GetLoanRepayHistoryRequestV2, + GetSharkfinAssetsRequestV2, + GetSharkfinRecordsRequestV2, + ModifyLoanPledgeRateRequestV2, + RedeemSavingsRequestV2, + RepayLoanRequestV2, +} from './types/request/v2/earn.js'; +import { + FuturesAccountBillRequestV2, + FuturesBatchCancelOrderRequestV2, + FuturesBatchOrderRequestV2, + FuturesCancelAllOrdersRequestV2, + FuturesCancelOrderRequestV2, + FuturesCancelPlanOrderRequestV2, + FuturesCandlesRequestV2, + FuturesFlashClosePositionsRequestV2, + FuturesGetHistoricalFillsRequestV2, + FuturesGetHistoryOrdersRequestV2, + FuturesGetHistoryPlanOrdersRequestV2, + FuturesGetOpenOrdersRequestV2, + FuturesGetOrderFillsRequestV2, + FuturesGetOrderRequestV2, + FuturesGetPlanOrdersRequestV2, + FuturesHistoricalPositionsRequestV2, + FuturesHistoricTradesRequestV2, + FuturesInterestHistoryRequestV2, + FuturesIsolatedSymbolsRequestV2, + FuturesLiquidationPriceRequestV2, + FuturesMaxOpenRequestV2, + FuturesMergeDepthRequestV2, + FuturesModifyOrderRequestV2, + FuturesModifyPlanOrderRequestV2, + FuturesModifyTPSLOrderRequestV2, + FuturesOpenCountRequestV2, + FuturesPlaceOrderRequestV2, + FuturesPlanOrderRequestV2, + FuturesRecentTradesRequestV2, + FuturesReversalOrderRequestV2, + FuturesSetAutoMarginRequestV2, + FuturesSetLeverageRequestV2, + FuturesSetMarginModeRequestV2, + FuturesSetPositionMarginRequestV2, + FuturesSingleAccountRequestV2, + FuturesTPSLOrderRequestV2, + GetUnionTransferLimitsRequestV2, + UnionConvertRequestV2, +} from './types/request/v2/futures.js'; +import { + GetBorrowHistoryRequestV2, + GetFinancialHistoryRequestV2, + GetHistoryOrdersRequestV2, + GetInterestHistoryRequestV2, + GetLiquidationHistoryRequestV2, + GetMarginCurrentOrdersRequestV2, + GetMarginLiquidationOrdersRequestV2, + GetMarginOrderFillsRequestV2, + GetRepayHistoryRequestV2, + MarginBatchOrdersRequestV2, + MarginPlaceOrderRequestV2, +} from './types/request/v2/margin.js'; +import { + GetSpotAccountBillsRequestV2, + GetSpotCurrentPlanOrdersRequestV2, + GetSpotDepositRecordRequestV2, + GetSpotFillsRequestV2, + GetSpotHistoryOrdersRequestV2, + GetSpotHistoryPlanOrdersRequestV2, + GetSpotOpenOrdersRequestV2, + GetSpotOrderInfoRequestV2, + GetSpotSubAccountDepositRecordRequestV2, + GetSpotTransferRecordRequestV2, + GetSpotWithdrawalRecordRequestV2, + SpotAccountTypeV2, + SpotBatchCancelOrderRequestV2, + SpotBatchOrderRequestV2, + SpotCancelandSubmitOrderRequestV2, + SpotCancelOrderRequestV2, + SpotCandlesRequestV2, + SpotHistoricCandlesRequestV2, + SpotHistoricTradesRequestV2, + SpotMainSubTransferRecordRequestV2, + SpotModifyPlanOrderRequestV2, + SpotOrderRequestV2, + SpotPlanOrderRequestV2, + SpotSubAccountTransferRequestV2, + SpotTransferRequestV2, + SpotWithdrawalRequestV2, +} from './types/request/v2/spot.js'; +import { + AllSubDepositWithdrawalRecordV2, + BrokerCommissionV2, + BrokerOrderCommissionV2, + BrokerRebateInfoV2, + BrokerSubaccountFutureAssetV2, + BrokerSubaccountInfoV2, + BrokerSubaccountSpotAssetV2, + BrokerSubaccountV2, + BrokerSubaccountWithdrawalV2, + BrokerTotalCommissionV2, + BrokerTradeVolumeV2, + CreateSubaccountApiKeyResponseV2, + CreateSubaccountDepositAddressV2, + CreateSubaccountResponseV2, + ModifySubaccountApiKeyResponseV2, + ModifySubaccountResponseV2, + SubaccountApiKeyV2, + SubaccountDepositV2, + SubaccountEmailV2, +} from './types/response/v2/broker.js'; +import { + AnnouncementV2, + BGBConvertCoinV2, + BGBConvertHistoryV2, + BotAssetV2, + ConvertBGBResponseV2, + ConvertCurrencyV2, + ConvertQuotedPriceV2, + ConvertRecordV2, + ConvertTradeResponseV2, + CreateVirtualSubAccountAndApiKeyV2, + CreateVirtualSubAccountApiKeyV2, + CreateVirtualSubAccountV2, + FundingAssetV2, + FuturesActiveBuySellVolumeV2, + FuturesActiveLongShortAccountV2, + FuturesActiveLongShortPositionV2, + FuturesLongShortRatioV2, + FuturesTransactionRecordV2, + IsolatedMarginBorrowingRatioV2, + LeveragedLongShortRatioV2, + MarginLoanGrowthRateV2, + MarginTransactionRecordV2, + ModifyVirtualSubAccountApiKeyV2, + P2PMerchantAdvertismentV2, + P2PMerchantInfoV2, + P2PMerchantOrdersV2, + P2PMerchantOrderV2, + P2PMerchantV2, + SpotFundFlowV2, + SpotTransactionRecordV2, + SpotWhaleNetFlowV2, + SubAccountApiKeyItemV2, + VirtualSubAccountV2, +} from './types/response/v2/common.js'; +import { + CTFuturesFollowerCurrentOrdersV2, + CTFuturesFollowerHistoryOrdersV2, + CTFuturesFollowerMyTradersV2, + CTFuturesFollowerSettingsV2, + CTFuturesTraderCurrentOrdersV2, + CTFuturesTraderHistoryOrderV2, + CTFuturesTraderHistoryProfitSummaryV2, + CTFuturesTraderMyFollowersV2, + CTFuturesTraderProfitShareHistoryV2, + CTFuturesTraderSymbolSettingsV2, + CTFuturesTraderTotalOrderSummaryV2, + CTSpotFollowerCurrentOrdersV2, + CTSpotFollowerFollowConfigurationV2, + CTSpotFollowerHistoryOrdersV2, + CTSpotFollowerMyTradersV2, + CTSpotTraderCurrentTrackingOrdersV2, + CTSpotTraderFollowerListV2, + CTSpotTraderHistoryOrdersV2, + CTSpotTraderHistoryProfitSharingV2, + CTSpotTraderProfitSummaryV2, + CTSpotTraderTotalOrderDetailV2, + CTSpotTraderUnrealizedProfitV2, +} from './types/response/v2/copy-trading.js'; +import { + EarnLoanCurrenciesV2, + EarnLoanDebtsV2, + EarnLoanHistoryV2, + EarnLoanLiquidationRecordsV2, + EarnLoanOrdersV2, + EarnLoanPledgeRateHistoryV2, + EarnLoanRepayHistoryV2, + EarnLoanRepayResponseV2, + EarnSavingsAccountV2, + EarnSavingsAssetsV2, + EarnSavingsProductsV2, + EarnSavingsRecordsV2, + EarnSavingsSubscriptionDetailV2, + EarnSharkfinAccountV2, + EarnSharkfinAssetsV2, + EarnSharkfinProductsV2, + EarnSharkfinRecordsV2, + EarnSharkfinSubscriptionDetailV2, +} from './types/response/v2/earn.js'; +import { + FuturesAccountBillV2, + FuturesAccountsV2, + FuturesAccountV2, + FuturesBatchOrderResponseV2, + FuturesCancelAllOrdersV2, + FuturesCancelPlanOrderV2, + FuturesCandlestickV2, + FuturesClosePositionResponseV2, + FuturesContractConfigV2, + FuturesDiscountRatesV2, + FuturesFillV2, + FuturesFundingTimeV2, + FuturesHistoricalFundingRateV2, + FuturesHistoryInterestRateV2, + FuturesHistoryOrderV2, + FuturesHistoryPlanOrderV2, + FuturesHistoryPositionV2, + FuturesInterestExchangeRateV2, + FuturesInterestHistoryV2, + FuturesIsolatedSymbolV2, + FuturesLiquidationPriceV2, + FuturesMaxOpenV2, + FuturesMergeDepthV2, + FuturesOpenInterestV2, + FuturesOpenOrderV2, + FuturesOrderDetailV2, + FuturesOrderFillV2, + FuturesPendingPlanOrderV2, + FuturesPositionTierV2, + FuturesPositionV2, + FuturesSubAccountAssetV2, + FuturesSymbolPriceV2, + FuturesTickerV2, + FuturesTriggerSubOrderV2, + FuturesVipFeeRateV2, + SetLeverageResponseV2, + SetMarginModeResponseV2, + UnionConfigV2, + UnionConvertV2, + UnionSwitchUsdtV2, + UnionTransferLimitsV2, +} from './types/response/v2/futures.js'; +import { + CrossInterestRateAndLimitResponseV2, + CrossMaxBorrowableResponseV2, + CrossMaxTransferableResponseV2, + CrossTierConfigurationResponseV2, + IsolatedInterestRateAndLimitResponseV2, + IsolatedMaxBorrowableResponseV2, + IsolatedMaxTransferableResponseV2, + IsolatedTierConfigurationResponseV2, + MarginAccountAssetV2, + MarginBatchOrdersResponseV2, + MarginBorrowHistoryItemV2, + MarginCurrencyV2, + MarginCurrentOrderV2, + MarginFinancialHistoryItemV2, + MarginHistoryOrderV2, + MarginInterestHistoryItemV2, + MarginLiquidationHistoryItemV2, + MarginLiquidationOrderV2, + MarginOrderFillV2, + MarginRepaymentHistoryItemV2, +} from './types/response/v2/margin.js'; +import { + CancelAndSubmitSpotOrderResponseV2, + SpotAccountAssetV2, + SpotAccountBillV2, + SpotAccountInfoV2, + SpotCancelPlanOrdersV2, + SpotCandlestickV2, + SpotCoinInfoV2, + SpotCurrentPlanOrderV2, + SpotDepositAddressV2, + SpotDepositRecordV2, + SpotFillV2, + SpotHistoryPlanOrderV2, + SpotMainSubTransferRecordV2, + SpotMergeDepthV2, + SpotOpenOrderV2, + SpotOrderBookDepthV2, + SpotOrderInfoV2, + SpotPlanSubOrderV2, + SpotSubAccountAssetsV2, + SpotSubAccountDepositRecordV2, + SpotSymbolInfoV2, + SpotTickerV2, + SpotTradeV2, + SpotTransferRecordV2, + SpotVipFeeRateV2, + SpotWithdrawalRecordV2, + SubmitSpotBatchOrdersResponseV2, +} from './types/response/v2/spot.js'; +import { APIResponse } from './types/shared.js'; +import BaseRestClient from './util/BaseRestClient.js'; +import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; +import { assertMarginType } from './util/type-guards.js'; +⋮---- +/** + * REST API client for all V2 endpoints + */ +export class RestClientV2 extends BaseRestClient +⋮---- +getClientType() +⋮---- +/** + * + * Custom SDK functions + * + */ +⋮---- +/** + * 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 +⋮---- +// Adjust server time by adding estimated one-way latency +⋮---- +// Calculate time difference between adjusted server time and local time +⋮---- +async fetchServerTime(): Promise +⋮---- +/** + * + * Bitget misc functions + * + */ +⋮---- +/** + * + * + * Common + * + * + */ +⋮---- +/** + * + * * Common | Notice + * + */ +⋮---- +getAnnouncements( + params?: GetAnnouncementsRequestV2, +): Promise> +⋮---- +/** + * + * * Common | Public + * + */ +⋮---- +getServerTime(): Promise< + APIResponse<{ + serverTime: string; + }> + > { + return this.get('/api/v2/public/time'); +⋮---- +getTradeRate(params: GetTradeRateRequestV2): Promise< + APIResponse<{ + makerFeeRate: string; + takerFeeRate: string; + }> + > { + return this.getPrivate('/api/v2/common/trade-rate', params); +⋮---- +/** + * + * * Common | Tax + * + */ +⋮---- +getSpotTransactionRecords( + params: GetSpotTransactionsRequestV2, +): Promise> +⋮---- +getFuturesTransactionRecords( + params: GetFuturesTransactionsRequestV2, +): Promise> +⋮---- +getMarginTransactionRecords( + params: GetMarginTransactionsRequestV2, +): Promise> +⋮---- +getP2PTransactionRecords( + params: GetP2PTransactionsRequestV2, +): Promise> +⋮---- +/** + * + * * Common | P2P + * + */ +⋮---- +getP2PMerchantList(params?: GetP2PMerchantsRequestV2): Promise< + APIResponse<{ + merchantList: P2PMerchantV2[]; + minMerchantId: string; + }> + > { + return this.getPrivate('/api/v2/p2p/merchantList', params); +⋮---- +getP2PMerchantInfo(): Promise> +⋮---- +getP2PMerchantOrders(params: GetMerchantP2POrdersRequestV2): Promise< + APIResponse<{ + orderList: P2PMerchantOrderV2[]; + minOrderId: string; + }> + > { + return this.getPrivate('/api/v2/p2p/orderList', params); +⋮---- +getP2PMerchantAdvertisementList( + params: GetMerchantAdvertisementsRequestV2, + ): Promise< + APIResponse<{ + advList: P2PMerchantAdvertismentV2[]; + minAdvId: string; + }> + > { + return this.getPrivate('/api/v2/p2p/advList', params); +⋮---- +/** + * + * * Common | Trading insights + * + */ +⋮---- +getSpotWhaleNetFlowData(params: { + symbol: string; +}): Promise> +⋮---- +getFuturesActiveTakerBuySellVolumeData(params: { + symbol: string; + period?: string; +}): Promise> +⋮---- +getFuturesActiveLongShortPositionData(params: { + symbol: string; + period?: string; +}): Promise> +⋮---- +getFuturesLongShortRatio(params: { + symbol: string; + period?: string; + coin?: string; +}): Promise> +⋮---- +getMarginLoanGrowthRate(params: { + symbol: string; + period?: string; + coin?: string; +}): Promise> +⋮---- +getIsolatedMarginBorrowingRatio(params: { + symbol: string; + period?: string; +}): Promise> +⋮---- +getFuturesActiveBuySellVolumeData(params: { + symbol: string; + period?: string; +}): Promise> +⋮---- +getSpotFundFlow(params: { + symbol: string; + period?: string; +}): Promise> +⋮---- +getTradeDataSupportSymbols(): Promise< + APIResponse<{ + spotList: string[]; + futureList: string[]; + }> + > { + return this.get('/api/v2/spot/market/support-symbols'); +⋮---- +getSpotFundNetFlowData(params: { symbol: string }): Promise< + APIResponse< + { + netFlow: string; + ts: string; + }[] + > + > { + return this.get('/api/v2/spot/market/fund-net-flow', params); +⋮---- +getFuturesActiveLongShortAccountData(params: { + symbol: string; + period?: string; +}): Promise> +⋮---- +/** + * + * * Common | Virtual Subaccount + * + */ +⋮---- +createVirtualSubaccount(params: { + subAccountList: string[]; +}): Promise> +⋮---- +modifyVirtualSubaccount(params: ModifyVirtualSubRequestV2): Promise< + APIResponse<{ + result: string; + }> + > { + return this.postPrivate('/api/v2/user/modify-virtual-subaccount', params); +⋮---- +batchCreateVirtualSubaccountAndAPIKey( + params: CreateVirtualSubRequestV2, +): Promise> +⋮---- +getVirtualSubaccounts(params?: { + limit?: string; + idLessThan?: string; + status?: 'normal' | 'freeze'; + }): Promise< + APIResponse<{ + endId: string; + subAccountList: VirtualSubAccountV2[]; + }> + > { + return this.getPrivate('/api/v2/user/virtual-subaccount-list', params); +⋮---- +createVirtualSubaccountAPIKey( + params: CreateVirtualSubApiKeyRequestV2, +): Promise> +⋮---- +modifyVirtualSubaccountAPIKey( + params: ModifyVirtualSubApiKeyRequestV2, +): Promise> +⋮---- +getVirtualSubaccountAPIKeys(params: { + subAccountUid: string; +}): Promise> +⋮---- +/** + * + * * Common | Assets + * + */ +getFundingAssets(params?: { + coin?: string; +}): Promise> +⋮---- +getBotAccount(params?: { + accountType?: string; +}): Promise> +⋮---- +/** Get assets overview */ +getBalances(): Promise< + APIResponse< + { + accountType: string; + usdtBalance: string; + }[] + > + > { + return this.getPrivate('/api/v2/account/all-account-balance'); +⋮---- +/** + * + * * Common | Convert + * + */ +⋮---- +getConvertCoins(): Promise> +⋮---- +getConvertQuotedPrice( + params: ConvertQuoteRequestV2, +): Promise> +⋮---- +convert( + params: ConvertRequestV2, +): Promise> +⋮---- +getConvertHistory(params: GetConvertHistoryRequestV2): Promise< + APIResponse<{ + dataList: ConvertRecordV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/convert/convert-record', params); +⋮---- +/** + * + * * Common | BGB Convert + * + */ +⋮---- +getConvertBGBCoins(): Promise< + APIResponse<{ + coinList: BGBConvertCoinV2[]; + }> + > { + return this.getPrivate('/api/v2/convert/bgb-convert-coin-list'); +⋮---- +convertBGB(params: { + coinList: string; +}): Promise> +⋮---- +getConvertBGBHistory( + params: GetConvertBGBHistoryRequestV2, +): Promise> +⋮---- +/** + * + * + * Spot + * + * + */ +⋮---- +/** + * + * * Spot | Market + * + */ +⋮---- +getSpotCoinInfo(params?: { + coin?: string; +}): Promise> +⋮---- +getSpotSymbolInfo(params?: { + symbol?: string; +}): Promise> +⋮---- +getSpotVIPFeeRate(): Promise> +⋮---- +getSpotTicker(params?: { + symbol?: string; +}): Promise> +⋮---- +getSpotMergeDepth(params: { + symbol: string; + precision?: string; + limit?: string; +}): Promise> +⋮---- +getSpotOrderBookDepth(params: { + symbol: string; + type?: string; + limit?: string; +}): Promise> +⋮---- +getSpotCandles( + params: SpotCandlesRequestV2, +): Promise> +⋮---- +getSpotHistoricCandles( + params: SpotHistoricCandlesRequestV2, +): Promise> +⋮---- +getSpotRecentTrades(params: { + symbol: string; + limit?: string; +}): Promise> +⋮---- +getSpotHistoricTrades( + params: SpotHistoricTradesRequestV2, +): Promise> +⋮---- +/** + * + * * Spot | Trade + * + */ +⋮---- +spotSubmitOrder(params: SpotOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/trade/place-order', params); +⋮---- +spotCancelandSubmitOrder( + params: SpotCancelandSubmitOrderRequestV2, +): Promise> +⋮---- +spotBatchCancelandSubmitOrder(params: { + orderList: SpotCancelandSubmitOrderRequestV2[]; +}): Promise> +⋮---- +spotCancelOrder(params: SpotCancelOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/trade/cancel-order', params); +⋮---- +spotBatchSubmitOrders( + params: SpotBatchOrderRequestV2, +): Promise> +⋮---- +spotBatchCancelOrders( + params: SpotBatchCancelOrderRequestV2, +): Promise> +⋮---- +spotCancelSymbolOrder(params: { symbol: string }): Promise< + APIResponse<{ + symbol: string; + }> + > { + return this.postPrivate('/api/v2/spot/trade/cancel-symbol-order', params); +⋮---- +getSpotOrder( + params?: GetSpotOrderInfoRequestV2, +): Promise> +⋮---- +getSpotOpenOrders( + params?: GetSpotOpenOrdersRequestV2, +): Promise> +⋮---- +getSpotHistoricOrders( + params?: GetSpotHistoryOrdersRequestV2, +): Promise> +⋮---- +getSpotFills( + params: GetSpotFillsRequestV2, +): Promise> +⋮---- +/** + * + * * Spot | Trigger Orders + * + */ +⋮---- +spotSubmitPlanOrder(params: SpotPlanOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/trade/place-plan-order', params); +⋮---- +spotModifyPlanOrder(params: SpotModifyPlanOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/trade/modify-plan-order', params); +⋮---- +spotCancelPlanOrder(params: { + clientOid?: string; + orderId?: string; + }): Promise< + APIResponse<{ + result: string; + }> + > { + return this.postPrivate('/api/v2/spot/trade/cancel-plan-order', params); +⋮---- +getSpotCurrentPlanOrders(params: GetSpotCurrentPlanOrdersRequestV2): Promise< + APIResponse<{ + nextFlag: boolean; + idLessThan: string; + orderList: SpotCurrentPlanOrderV2[]; + }> + > { + return this.getPrivate('/api/v2/spot/trade/current-plan-order', params); +⋮---- +getSpotPlanSubOrder(params: { + planOrderId: string; +}): Promise> +⋮---- +getSpotHistoricPlanOrders(params: GetSpotHistoryPlanOrdersRequestV2): Promise< + APIResponse<{ + nextFlag: boolean; + idLessThan: string; + orderList: SpotHistoryPlanOrderV2[]; + }> + > { + return this.getPrivate('/api/v2/spot/trade/history-plan-order', params); +⋮---- +spotCancelPlanOrders(params?: { + symbolList?: string[]; +}): Promise> +⋮---- +/** + * + * * Spot | Account + * + */ +⋮---- +getSpotAccount(): Promise> +⋮---- +getSpotAccountAssets(params?: { + coin?: string; + assetType?: string; +}): Promise> +⋮---- +getSpotSubAccountAssets(): Promise> +⋮---- +spotModifyDepositAccount(params: { + accountType: string; + coin: string; +}): Promise> +⋮---- +getSpotAccountBills( + params?: GetSpotAccountBillsRequestV2, +): Promise> +⋮---- +spotTransfer(params: SpotTransferRequestV2): Promise< + APIResponse<{ + transferId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/wallet/transfer', params); +⋮---- +getSpotTransferableCoins(params: { + fromType: SpotAccountTypeV2; + toType: SpotAccountTypeV2; +}): Promise> +⋮---- +spotSubTransfer(params: SpotSubAccountTransferRequestV2): Promise< + APIResponse<{ + transferId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/wallet/subaccount-transfer', params); +⋮---- +spotWithdraw(params: SpotWithdrawalRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/spot/wallet/withdrawal', params); +⋮---- +getSpotMainSubTransferRecord( + params: SpotMainSubTransferRecordRequestV2, +): Promise> +⋮---- +getSpotTransferHistory( + params: GetSpotTransferRecordRequestV2, +): Promise> +⋮---- +spotSwitchBGBDeduct(params: { + deduct: boolean; +}): Promise> +⋮---- +getSpotDepositAddress(params: { + coin: string; + chain?: string; + size: string; +}): Promise> +⋮---- +getSpotSubDepositAddress(params: { + subUid: string; + coin: string; + chain?: string; + size: string; +}): Promise> +⋮---- +getSpotBGBDeductInfo(): Promise< + APIResponse<{ + deduct: string; + }> + > { + return this.getPrivate('/api/v2/spot/account/deduct-info'); +⋮---- +spotCancelWithdrawal(params: { + orderId: string; +}): Promise> +⋮---- +getSubAccountDepositRecords( + params: GetSpotSubAccountDepositRecordRequestV2, +): Promise> +⋮---- +getSpotWithdrawalHistory( + params: GetSpotWithdrawalRecordRequestV2, +): Promise> +⋮---- +getSpotDepositHistory( + params: GetSpotDepositRecordRequestV2, +): Promise> +⋮---- +/** + * Upgrade Account - Upgrade to unified account mode + * No account type restrictions; both parent and sub-accounts are supported. + * This interface is only used for upgrading to the unified account mode. + * Please note that as the account upgrade process takes approximately 1 minute, + * the successful response you receive only indicates that the request has been received, + * and does not mean that the account has been successfully upgraded to a unified account. + * Please use the query upgrade status interface to confirm whether the account upgrade is successful. + */ +upgradeToUnifiedAccount(params?: { + subUid?: string; +}): Promise> +⋮---- +/** + * Get Upgrade Status - Get account upgrade status + * No account type restrictions; both parent and sub-accounts are supported. + */ +getUnifiedAccountSwitchStatus(params?: { subUid?: string }): Promise< + APIResponse<{ + status: 'processProcessing' | 'successSuccess' | 'failFailed'; + }> + > { + return this.getPrivate('/api/v2/spot/account/upgrade-status', params); +⋮---- +/** + * + * + * Futures + * + * + */ +⋮---- +/** + * + * * Futures | Market + * + */ +⋮---- +getFuturesVIPFeeRate(): Promise> +⋮---- +getFuturesInterestRateHistory(params: { coin: string }): Promise< + APIResponse<{ + coin: string; + historyInterestRateList: FuturesHistoryInterestRateV2[]; + }> + > { + return this.get('/api/v2/mix/market/union-interest-rate-history', params); +⋮---- +getFuturesInterestExchangeRate(): Promise< + APIResponse< + { + coin: string; + exchangeRateList: FuturesInterestExchangeRateV2[]; + }[] + > + > { + return this.get('/api/v2/mix/market/exchange-rate'); +⋮---- +getFuturesDiscountRate(): Promise> +⋮---- +getFuturesMergeDepth( + params: FuturesMergeDepthRequestV2, +): Promise> +⋮---- +getFuturesTicker(params: { + symbol: string; + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +getFuturesAllTickers(params: { + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +getFuturesRecentTrades( + params: FuturesRecentTradesRequestV2, +): Promise> +⋮---- +getFuturesHistoricTrades( + params: FuturesHistoricTradesRequestV2, +): Promise> +⋮---- +getFuturesCandles( + params: FuturesCandlesRequestV2, +): Promise> +⋮---- +getFuturesHistoricCandles( + params: FuturesCandlesRequestV2, +): Promise> +⋮---- +getFuturesHistoricIndexPriceCandles( + params: FuturesCandlesRequestV2, +): Promise> +⋮---- +getFuturesHistoricMarkPriceCandles( + params: FuturesCandlesRequestV2, +): Promise> +⋮---- +getFuturesOpenInterest(params: { + symbol: string; + productType: FuturesProductTypeV2; + }): Promise< + APIResponse<{ + openInterestList: FuturesOpenInterestV2[]; + ts: string; + }> + > { + return this.get('/api/v2/mix/market/open-interest', params); +⋮---- +getFuturesNextFundingTime(params: { + symbol: string; + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +getFuturesSymbolPrice(params: { + symbol: string; + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +getFuturesHistoricFundingRates(params: { + symbol: string; + productType: FuturesProductTypeV2; + pageSize?: string; + pageNo?: string; +}): Promise> +⋮---- +getFuturesCurrentFundingRate(params: { + symbol?: string; + productType: FuturesProductTypeV2; + }): Promise< + APIResponse< + { + symbol: string; + fundingRate: string; // '0.0001'; + fundingRateInterval: string; // hours, example: '1' | '2' | '4' | '8'; + nextUpdate: string; // timestamp in milliseconds + minFundingRate: string; + maxFundingRate: string; + }[] + > + > { + return this.get('/api/v2/mix/market/current-fund-rate', params); +⋮---- +fundingRate: string; // '0.0001'; +fundingRateInterval: string; // hours, example: '1' | '2' | '4' | '8'; +nextUpdate: string; // timestamp in milliseconds +⋮---- +getFuturesContractConfig(params: { + symbol?: string; + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +/** + * + * * Futures | Account + * + */ +⋮---- +getFuturesAccountAsset( + params: FuturesSingleAccountRequestV2, +): Promise> +⋮---- +getFuturesAccountAssets(params: { + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +getFuturesSubAccountAssets(params: { + productType: FuturesProductTypeV2; + }): Promise< + APIResponse< + { + userId: number; + assetList: FuturesSubAccountAssetV2[]; + }[] + > + > { + return this.getPrivate('/api/v2/mix/account/sub-account-assets', params); +⋮---- +getFuturesInterestHistory( + params: FuturesInterestHistoryRequestV2, +): Promise> +⋮---- +getFuturesOpenCount(params: FuturesOpenCountRequestV2): Promise< + APIResponse<{ + size: string; + }> + > { + return this.getPrivate('/api/v2/mix/account/open-count', params); +⋮---- +setFuturesPositionAutoMargin( + params: FuturesSetAutoMarginRequestV2, +): Promise> +⋮---- +setFuturesLeverage( + params: FuturesSetLeverageRequestV2, +): Promise> +⋮---- +setFuturesPositionMargin( + params: FuturesSetPositionMarginRequestV2, +): Promise> +⋮---- +setFuturesAssetMode(params: { + productType: 'USDT-FUTURES' | 'SUSDT-FUTURES'; + assetMode: 'single' | 'union'; +}): Promise> +⋮---- +setFuturesMarginMode( + params: FuturesSetMarginModeRequestV2, +): Promise> +⋮---- +setFuturesPositionMode(params: { + productType: FuturesProductTypeV2; + posMode: 'one_way_mode' | 'hedge_mode'; + }): Promise< + APIResponse<{ + posMode: 'one_way_mode' | 'hedge_mode'; + }> + > { + return this.postPrivate('/api/v2/mix/account/set-position-mode', params); +⋮---- +getFuturesAccountBills(params: FuturesAccountBillRequestV2): Promise< + APIResponse<{ + bills: FuturesAccountBillV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/account/bill', params); +⋮---- +/** + * Get Union Transfer Limits + * + * - Rate limit: 1 time/1s (uid) + * - Get union margin currency transfer limits + */ +getUnionTransferLimits( + params: GetUnionTransferLimitsRequestV2, +): Promise> +⋮---- +/** + * Get Union Config + * + * - Rate limit: 1 time/1s (uid) + * - Get API for union margin configuration parameters (Liability Initial Margin Rate, Liability Maintenance Margin Rate, Personal Liability Limit, Personal Liability Limit Ratio) + */ +getUnionConfig(): Promise> +⋮---- +/** + * Get Switch Union USDT + * + * - Rate limit: 1 time/1s (uid) + * - Get USDT quota for switching from union margin to single margin + */ +getSwitchUnionUsdt(): Promise> +⋮---- +/** + * Union Convert + * + * - Rate limit: 1 time/1s (uid) + * - Union margin exchange + */ +unionConvert( + params: UnionConvertRequestV2, +): Promise> +⋮---- +/** + * Get Max Openable Quantity + * + * - Rate limit: 20 req/sec/UID + * - Get Max Openable Quantity + */ +getFuturesMaxOpenableQuantity( + params: FuturesMaxOpenRequestV2, +): Promise> +⋮---- +/** + * Get Liquidation Price + * + * - Rate limit: 20 req/sec/UID + * - Get Liquidation Price + */ +getFuturesLiquidationPrice( + params: FuturesLiquidationPriceRequestV2, +): Promise> +⋮---- +/** + * Get Isolated Symbols + * + * - Rate limits: 10 time/1s (uid) + * - Retrieve trading pairs with isolated margin mode under the account. + */ +getFuturesIsolatedSymbols( + params: FuturesIsolatedSymbolsRequestV2, +): Promise> +⋮---- +/** + * + * * Futures | Position + * + */ +⋮---- +getFuturesPositionTier(params: { + productType: FuturesProductTypeV2; + symbol: string; +}): Promise> +⋮---- +getFuturesPosition(params: { + productType: FuturesProductTypeV2; + symbol: string; + marginCoin: string; +}): Promise> +⋮---- +getFuturesPositions(params: { + productType: FuturesProductTypeV2; + marginCoin?: string; +}): Promise> +⋮---- +getFuturesHistoricPositions( + params?: FuturesHistoricalPositionsRequestV2, + ): Promise< + APIResponse<{ + list: FuturesHistoryPositionV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/position/history-position', params); +⋮---- +/** + * + * * Futures | Trade + * + */ +⋮---- +futuresSubmitOrder(params: FuturesPlaceOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/place-order', params); +⋮---- +futuresSubmitReversal(params: FuturesReversalOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/click-backhand', params); +⋮---- +futuresBatchSubmitOrders( + params: FuturesBatchOrderRequestV2, +): Promise> +⋮---- +futuresModifyOrder(params: FuturesModifyOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/modify-order', params); +⋮---- +futuresCancelOrder(params: FuturesCancelOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/cancel-order', params); +⋮---- +futuresBatchCancelOrders( + params: FuturesBatchCancelOrderRequestV2, +): Promise> +⋮---- +futuresFlashClosePositions( + params: FuturesFlashClosePositionsRequestV2, +): Promise> +⋮---- +getFuturesOrder( + params: FuturesGetOrderRequestV2, +): Promise> +⋮---- +getFuturesFills(params: FuturesGetOrderFillsRequestV2): Promise< + APIResponse<{ + fillList: FuturesOrderFillV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/order/fills', params); +⋮---- +getFuturesHistoricOrderFills( + params: FuturesGetHistoricalFillsRequestV2, + ): Promise< + APIResponse<{ + fillList: FuturesOrderFillV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/order/fill-history', params); +⋮---- +getFuturesOpenOrders(params: FuturesGetOpenOrdersRequestV2): Promise< + APIResponse<{ + entrustedList: FuturesOpenOrderV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/order/orders-pending', params); +⋮---- +getFuturesHistoricOrders(params: FuturesGetHistoryOrdersRequestV2): Promise< + APIResponse<{ + entrustedList: FuturesHistoryOrderV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/order/orders-history', params); +⋮---- +futuresCancelAllOrders( + params: FuturesCancelAllOrdersRequestV2, +): Promise> +⋮---- +/** + * + * * Futures | Trigger Orders + * + */ +⋮---- +getFuturesTriggerSubOrder(params: { + planType: 'normal_plan' | 'track_plan'; + planOrderId: string; + productType: FuturesProductTypeV2; +}): Promise> +⋮---- +futuresSubmitTPSLOrder(params: FuturesTPSLOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/place-tpsl-order', params); +⋮---- +futuresSubmitPlanOrder(params: FuturesPlanOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/place-plan-order', params); +⋮---- +futuresModifyTPSLPOrder(params: FuturesModifyTPSLOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/modify-tpsl-order', params); +⋮---- +futuresModifyPlanOrder(params: FuturesModifyPlanOrderRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v2/mix/order/modify-plan-order', params); +⋮---- +getFuturesPlanOrders(params: FuturesGetPlanOrdersRequestV2): Promise< + APIResponse<{ + entrustedList: FuturesPendingPlanOrderV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/order/orders-plan-pending', params); +⋮---- +futuresCancelPlanOrder( + params: FuturesCancelPlanOrderRequestV2, +): Promise> +⋮---- +getFuturesHistoricPlanOrders( + params: FuturesGetHistoryPlanOrdersRequestV2, + ): Promise< + APIResponse<{ + entrustedList: FuturesHistoryPlanOrderV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/mix/order/orders-plan-history', params); +⋮---- +/** + * + * + * Broker + * + * + */ +⋮---- +/** + * + * * Broker | Subaccount + * + */ +⋮---- +modifySubaccountEmail(params: { + subUid: string; + subaccountEmail: string; +}): Promise> +⋮---- +getBrokerInfo(): Promise< + APIResponse<{ + subAccountSize: string; + maxSubAccountSize: string; + uTime: string; + }> + > { + return this.getPrivate('/api/v2/broker/account/info'); +⋮---- +createSubaccount(params: { + subaccountName: string; + label: string; +}): Promise> +⋮---- +getSubaccounts(params?: GetSubAccountsRequestV2): Promise< + APIResponse<{ + hasNextPage: boolean; + idLessThan: number; + subList: BrokerSubaccountV2[]; + }> + > { + return this.getPrivate('/api/v2/broker/account/subaccount-list', params); +⋮---- +modifySubaccount( + params: ModifySubRequestV2, +): Promise> +⋮---- +getSubaccountEmail(params: { + subUid: string; +}): Promise> +⋮---- +getSubaccountSpotAssets(params: { + subUid: string; + coin?: string; + assetType?: 'hold_only' | 'all'; + }): Promise< + APIResponse<{ + assetsList: BrokerSubaccountSpotAssetV2[]; + }> + > { + return this.getPrivate( + '/api/v2/broker/account/subaccount-spot-assets', + params, + ); +⋮---- +getSubaccountFuturesAssets(params: { + subUid: string; + productType: FuturesProductTypeV2; + }): Promise< + APIResponse<{ + assetsList: BrokerSubaccountFutureAssetV2[]; + }> + > { + return this.getPrivate( + '/api/v2/broker/account/subaccount-future-assets', + params, + ); +⋮---- +createSubaccountDepositAddress(params: { + subUid: string; + coin: string; + chain?: string; +}): Promise> +⋮---- +subaccountWithdrawal(params: SubWithdrawalRequestV2): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + return this.postPrivate( + '/api/v2/broker/account/subaccount-withdrawal', + params, + ); +⋮---- +subaccountSetAutoTransfer(params: { + subUid: string; + coin: string; + toAccountType: string; +}): Promise> +⋮---- +/** + * Sub Deposit Records + * + * - Only applicable for ND broker main-account to get ND sub-accounts deposit record */ - try { - const res = await wsClient.submitNewOrder('spot', { - orderType: 'limit', - price: '100', - qty: '0.1', - side: 'buy', - symbol: 'BTCUSDT', - timeInForce: 'gtc', - }); - - console.log(new Date(), 'WS API "submitNewOrder()" result: ', res); - } catch (e) { - console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e); - } -} - -start().catch((e) => console.error('Exception in example: '.e)); -``` - -###### Receiving realtime data - -Use the WebsocketClientV3 to receive data via the V3 WebSockets - -```typescript -import { WebsocketClientV3 } from "bitget-api"; -// or if you prefer require: -// const { WebsocketClientV3 } = require("bitget-api"); - -const API_KEY = "yourAPIKeyHere"; -const API_SECRET = "yourAPISecretHere; -const API_PASS = "yourAPIPassHere"; - -const wsClient = new WebsocketClientV3( - { - // Only necessary if you plan on using private/account websocket topics - apiKey: API_KEY, - apiSecret: API_SECRET, - apiPass: API_PASS, - } -); - -// Connect event handlers to process incoming events -wsClient.on('update', (data) => { - console.log('WS raw message received ', data); - // console.log('WS raw message received ', JSON.stringify(data, null, 2)); -}); - -wsClient.on('open', (data) => { - console.log('WS connection opened:', data.wsKey); -}); -wsClient.on('response', (data) => { - console.log('WS response: ', JSON.stringify(data, null, 2)); -}); -wsClient.on('reconnect', ({ wsKey }) => { - console.log('WS automatically reconnecting.... ', wsKey); -}); -wsClient.on('reconnected', (data) => { - console.log('WS reconnected ', data?.wsKey); -}); -wsClient.on('exception', (data) => { - console.log('WS error', data); -}); - +subaccountDepositRecords( + params: SubDepositRecordsRequestV2, +): Promise> +⋮---- +/** + * Sub Withdrawal Records + * + * - Only applicable for ND broker main-account + */ +subaccountWithdrawalRecords(params: SubWithdrawalRecordsRequestV2): Promise< + APIResponse<{ + resultList: BrokerSubaccountWithdrawalV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/broker/subaccount-withdrawal', params); +⋮---- +/** + * + * Broker | Api Key + * + */ +⋮---- +createSubaccountApiKey( + params: CreateSubAccountApiKeyRequestV2, +): Promise> +⋮---- +getSubaccountApiKey(params: { + subUid: string; +}): Promise> +⋮---- +modifySubaccountApiKey( + params: ModifySubAccountApiKeyRequestV2, +): Promise> +⋮---- +/** + * Get All Sub-accounts Deposit and Withdrawal Records + * + * - Only applicable for ND broker main-account + * - Rate limit: 5 req/sec/UID + * - Able to get ND sub-accounts deposit and withdrawal records within 90 days + */ +getAllSubDepositWithdrawalRecords( + params?: GetAllSubDepositWithdrawalRequestV2, + ): Promise< + APIResponse<{ + list: AllSubDepositWithdrawalRecordV2[]; + endId: string; + }> + > { + return this.getPrivate('/api/v2/broker/all-sub-deposit-withdrawal', params); +⋮---- +/** + * Get Broker Subaccounts + * + * - Rate limit: 5 req/sec/UID + * - Please contact your BD or RM to apply for access permissions + */ +getBrokerSubaccounts( + params?: GetBrokerSubaccountsRequestV2, +): Promise> +⋮---- +/** + * Get Broker Subaccounts Commissions + * + * - Rate limit: 5 req/sec/UID + * - Please contact your BD or RM to apply for access permissions + */ +getBrokerCommissions( + params?: GetBrokerCommissionsRequestV2, +): Promise> +⋮---- +/** + * Get Broker Trade Volume + * + * - Rate limit: 5 req/sec/UID + * - Please contact your BD or RM to apply for access permissions + */ +getBrokerTradeVolume( + params?: GetBrokerTradeVolumeRequestV2, +): Promise> +⋮---- +/** + * Get Total Commission + * + * - Rate limit: 20 req/sec/UID + * - Data retention: 365 days + * - Historical data available from: 2025/6/1 + * - Data granularity: daily + * - Data update granularity: daily, previous day's data is updated on the current day + * - Time zone: UTC+8 + * - startTime and endTime should either both be set or both left unset + * - This API supports retrieving data within the past 365 days (data is available starting from 2025/6/1 at the earliest) + * - If startTime and endTime are not set in the request, the default returned information will be for yesterday (00:00-23:59 UTC+8) + * - Data update frequency: T+1 (UTC+8) + */ +getBrokerTotalCommission( + params?: GetBrokerTotalCommissionRequestV2, +): Promise> +⋮---- +/** + * Get Order Commission + * + * - Rate limit: 20 req/sec/UID + * - Data storage: 30 days + * - Historical data backtracking: 2025/9/1 + * - Data granularity: daily + * - Data update frequency: daily, previous day's data is updated on the current day + * - Time zone: UTC+8 + * - startTime and endTime should either both be set or both not set + * - The maximum time span supported for startTime and endTime is 30 days + * - This API supports retrieving data within the past 30 days + * - If startTime and endTime are not set in the request, the default return will be information for yesterday (00:00-23:59 UTC+8) + * - This API data is updated on a T+1 basis + * - Transaction details only show those marked with broker channel id + */ +getBrokerOrderCommission( + params?: GetBrokerOrderCommissionRequestV2, +): Promise> +⋮---- /** - * Subscribe to topics as you wish - */ - -// You can subscribe to one topic at a time -wsClient.subscribe( - { - topic: 'account', - payload: { - instType: 'UTA', // Note: all account events go on the UTA instType - }, - }, - WS_KEY_MAP.v3Private, // This parameter points to private or public -); - -// Note: all account events go on the UTA instType -const ACCOUNT_INST_TYPE = 'UTA'; -const ACCOUNT_WS_KEY = WS_KEY_MAP.v3Private; - -// Or multiple at once: -wsClient.subscribe( - [ - { - topic: 'account', - payload: { - instType: ACCOUNT_INST_TYPE, - }, - }, - { - topic: 'position', - payload: { - instType: ACCOUNT_INST_TYPE, - }, - }, - { - topic: 'fill', - payload: { - instType: ACCOUNT_INST_TYPE, - }, - }, - { - topic: 'order', - payload: { - instType: ACCOUNT_INST_TYPE, - }, - }, - ], - ACCOUNT_WS_KEY, -); - -// Example public events -wsClient.subscribe( - [ - { - topic: 'ticker', - payload: { - instType: 'spot', - symbol: 'BTCUSDT', - }, - }, - { - topic: 'ticker', - payload: { - instType: 'spot', - symbol: 'ETHUSDT', - }, - }, - { - topic: 'ticker', - payload: { - instType: 'spot', - symbol: 'XRPUSDT', - }, + * Get Rebate Info + * + * - Rate limit: 20 req/sec/UID + * - Data retention: 30 days + * - Real-time data + */ +getBrokerRebateInfo( + params: GetBrokerRebateInfoRequestV2, +): Promise> +⋮---- +/** + * + * + * Margin + * + * + */ +⋮---- +/** + * + * * Margin | Common + * + */ +⋮---- +getMarginCurrencies(): Promise> +⋮---- +/** + * + * * Margin | Cross/Isolated | Order Record + * + */ +⋮---- +getMarginBorrowHistory( + marginType: MarginType, + params: GetBorrowHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginBorrowHistoryItemV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginRepayHistory( + marginType: MarginType, + params: GetRepayHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginRepaymentHistoryItemV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginInterestHistory( + marginType: MarginType, + params: GetInterestHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginInterestHistoryItemV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginLiquidationHistory( + marginType: MarginType, + params: GetLiquidationHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginLiquidationHistoryItemV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginFinancialHistory( + marginType: MarginType, + params: GetFinancialHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginFinancialHistoryItemV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +/** + * + * * Margin | Cross/Isolated | Account + * + */ +⋮---- +getMarginAccountAssets( + marginType: MarginType, + params?: { coin?: string }, +): Promise> +⋮---- +marginBorrow( + marginType: MarginType, + params: { + loanId: string; + symbol: string; + coin: string; + borrowAmount: string; }, - { - topic: 'ticker', - payload: { - instType: 'usdt-futures', - symbol: 'BTCUSDT', - }, + ): Promise< + APIResponse<{ + loanId: string; + symbol: string; + coin: string; + borrowAmount: string; + }> + > { + assertMarginType(marginType); +⋮---- +marginRepay( + marginType: MarginType, + params: { + remainDebtAmount: string; + symbol: string; + repayId: string; + coin: string; + repayAmount: string; }, - { - topic: 'ticker', - payload: { - instType: 'usdt-futures', - symbol: 'BTCUSDT', - }, + ): Promise< + APIResponse<{ + symbol: string; + coin: string; + repayId: string; + remainDebtAmount: string; + repayAmount: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginRiskRate(marginType: MarginType): Promise< + APIResponse< + { + symbol: string; + riskRateRatio: string; + }[] + > + > { + assertMarginType(marginType); +⋮---- +getMarginMaxBorrowable( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse + > { + assertMarginType(marginType); +⋮---- +getMarginMaxTransferable( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse< + CrossMaxTransferableResponseV2 | IsolatedMaxTransferableResponseV2 + > + > { + assertMarginType(marginType); +⋮---- +getMarginInterestRateAndMaxBorrowable( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse< + | IsolatedInterestRateAndLimitResponseV2[] + | CrossInterestRateAndLimitResponseV2[] + > + > { + assertMarginType(marginType); +⋮---- +getMarginTierConfiguration( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse< + CrossTierConfigurationResponseV2[] | IsolatedTierConfigurationResponseV2[] + > + > { + assertMarginType(marginType); +⋮---- +marginFlashRepay( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse<{ + repayId: string; + coin?: string; + symbol?: string; + result?: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginFlashRepayResult( + marginType: MarginType, + params: { idList: string }, + ): Promise< + APIResponse< + { + repayId: string; + status: string; + }[] + > + > { + assertMarginType(marginType); +⋮---- +/** + * + * * Margin | Cross/Isolated | Trade + * + */ +⋮---- +marginSubmitOrder( + marginType: MarginType, + params: MarginPlaceOrderRequestV2, + ): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + assertMarginType(marginType); +⋮---- +marginBatchSubmitOrders( + marginType: MarginType, + params: MarginBatchOrdersRequestV2, +): Promise> +⋮---- +marginCancelOrder( + marginType: MarginType, + params: { + symbol: string; + orderId?: string; + clientOid?: string; }, - ], - WS_KEY_MAP.v3Public, -); -``` - -For more examples, including how to use websockets with Bitget, check the [examples](./examples/) and [test](./test/) folders. - -### V2 WebSockets - -If you haven't upgraded to the Unified Trading Account, use the V2 WebSocket client: - -```javascript -import { WebsocketClientV2 } from 'bitget-api'; -// or if you prefer require: -// const { WebsocketClientV2 } = require('bitget-api'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; -const API_PASS = 'zzz'; - -const wsClient = new WebsocketClientV2({ - apiKey: API_KEY, - apiSecret: API_SECRET, - apiPass: API_PASS, - // Optional: connect to demo trading environment - // demoTrading: true, -}); - -// Handle incoming messages -wsClient.on('update', (data) => { - console.log('WS update received: ', data); -}); - -wsClient.on('open', (data) => { - console.log('WS connection opened: ', data.wsKey); -}); - -wsClient.on('reconnected', (data) => { - console.log('WS reconnected: ', data?.wsKey); -}); - -wsClient.on('exception', (data) => { - console.log('WS error: ', data); -}); - -// Subscribe to public data streams -wsClient.subscribeTopic('SPOT', 'ticker', symbol); - -// Subscribe to private data streams (requires authentication) -wsClient.subscribeTopic('SPOT', 'account'); -``` - ---- - -## Logging - -### Customise logging - -Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. - -```javascript -import { WebsocketClientV2, DefaultLogger } from 'bitget-api'; -// or if you prefer require: -// const { WebsocketClientV2, DefaultLogger } = require('bitget-api'); - -// Disable all logging on the trace level (less console logs) -const customLogger = { - ...DefaultLogger, - trace: () => {}, -}; - -const ws = new WebsocketClientV2( - { - apiKey: 'API_KEY', - apiSecret: 'API_SECRET', - apiPass: 'API_PASS', - }, - customLogger, -); -``` - -### Debug HTTP requests - -In rare situations, you may want to see the raw HTTP requets being built as well as the API response. These can be enabled by setting the `BITGETTRACE` env var to `true`. - -## Browser Usage - -### Import - -This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. - -1. Install these dependencies - ```sh - npm install crypto-browserify stream-browserify - ``` -2. Add this to your `tsconfig.json` - ```json - { - "compilerOptions": { - "paths": { - "crypto": [ - "./node_modules/crypto-browserify" - ], - "stream": [ - "./node_modules/stream-browserify" - ] - } - ``` -3. Declare this in the global context of your application (ex: in polyfills for angular) - ```js - (window as any).global = window; - ``` - -### Webpack - -This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. - -Build a bundle using webpack: - -- `npm install` -- `npm build` -- `npm pack` - -The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO - contributions welcome. - -## Use with LLMs & AI - -This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. - -This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. - ---- - -## Used By - -[![Repository Users Preview Image](https://dependents.info/tiagosiebler/bitget-api/image)](https://github.com/tiagosiebler/bitget-api/network/dependents) - ---- - - - -### Contributions & Thanks - -Have my projects helped you? Share the love, there are many ways you can show your thanks: - -- Star & share my projects. -- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler -- Have an interesting project? Get in touch & invite me to it. -- Or buy me all the coffee: - - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` - - - - -### Contributions & Pull Requests - -Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. - - - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) + ): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > { + assertMarginType(marginType); +⋮---- +marginBatchCancelOrders( + marginType: MarginType, + params: { + symbol: string; + orderIdList: string[]; + }, +): Promise> +⋮---- +getMarginOpenOrders( + marginType: MarginType, + params: GetMarginCurrentOrdersRequestV2, + ): Promise< + APIResponse<{ + orderList: MarginCurrentOrderV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginHistoricOrders( + marginType: MarginType, + params: GetHistoryOrdersRequestV2, + ): Promise< + APIResponse<{ + orderList: MarginHistoryOrderV2[]; + maxId: string; + minId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginHistoricOrderFills( + marginType: MarginType, + params: GetMarginOrderFillsRequestV2, + ): Promise< + APIResponse<{ + fills: MarginOrderFillV2[]; + minId: string; + maxId: string; + }> + > { + assertMarginType(marginType); +⋮---- +getMarginLiquidationOrders( + marginType: MarginType, + params: GetMarginLiquidationOrdersRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginLiquidationOrderV2[]; + idLessThan: string; + }> + > { + assertMarginType(marginType); +⋮---- +/** + * + * + * Copy Trading + * + * + */ +⋮---- +/** + * + * + * Copy Trading | Future copy trading | Trader Api + * + * + */ +⋮---- +getFuturesTraderCurrentOrder( + params: GetFuturesTraderCurrentOrdersRequestV2, +): Promise> +⋮---- +getFuturesTraderHistoryOrders( + params: GetFuturesTraderHistoryOrdersRequestV2, +): Promise> +⋮---- +modifyFuturesTraderOrderTPSL( + params: ModifyFuturesTraderOrderTPSLRequestV2, +): Promise> +⋮---- +getFuturesTraderOrder(): Promise< + APIResponse + > { + return this.getPrivate('/api/v2/copy/mix-trader/order-total-detail'); +⋮---- +getFuturesTraderProfitHistory(): Promise< + APIResponse + > { + return this.getPrivate('/api/v2/copy/mix-trader/profit-history-summarys'); +⋮---- +getFuturesTraderProfitShareHistory( + params: GetFuturesTraderProfitShareDetailRequestV2, +): Promise> +⋮---- +closeFuturesTraderOrder(params: { + trackingNo: string; + symbol: string; + productType: CopyTradingProductTypeV2; + }): Promise< + APIResponse< + { + trackingNo: string; + symbol: string; + productType: string; + }[] + > + > { + return this.postPrivate( + '/api/v2/copy/mix-trader/order-close-positions', + params, + ); +⋮---- +getFuturesTraderProfitShare(params?: { + coin?: string; + pageSize?: string; + pageNo?: string; + }): Promise< + APIResponse< + { + coin: string; + profit: string; + nickName: string; + }[] + > + > { + return this.getPrivate('/api/v2/copy/mix-trader/profit-details', params); +⋮---- +getFuturesTraderProfitShareGroup(params?: { + pageSize?: string; + pageNo?: string; + }): Promise< + APIResponse< + { + coin: string; + profit: string; + profitTime: string; + }[] + > + > { + return this.getPrivate( + '/api/v2/copy/mix-trader/profits-group-coin-date', + params, + ); +⋮---- +getFuturesTraderSymbolSettings(params: { + productType: CopyTradingProductTypeV2; +}): Promise> +⋮---- +updateFuturesTraderSymbolSettings(params: { + settingList: FuturesTraderSymbolSettingRequestV2[]; +}): Promise> +⋮---- +updateFuturesTraderGlobalSettings(params?: { + enable?: 'YES' | 'NO'; + showTotalEquity?: 'YES' | 'NO'; + showTpsl?: 'YES' | 'NO'; +}): Promise> +⋮---- +getFuturesTraderFollowers( + params?: GetFuturesTraderFollowersRequestV2, +): Promise> +⋮---- +removeFuturesTraderFollower(params: { + followerUid: string; +}): Promise> +⋮---- +/** + * + * + * Copy Trading | Future copy trading | Follower Api + * + * + */ +⋮---- +getFuturesFollowerCurrentOrders( + params: GetFollowerFuturesCurrentTrackingOrdersRequestV2, +): Promise> +⋮---- +getFuturesFollowerHistoryOrders( + params: GetFollowerFuturesHistoryTrackingOrdersRequestV2, +): Promise> +⋮---- +updateFuturesFollowerTPSL( + params: UpdateFuturesFollowerTPSLRequestV2, +): Promise> +⋮---- +updateFuturesFollowerSettings( + params: UpdateFuturesFollowerSettingsRequestV2, +): Promise> +⋮---- +getFuturesFollowerSettings(params: { + traderId: string; +}): Promise> +⋮---- +closeFuturesFollowerPositions( + params: CloseFuturesFollowerPositionsRequestV2, + ): Promise< + APIResponse<{ + orderIdList: string[]; + }> + > { + return this.postPrivate( + '/api/v2/copy/mix-follower/close-positions', + params, + ); +⋮---- +getFuturesFollowerTraders( + params: GetFuturesFollowerTradersRequestV2, +): Promise> +⋮---- +getFuturesFollowerFollowLimit(params: { + symbol: string; + productType: CopyTradingProductTypeV2; + }): Promise< + APIResponse< + { + maxFollowSize: string; + minFollowSize: string; + symbol: string; + }[] + > + > { + return this.getPrivate( + '/api/v2/copy/mix-follower/query-quantity-limit', + params, + ); +⋮---- +unfollowFuturesTrader(params: { + traderId: string; +}): Promise> +⋮---- +/** + * + * + * Copy Trading | Future copy trading | Broker api + * + * + */ +⋮---- +getBrokerTraders(params: object): Promise> +⋮---- +getBrokerTradersHistoricalOrders(params: object): Promise> +⋮---- +getBrokerTradersPendingOrders(params: object): Promise> +⋮---- +/** + * + * + * Copy Trading | Spot copy trading | Trader api + * + * + */ +⋮---- +getSpotTraderProfit(): Promise> +⋮---- +getSpotTraderHistoryProfit( + params: GetSpotTraderHistoryProfitRequestV2, +): Promise> +⋮---- +getSpotTraderUnrealizedProfit(params?: { + coin?: string; + pageNo?: string; + pageSize?: string; +}): Promise> +⋮---- +getSpotTraderOrder(): Promise> +⋮---- +modifySpotTraderOrderTPSL(params: { + trackingNo: string; + stopSurplusPrice?: string; + stopLossPrice?: string; +}): Promise> +⋮---- +getSpotTraderHistoryOrders( + params: GetSpotTraderHistoryOrdersRequestV2, +): Promise> +⋮---- +getSpotTraderCurrentOrders( + params: GetSpotTraderCurrentOrdersRequestV2, +): Promise> +⋮---- +sellSpotTrader(params: { + trackingNoList: string[]; + symbol: string; +}): Promise> +⋮---- +getSpotTraderSymbolSettings(params: { + symbolList: string[]; + settingType: 'add' | 'delete'; +}): Promise> +⋮---- +removeSpotTraderFollowers(params: { + followerUid: string; +}): Promise> +⋮---- +getSpotTraderConfiguration(): Promise> +⋮---- +getSpotTraderFollowers( + params: GetSpotTraderFollowersRequestV2, +): Promise> +⋮---- +/** + * + * + * Copy Trading | Spot copy trading | Follower api + * + * + */ +⋮---- +cancelSpotFollowerOrder(params: { + trackingNoList: string[]; +}): Promise> +⋮---- +updateSpotFollowerSettings(params: { + traderId: string; + autoCopy?: 'on' | 'off'; + mode?: 'basic' | 'advanced'; + settings: SpotFollowerCopyTradeSettingV2[]; +}): Promise> +⋮---- +updateSpotFollowerTPSL(params: { + trackingNo: string; + stopSurplusPrice?: string; + stopLossPrice?: string; +}): Promise> +⋮---- +getSpotFollowerTraders(params?: { + pageNo?: string; + pageSize?: string; + startTime?: string; + endTime?: string; +}): Promise> +⋮---- +getSpotFollowerCurrentTraderSymbols(params: { traderId: string }): Promise< + APIResponse<{ + currentTradingList: string[]; + }> + > { + return this.getPrivate( + '/api/v2/copy/spot-follower/query-trader-symbols', + params, + ); +⋮---- +getSpotFollowerSettings(params: { + traderId: string; +}): Promise> +⋮---- +getSpotFollowerHistoryOrders( + params: GetSpotFollowerHistoryOrdersRequestV2, +): Promise> +⋮---- +getSpotFollowerOpenOrders( + params: GetSpotFollowerOpenOrdersRequestV2, +): Promise> +⋮---- +sellSpotFollower(params: { + trackingNoList: string[]; + symbol: string; +}): Promise> +⋮---- +unfollowSpotTrader(params: { + traderId: string; +}): Promise> +⋮---- +/** + * + * + * Earn | Savings + * + * + */ +⋮---- +getEarnSavingsProducts(params?: { + coin?: string; + filter?: string; +}): Promise> +⋮---- +getEarnSavingsAccount(): Promise> +⋮---- +getEarnSavingsAssets( + params: GetEarnSavingsAssetsRequestV2, +): Promise> +⋮---- +getEarnSavingsRecords( + params: GetEarnSavingsRecordsRequestV2, +): Promise> +⋮---- +getEarnSavingsSubscription(params: { + productId: string; + periodType: string; +}): Promise> +⋮---- +earnSubscribeSavings(params: { + productId: string; + periodType: string; + amount: string; + }): Promise< + APIResponse<{ + orderId: string; + status: string; + }> + > { + return this.postPrivate('/api/v2/earn/savings/subscribe', params); +⋮---- +getEarnSavingsSubscriptionResult(params: { + productId: string; + periodType: string; + }): Promise< + APIResponse<{ + result: 'success' | 'fail'; + msg: string; + }> + > { + return this.getPrivate('/api/v2/earn/savings/subscribe-result', params); +⋮---- +earnRedeemSavings(params: RedeemSavingsRequestV2): Promise< + APIResponse<{ + orderId: string; + status: string; + }> + > { + return this.postPrivate('/api/v2/earn/savings/redeem', params); +⋮---- +getEarnSavingsRedemptionResult(params: { + orderId: string; + periodType: string; + }): Promise< + APIResponse<{ + result: 'success' | 'fail'; + msg: string; + }> + > { + return this.getPrivate('/api/v2/earn/savings/redeem-result', params); +⋮---- +/** + * + * + * Earn | Earn Account + * + * + */ +⋮---- +getEarnAccount(params?: { coin?: string }): Promise< + APIResponse< + { + coin: string; + amount: string; + }[] + > + > { + return this.getPrivate('/api/v2/earn/account/assets', params); +⋮---- +/** + * + * + * Earn | Shark Fin + * + * + */ +⋮---- +getSharkfinProducts(params: { + coin: string; + limit?: string; + idLessThan?: string; +}): Promise> +⋮---- +getSharkfinAccount(): Promise> +⋮---- +getSharkfinAssets( + params: GetSharkfinAssetsRequestV2, +): Promise> +⋮---- +getSharkfinRecords( + params: GetSharkfinRecordsRequestV2, +): Promise> +⋮---- +getSharkfinSubscription(params: { + productId: string; +}): Promise> +⋮---- +subscribeSharkfin(params: { productId: string; amount: string }): Promise< + APIResponse<{ + orderId: string; + status: string; + }> + > { + return this.postPrivate('/api/v2/earn/sharkfin/subscribe', params); +⋮---- +getSharkfinSubscriptionResult(params: { orderId: string }): Promise< + APIResponse<{ + result: 'success' | 'fail'; + msg: string; + }> + > { + return this.getPrivate('/api/v2/earn/sharkfin/subscribe-result', params); +⋮---- +/** + * + * + * Earn | Loan + * + * + */ +⋮---- +getLoanCurrencies(params?: { + coin?: string; +}): Promise> +⋮---- +getLoanEstInterestAndBorrowable( + params: GetLoanEstInterestAndBorrowableRequestV2, + ): Promise< + APIResponse<{ + hourInterest: string; + loanAmount: string; + }> + > { + return this.get('/api/v2/earn/loan/public/hour-interest', params); +⋮---- +borrowLoan(params: BorrowLoanRequestV2): Promise< + APIResponse<{ + orderId: string; + }> + > { + return this.postPrivate('/api/v2/earn/loan/borrow', params); +⋮---- +getOngoingLoanOrders(params?: { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; +}): Promise> +⋮---- +repayLoan( + params: RepayLoanRequestV2, +): Promise> +⋮---- +getRepayHistory( + params: GetLoanRepayHistoryRequestV2, +): Promise> +⋮---- +updateLoanPledgeRate(params: ModifyLoanPledgeRateRequestV2): Promise< + APIResponse<{ + loanCoin: string; + pledgeCoin: string; + afterPledgeRate: string; + }> + > { + return this.postPrivate('/api/v2/earn/loan/revise-pledge', params); +⋮---- +getLoanPledgeRateHistory( + params: GetLoanPledgeRateHistoryRequestV2, +): Promise> +⋮---- +getLoanHistory( + params: GetLoanHistoryRequestV2, +): Promise> +⋮---- +getLoanDebts(): Promise> +⋮---- +getLoanLiquidationRecords( + params: GetLiquidationRecordsRequestV2, +): Promise> - +================ +File: src/rest-client-v3.ts +================ +import { + CreateSubAccountApiKeyRequestV3, + CreateSubAccountRequestV3, + DeleteSubAccountApiKeyRequestV3, + FreezeSubAccountRequestV3, + GetConvertRecordsRequestV3, + GetDepositAddressRequestV3, + GetDepositRecordsRequestV3, + GetFeeRateRequestV3, + GetFinancialRecordsRequestV3, + GetFundingAssetsRequestV3, + GetMaxTransferableRequestV3, + GetOpenInterestLimitRequestV3, + GetSubAccountApiKeysRequestV3, + GetSubAccountListRequestV3, + GetSubDepositAddressRequestV3, + GetSubDepositRecordsRequestV3, + GetSubTransferRecordsRequestV3, + GetSubUnifiedAssetsRequestV3, + GetTaxRecordsRequestV3, + GetTransferableCoinsRequestV3, + GetWithdrawRecordsRequestV3, + RepayRequestV3, + SetDepositAccountRequestV3, + SetLeverageRequestV3, + SubAccountTransferRequestV3, + SwitchDeductRequestV3, + TransferRequestV3, + UpdateSubAccountApiKeyRequestV3, + WithdrawRequestV3, +} from './types/request/v3/account.js'; +import { + BrokerSubWithdrawalRequestV3, + CreateBrokerSubAccountRequestV3, + CreateBrokerSubApiKeyRequestV3, + DeleteBrokerSubApiKeyRequestV3, + GetBrokerAllSubDepositWithdrawalRequestV3, + GetBrokerCommissionRequestV3, + GetBrokerSubAccountListRequestV3, + GetBrokerSubApiKeyRequestV3, + GetBrokerSubDepositAddressRequestV3, + ModifyBrokerSubAccountRequestV3, + ModifyBrokerSubApiKeyRequestV3, +} from './types/request/v3/broker.js'; +import { + BindUidRequestV3, + GetEnsureCoinsRequestV3, + GetLoanOrderRequestV3, + GetLTVConvertRequestV3, + GetProductInfosRequestV3, + GetRepaidHistoryRequestV3, + GetSymbolsRequestV3, + GetTransferedRequestV3, +} from './types/request/v3/loan.js'; +import { + GetCandlesRequestV3, + GetContractsOiRequestV3, + GetCurrentFundingRateRequestV3, + GetHistoryCandlesRequestV3, + GetHistoryFundingRateRequestV3, + GetIndexComponentsRequestV3, + GetInstrumentsRequestV3, + GetMarginLoansRequestV3, + GetOpenInterestRequestV3, + GetOrderBookRequestV3, + GetPositionTierRequestV3, + GetPublicFillsRequestV3, + GetRiskReserveRequestV3, + GetTickersRequestV3, +} from './types/request/v3/public.js'; +import { + CancelStrategyOrderRequestV3, + GetHistoryStrategyOrdersRequestV3, + GetUnfilledStrategyOrdersRequestV3, + ModifyStrategyOrderRequestV3, + PlaceStrategyOrderRequestV3, +} from './types/request/v3/strategy.js'; +import { + BatchModifyOrderRequestV3, + CancelAllOrdersRequestV3, + CancelBatchOrdersRequestV3, + CancelOrderRequestV3, + CloseAllPositionsRequestV3, + CountdownCancelAllRequestV3, + GetCurrentPositionRequestV3, + GetFillsRequestV3, + GetHistoryOrdersRequestV3, + GetMaxOpenAvailableRequestV3, + GetOrderInfoRequestV3, + GetPositionHistoryRequestV3, + GetUnfilledOrdersRequestV3, + ModifyOrderRequestV3, + PlaceBatchOrdersRequestV3, + PlaceOrderRequestV3, +} from './types/request/v3/trade.js'; +import { + AccountAssetsV3, + AccountSettingsV3, + ConvertRecordV3, + CreateSubAccountApiKeyResponseV3, + CreateSubAccountResponseV3, + DepositAddressV3, + DepositRecordV3, + FinancialRecordV3, + FundingAssetV3, + MaxTransferableV3, + OpenInterestLimitV3, + PaymentCoinV3, + RepayableCoinV3, + RepayResponseV3, + SubAccountApiKeyV3, + SubAccountV3, + SubTransferRecordV3, + SubUnifiedAssetV3, + TaxRecordV3, + TransferResponseV3, + UpdateSubAccountApiKeyResponseV3, + WithdrawRecordV3, + WithdrawResponseV3, +} from './types/response/v3/account.js'; +import { + BrokerCommissionRecordV3, + BrokerSubDepositAddressV3, + BrokerSubWithdrawalResponseV3, + CreateBrokerSubAccountResponseV3, + CreateBrokerSubApiKeyResponseV3, + GetBrokerAllSubDepositWithdrawalResponseV3, + GetBrokerSubAccountListResponseV3, + GetBrokerSubApiKeyResponseV3, + ModifyBrokerSubAccountResponseV3, + ModifyBrokerSubApiKeyResponseV3, +} from './types/response/v3/broker.js'; +import { + BindUidResponseV3, + CoinInfoV3, + LoanOrderV3, + LoanProductInfoV3, + LoanSymbolsV3, + LoanTransfersV3, + LTVConvertResponseV3, + RepaidHistoryItemV3, +} from './types/response/v3/loan.js'; +import { + CandlestickV3, + ContractOiV3, + CurrentFundingRateV3, + DiscountRateV3, + HistoryFundingRateV3, + IndexPriceComponentsV3, + InstrumentV3, + MarginLoanV3, + OpenInterestV3, + OrderBookV3, + PositionTierV3, + ProofOfReservesV3, + PublicFillV3, + RiskReserveV3, + TickerV3, +} from './types/response/v3/public.js'; +import { + ModifyStrategyOrderResponseV3, + PlaceStrategyOrderResponseV3, + StrategyOrderV3, +} from './types/response/v3/strategy.js'; +import { + BatchModifyOrderResponseV3, + CancelAllOrdersResponseV3, + CancelBatchOrdersResponseV3, + CancelOrderResponseV3, + CloseAllPositionsResponseV3, + CurrentPositionV3, + FillV3, + GetMaxOpenAvailableResponseV3, + HistoryOrderV3, + ModifyOrderResponseV3, + OrderInfoV3, + PlaceBatchOrdersResponseV3, + PlaceOrderResponseV3, + PositionAdlRankV3, + PositionHistoryV3, + UnfilledOrderV3, +} from './types/response/v3/trade.js'; +import { APIResponse } from './types/shared.js'; +import BaseRestClient from './util/BaseRestClient.js'; +import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; +⋮---- +/** + * REST API client for all V3 endpoints + */ +export class RestClientV3 extends BaseRestClient +⋮---- +getClientType() +⋮---- +/** + * + * Custom SDK functions + * + */ +⋮---- +/** + * 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 +⋮---- +// Adjust server time by adding estimated one-way latency +⋮---- +// Calculate time difference between adjusted server time and local time +⋮---- +async fetchServerTime(): Promise +⋮---- +/** + * + * Public endpoints + * + */ +⋮---- +getServerTime(): Promise< + APIResponse<{ + serverTime: string; + }> + > { + return this.get('/api/v3/public/time'); +⋮---- +/** + * + * =====Market======= endpoints + * + */ +⋮---- +/** + * Get Instruments + */ +getInstruments( + params: GetInstrumentsRequestV3, +): Promise> +⋮---- +/** + * Get Tickers + */ +getTickers(params: GetTickersRequestV3): Promise> +⋮---- +/** + * Get OrderBook + */ +getOrderBook( + params: GetOrderBookRequestV3, +): Promise> +⋮---- +/** + * Get Recent Public Fills + */ +getFills( + params: GetPublicFillsRequestV3, +): Promise> +⋮---- +/** + * Get Proof Of Reserves + */ +getProofOfReserves(): Promise> +⋮---- +/** + * Get Open Interest + */ +getOpenInterest( + params: GetOpenInterestRequestV3, +): Promise> +⋮---- +/** + * Get Kline/Candlestick + * Maximum number of returned entries: 1,000 + */ +getCandles( + params: GetCandlesRequestV3, +): Promise> +⋮---- +/** + * Get Kline/Candlestick History + */ +getHistoryCandles( + params: GetHistoryCandlesRequestV3, +): Promise> +⋮---- +/** + * Get Current Funding Rate + */ +getCurrentFundingRate( + params: GetCurrentFundingRateRequestV3, +): Promise> +⋮---- +/** + * Get Funding Rate History + */ +getHistoryFundingRate( + params: GetHistoryFundingRateRequestV3, +): Promise> +⋮---- +/** + * Get Risk Reserve + */ +getRiskReserve( + params: GetRiskReserveRequestV3, +): Promise> +⋮---- +/** + * Get Discount Rate + */ +getDiscountRate(): Promise> +⋮---- +/** + * Get Margin Loan + */ +getMarginLoans( + params: GetMarginLoansRequestV3, +): Promise> +⋮---- +/** + * Get Position Tier + */ +getPositionTier( + params: GetPositionTierRequestV3, +): Promise> +⋮---- +/** + * Get Open Interest Limit + */ +getContractsOi( + params: GetContractsOiRequestV3, +): Promise> +⋮---- +/** + * Get Index Price Components + */ +getIndexComponents( + params: GetIndexComponentsRequestV3, +): Promise> +⋮---- +/** + * + * =====Account======= endpoints + * + */ +⋮---- +/** + * Get Account Assets + */ +getBalances(): Promise> +⋮---- +/** + * Get Fund Account Assets + */ +getFundingAssets( + params?: GetFundingAssetsRequestV3, +): Promise> +⋮---- +/** + * Get Account Info + */ +getAccountSettings(): Promise> +⋮---- +/** + * Set Leverage + */ +setLeverage(params: SetLeverageRequestV3): Promise> +⋮---- +/** + * Set Holding Mode + */ +setHoldMode(params: { + holdMode: 'one_way_mode' | 'hedge_mode'; +}): Promise> +⋮---- +/** + * Get Financial Records + */ +getFinancialRecords(params: GetFinancialRecordsRequestV3): Promise< + APIResponse<{ + list: FinancialRecordV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/account/financial-records', params); +⋮---- +/** + * Get Repayable Coins + */ +getRepayableCoins(): Promise< + APIResponse<{ + repayableCoinList: RepayableCoinV3[]; + maxSelection: string; + }> + > { + return this.getPrivate('/api/v3/account/repayable-coins'); +⋮---- +/** + * Get Payment Coins + */ +getPaymentCoins(): Promise< + APIResponse<{ + paymentCoinList: PaymentCoinV3[]; + maxSelection: string; + }> + > { + return this.getPrivate('/api/v3/account/payment-coins'); +⋮---- +/** + * Repay + */ +submitRepay(params: RepayRequestV3): Promise> +⋮---- +/** + * Get Convert Records + */ +getConvertRecords(params: GetConvertRecordsRequestV3): Promise< + APIResponse<{ + list: ConvertRecordV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/account/convert-records', params); +⋮---- +/** + * Set up deposit account - Configure default recharge account for a certain symbol + * This configuration item remains valid for a long time. That is, once a user sets a default + * recharge account for a certain symbol, it will be retained permanently, and there is no need to reconfigure it. + * Permission: UTA mgt. (read & write) + */ +setDepositAccount( + params: SetDepositAccountRequestV3, +): Promise> +⋮---- +/** + * Switch Deduct - Set BGB deduction + */ +switchDeduct(params: SwitchDeductRequestV3): Promise> +⋮---- +/** + * Get Deduct Info - Get BGB deduction status + */ +getDeductInfo(): Promise< + APIResponse<{ + deduct: 'on' | 'off'; + }> + > { + return this.getPrivate('/api/v3/account/deduct-info'); +⋮---- +/** + * Get Trading Fee Rate + */ +getFeeRate(params: GetFeeRateRequestV3): Promise< + APIResponse<{ + makerFeeRate: string; + takerFeeRate: string; + }> + > { + return this.getPrivate('/api/v3/account/fee-rate', params); +⋮---- +/** + * Get Max Transferable + * + * - Rate limit: 3 req/sec/UID + * - Permission: UTA mgt. (read) + * - Get the maximum transferable amount for the unified account. + */ +getMaxTransferable( + params: GetMaxTransferableRequestV3, +): Promise> +⋮---- +/** + * Get Open Interest Limit + * + * - Rate limit: 5/sec/UID + * - Get open interest limit for a symbol + */ +getOpenInterestLimit( + params: GetOpenInterestLimitRequestV3, +): Promise> +⋮---- +/** + * Switch Account - Switch to classic account mode + * Only supports parent accounts. + * This endpoint is only used for switching to classic account mode. + * Please note that since the account switching process takes approximately 1 minute, + * the successful response you receive only indicates that the request has been received, + * and does not mean that the account has been successfully switched to the classic account. + * Please use the query switching status interface to confirm whether the account switching is successful. + */ +downgradeAccountToClassic(): Promise> +⋮---- +/** + * Get Switch Status - Get account switching status + * Only supports parent accounts. + */ +getUnifiedAccountSwitchStatus(): Promise< + APIResponse<{ + status: 'processProcessing' | 'successSuccess' | 'failFailed'; + }> + > { + return this.getPrivate('/api/v3/account/switch-status'); +⋮---- +/** + * Get Tax Records + * + * - Rate limit: 1/sec/UID + * - Data query range: 366 days + * - Please use the tax API Key to request Creation Portal + * - Get Unified Account Tax Records + */ +getTaxRecords( + params: GetTaxRecordsRequestV3, +): Promise> +⋮---- +/** + * + * =====SubAccount======= endpoints + * + */ +⋮---- +/** + * Create Sub-account + */ +createSubAccount( + params: CreateSubAccountRequestV3, +): Promise> +⋮---- +/** + * Freeze/Unfreeze Sub-account + */ +freezeSubAccount( + params: FreezeSubAccountRequestV3, +): Promise> +⋮---- +/** + * Get Sub-account Unified Account Assets + */ +getSubUnifiedAssets( + params?: GetSubUnifiedAssetsRequestV3, +): Promise> +⋮---- +/** + * Get Sub-account List + */ +getSubAccountList(params?: GetSubAccountListRequestV3): Promise< + APIResponse<{ + list: SubAccountV3[]; + hasNext: boolean; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/user/sub-list', params); +⋮---- +/** + * Create Sub-account API Key + */ +createSubAccountApiKey( + params: CreateSubAccountApiKeyRequestV3, +): Promise> +⋮---- +/** + * Modify Sub-account API Key + */ +updateSubAccountApiKey( + params: UpdateSubAccountApiKeyRequestV3, +): Promise> +⋮---- +/** + * Delete Sub-account API Key + */ +deleteSubAccountApiKey( + params: DeleteSubAccountApiKeyRequestV3, +): Promise> +⋮---- +/** + * Get Sub-account API Keys + */ +getSubAccountApiKeys(params: GetSubAccountApiKeysRequestV3): Promise< + APIResponse<{ + items: SubAccountApiKeyV3[]; + hasNext: boolean; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/user/sub-api-list', params); +⋮---- +/** + * + * =====Transfer======= endpoints + * + */ +⋮---- +/** + * Get Transferable Coins + */ +getTransferableCoins( + params: GetTransferableCoinsRequestV3, +): Promise> +⋮---- +/** + * Transfer + */ +submitTransfer( + params: TransferRequestV3, +): Promise> +⋮---- +/** + * Main-Sub Account Transfer + */ +subAccountTransfer(params: SubAccountTransferRequestV3): Promise< + APIResponse<{ + transferId: string; + clientOid: string; + }> + > { + return this.postPrivate('/api/v3/account/sub-transfer', params); +⋮---- +/** + * Get Main-Sub Transfer Records + */ +getSubTransferRecords(params?: GetSubTransferRecordsRequestV3): Promise< + APIResponse<{ + items: SubTransferRecordV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/account/sub-transfer-record', params); +⋮---- +/** + * + * =====Deposit======= endpoints + * + */ +⋮---- +/** + * Get Deposit Address + */ +getDepositAddress( + params: GetDepositAddressRequestV3, +): Promise> +⋮---- +/** + * Get Sub Deposit Address + */ +getSubDepositAddress( + params: GetSubDepositAddressRequestV3, +): Promise> +⋮---- +/** + * Get Deposit Records + */ +getDepositRecords( + params: GetDepositRecordsRequestV3, +): Promise> +⋮---- +/** + * Get Sub Deposit Records + */ +getSubDepositRecords( + params: GetSubDepositRecordsRequestV3, +): Promise> +⋮---- +/** + * + * =====Withdraw======= endpoints + * + */ +⋮---- +/** + * Withdraw - Includes on-chain withdrawals and internal transfers + */ +submitWithdraw( + params: WithdrawRequestV3, +): Promise> +⋮---- +/** + * Get Withdraw Records + */ +getWithdrawRecords( + params: GetWithdrawRecordsRequestV3, +): Promise> +⋮---- +/** + * + * =====Trade======= endpoints + * + */ +⋮---- +/** + * Place Order + */ +submitNewOrder( + params: PlaceOrderRequestV3, +): Promise> +⋮---- +/** + * Modify Order + */ +modifyOrder( + params: ModifyOrderRequestV3, +): Promise> +⋮---- +/** + * Cancel Order + */ +cancelOrder( + params: CancelOrderRequestV3, +): Promise> +⋮---- +/** + * Batch Order + */ +placeBatchOrders( + params: PlaceBatchOrdersRequestV3[], +): Promise> +⋮---- +/** + * Batch Modify Orders + */ +batchModifyOrders( + params: BatchModifyOrderRequestV3[], +): Promise> +⋮---- +/** + * Batch Cancel + */ +cancelBatchOrders( + params: CancelBatchOrdersRequestV3[], +): Promise> +⋮---- +/** + * Cancel All Orders + */ +cancelAllOrders( + params: CancelAllOrdersRequestV3, +): Promise> +⋮---- +/** + * Close All Positions + */ +closeAllPositions( + params: CloseAllPositionsRequestV3, +): Promise> +⋮---- +/** + * Get Order Details + */ +getOrderInfo( + params: GetOrderInfoRequestV3, +): Promise> +⋮---- +/** + * Get Open Orders + */ +getUnfilledOrders(params?: GetUnfilledOrdersRequestV3): Promise< + APIResponse<{ + list: UnfilledOrderV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/trade/unfilled-orders', params); +⋮---- +/** + * Get Order History + */ +getHistoryOrders(params: GetHistoryOrdersRequestV3): Promise< + APIResponse<{ + list: HistoryOrderV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/trade/history-orders', params); +⋮---- +/** + * Get Fill History + */ +getTradeFills(params?: GetFillsRequestV3): Promise< + APIResponse<{ + list: FillV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/trade/fills', params); +⋮---- +/** + * Get Position Info + */ +getCurrentPosition(params: GetCurrentPositionRequestV3): Promise< + APIResponse<{ + list: CurrentPositionV3[]; + }> + > { + return this.getPrivate('/api/v3/position/current-position', params); +⋮---- +/** + * Get Positions History + */ +getPositionHistory(params: GetPositionHistoryRequestV3): Promise< + APIResponse<{ + list: PositionHistoryV3[]; + cursor: string; + }> + > { + return this.getPrivate('/api/v3/position/history-position', params); +⋮---- +/** + * Get Max Open Available + */ +getMaxOpenAvailable( + params: GetMaxOpenAvailableRequestV3, +): Promise> +⋮---- +/** + * Get Position ADL Rank - Get position auto-deleveraging ranking + */ +getPositionAdlRank(): Promise> +⋮---- +/** + * CountDown Cancel All + */ +countdownCancelAll( + params: CountdownCancelAllRequestV3, +): Promise> +⋮---- +/** + * + * =====Inst Loan======= endpoints + * + */ +⋮---- +/** + * Get Transferred Quantity + */ +getLoanTransfered( + params: GetTransferedRequestV3, +): Promise> +⋮---- +/** + * Get Trade Symbols + */ +getLoanSymbols( + params: GetSymbolsRequestV3, +): Promise> +⋮---- +/** + * Get Risk Unit + */ +getLoanRiskUnit(): Promise< + APIResponse<{ + riskUnitId: string[]; + }> + > { + return this.getPrivate('/api/v3/ins-loan/risk-unit'); +⋮---- +/** + * Get Repayment Orders + */ +getLoanRepaidHistory( + params?: GetRepaidHistoryRequestV3, +): Promise> +⋮---- +/** + * Get Product Info + */ +getLoanProductInfo( + params: GetProductInfosRequestV3, +): Promise> +⋮---- +/** + * Get Loan Orders + */ +getLoanOrder( + params?: GetLoanOrderRequestV3, +): Promise> +⋮---- +/** + * Get LTV + */ +getLoanLTVConvert( + params?: GetLTVConvertRequestV3, +): Promise> +⋮---- +/** + * Get Margin Coin Info + */ +getLoanMarginCoinInfo(params: GetEnsureCoinsRequestV3): Promise< + APIResponse<{ + productId: string; + coinInfo: CoinInfoV3[]; + }> + > { + return this.getPrivate('/api/v3/ins-loan/ensure-coins-convert', params); +⋮---- +/** + * Bind/Unbind UID to Risk Unit + */ +bindLoanUid( + params: BindUidRequestV3, +): Promise> +⋮---- +/** + * + * =====Strategy======= endpoints + * + */ +⋮---- +/** + * Place Strategy Order + */ +submitStrategyOrder( + params: PlaceStrategyOrderRequestV3, +): Promise> +⋮---- +/** + * Modify Strategy Order + */ +modifyStrategyOrder( + params: ModifyStrategyOrderRequestV3, +): Promise> +⋮---- +/** + * Cancel Strategy Order + */ +cancelStrategyOrder( + params: CancelStrategyOrderRequestV3, +): Promise> +⋮---- +/** + * Get Unfilled Strategy Orders + */ +getUnfilledStrategyOrders( + params: GetUnfilledStrategyOrdersRequestV3, +): Promise> +⋮---- +/** + * Get Strategy Order History + */ +getHistoryStrategyOrders(params: GetHistoryStrategyOrdersRequestV3): Promise< + APIResponse<{ + list: StrategyOrderV3[]; + cursor?: string; + }> + > { + return this.getPrivate('/api/v3/trade/history-strategy-orders', params); +⋮---- +/** + * + * =====Broker======= endpoints + * + */ +⋮---- +/** + * Create Broker Sub-Account + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +createBrokerSubAccount( + params: CreateBrokerSubAccountRequestV3, +): Promise> +⋮---- +/** + * Get Broker Sub-Account List + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +getBrokerSubAccountList( + params?: GetBrokerSubAccountListRequestV3, +): Promise> +⋮---- +/** + * Modify Broker Sub-Account + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +modifyBrokerSubAccount( + params: ModifyBrokerSubAccountRequestV3, +): Promise> +⋮---- +/** + * Broker Subaccount Withdrawal + * + * Broker sub-account withdrawal API has restrictions and currently supports only the following currencies: + * BTC, ETH, USDT, USDC, TRX, XRP, LTC, SOL, BNB, FTM, DOGE, ADA, SHIB, UNI, SEI, SUI, POL, FIL, LINK, TON, ARB, OP, DOT, AVAX + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +brokerSubWithdrawal( + params: BrokerSubWithdrawalRequestV3, +): Promise> +⋮---- +/** + * Get Broker Subaccount Deposit Address + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +getBrokerSubDepositAddress( + params: GetBrokerSubDepositAddressRequestV3, +): Promise> +⋮---- +/** + * Get All Broker Subaccount Deposit Withdrawal + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +getBrokerAllSubDepositWithdrawal( + params?: GetBrokerAllSubDepositWithdrawalRequestV3, +): Promise> +⋮---- +/** + * Get Broker Commission + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +getBrokerCommission( + params?: GetBrokerCommissionRequestV3, +): Promise> +⋮---- +/** + * Create Broker Sub-Account API Key + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +createBrokerSubApiKey( + params: CreateBrokerSubApiKeyRequestV3, +): Promise> +⋮---- +/** + * Modify Broker Sub-Account API Key + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +modifyBrokerSubApiKey( + params: ModifyBrokerSubApiKeyRequestV3, +): Promise> +⋮---- +/** + * Delete Broker Subaccount Apikey + * + * This endpoint has no response parameters. + * It returns the deletion result synchronously. + * Determine whether the deletion succeeded or failed (and the failure reason) based on the returned code and msg. + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +deleteBrokerSubApiKey( + params: DeleteBrokerSubApiKeyRequestV3, +): Promise> +⋮---- +/** + * Get Broker Sub-Account API Key + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ +getBrokerSubApiKey( + params: GetBrokerSubApiKeyRequestV3, +): Promise> ================ File: package.json ================ { "name": "bitget-api", - "version": "3.0.11", + "version": "3.1.2", "description": "Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.", "scripts": { "test": "jest", @@ -15087,7 +13405,7 @@ File: package.json "build": "npm run clean && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", "build:clean": "npm run clean && npm run build", "build:watch": "npm run clean && tsc --watch", - "pack": "webpack --config webpack/webpack.config.js", + "pack": "webpack --config webpack/webpack.config.cjs", "lint": "eslint src", "prepublish": "npm run build:clean", "betapublish": "npm publish --tag beta" @@ -15110,7 +13428,7 @@ File: package.json "author": "Tiago Siebler (https://github.com/tiagosiebler)", "contributors": [], "dependencies": { - "axios": "^1.12.2", + "axios": "^1.13.2", "isomorphic-ws": "^5.0.0", "ws": "^8.18.3" }, @@ -15132,8 +13450,9 @@ File: package.json }, "optionalDependencies": { "source-map-loader": "^4.0.0", - "ts-loader": "^9.4.1", + "ts-loader": "^9.5.4", "webpack": "^5.74.0", + "webpack-bundle-analyzer": "^5.1.1", "webpack-cli": "^4.10.0" }, "keywords": [ diff --git a/package-lock.json b/package-lock.json index ead0c08..1aff0bb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bitget-api", - "version": "3.1.1", + "version": "3.1.2", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "bitget-api", - "version": "3.1.1", + "version": "3.1.2", "license": "MIT", "dependencies": { "axios": "^1.13.2", diff --git a/package.json b/package.json index 67d1506..0d6aefb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bitget-api", - "version": "3.1.1", + "version": "3.1.2", "description": "Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.", "scripts": { "test": "jest", diff --git a/src/rest-client-v3.ts b/src/rest-client-v3.ts index 176a196..39881c1 100644 --- a/src/rest-client-v3.ts +++ b/src/rest-client-v3.ts @@ -29,6 +29,19 @@ import { UpdateSubAccountApiKeyRequestV3, WithdrawRequestV3, } from './types/request/v3/account.js'; +import { + BrokerSubWithdrawalRequestV3, + CreateBrokerSubAccountRequestV3, + CreateBrokerSubApiKeyRequestV3, + DeleteBrokerSubApiKeyRequestV3, + GetBrokerAllSubDepositWithdrawalRequestV3, + GetBrokerCommissionRequestV3, + GetBrokerSubAccountListRequestV3, + GetBrokerSubApiKeyRequestV3, + GetBrokerSubDepositAddressRequestV3, + ModifyBrokerSubAccountRequestV3, + ModifyBrokerSubApiKeyRequestV3, +} from './types/request/v3/broker.js'; import { BindUidRequestV3, GetEnsureCoinsRequestV3, @@ -45,6 +58,7 @@ import { GetCurrentFundingRateRequestV3, GetHistoryCandlesRequestV3, GetHistoryFundingRateRequestV3, + GetIndexComponentsRequestV3, GetInstrumentsRequestV3, GetMarginLoansRequestV3, GetOpenInterestRequestV3, @@ -104,6 +118,18 @@ import { WithdrawRecordV3, WithdrawResponseV3, } from './types/response/v3/account.js'; +import { + BrokerCommissionRecordV3, + BrokerSubDepositAddressV3, + BrokerSubWithdrawalResponseV3, + CreateBrokerSubAccountResponseV3, + CreateBrokerSubApiKeyResponseV3, + GetBrokerAllSubDepositWithdrawalResponseV3, + GetBrokerSubAccountListResponseV3, + GetBrokerSubApiKeyResponseV3, + ModifyBrokerSubAccountResponseV3, + ModifyBrokerSubApiKeyResponseV3, +} from './types/response/v3/broker.js'; import { BindUidResponseV3, CoinInfoV3, @@ -120,6 +146,7 @@ import { CurrentFundingRateV3, DiscountRateV3, HistoryFundingRateV3, + IndexPriceComponentsV3, InstrumentV3, MarginLoanV3, OpenInterestV3, @@ -383,6 +410,15 @@ export class RestClientV3 extends BaseRestClient { return this.get('/api/v3/market/oi-limit', params); } + /** + * Get Index Price Components + */ + getIndexComponents( + params: GetIndexComponentsRequestV3, + ): Promise> { + return this.get('/api/v3/market/index-components', params); + } + /** * * =====Account======= endpoints @@ -1105,4 +1141,149 @@ export class RestClientV3 extends BaseRestClient { > { return this.getPrivate('/api/v3/trade/history-strategy-orders', params); } + + /** + * + * =====Broker======= endpoints + * + */ + + /** + * Create Broker Sub-Account + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + createBrokerSubAccount( + params: CreateBrokerSubAccountRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/create-sub', params); + } + + /** + * Get Broker Sub-Account List + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + getBrokerSubAccountList( + params?: GetBrokerSubAccountListRequestV3, + ): Promise> { + return this.getPrivate('/api/v3/broker/sub-list', params); + } + + /** + * Modify Broker Sub-Account + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + modifyBrokerSubAccount( + params: ModifyBrokerSubAccountRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/modify-sub', params); + } + + /** + * Broker Subaccount Withdrawal + * + * Broker sub-account withdrawal API has restrictions and currently supports only the following currencies: + * BTC, ETH, USDT, USDC, TRX, XRP, LTC, SOL, BNB, FTM, DOGE, ADA, SHIB, UNI, SEI, SUI, POL, FIL, LINK, TON, ARB, OP, DOT, AVAX + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + brokerSubWithdrawal( + params: BrokerSubWithdrawalRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/sub-withdrawal', params); + } + + /** + * Get Broker Subaccount Deposit Address + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + getBrokerSubDepositAddress( + params: GetBrokerSubDepositAddressRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/sub-deposit-address', params); + } + + /** + * Get All Broker Subaccount Deposit Withdrawal + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + getBrokerAllSubDepositWithdrawal( + params?: GetBrokerAllSubDepositWithdrawalRequestV3, + ): Promise> { + return this.getPrivate('/api/v3/broker/all-sub-deposit-withdrawal', params); + } + + /** + * Get Broker Commission + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + getBrokerCommission( + params?: GetBrokerCommissionRequestV3, + ): Promise> { + return this.getPrivate('/api/v3/broker/commission', params); + } + + /** + * Create Broker Sub-Account API Key + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + createBrokerSubApiKey( + params: CreateBrokerSubApiKeyRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/create-sub-apikey', params); + } + + /** + * Modify Broker Sub-Account API Key + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + modifyBrokerSubApiKey( + params: ModifyBrokerSubApiKeyRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/modify-sub-apikey', params); + } + + /** + * Delete Broker Subaccount Apikey + * + * This endpoint has no response parameters. + * It returns the deletion result synchronously. + * Determine whether the deletion succeeded or failed (and the failure reason) based on the returned code and msg. + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + deleteBrokerSubApiKey( + params: DeleteBrokerSubApiKeyRequestV3, + ): Promise> { + return this.postPrivate('/api/v3/broker/delete-sub-apikey', params); + } + + /** + * Get Broker Sub-Account API Key + * + * Rate limit: 20/sec/UID + * Only the master account with a user type of ND Broker can call this API endpoint. + */ + getBrokerSubApiKey( + params: GetBrokerSubApiKeyRequestV3, + ): Promise> { + return this.getPrivate('/api/v3/broker/query-sub-apikey', params); + } } diff --git a/src/types/request/v3/broker.ts b/src/types/request/v3/broker.ts new file mode 100644 index 0000000..2f59c85 --- /dev/null +++ b/src/types/request/v3/broker.ts @@ -0,0 +1,83 @@ +export interface CreateBrokerSubAccountRequestV3 { + subaccountName: string; + label: string; +} + +export interface GetBrokerSubAccountListRequestV3 { + limit?: string; + cursor?: string; + status?: 'normal' | 'freeze'; +} + +export interface ModifyBrokerSubAccountRequestV3 { + subUid: string; + status?: 'normal' | 'freeze'; + permList?: string[]; +} + +export interface BrokerSubWithdrawalRequestV3 { + subUid: string; + coin: string; + dest: 'on_chain' | 'internal_transfer'; + address: string; + amount: string; + chain?: string; + tag?: string; + clientOid?: string; +} + +export interface GetBrokerSubDepositAddressRequestV3 { + subUid: string; + coin: string; + chain?: string; +} + +export interface GetBrokerAllSubDepositWithdrawalRequestV3 { + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; + status?: 'pending' | 'fail' | 'success'; +} + +export interface GetBrokerCommissionRequestV3 { + startTime?: string; + endTime?: string; + pageSize?: string; + pageNo?: string; + bizType?: 'spot' | 'futures'; + subBizType?: + | 'spot_trade' + | 'spot_margin' + | 'usdt_futures' + | 'usdc_futures' + | 'coin_futures'; +} + +export interface CreateBrokerSubApiKeyRequestV3 { + subUid: string; + passphrase: string; + label: string; + ipList?: string[]; + permType: 'read_and_write' | 'readonly'; + permList: string[]; +} + +export interface ModifyBrokerSubApiKeyRequestV3 { + subUid: string; + passphrase: string; + apiKey: string; + label?: string; + ipList?: string[]; + permType?: 'read_and_write' | 'readonly'; + permList?: string[]; +} + +export interface DeleteBrokerSubApiKeyRequestV3 { + subUid: string; + apiKey: string; +} + +export interface GetBrokerSubApiKeyRequestV3 { + subUid: string; +} diff --git a/src/types/request/v3/public.ts b/src/types/request/v3/public.ts index 467a365..6c39296 100644 --- a/src/types/request/v3/public.ts +++ b/src/types/request/v3/public.ts @@ -105,3 +105,7 @@ export interface GetTickersRequestV3 { category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; } + +export interface GetIndexComponentsRequestV3 { + symbol: string; +} diff --git a/src/types/response/v3/broker.ts b/src/types/response/v3/broker.ts new file mode 100644 index 0000000..c208fc8 --- /dev/null +++ b/src/types/response/v3/broker.ts @@ -0,0 +1,107 @@ +export interface CreateBrokerSubAccountResponseV3 { + subUid: string; + subaccountName: string; + subaccountEmail: string; + status: 'normal' | 'freeze'; + permList: string[]; + label: string; + cTime: string; +} + +export interface BrokerSubAccountV3 { + subUid: string; + subaccountName: string; + subaccountEmail: string | null; + status: 'normal' | 'freeze'; + permList: string[]; + label: string; + language: string; + cTime: string; + uTime: string; +} + +export interface GetBrokerSubAccountListResponseV3 { + subList: BrokerSubAccountV3[]; +} + +export interface ModifyBrokerSubAccountResponseV3 { + subUid: string; + subaccountName: string; + status: 'normal' | 'freeze'; + permList: string[]; + label: string; + cTime: string; + uTime: string; +} + +export interface BrokerSubWithdrawalResponseV3 { + orderId: string; + clientOid: string; +} + +export interface BrokerSubDepositAddressV3 { + subUid: string; + coin: string; + address: string; + chain: string; + tag: string | null; + url: string; + cTime: string; +} + +export interface BrokerSubDepositWithdrawalRecordV3 { + uid: string; + txId: string; + type: 'deposit' | 'withdrawal'; + subType: 'onchain' | 'internal' | 'fast'; + coin: string; + amount: string; + status: 'pending' | 'fail' | 'success'; + ts: string; +} + +export interface GetBrokerAllSubDepositWithdrawalResponseV3 { + list: BrokerSubDepositWithdrawalRecordV3[]; + endId: string; +} + +export interface BrokerCommissionRecordV3 { + uid: string; + coin: string; + symbol: string; + dealtAmount: string; + totalFee: string; + deductedFee: string; + paidFee: string; + markUpFee: string; + totalCommission: string; +} + +export interface CreateBrokerSubApiKeyResponseV3 { + subUid: string; + label: string; + apiKey: string; + secretKey: string; + permType: 'read_and_write' | 'readonly'; + permList: string[]; + ipList: string[] | null; +} + +export interface ModifyBrokerSubApiKeyResponseV3 { + subUid: string; + label: string; + apiKey: string; + permType: 'read_and_write' | 'readonly'; + permList: string[]; + ipList: string[]; +} + +export interface GetBrokerSubApiKeyResponseV3 { + subUid: string; + label: string; + apiKey: string; + secretKey: string; + permType: 'read_and_write' | 'readonly'; + permList: string[]; + ipList: string[] | null; +} diff --git a/src/types/response/v3/public.ts b/src/types/response/v3/public.ts index a8bfc9c..64b56b0 100644 --- a/src/types/response/v3/public.ts +++ b/src/types/response/v3/public.ts @@ -183,3 +183,15 @@ export interface ProofOfReservesV3 { reserveRatio: string; }[]; } + +export interface IndexComponentV3 { + exchange: string; + spotPair: string; + equivalentPrice: string; + weight: string; +} + +export interface IndexPriceComponentsV3 { + symbol: string; + componentList: IndexComponentV3[]; +} diff --git a/src/types/response/v3/trade.ts b/src/types/response/v3/trade.ts index c5f9c41..e6c86e1 100644 --- a/src/types/response/v3/trade.ts +++ b/src/types/response/v3/trade.ts @@ -108,6 +108,7 @@ export interface UnfilledOrderV3 { orderStatus: string; posSide: string; holdMode: string; + delegateType?: string; reduceOnly: string; feeDetail: FeeDetailV3[]; stpMode?: string; @@ -132,6 +133,7 @@ export interface HistoryOrderV3 { orderStatus: string; posSide: string; holdMode: string; + delegateType?: string; reduceOnly: string; feeDetail: FeeDetailV3[]; cancelReason: string;