diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 09406268..9ddb1c54 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -4,8 +4,8 @@

- - SDK Logo + + SDK Logo

@@ -14,7 +14,7 @@ Each REST client is a JavaScript class, which provides functions individually ma The following table shows all methods available in each REST client, whether the method requires authentication (automatically handled if API keys are provided), as well as the exact endpoint each method is connected to. -This can be used to easily find which method to call, once you have [found which endpoint you're looking to use](https://github.com/tiagosiebler/awesome-crypto-examples/wiki/How-to-find-SDK-functions-that-match-API-docs-endpoint). +This can be used to easily find which method to call, once you have [found which endpoint you're looking to use](https://github.com/sieblyio/awesome-crypto-examples/wiki/How-to-find-SDK-functions-that-match-API-docs-endpoint). All REST clients are in the [src](/src) folder. For usage examples, make sure to check the [examples](/examples) folder. @@ -49,392 +49,406 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getSystemStatus()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L659) | :closed_lock_with_key: | GET | `/v5/system/status` | -| [getServerTime()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L676) | | GET | `/v5/market/time` | -| [requestDemoTradingFunds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L688) | :closed_lock_with_key: | POST | `/v5/account/demo-apply-money` | -| [createDemoAccount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L701) | :closed_lock_with_key: | POST | `/v5/user/create-demo-member` | -| [getSpreadInstrumentsInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L714) | | GET | `/v5/spread/instrument` | -| [getSpreadOrderbook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L726) | | GET | `/v5/spread/orderbook` | -| [getSpreadTickers()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L736) | | GET | `/v5/spread/tickers` | -| [getSpreadRecentTrades()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L747) | | GET | `/v5/spread/recent-trade` | -| [getSpreadMaxQty()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L759) | :closed_lock_with_key: | GET | `/v5/spread/max-qty` | -| [submitSpreadOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L768) | :closed_lock_with_key: | POST | `/v5/spread/order/create` | -| [amendSpreadOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L781) | :closed_lock_with_key: | POST | `/v5/spread/order/amend` | -| [cancelSpreadOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L793) | :closed_lock_with_key: | POST | `/v5/spread/order/cancel` | -| [cancelAllSpreadOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L811) | :closed_lock_with_key: | POST | `/v5/spread/order/cancel-all` | -| [getSpreadOpenOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L830) | :closed_lock_with_key: | GET | `/v5/spread/order/realtime` | -| [getSpreadOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L847) | :closed_lock_with_key: | GET | `/v5/spread/order/history` | -| [getSpreadTradeHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L863) | :closed_lock_with_key: | GET | `/v5/spread/execution/list` | -| [getKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L883) | | GET | `/v5/market/kline` | -| [getMarkPriceKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L900) | | GET | `/v5/market/mark-price-kline` | -| [getIndexPriceKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L915) | | GET | `/v5/market/index-price-kline` | -| [getPremiumIndexPriceKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L930) | | GET | `/v5/market/premium-index-price-kline` | -| [getInstrumentsInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L946) | | GET | `/v5/market/instruments-info` | -| [getOrderbook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L957) | | GET | `/v5/market/orderbook` | -| [getRPIOrderbook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L971) | | GET | `/v5/market/rpi_orderbook` | -| [getTickers()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L977) | | GET | `/v5/market/tickers` | -| [getFundingRateHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1015) | | GET | `/v5/market/funding/history` | -| [getPublicTradingHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1030) | | GET | `/v5/market/recent-trade` | -| [getOpenInterest()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1043) | | GET | `/v5/market/open-interest` | -| [getHistoricalVolatility()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1053) | | GET | `/v5/market/historical-volatility` | -| [getInsurance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1064) | | GET | `/v5/market/insurance` | -| [getRiskLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1075) | | GET | `/v5/market/risk-limit` | -| [getOptionDeliveryPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1090) | | GET | `/v5/market/delivery-price` | -| [getDeliveryPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1103) | | GET | `/v5/market/delivery-price` | -| [getNewDeliveryPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1119) | | GET | `/v5/market/new-delivery-price` | -| [getLongShortRatio()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1135) | | GET | `/v5/market/account-ratio` | -| [getIndexPriceComponents()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1145) | | GET | `/v5/market/index-price-components` | -| [getOrderPriceLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1151) | | GET | `/v5/market/price-limit` | -| [getADLAlert()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1165) | | GET | `/v5/market/adlAlert` | -| [getFeeGroupStructure()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1178) | | GET | `/v5/market/fee-group-info` | -| [submitOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1190) | :closed_lock_with_key: | POST | `/v5/order/create` | -| [amendOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1196) | :closed_lock_with_key: | POST | `/v5/order/amend` | -| [cancelOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1202) | :closed_lock_with_key: | POST | `/v5/order/cancel` | -| [getActiveOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1211) | :closed_lock_with_key: | GET | `/v5/order/realtime` | -| [cancelAllOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1217) | :closed_lock_with_key: | POST | `/v5/order/cancel-all` | -| [getHistoricOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1230) | :closed_lock_with_key: | GET | `/v5/order/history` | -| [getExecutionList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1242) | :closed_lock_with_key: | GET | `/v5/execution/list` | -| [batchSubmitOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1260) | :closed_lock_with_key: | POST | `/v5/order/create-batch` | -| [batchAmendOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1285) | :closed_lock_with_key: | POST | `/v5/order/amend-batch` | -| [batchCancelOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1310) | :closed_lock_with_key: | POST | `/v5/order/cancel-batch` | -| [getSpotBorrowCheck()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1332) | :closed_lock_with_key: | GET | `/v5/order/spot-borrow-check` | -| [setDisconnectCancelAllWindow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1353) | :closed_lock_with_key: | POST | `/v5/order/disconnected-cancel-all` | -| [setDisconnectCancelAllWindowV2()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1371) | :closed_lock_with_key: | POST | `/v5/order/disconnected-cancel-all` | -| [preCheckOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1386) | :closed_lock_with_key: | POST | `/v5/order/pre-check` | -| [createStrategyOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1403) | :closed_lock_with_key: | POST | `/v5/strategy/create` | -| [getStrategyList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1414) | :closed_lock_with_key: | GET | `/v5/strategy/list` | -| [getStrategyOrderList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1425) | :closed_lock_with_key: | GET | `/v5/strategy/order-list` | -| [stopStrategy()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1436) | :closed_lock_with_key: | POST | `/v5/strategy/stop` | -| [getPositionInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1461) | :closed_lock_with_key: | GET | `/v5/position/list` | -| [getFuturesLeverage()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1473) | :closed_lock_with_key: | GET | `/v5/position/symbol-info` | -| [setLeverage()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1488) | :closed_lock_with_key: | POST | `/v5/position/set-leverage` | -| [switchIsolatedMargin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1501) | :closed_lock_with_key: | POST | `/v5/position/switch-isolated` | -| [setTPSLMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1515) | :closed_lock_with_key: | POST | `/v5/position/set-tpsl-mode` | -| [switchPositionMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1530) | :closed_lock_with_key: | POST | `/v5/position/switch-mode` | -| [setRiskLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1544) | :closed_lock_with_key: | POST | `/v5/position/set-risk-limit` | -| [setTradingStop()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1559) | :closed_lock_with_key: | POST | `/v5/position/trading-stop` | -| [setAutoAddMargin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1570) | :closed_lock_with_key: | POST | `/v5/position/set-auto-add-margin` | -| [addOrReduceMargin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1582) | :closed_lock_with_key: | POST | `/v5/position/add-margin` | -| [getClosedPnL()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1594) | :closed_lock_with_key: | GET | `/v5/position/closed-pnl` | -| [getClosedOptionsPositions()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1608) | :closed_lock_with_key: | GET | `/v5/position/get-closed-positions` | -| [movePosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1633) | :closed_lock_with_key: | POST | `/v5/position/move-positions` | -| [getMovePositionHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1644) | :closed_lock_with_key: | GET | `/v5/position/move-history` | -| [confirmNewRiskLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1663) | :closed_lock_with_key: | POST | `/v5/position/confirm-pending-mmr` | -| [getPreUpgradeOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1683) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/order/history` | -| [getPreUpgradeTradeHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1698) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/execution/list` | -| [getPreUpgradeClosedPnl()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1709) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/position/closed-pnl` | -| [getPreUpgradeTransactions()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1723) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/account/transaction-log` | -| [getPreUpgradeOptionDeliveryRecord()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1740) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/asset/delivery-record` | -| [getPreUpgradeUSDCSessionSettlements()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1754) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/asset/settlement-record` | -| [getWalletBalance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1775) | :closed_lock_with_key: | GET | `/v5/account/wallet-balance` | -| [getTransferableAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1786) | :closed_lock_with_key: | GET | `/v5/account/withdrawal` | -| [getAccountInstrumentsInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1803) | :closed_lock_with_key: | GET | `/v5/account/instruments-info` | -| [upgradeToUnifiedAccount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1814) | :closed_lock_with_key: | POST | `/v5/account/upgrade-to-uta` | -| [getBorrowHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1825) | :closed_lock_with_key: | GET | `/v5/account/borrow-history` | -| [repayLiability()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1846) | :closed_lock_with_key: | POST | `/v5/account/quick-repayment` | -| [manualRepay()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1871) | :closed_lock_with_key: | POST | `/v5/account/repay` | -| [setCollateralCoin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1880) | :closed_lock_with_key: | POST | `/v5/account/set-collateral-switch` | -| [batchSetCollateralCoin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1886) | :closed_lock_with_key: | POST | `/v5/account/set-collateral-switch-batch` | -| [getCollateralInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1896) | :closed_lock_with_key: | GET | `/v5/account/collateral-info` | -| [getCoinGreeks()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1905) | :closed_lock_with_key: | GET | `/v5/asset/coin-greeks` | -| [getFeeRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1918) | :closed_lock_with_key: | GET | `/v5/account/fee-rate` | -| [getAccountInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1927) | :closed_lock_with_key: | GET | `/v5/account/info` | -| [getDCPInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1940) | :closed_lock_with_key: | GET | `/v5/account/query-dcp-info` | -| [getTransactionLog()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1947) | :closed_lock_with_key: | GET | `/v5/account/transaction-log` | -| [getClassicTransactionLogs()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1958) | :closed_lock_with_key: | GET | `/v5/account/contract-transaction-log` | -| [getSMPGroup()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1969) | :closed_lock_with_key: | GET | `/v5/account/smp-group` | -| [setMarginMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1982) | :closed_lock_with_key: | POST | `/v5/account/set-margin-mode` | -| [setSpotHedging()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1999) | :closed_lock_with_key: | POST | `/v5/account/set-hedging-mode` | -| [setLimitPriceAction()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2012) | :closed_lock_with_key: | POST | `/v5/account/set-limit-px-action` | -| [getLimitPriceAction()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2023) | :closed_lock_with_key: | GET | `/v5/account/user-setting-config` | -| [setDeltaNeutralMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2031) | :closed_lock_with_key: | POST | `/v5/account/set-delta-mode` | -| [setMMP()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2040) | :closed_lock_with_key: | POST | `/v5/account/mmp-modify` | -| [resetMMP()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2047) | :closed_lock_with_key: | POST | `/v5/account/mmp-reset` | -| [getMMPState()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2054) | :closed_lock_with_key: | GET | `/v5/account/mmp-state` | -| [getOptionAssetInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2064) | :closed_lock_with_key: | GET | `/v5/account/option-asset-info` | -| [getPayInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2074) | :closed_lock_with_key: | GET | `/v5/account/pay-info` | -| [getTradeInfoForAnalysis()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2084) | :closed_lock_with_key: | GET | `/v5/account/trade-info-for-analysis` | -| [getAssetOverview()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2104) | :closed_lock_with_key: | GET | `/v5/asset/asset-overview` | -| [getPortfolioMarginInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2114) | :closed_lock_with_key: | GET | `/v5/asset/portfolio-margin` | -| [getTotalMembersAssets()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2124) | :closed_lock_with_key: | GET | `/v5/asset/total-members-assets` | -| [getFundingAccountTransactionHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2136) | :closed_lock_with_key: | GET | `/v5/asset/fundinghistory` | -| [getDeliveryRecord()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2152) | :closed_lock_with_key: | GET | `/v5/asset/delivery-record` | -| [getSettlementRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2163) | :closed_lock_with_key: | GET | `/v5/asset/settlement-record` | -| [getCoinExchangeRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2176) | :closed_lock_with_key: | GET | `/v5/asset/exchange/order-record` | -| [getCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2191) | :closed_lock_with_key: | GET | `/v5/asset/coin/query-info` | -| [getSubUID()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2205) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-sub-member-list` | -| [getAssetInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2220) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-asset-info` | -| [getAllCoinsBalance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2231) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-account-coins-balance` | -| [getCoinBalance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2245) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-account-coin-balance` | -| [getWithdrawableAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2259) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/withdrawable-amount` | -| [getTransferableCoinList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2268) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-transfer-coin-list` | -| [createInternalTransfer()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2284) | :closed_lock_with_key: | POST | `/v5/asset/transfer/inter-transfer` | -| [getInternalTransferRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2303) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-inter-transfer-list` | -| [enableUniversalTransferForSubUIDs()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2323) | :closed_lock_with_key: | POST | `/v5/asset/transfer/save-transfer-sub-member` | -| [createUniversalTransfer()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2334) | :closed_lock_with_key: | POST | `/v5/asset/transfer/universal-transfer` | -| [getUniversalTransferRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2346) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-universal-transfer-list` | -| [getAllowedDepositCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2359) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-allowed-list` | -| [setDepositAccount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2374) | :closed_lock_with_key: | POST | `/v5/asset/deposit/deposit-to-account` | -| [getDepositRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2390) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-record` | -| [getSubAccountDepositRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2405) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-sub-member-record` | -| [getInternalDepositRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2421) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-internal-record` | -| [getMasterDepositAddress()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2433) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-address` | -| [getSubDepositAddress()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2451) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-sub-member-address` | -| [querySubMemberAddress()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2476) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-sub-member-address` | -| [getWithdrawalRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2496) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/query-record` | -| [getWithdrawalAddressList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2508) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/query-address` | -| [getExchangeEntities()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2522) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/vasp/list` | -| [submitDepositOriginatorInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2532) | :closed_lock_with_key: | POST | `/v5/asset/travel-rule/deposit/submit` | -| [submitWithdrawal()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2547) | :closed_lock_with_key: | POST | `/v5/asset/withdraw/create` | -| [cancelWithdrawal()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2558) | :closed_lock_with_key: | POST | `/v5/asset/withdraw/cancel` | -| [getConvertCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2567) | :closed_lock_with_key: | GET | `/v5/asset/exchange/query-coin-list` | -| [requestConvertQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2578) | :closed_lock_with_key: | POST | `/v5/asset/exchange/quote-apply` | -| [confirmConvertQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2587) | :closed_lock_with_key: | POST | `/v5/asset/exchange/convert-execute` | -| [getConvertStatus()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2599) | :closed_lock_with_key: | GET | `/v5/asset/exchange/convert-result-query` | -| [getConvertHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2618) | :closed_lock_with_key: | GET | `/v5/asset/exchange/query-convert-history` | -| [getSmallBalanceList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2635) | :closed_lock_with_key: | GET | `/v5/asset/covert/small-balance-list` | -| [getFiatTradingPairList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2649) | :closed_lock_with_key: | GET | `/v5/fiat/query-coin-list` | -| [createSubMember()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2667) | :closed_lock_with_key: | POST | `/v5/user/create-sub-member` | -| [createSubUIDAPIKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2679) | :closed_lock_with_key: | POST | `/v5/user/create-sub-api` | -| [getSubUIDList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2688) | :closed_lock_with_key: | GET | `/v5/user/query-sub-members` | -| [getSubUIDListUnlimited()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2697) | :closed_lock_with_key: | GET | `/v5/user/submembers` | -| [setSubUIDFrozenState()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2715) | :closed_lock_with_key: | POST | `/v5/user/frozen-sub-member` | -| [getQueryApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2730) | :closed_lock_with_key: | GET | `/v5/user/query-api` | -| [getSubAccountAllApiKeys()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2737) | :closed_lock_with_key: | GET | `/v5/user/sub-apikeys` | -| [getUIDWalletType()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2746) | :closed_lock_with_key: | GET | `/v5/user/get-member-type` | -| [updateMasterApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2765) | :closed_lock_with_key: | POST | `/v5/user/update-api` | -| [updateSubApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2779) | :closed_lock_with_key: | POST | `/v5/user/update-sub-api` | -| [deleteSubMember()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2792) | :closed_lock_with_key: | POST | `/v5/user/del-submember` | -| [deleteMasterApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2807) | :closed_lock_with_key: | POST | `/v5/user/delete-api` | -| [deleteSubApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2821) | :closed_lock_with_key: | POST | `/v5/user/delete-sub-api` | -| [getAffiliateUserList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2841) | :closed_lock_with_key: | GET | `/v5/affiliate/aff-user-list` | -| [getAffiliateSubAffiliateList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2859) | :closed_lock_with_key: | GET | `/v5/affiliate/affiliate-sub-list` | -| [getAffiliateUserInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2875) | :closed_lock_with_key: | GET | `/v5/user/aff-customer-info` | -| [getFriendReferrals()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2887) | :closed_lock_with_key: | GET | `/v5/user/invitation/referrals` | -| [signAgreement()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2908) | :closed_lock_with_key: | POST | `/v5/user/agreement` | -| [getAlphaTradeQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2925) | :closed_lock_with_key: | POST | `/v5/alpha/trade/quote` | -| [executeAlphaTradePurchase()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2936) | :closed_lock_with_key: | POST | `/v5/alpha/trade/purchase` | -| [executeAlphaTradeRedeem()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2947) | :closed_lock_with_key: | POST | `/v5/alpha/trade/redeem` | -| [getAlphaPayTokenList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2957) | :closed_lock_with_key: | POST | `/v5/alpha/trade/pay-token-list` | -| [getAlphaTradeOrderList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2967) | :closed_lock_with_key: | POST | `/v5/alpha/trade/order-list` | -| [getAlphaBizTokenList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2977) | :closed_lock_with_key: | POST | `/v5/alpha/trade/biz-token-list` | -| [getAlphaBizTokenPriceList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2987) | :closed_lock_with_key: | POST | `/v5/alpha/trade/biz-token-price-list` | -| [getAlphaBizTokenDetails()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2997) | :closed_lock_with_key: | POST | `/v5/alpha/trade/biz-token-details` | -| [getAlphaAssetList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3007) | :closed_lock_with_key: | POST | `/v5/alpha/trade/asset-list` | -| [getAlphaAssetDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3015) | :closed_lock_with_key: | POST | `/v5/alpha/trade/asset-detail` | -| [getAlphaPredictionEngineStatus()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3031) | :closed_lock_with_key: | GET | `/v5/alpha/prediction/engine-status` | -| [getAlphaPredictionPayTokenList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3041) | :closed_lock_with_key: | GET | `/v5/alpha/prediction/pay-token-list` | -| [getAlphaPredictionEventDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3051) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/event-detail` | -| [getAlphaPredictionOrderEstimate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3061) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/order-estimate` | -| [executeAlphaPredictionBuy()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3071) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/buy` | -| [executeAlphaPredictionSell()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3081) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/sell` | -| [getAlphaPredictionOrderList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3091) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/order-list` | -| [getAlphaPredictionOrderBook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3101) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/order-book` | -| [getAlphaPredictionTokenPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3111) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/token-price` | -| [getAlphaPredictionPriceHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3121) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/price-history` | -| [getAlphaPredictionPositionList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3131) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/position-list` | -| [getAlphaPredictionPositionHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3141) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/position-history` | -| [getAlphaPredictionPortfolioSummary()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3151) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/portfolio-summary` | -| [getAlphaPredictionSideMarketList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3161) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/side-market-list` | -| [getAlphaPredictionSportsMatchList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3171) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/sports/match-list` | -| [getAlphaPredictionSportsTimelineStages()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3181) | :closed_lock_with_key: | GET | `/v5/alpha/prediction/sports/timeline-stages` | -| [getAlphaPredictionSportsGroupStageDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3194) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/sports/group-stage-detail` | -| [getAlphaLPPoolList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3213) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pool-list` | -| [getAlphaLPPoolInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3223) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pool-info` | -| [executeAlphaLPStake()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3233) | :closed_lock_with_key: | POST | `/v5/alpha/lp/stake` | -| [executeAlphaLPRedeem()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3243) | :closed_lock_with_key: | POST | `/v5/alpha/lp/redeem` | -| [getAlphaLPOrderList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3253) | :closed_lock_with_key: | POST | `/v5/alpha/lp/order-list` | -| [getAlphaLPPayTokenList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3263) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pay-token-list` | -| [getAlphaLPPayTokenPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3273) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pay-token-price` | -| [getAlphaLPPositionList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3283) | :closed_lock_with_key: | POST | `/v5/alpha/lp/position-list` | -| [getVIPMarginData()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3303) | | GET | `/v5/spot-margin-trade/data` | -| [getHistoricalInterestRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3314) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/interest-rate-history` | -| [getSpotMarginCurrencyData()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3339) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/currency-data` | -| [toggleSpotMarginTrade()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3351) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/switch-mode` | -| [setSpotMarginLeverage()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3362) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/set-leverage` | -| [setSpotMarginLeverageV2()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3370) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/set-leverage` | -| [getSpotMarginState()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3381) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/state` | -| [manualBorrow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3388) | :closed_lock_with_key: | POST | `/v5/account/borrow` | -| [getMaxBorrowableAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3397) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/max-borrowable` | -| [getPositionTiers()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3406) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/position-tiers` | -| [getCoinState()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3417) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/coinstate` | -| [getAvailableAmountToRepay()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3428) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/repayment-available-amount` | -| [manualRepayWithoutConversion()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3447) | :closed_lock_with_key: | POST | `/v5/account/no-convert-repay` | -| [getAutoRepayMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3460) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/get-auto-repay-mode` | -| [setAutoRepayMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3476) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/set-auto-repay-mode` | -| [getSpotMarginLiability()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3488) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/liability` | -| [submitFixedRateBorrow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3497) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/fixedborrow` | -| [getFixedRateBorrowOrderInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3506) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixedborrow-order-info` | -| [getFixedRateBorrowContractInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3523) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixedborrow-contract-info` | -| [getFixedRateBorrowOrderQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3540) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixedborrow-order-quote` | -| [renewFixedRateBorrow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3552) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/fixedborrow-renew` | -| [getSpotMarginCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3567) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/pledge-token` | -| [getSpotMarginBorrowableCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3584) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/borrow-token` | -| [getSpotMarginInterestAndQuota()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3601) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/loan-info` | -| [getSpotMarginLoanAccountInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3619) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/account` | -| [spotMarginBorrow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3643) | :closed_lock_with_key: | POST | `/v5/spot-cross-margin-trade/loan` | -| [spotMarginRepay()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3654) | :closed_lock_with_key: | POST | `/v5/spot-cross-margin-trade/repay` | -| [getSpotMarginBorrowOrderDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3669) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/orders` | -| [getSpotMarginRepaymentOrderDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3698) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/repay-history` | -| [toggleSpotCrossMarginTrade()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3727) | :closed_lock_with_key: | POST | `/v5/spot-cross-margin-trade/switch` | -| [getCollateralCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3747) | | GET | `/v5/crypto-loan/collateral-data` | -| [getBorrowableCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3764) | | GET | `/v5/crypto-loan/loanable-data` | -| [getAccountBorrowCollateralLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3782) | :closed_lock_with_key: | GET | `/v5/crypto-loan/borrowable-collateralisable-number` | -| [borrowCryptoLoan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3802) | :closed_lock_with_key: | POST | `/v5/crypto-loan/borrow` | -| [repayCryptoLoan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3823) | :closed_lock_with_key: | POST | `/v5/crypto-loan/repay` | -| [getUnpaidLoanOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3839) | :closed_lock_with_key: | GET | `/v5/crypto-loan/ongoing-orders` | -| [getRepaymentHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3860) | :closed_lock_with_key: | GET | `/v5/crypto-loan/repayment-history` | -| [getCompletedLoanOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3880) | :closed_lock_with_key: | GET | `/v5/crypto-loan/borrow-history` | -| [getMaxAllowedReductionCollateralAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3899) | :closed_lock_with_key: | GET | `/v5/crypto-loan/max-collateral-amount` | -| [adjustCollateralAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3918) | :closed_lock_with_key: | POST | `/v5/crypto-loan/adjust-ltv` | -| [getLoanLTVAdjustmentHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3942) | :closed_lock_with_key: | GET | `/v5/crypto-loan/adjustment-history` | -| [getLoanBorrowableCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3963) | | GET | `/v5/crypto-loan-common/loanable-data` | -| [getLoanCollateralCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3975) | | GET | `/v5/crypto-loan-common/collateral-data` | -| [getMaxCollateralAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3985) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/max-collateral-amount` | -| [getMaxLoanAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4004) | :closed_lock_with_key: | POST | `/v5/crypto-loan-common/max-loan` | -| [updateCollateralAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4014) | :closed_lock_with_key: | POST | `/v5/crypto-loan-common/adjust-ltv` | -| [getCollateralAdjustmentHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4025) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/adjustment-history` | -| [getCryptoLoanPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4040) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/position` | -| [borrowFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4057) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/borrow` | -| [repayFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4068) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay` | -| [repayCollateralFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4078) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay-collateral` | -| [getOngoingFlexibleLoans()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4092) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/ongoing-coin` | -| [getBorrowHistoryFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4104) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/borrow-history` | -| [getRepaymentHistoryFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4117) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/repayment-history` | -| [getSupplyOrderQuoteFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4142) | | GET | `/v5/crypto-loan-fixed/supply-order-quote` | -| [getBorrowOrderQuoteFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4155) | | GET | `/v5/crypto-loan-fixed/borrow-order-quote` | -| [createBorrowOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4168) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/borrow` | -| [createSupplyOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4181) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/supply` | -| [cancelBorrowOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4191) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/borrow-order-cancel` | -| [cancelSupplyOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4205) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/supply-order-cancel` | -| [getBorrowContractInfoFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4218) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/borrow-contract-info` | -| [getSupplyContractInfoFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4236) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/supply-contract-info` | -| [getBorrowOrderInfoFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4254) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/borrow-order-info` | -| [getSupplyOrderInfoFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4267) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/supply-order-info` | -| [repayFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4281) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/fully-repay` | -| [repayCollateralFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4292) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay-collateral` | -| [getRepaymentHistoryFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4305) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/repayment-history` | -| [renewBorrowOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4322) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/renew` | -| [getRenewOrderInfoFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4335) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/renew-info` | -| [getInstitutionalLendingProductInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4353) | | GET | `/v5/ins-loan/product-infos` | -| [getInstitutionalLendingCoinDeltaAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4365) | :closed_lock_with_key: | GET | `/v5/ins-loan/coin-delta-amount` | -| [getInstitutionalLendingMarginCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4375) | | GET | `/v5/ins-loan/ensure-tokens` | -| [getInstitutionalLendingMarginCoinInfoWithConversionRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4384) | | GET | `/v5/ins-loan/ensure-tokens-convert` | -| [getInstitutionalLendingLoanOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4393) | :closed_lock_with_key: | GET | `/v5/ins-loan/loan-order` | -| [getInstitutionalLendingRepayOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4405) | :closed_lock_with_key: | GET | `/v5/ins-loan/repaid-history` | -| [getInstitutionalLendingLTV()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4417) | :closed_lock_with_key: | GET | `/v5/ins-loan/ltv` | -| [getInstitutionalLendingLTVWithLadderConversionRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4426) | :closed_lock_with_key: | GET | `/v5/ins-loan/ltv-convert` | -| [bindOrUnbindUID()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4441) | :closed_lock_with_key: | POST | `/v5/ins-loan/association-uid` | -| [repayInstitutionalLoan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4461) | :closed_lock_with_key: | POST | `/v5/ins-loan/repay-loan` | -| [getExchangeBrokerEarnings()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4482) | :closed_lock_with_key: | GET | `/v5/broker/earnings-info` | -| [getExchangeBrokerAccountInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4495) | :closed_lock_with_key: | GET | `/v5/broker/account-info` | -| [getBrokerSubAccountDeposits()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4511) | :closed_lock_with_key: | GET | `/v5/broker/asset/query-sub-member-deposit-record` | -| [getBrokerVoucherSpec()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4526) | :closed_lock_with_key: | POST | `/v5/broker/award/info` | -| [issueBrokerVoucher()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4538) | :closed_lock_with_key: | POST | `/v5/broker/award/distribute-award` | -| [getBrokerIssuedVoucher()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4550) | :closed_lock_with_key: | POST | `/v5/broker/award/distribution-record` | -| [setBrokerRateLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4567) | :closed_lock_with_key: | POST | `/v5/broker/apilimit/set` | -| [getBrokerRateLimitCap()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4586) | :closed_lock_with_key: | GET | `/v5/broker/apilimit/query-cap` | -| [getAllBrokerRateLimits()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4604) | :closed_lock_with_key: | GET | `/v5/broker/apilimit/query-all` | -| [getEarnProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4624) | | GET | `/v5/earn/product` | -| [getEarnCouponList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4636) | :closed_lock_with_key: | GET | `/v5/earn/coupons` | -| [getRWAProductList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4646) | | GET | `/v5/earn/rwa/product` | -| [placeRWAOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4656) | :closed_lock_with_key: | POST | `/v5/earn/rwa/place-order` | -| [getRWAPositionList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4665) | :closed_lock_with_key: | GET | `/v5/earn/rwa/position` | -| [getRWAOrderList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4674) | :closed_lock_with_key: | GET | `/v5/earn/rwa/order` | -| [getRWANavChart()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4684) | | GET | `/v5/earn/rwa/nav-chart` | -| [getHoldToEarnAirdropProducts()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4695) | | GET | `/v5/earn/hold-to-earn/product` | -| [getAdvanceEarnProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4706) | | GET | `/v5/earn/advance/product` | -| [getLiquidityMiningProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4717) | | GET | `/v5/earn/liquidity-mining/product` | -| [getFixedTermEarnProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4728) | | GET | `/v5/earn/fixed-term/product` | -| [getAdvanceEarnProductExtraInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4740) | | GET | `/v5/earn/advance/product-extra-info` | -| [submitAdvanceEarnPlaceOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4751) | :closed_lock_with_key: | POST | `/v5/earn/advance/place-order` | -| [getAdvanceEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4762) | :closed_lock_with_key: | GET | `/v5/earn/advance/position` | -| [getAdvanceEarnOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4773) | :closed_lock_with_key: | GET | `/v5/earn/advance/order` | -| [submitFixedTermEarnOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4784) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/place-order` | -| [redeemFixedTermEarn()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4795) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/redeem` | -| [getFixedTermEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4806) | :closed_lock_with_key: | GET | `/v5/earn/fixed-term/position` | -| [getFixedTermEarnOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4817) | :closed_lock_with_key: | GET | `/v5/earn/fixed-term/order` | -| [setFixedTermEarnAutoInvest()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4828) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/position/auto-invest` | -| [submitStakeRedeem()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4844) | :closed_lock_with_key: | POST | `/v5/earn/place-order` | -| [getEarnOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4863) | :closed_lock_with_key: | GET | `/v5/earn/order` | -| [getEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4881) | :closed_lock_with_key: | GET | `/v5/earn/position` | -| [modifyEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4894) | :closed_lock_with_key: | POST | `/v5/earn/position/modify` | -| [getEarnYieldHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4907) | :closed_lock_with_key: | GET | `/v5/earn/yield` | -| [getHoldToEarnAirdropYieldHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4921) | :closed_lock_with_key: | GET | `/v5/earn/hold-to-earn/yield-history` | -| [getEarnHourlyYieldHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4932) | :closed_lock_with_key: | GET | `/v5/earn/hourly-yield` | -| [getEarnAprHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4946) | | GET | `/v5/earn/apr-history` | -| [getEarnTokenProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4956) | | GET | `/v5/earn/token/product` | -| [submitEarnTokenOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4965) | :closed_lock_with_key: | POST | `/v5/earn/token/place-order` | -| [getEarnTokenOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4974) | :closed_lock_with_key: | GET | `/v5/earn/token/order` | -| [getEarnTokenPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4986) | :closed_lock_with_key: | GET | `/v5/earn/token/position` | -| [getEarnTokenDailyYield()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4995) | :closed_lock_with_key: | GET | `/v5/earn/token/yield` | -| [getEarnTokenHourlyYield()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5007) | :closed_lock_with_key: | GET | `/v5/earn/token/hourly-yield` | -| [getEarnTokenHistoryApr()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5019) | | GET | `/v5/earn/token/history-apr` | -| [getPwmInvestmentPlanList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5034) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/list` | -| [getPwmInvestmentPlanDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5043) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/detail` | -| [getPwmPendingInvestmentPlanDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5052) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/new-plan` | -| [claimPwmWithdrawableFunds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5061) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/claim` | -| [getPwmInvestmentPlanAssetTrend()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5070) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/asset-trend` | -| [getPwmFundHistoricalNav()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5079) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/fund-nav` | -| [subscribePwmInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5088) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/subscribe` | -| [investMorePwmInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5097) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/invest-more` | -| [redeemPwmInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5106) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/redeem` | -| [getPwmInvestmentPlanOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5115) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/order` | -| [getPwmSubscribableProductInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5124) | | GET | `/v5/earn/pwm/customize-plan/product` | -| [createPwmCustomizeInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5133) | :closed_lock_with_key: | POST | `/v5/earn/pwm/customize-plan/create` | -| [getPwmAllFunds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5148) | :closed_lock_with_key: | GET | `/v5/earn/pwm/asset-manager/all-funds` | -| [settlePwmFundProfit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5157) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/settle-profit` | -| [createPwmFund()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5166) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/create-fund` | -| [createPwmAssetManagerInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5175) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/create-investment-plan` | -| [getPwmAssetManagerInvestmentPlans()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5189) | :closed_lock_with_key: | GET | `/v5/earn/pwm/asset-manager/get-investment-plan` | -| [managePwmAssetManagerInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5201) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/manage-investment-plan` | -| [getPwmAllFundOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5215) | :closed_lock_with_key: | GET | `/v5/earn/pwm/asset-manager/all-order` | -| [managePwmFundOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5224) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/manage-order` | -| [createPwmFundSubAccount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5233) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/create-sub-account` | -| [pwmFundTransfer()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5245) | :closed_lock_with_key: | POST | `/v5/earn/pwm/fund-transfer` | -| [getPwmFundTransferRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5254) | :closed_lock_with_key: | GET | `/v5/earn/pwm/query-fund-transfer-result` | -| [queryCardAssetRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5269) | :closed_lock_with_key: | POST | `/v5/card/transaction/query-asset-records` | -| [queryCardPointsBalance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5278) | :closed_lock_with_key: | POST | `/v5/card/reward/points/balance` | -| [queryCardPointsRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5285) | :closed_lock_with_key: | POST | `/v5/card/reward/points/records` | -| [queryCardPointsTier()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5294) | :closed_lock_with_key: | POST | `/v5/card/reward/points/tier` | -| [queryCardMallItemList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5301) | :closed_lock_with_key: | POST | `/v5/card/reward/mall/item/list` | -| [queryCardPointCashbackDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5310) | :closed_lock_with_key: | POST | `/v5/card/reward/point/cashback/detail` | -| [createRFQ()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5326) | :closed_lock_with_key: | POST | `/v5/rfq/create-rfq` | -| [getRFQConfig()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5337) | :closed_lock_with_key: | GET | `/v5/rfq/config` | -| [cancelRFQ()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5346) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-rfq` | -| [cancelAllRFQ()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5356) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-all-rfq` | -| [createRFQQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5365) | :closed_lock_with_key: | POST | `/v5/rfq/create-quote` | -| [executeRFQQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5376) | :closed_lock_with_key: | POST | `/v5/rfq/execute-quote` | -| [cancelRFQQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5387) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-quote` | -| [cancelAllRFQQuotes()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5397) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-all-quotes` | -| [getRFQRealtimeInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5411) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-realtime` | -| [getRFQHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5423) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-list` | -| [getRFQRealtimeQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5437) | :closed_lock_with_key: | GET | `/v5/rfq/quote-realtime` | -| [getRFQHistoryQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5452) | :closed_lock_with_key: | GET | `/v5/rfq/quote-list` | -| [getRFQTrades()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5465) | :closed_lock_with_key: | GET | `/v5/rfq/trade-list` | -| [getRFQPublicTrades()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5478) | :closed_lock_with_key: | GET | `/v5/rfq/public-trades` | -| [acceptNonLPQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5494) | :closed_lock_with_key: | POST | `/v5/rfq/accept-other-quote` | -| [getP2PAccountCoinsBalance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5516) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-account-coins-balance` | -| [getP2POnlineAds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5533) | :closed_lock_with_key: | POST | `/v5/p2p/item/online` | -| [createP2PAd()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5542) | :closed_lock_with_key: | POST | `/v5/p2p/item/create` | -| [cancelP2PAd()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5551) | :closed_lock_with_key: | POST | `/v5/p2p/item/cancel` | -| [updateP2PAd()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5565) | :closed_lock_with_key: | POST | `/v5/p2p/item/update` | -| [getP2PPersonalAds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5575) | :closed_lock_with_key: | POST | `/v5/p2p/item/personal/list` | -| [getP2PAdDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5584) | :closed_lock_with_key: | POST | `/v5/p2p/item/info` | -| [getP2POrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5599) | :closed_lock_with_key: | POST | `/v5/p2p/order/simplifyList` | -| [getP2POrderDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5609) | :closed_lock_with_key: | POST | `/v5/p2p/order/info` | -| [getP2PPendingOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5618) | :closed_lock_with_key: | POST | `/v5/p2p/order/pending/simplifyList` | -| [markP2POrderAsPaid()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5627) | :closed_lock_with_key: | POST | `/v5/p2p/order/pay` | -| [releaseP2POrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5636) | :closed_lock_with_key: | POST | `/v5/p2p/order/finish` | -| [sendP2POrderMessage()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5645) | :closed_lock_with_key: | POST | `/v5/p2p/order/message/send` | -| [getP2POrderMessages()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5679) | :closed_lock_with_key: | POST | `/v5/p2p/order/message/listpage` | -| [getP2PUserInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5693) | :closed_lock_with_key: | POST | `/v5/p2p/user/personal/info` | -| [getP2PCounterpartyUserInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5700) | :closed_lock_with_key: | POST | `/v5/p2p/user/order/personal/info` | -| [getP2PUserPayments()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5709) | :closed_lock_with_key: | POST | `/v5/p2p/user/payment/list` | -| [setApiRateLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5729) | :closed_lock_with_key: | POST | `/v5/apilimit/set` | -| [queryApiRateLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5758) | :closed_lock_with_key: | GET | `/v5/apilimit/query` | -| [getRateLimitCap()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5777) | :closed_lock_with_key: | GET | `/v5/apilimit/query-cap` | -| [getAllRateLimits()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5796) | :closed_lock_with_key: | GET | `/v5/apilimit/query-all` | +| [getSystemStatus()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L684) | :closed_lock_with_key: | GET | `/v5/system/status` | +| [getServerTime()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L701) | | GET | `/v5/market/time` | +| [requestDemoTradingFunds()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L713) | :closed_lock_with_key: | POST | `/v5/account/demo-apply-money` | +| [createDemoAccount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L726) | :closed_lock_with_key: | POST | `/v5/user/create-demo-member` | +| [getSpreadInstrumentsInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L739) | | GET | `/v5/spread/instrument` | +| [getSpreadOrderbook()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L751) | | GET | `/v5/spread/orderbook` | +| [getSpreadTickers()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L761) | | GET | `/v5/spread/tickers` | +| [getSpreadRecentTrades()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L772) | | GET | `/v5/spread/recent-trade` | +| [getSpreadMaxQty()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L784) | :closed_lock_with_key: | GET | `/v5/spread/max-qty` | +| [submitSpreadOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L793) | :closed_lock_with_key: | POST | `/v5/spread/order/create` | +| [amendSpreadOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L806) | :closed_lock_with_key: | POST | `/v5/spread/order/amend` | +| [cancelSpreadOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L818) | :closed_lock_with_key: | POST | `/v5/spread/order/cancel` | +| [cancelAllSpreadOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L836) | :closed_lock_with_key: | POST | `/v5/spread/order/cancel-all` | +| [getSpreadOpenOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L855) | :closed_lock_with_key: | GET | `/v5/spread/order/realtime` | +| [getSpreadOrderHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L872) | :closed_lock_with_key: | GET | `/v5/spread/order/history` | +| [getSpreadTradeHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L888) | :closed_lock_with_key: | GET | `/v5/spread/execution/list` | +| [getKline()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L908) | | GET | `/v5/market/kline` | +| [getMarkPriceKline()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L925) | | GET | `/v5/market/mark-price-kline` | +| [getIndexPriceKline()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L940) | | GET | `/v5/market/index-price-kline` | +| [getPremiumIndexPriceKline()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L955) | | GET | `/v5/market/premium-index-price-kline` | +| [getInstrumentsInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L971) | | GET | `/v5/market/instruments-info` | +| [getOrderbook()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L982) | | GET | `/v5/market/orderbook` | +| [getFullDepthOrderbook()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L988) | | GET | `/v5/market/full_orderbook` | +| [getRPIOrderbook()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1002) | | GET | `/v5/market/rpi_orderbook` | +| [getTickers()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1008) | | GET | `/v5/market/tickers` | +| [getFundingRateHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1046) | | GET | `/v5/market/funding/history` | +| [getPublicTradingHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1061) | | GET | `/v5/market/recent-trade` | +| [getOpenInterest()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1074) | | GET | `/v5/market/open-interest` | +| [getHistoricalVolatility()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1084) | | GET | `/v5/market/historical-volatility` | +| [getInsurance()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1095) | | GET | `/v5/market/insurance` | +| [getRiskLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1106) | | GET | `/v5/market/risk-limit` | +| [getOptionDeliveryPrice()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1121) | | GET | `/v5/market/delivery-price` | +| [getDeliveryPrice()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1134) | | GET | `/v5/market/delivery-price` | +| [getNewDeliveryPrice()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1150) | | GET | `/v5/market/new-delivery-price` | +| [getLongShortRatio()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1166) | | GET | `/v5/market/account-ratio` | +| [getIndexPriceComponents()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1176) | | GET | `/v5/market/index-price-components` | +| [getOrderPriceLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1182) | | GET | `/v5/market/price-limit` | +| [getADLAlert()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1196) | | GET | `/v5/market/adlAlert` | +| [getFeeGroupStructure()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1209) | | GET | `/v5/market/fee-group-info` | +| [submitOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1221) | :closed_lock_with_key: | POST | `/v5/order/create` | +| [amendOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1227) | :closed_lock_with_key: | POST | `/v5/order/amend` | +| [cancelOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1233) | :closed_lock_with_key: | POST | `/v5/order/cancel` | +| [getActiveOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1242) | :closed_lock_with_key: | GET | `/v5/order/realtime` | +| [cancelAllOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1248) | :closed_lock_with_key: | POST | `/v5/order/cancel-all` | +| [getHistoricOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1261) | :closed_lock_with_key: | GET | `/v5/order/history` | +| [getExecutionList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1273) | :closed_lock_with_key: | GET | `/v5/execution/list` | +| [batchSubmitOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1291) | :closed_lock_with_key: | POST | `/v5/order/create-batch` | +| [batchAmendOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1316) | :closed_lock_with_key: | POST | `/v5/order/amend-batch` | +| [batchCancelOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1341) | :closed_lock_with_key: | POST | `/v5/order/cancel-batch` | +| [getSpotBorrowCheck()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1363) | :closed_lock_with_key: | GET | `/v5/order/spot-borrow-check` | +| [setDisconnectCancelAllWindow()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1384) | :closed_lock_with_key: | POST | `/v5/order/disconnected-cancel-all` | +| [setDisconnectCancelAllWindowV2()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1402) | :closed_lock_with_key: | POST | `/v5/order/disconnected-cancel-all` | +| [preCheckOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1417) | :closed_lock_with_key: | POST | `/v5/order/pre-check` | +| [createStrategyOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1434) | :closed_lock_with_key: | POST | `/v5/strategy/create` | +| [getStrategyList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1445) | :closed_lock_with_key: | GET | `/v5/strategy/list` | +| [getStrategyOrderList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1456) | :closed_lock_with_key: | GET | `/v5/strategy/order-list` | +| [stopStrategy()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1467) | :closed_lock_with_key: | POST | `/v5/strategy/stop` | +| [getPositionInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1492) | :closed_lock_with_key: | GET | `/v5/position/list` | +| [getFuturesLeverage()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1504) | :closed_lock_with_key: | GET | `/v5/position/symbol-info` | +| [setLeverage()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1519) | :closed_lock_with_key: | POST | `/v5/position/set-leverage` | +| [switchIsolatedMargin()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1532) | :closed_lock_with_key: | POST | `/v5/position/switch-isolated` | +| [setTPSLMode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1546) | :closed_lock_with_key: | POST | `/v5/position/set-tpsl-mode` | +| [switchPositionMode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1561) | :closed_lock_with_key: | POST | `/v5/position/switch-mode` | +| [setRiskLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1575) | :closed_lock_with_key: | POST | `/v5/position/set-risk-limit` | +| [setTradingStop()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1590) | :closed_lock_with_key: | POST | `/v5/position/trading-stop` | +| [setAutoAddMargin()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1601) | :closed_lock_with_key: | POST | `/v5/position/set-auto-add-margin` | +| [addOrReduceMargin()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1613) | :closed_lock_with_key: | POST | `/v5/position/add-margin` | +| [getClosedPnL()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1625) | :closed_lock_with_key: | GET | `/v5/position/closed-pnl` | +| [getClosedOptionsPositions()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1639) | :closed_lock_with_key: | GET | `/v5/position/get-closed-positions` | +| [movePosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1664) | :closed_lock_with_key: | POST | `/v5/position/move-positions` | +| [getMovePositionHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1675) | :closed_lock_with_key: | GET | `/v5/position/move-history` | +| [confirmNewRiskLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1694) | :closed_lock_with_key: | POST | `/v5/position/confirm-pending-mmr` | +| [getPreUpgradeOrderHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1714) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/order/history` | +| [getPreUpgradeTradeHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1729) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/execution/list` | +| [getPreUpgradeClosedPnl()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1740) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/position/closed-pnl` | +| [getPreUpgradeTransactions()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1754) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/account/transaction-log` | +| [getPreUpgradeOptionDeliveryRecord()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1771) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/asset/delivery-record` | +| [getPreUpgradeUSDCSessionSettlements()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1785) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/asset/settlement-record` | +| [getWalletBalance()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1806) | :closed_lock_with_key: | GET | `/v5/account/wallet-balance` | +| [getTransferableAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1817) | :closed_lock_with_key: | GET | `/v5/account/withdrawal` | +| [getAccountInstrumentsInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1834) | :closed_lock_with_key: | GET | `/v5/account/instruments-info` | +| [upgradeToUnifiedAccount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1845) | :closed_lock_with_key: | POST | `/v5/account/upgrade-to-uta` | +| [getBorrowHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1856) | :closed_lock_with_key: | GET | `/v5/account/borrow-history` | +| [repayLiability()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1877) | :closed_lock_with_key: | POST | `/v5/account/quick-repayment` | +| [manualRepay()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1902) | :closed_lock_with_key: | POST | `/v5/account/repay` | +| [setCollateralCoin()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1911) | :closed_lock_with_key: | POST | `/v5/account/set-collateral-switch` | +| [batchSetCollateralCoin()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1917) | :closed_lock_with_key: | POST | `/v5/account/set-collateral-switch-batch` | +| [getCollateralInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1927) | :closed_lock_with_key: | GET | `/v5/account/collateral-info` | +| [getCoinGreeks()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1936) | :closed_lock_with_key: | GET | `/v5/asset/coin-greeks` | +| [getFeeRate()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1949) | :closed_lock_with_key: | GET | `/v5/account/fee-rate` | +| [getAccountInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1958) | :closed_lock_with_key: | GET | `/v5/account/info` | +| [getDCPInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1971) | :closed_lock_with_key: | GET | `/v5/account/query-dcp-info` | +| [getTransactionLog()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1978) | :closed_lock_with_key: | GET | `/v5/account/transaction-log` | +| [getClassicTransactionLogs()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L1989) | :closed_lock_with_key: | GET | `/v5/account/contract-transaction-log` | +| [getSMPGroup()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2000) | :closed_lock_with_key: | GET | `/v5/account/smp-group` | +| [setMarginMode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2013) | :closed_lock_with_key: | POST | `/v5/account/set-margin-mode` | +| [setSpotHedging()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2030) | :closed_lock_with_key: | POST | `/v5/account/set-hedging-mode` | +| [setLimitPriceAction()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2043) | :closed_lock_with_key: | POST | `/v5/account/set-limit-px-action` | +| [getLimitPriceAction()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2054) | :closed_lock_with_key: | GET | `/v5/account/user-setting-config` | +| [setDeltaNeutralMode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2062) | :closed_lock_with_key: | POST | `/v5/account/set-delta-mode` | +| [setMMP()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2071) | :closed_lock_with_key: | POST | `/v5/account/mmp-modify` | +| [resetMMP()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2078) | :closed_lock_with_key: | POST | `/v5/account/mmp-reset` | +| [getMMPState()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2085) | :closed_lock_with_key: | GET | `/v5/account/mmp-state` | +| [getOptionAssetInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2095) | :closed_lock_with_key: | GET | `/v5/account/option-asset-info` | +| [getPayInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2105) | :closed_lock_with_key: | GET | `/v5/account/pay-info` | +| [getTradeInfoForAnalysis()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2115) | :closed_lock_with_key: | GET | `/v5/account/trade-info-for-analysis` | +| [getAssetOverview()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2135) | :closed_lock_with_key: | GET | `/v5/asset/asset-overview` | +| [getPortfolioMarginInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2145) | :closed_lock_with_key: | GET | `/v5/asset/portfolio-margin` | +| [getTotalMembersAssets()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2155) | :closed_lock_with_key: | GET | `/v5/asset/total-members-assets` | +| [getFundingAccountTransactionHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2167) | :closed_lock_with_key: | GET | `/v5/asset/fundinghistory` | +| [getDeliveryRecord()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2183) | :closed_lock_with_key: | GET | `/v5/asset/delivery-record` | +| [getSettlementRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2194) | :closed_lock_with_key: | GET | `/v5/asset/settlement-record` | +| [getCoinExchangeRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2207) | :closed_lock_with_key: | GET | `/v5/asset/exchange/order-record` | +| [getCoinInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2222) | :closed_lock_with_key: | GET | `/v5/asset/coin/query-info` | +| [getSubUID()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2236) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-sub-member-list` | +| [getAssetInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2251) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-asset-info` | +| [getAllCoinsBalance()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2262) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-account-coins-balance` | +| [getCoinBalance()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2276) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-account-coin-balance` | +| [getWithdrawableAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2290) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/withdrawable-amount` | +| [getTransferableCoinList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2299) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-transfer-coin-list` | +| [createInternalTransfer()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2315) | :closed_lock_with_key: | POST | `/v5/asset/transfer/inter-transfer` | +| [getInternalTransferRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2334) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-inter-transfer-list` | +| [enableUniversalTransferForSubUIDs()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2354) | :closed_lock_with_key: | POST | `/v5/asset/transfer/save-transfer-sub-member` | +| [createUniversalTransfer()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2365) | :closed_lock_with_key: | POST | `/v5/asset/transfer/universal-transfer` | +| [getUniversalTransferRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2377) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-universal-transfer-list` | +| [getAllowedDepositCoinInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2390) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-allowed-list` | +| [setDepositAccount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2405) | :closed_lock_with_key: | POST | `/v5/asset/deposit/deposit-to-account` | +| [getDepositRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2421) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-record` | +| [getSubAccountDepositRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2436) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-sub-member-record` | +| [getInternalDepositRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2452) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-internal-record` | +| [getMasterDepositAddress()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2464) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-address` | +| [getSubDepositAddress()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2482) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-sub-member-address` | +| [querySubMemberAddress()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2507) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-sub-member-address` | +| [getWithdrawalRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2527) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/query-record` | +| [getWithdrawalAddressList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2539) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/query-address` | +| [getExchangeEntities()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2553) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/vasp/list` | +| [submitDepositOriginatorInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2563) | :closed_lock_with_key: | POST | `/v5/asset/travel-rule/deposit/submit` | +| [submitWithdrawal()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2578) | :closed_lock_with_key: | POST | `/v5/asset/withdraw/create` | +| [cancelWithdrawal()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2589) | :closed_lock_with_key: | POST | `/v5/asset/withdraw/cancel` | +| [getConvertCoins()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2598) | :closed_lock_with_key: | GET | `/v5/asset/exchange/query-coin-list` | +| [requestConvertQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2609) | :closed_lock_with_key: | POST | `/v5/asset/exchange/quote-apply` | +| [confirmConvertQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2618) | :closed_lock_with_key: | POST | `/v5/asset/exchange/convert-execute` | +| [getConvertStatus()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2630) | :closed_lock_with_key: | GET | `/v5/asset/exchange/convert-result-query` | +| [getConvertHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2649) | :closed_lock_with_key: | GET | `/v5/asset/exchange/query-convert-history` | +| [getSmallBalanceList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2666) | :closed_lock_with_key: | GET | `/v5/asset/covert/small-balance-list` | +| [getFiatTradingPairList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2680) | :closed_lock_with_key: | GET | `/v5/fiat/query-coin-list` | +| [createSubMember()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2698) | :closed_lock_with_key: | POST | `/v5/user/create-sub-member` | +| [createSubUIDAPIKey()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2710) | :closed_lock_with_key: | POST | `/v5/user/create-sub-api` | +| [getSubUIDList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2719) | :closed_lock_with_key: | GET | `/v5/user/query-sub-members` | +| [getSubUIDListUnlimited()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2728) | :closed_lock_with_key: | GET | `/v5/user/submembers` | +| [setSubUIDFrozenState()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2746) | :closed_lock_with_key: | POST | `/v5/user/frozen-sub-member` | +| [getQueryApiKey()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2761) | :closed_lock_with_key: | GET | `/v5/user/query-api` | +| [getSubAccountAllApiKeys()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2768) | :closed_lock_with_key: | GET | `/v5/user/sub-apikeys` | +| [getUIDWalletType()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2777) | :closed_lock_with_key: | GET | `/v5/user/get-member-type` | +| [updateMasterApiKey()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2796) | :closed_lock_with_key: | POST | `/v5/user/update-api` | +| [updateSubApiKey()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2810) | :closed_lock_with_key: | POST | `/v5/user/update-sub-api` | +| [deleteSubMember()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2823) | :closed_lock_with_key: | POST | `/v5/user/del-submember` | +| [deleteMasterApiKey()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2838) | :closed_lock_with_key: | POST | `/v5/user/delete-api` | +| [deleteSubApiKey()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2852) | :closed_lock_with_key: | POST | `/v5/user/delete-sub-api` | +| [getAffiliateUserList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2872) | :closed_lock_with_key: | GET | `/v5/affiliate/aff-user-list` | +| [getAffiliateSubAffiliateList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2890) | :closed_lock_with_key: | GET | `/v5/affiliate/affiliate-sub-list` | +| [getAffiliateUserInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2906) | :closed_lock_with_key: | GET | `/v5/user/aff-customer-info` | +| [getFriendReferrals()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2918) | :closed_lock_with_key: | GET | `/v5/user/invitation/referrals` | +| [getReferralCode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2927) | :closed_lock_with_key: | GET | `/v5/user/invitation/code` | +| [signAgreement()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2943) | :closed_lock_with_key: | POST | `/v5/user/agreement` | +| [getAlphaTradeQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2960) | :closed_lock_with_key: | POST | `/v5/alpha/trade/quote` | +| [executeAlphaTradePurchase()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2971) | :closed_lock_with_key: | POST | `/v5/alpha/trade/purchase` | +| [executeAlphaTradeRedeem()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2982) | :closed_lock_with_key: | POST | `/v5/alpha/trade/redeem` | +| [getAlphaPayTokenList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L2992) | :closed_lock_with_key: | POST | `/v5/alpha/trade/pay-token-list` | +| [getAlphaTradeOrderList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3002) | :closed_lock_with_key: | POST | `/v5/alpha/trade/order-list` | +| [getAlphaBizTokenList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3012) | :closed_lock_with_key: | POST | `/v5/alpha/trade/biz-token-list` | +| [getAlphaBizTokenPriceList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3022) | :closed_lock_with_key: | POST | `/v5/alpha/trade/biz-token-price-list` | +| [getAlphaBizTokenDetails()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3032) | :closed_lock_with_key: | POST | `/v5/alpha/trade/biz-token-details` | +| [getAlphaAssetList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3042) | :closed_lock_with_key: | POST | `/v5/alpha/trade/asset-list` | +| [getAlphaAssetDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3050) | :closed_lock_with_key: | POST | `/v5/alpha/trade/asset-detail` | +| [getAlphaPredictionEngineStatus()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3066) | :closed_lock_with_key: | GET | `/v5/alpha/prediction/engine-status` | +| [getAlphaPredictionPayTokenList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3076) | :closed_lock_with_key: | GET | `/v5/alpha/prediction/pay-token-list` | +| [getAlphaPredictionEventDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3086) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/event-detail` | +| [getAlphaPredictionOrderEstimate()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3096) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/order-estimate` | +| [executeAlphaPredictionBuy()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3106) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/buy` | +| [executeAlphaPredictionSell()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3116) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/sell` | +| [getAlphaPredictionOrderList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3126) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/order-list` | +| [getAlphaPredictionOrderBook()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3136) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/order-book` | +| [getAlphaPredictionTokenPrice()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3146) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/token-price` | +| [getAlphaPredictionPriceHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3156) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/price-history` | +| [getAlphaPredictionPositionList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3166) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/position-list` | +| [getAlphaPredictionPositionHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3176) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/position-history` | +| [getAlphaPredictionPortfolioSummary()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3186) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/portfolio-summary` | +| [getAlphaPredictionSideMarketList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3196) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/side-market-list` | +| [getAlphaPredictionSportsMatchList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3206) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/sports/match-list` | +| [getAlphaPredictionSportsTimelineStages()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3216) | :closed_lock_with_key: | GET | `/v5/alpha/prediction/sports/timeline-stages` | +| [getAlphaPredictionSportsGroupStageDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3229) | :closed_lock_with_key: | POST | `/v5/alpha/prediction/sports/group-stage-detail` | +| [getAlphaLPPoolList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3248) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pool-list` | +| [getAlphaLPPoolInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3258) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pool-info` | +| [executeAlphaLPStake()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3268) | :closed_lock_with_key: | POST | `/v5/alpha/lp/stake` | +| [executeAlphaLPRedeem()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3278) | :closed_lock_with_key: | POST | `/v5/alpha/lp/redeem` | +| [getAlphaLPOrderList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3288) | :closed_lock_with_key: | POST | `/v5/alpha/lp/order-list` | +| [getAlphaLPPayTokenList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3298) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pay-token-list` | +| [getAlphaLPPayTokenPrice()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3308) | :closed_lock_with_key: | POST | `/v5/alpha/lp/pay-token-price` | +| [getAlphaLPPositionList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3318) | :closed_lock_with_key: | POST | `/v5/alpha/lp/position-list` | +| [getVIPMarginData()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3338) | | GET | `/v5/spot-margin-trade/data` | +| [getHistoricalInterestRate()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3349) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/interest-rate-history` | +| [getSpotMarginCurrencyData()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3374) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/currency-data` | +| [toggleSpotMarginTrade()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3386) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/switch-mode` | +| [setSpotMarginLeverage()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3397) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/set-leverage` | +| [setSpotMarginLeverageV2()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3405) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/set-leverage` | +| [getSpotMarginState()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3416) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/state` | +| [manualBorrow()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3423) | :closed_lock_with_key: | POST | `/v5/account/borrow` | +| [getMaxBorrowableAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3432) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/max-borrowable` | +| [getPositionTiers()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3441) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/position-tiers` | +| [getCoinState()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3452) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/coinstate` | +| [getAvailableAmountToRepay()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3463) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/repayment-available-amount` | +| [manualRepayWithoutConversion()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3482) | :closed_lock_with_key: | POST | `/v5/account/no-convert-repay` | +| [getAutoRepayMode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3495) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/get-auto-repay-mode` | +| [setAutoRepayMode()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3511) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/set-auto-repay-mode` | +| [getSpotMarginLiability()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3523) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/liability` | +| [submitFixedRateBorrow()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3532) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/fixedborrow` | +| [getFixedRateBorrowOrderInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3541) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixedborrow-order-info` | +| [getFixedRateBorrowContractInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3558) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixedborrow-contract-info` | +| [getFixedRateBorrowOrderQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3575) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixedborrow-order-quote` | +| [renewFixedRateBorrow()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3587) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/fixedborrow-renew` | +| [getFlexibleAvailableInventory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3593) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/flexible-available-inventory` | +| [getFixedRateAvailableInventory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3602) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/fixed-available-inventory` | +| [getSpotMarginCoinInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3620) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/pledge-token` | +| [getSpotMarginBorrowableCoinInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3637) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/borrow-token` | +| [getSpotMarginInterestAndQuota()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3654) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/loan-info` | +| [getSpotMarginLoanAccountInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3672) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/account` | +| [spotMarginBorrow()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3696) | :closed_lock_with_key: | POST | `/v5/spot-cross-margin-trade/loan` | +| [spotMarginRepay()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3707) | :closed_lock_with_key: | POST | `/v5/spot-cross-margin-trade/repay` | +| [getSpotMarginBorrowOrderDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3722) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/orders` | +| [getSpotMarginRepaymentOrderDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3751) | :closed_lock_with_key: | GET | `/v5/spot-cross-margin-trade/repay-history` | +| [toggleSpotCrossMarginTrade()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3780) | :closed_lock_with_key: | POST | `/v5/spot-cross-margin-trade/switch` | +| [getCollateralCoins()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3800) | | GET | `/v5/crypto-loan/collateral-data` | +| [getBorrowableCoins()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3817) | | GET | `/v5/crypto-loan/loanable-data` | +| [getAccountBorrowCollateralLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3835) | :closed_lock_with_key: | GET | `/v5/crypto-loan/borrowable-collateralisable-number` | +| [borrowCryptoLoan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3855) | :closed_lock_with_key: | POST | `/v5/crypto-loan/borrow` | +| [repayCryptoLoan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3876) | :closed_lock_with_key: | POST | `/v5/crypto-loan/repay` | +| [getUnpaidLoanOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3892) | :closed_lock_with_key: | GET | `/v5/crypto-loan/ongoing-orders` | +| [getRepaymentHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3913) | :closed_lock_with_key: | GET | `/v5/crypto-loan/repayment-history` | +| [getCompletedLoanOrderHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3933) | :closed_lock_with_key: | GET | `/v5/crypto-loan/borrow-history` | +| [getMaxAllowedReductionCollateralAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3952) | :closed_lock_with_key: | GET | `/v5/crypto-loan/max-collateral-amount` | +| [adjustCollateralAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3971) | :closed_lock_with_key: | POST | `/v5/crypto-loan/adjust-ltv` | +| [getLoanLTVAdjustmentHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L3995) | :closed_lock_with_key: | GET | `/v5/crypto-loan/adjustment-history` | +| [getLoanBorrowableCoins()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4016) | | GET | `/v5/crypto-loan-common/loanable-data` | +| [getLoanCollateralCoins()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4028) | | GET | `/v5/crypto-loan-common/collateral-data` | +| [getMaxCollateralAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4038) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/max-collateral-amount` | +| [getMaxLoanAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4057) | :closed_lock_with_key: | POST | `/v5/crypto-loan-common/max-loan` | +| [updateCollateralAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4067) | :closed_lock_with_key: | POST | `/v5/crypto-loan-common/adjust-ltv` | +| [getCollateralAdjustmentHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4078) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/adjustment-history` | +| [getCryptoLoanPosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4093) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/position` | +| [borrowFlexible()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4110) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/borrow` | +| [repayFlexible()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4121) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay` | +| [repayCollateralFlexible()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4131) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay-collateral` | +| [getOngoingFlexibleLoans()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4145) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/ongoing-coin` | +| [getBorrowHistoryFlexible()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4157) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/borrow-history` | +| [getRepaymentHistoryFlexible()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4170) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/repayment-history` | +| [getFlexibleLoanAvailableInventory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4184) | :closed_lock_with_key: | GET | `/v5/crypto-loan-flexible/available-inventory` | +| [getSupplyOrderQuoteFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4204) | | GET | `/v5/crypto-loan-fixed/supply-order-quote` | +| [getBorrowOrderQuoteFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4217) | | GET | `/v5/crypto-loan-fixed/borrow-order-quote` | +| [createBorrowOrderFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4230) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/borrow` | +| [createSupplyOrderFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4243) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/supply` | +| [cancelBorrowOrderFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4253) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/borrow-order-cancel` | +| [cancelSupplyOrderFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4267) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/supply-order-cancel` | +| [getBorrowContractInfoFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4280) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/borrow-contract-info` | +| [getSupplyContractInfoFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4298) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/supply-contract-info` | +| [getBorrowOrderInfoFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4316) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/borrow-order-info` | +| [getSupplyOrderInfoFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4329) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/supply-order-info` | +| [repayFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4343) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/fully-repay` | +| [repayCollateralFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4354) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay-collateral` | +| [getRepaymentHistoryFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4367) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/repayment-history` | +| [renewBorrowOrderFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4384) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/renew` | +| [getRenewOrderInfoFixed()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4397) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/renew-info` | +| [getFixedLoanAvailableInventory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4406) | :closed_lock_with_key: | GET | `/v5/crypto-loan-fixed/available-inventory` | +| [getInstitutionalLendingProductInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4421) | | GET | `/v5/ins-loan/product-infos` | +| [getInstitutionalLendingCoinDeltaAmount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4433) | :closed_lock_with_key: | GET | `/v5/ins-loan/coin-delta-amount` | +| [getInstitutionalLendingMarginCoinInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4443) | | GET | `/v5/ins-loan/ensure-tokens` | +| [getInstitutionalLendingMarginCoinInfoWithConversionRate()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4452) | | GET | `/v5/ins-loan/ensure-tokens-convert` | +| [getInstitutionalLendingLoanOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4461) | :closed_lock_with_key: | GET | `/v5/ins-loan/loan-order` | +| [getInstitutionalLendingRepayOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4473) | :closed_lock_with_key: | GET | `/v5/ins-loan/repaid-history` | +| [getInstitutionalLendingLTV()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4485) | :closed_lock_with_key: | GET | `/v5/ins-loan/ltv` | +| [getInstitutionalLendingLTVWithLadderConversionRate()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4494) | :closed_lock_with_key: | GET | `/v5/ins-loan/ltv-convert` | +| [bindOrUnbindUID()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4509) | :closed_lock_with_key: | POST | `/v5/ins-loan/association-uid` | +| [repayInstitutionalLoan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4529) | :closed_lock_with_key: | POST | `/v5/ins-loan/repay-loan` | +| [getExchangeBrokerEarnings()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4550) | :closed_lock_with_key: | GET | `/v5/broker/earnings-info` | +| [getExchangeBrokerAccountInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4563) | :closed_lock_with_key: | GET | `/v5/broker/account-info` | +| [getBrokerSubAccountDeposits()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4579) | :closed_lock_with_key: | GET | `/v5/broker/asset/query-sub-member-deposit-record` | +| [getBrokerVoucherSpec()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4594) | :closed_lock_with_key: | POST | `/v5/broker/award/info` | +| [issueBrokerVoucher()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4606) | :closed_lock_with_key: | POST | `/v5/broker/award/distribute-award` | +| [getBrokerIssuedVoucher()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4618) | :closed_lock_with_key: | POST | `/v5/broker/award/distribution-record` | +| [setBrokerRateLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4635) | :closed_lock_with_key: | POST | `/v5/broker/apilimit/set` | +| [getBrokerRateLimitCap()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4654) | :closed_lock_with_key: | GET | `/v5/broker/apilimit/query-cap` | +| [getAllBrokerRateLimits()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4672) | :closed_lock_with_key: | GET | `/v5/broker/apilimit/query-all` | +| [getEarnProduct()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4692) | | GET | `/v5/earn/product` | +| [getEarnCouponList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4704) | :closed_lock_with_key: | GET | `/v5/earn/coupons` | +| [getRWAProductList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4714) | | GET | `/v5/earn/rwa/product` | +| [placeRWAOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4724) | :closed_lock_with_key: | POST | `/v5/earn/rwa/place-order` | +| [getRWAPositionList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4733) | :closed_lock_with_key: | GET | `/v5/earn/rwa/position` | +| [getRWAOrderList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4742) | :closed_lock_with_key: | GET | `/v5/earn/rwa/order` | +| [getRWANavChart()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4752) | | GET | `/v5/earn/rwa/nav-chart` | +| [getHoldToEarnAirdropProducts()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4763) | | GET | `/v5/earn/hold-to-earn/product` | +| [getAdvanceEarnProduct()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4774) | | GET | `/v5/earn/advance/product` | +| [getLiquidityMiningProduct()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4785) | | GET | `/v5/earn/liquidity-mining/product` | +| [getFixedTermEarnProduct()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4796) | | GET | `/v5/earn/fixed-term/product` | +| [getAdvanceEarnProductExtraInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4808) | | GET | `/v5/earn/advance/product-extra-info` | +| [submitAdvanceEarnPlaceOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4819) | :closed_lock_with_key: | POST | `/v5/earn/advance/place-order` | +| [getAdvanceEarnPosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4830) | :closed_lock_with_key: | GET | `/v5/earn/advance/position` | +| [getAdvanceEarnOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4841) | :closed_lock_with_key: | GET | `/v5/earn/advance/order` | +| [submitFixedTermEarnOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4852) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/place-order` | +| [redeemFixedTermEarn()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4863) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/redeem` | +| [getFixedTermEarnPosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4874) | :closed_lock_with_key: | GET | `/v5/earn/fixed-term/position` | +| [getFixedTermEarnOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4885) | :closed_lock_with_key: | GET | `/v5/earn/fixed-term/order` | +| [setFixedTermEarnAutoInvest()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4896) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/position/auto-invest` | +| [submitStakeRedeem()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4912) | :closed_lock_with_key: | POST | `/v5/earn/place-order` | +| [getEarnOrderHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4931) | :closed_lock_with_key: | GET | `/v5/earn/order` | +| [getEarnPosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4949) | :closed_lock_with_key: | GET | `/v5/earn/position` | +| [modifyEarnPosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4962) | :closed_lock_with_key: | POST | `/v5/earn/position/modify` | +| [getEarnYieldHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4975) | :closed_lock_with_key: | GET | `/v5/earn/yield` | +| [getHoldToEarnAirdropYieldHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L4989) | :closed_lock_with_key: | GET | `/v5/earn/hold-to-earn/yield-history` | +| [getEarnHourlyYieldHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5000) | :closed_lock_with_key: | GET | `/v5/earn/hourly-yield` | +| [getEarnAprHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5014) | | GET | `/v5/earn/apr-history` | +| [getEarnTokenProduct()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5024) | | GET | `/v5/earn/token/product` | +| [submitEarnTokenOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5033) | :closed_lock_with_key: | POST | `/v5/earn/token/place-order` | +| [getEarnTokenOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5042) | :closed_lock_with_key: | GET | `/v5/earn/token/order` | +| [getEarnTokenPosition()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5054) | :closed_lock_with_key: | GET | `/v5/earn/token/position` | +| [getEarnTokenDailyYield()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5063) | :closed_lock_with_key: | GET | `/v5/earn/token/yield` | +| [getEarnTokenHourlyYield()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5075) | :closed_lock_with_key: | GET | `/v5/earn/token/hourly-yield` | +| [getEarnTokenHistoryApr()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5087) | | GET | `/v5/earn/token/history-apr` | +| [getPwmInvestmentPlanList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5102) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/list` | +| [getPwmInvestmentPlanDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5111) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/detail` | +| [getPwmPendingInvestmentPlanDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5120) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/new-plan` | +| [claimPwmWithdrawableFunds()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5129) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/claim` | +| [getPwmInvestmentPlanAssetTrend()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5138) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/asset-trend` | +| [getPwmFundHistoricalNav()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5147) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/fund-nav` | +| [subscribePwmInvestmentPlan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5156) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/subscribe` | +| [investMorePwmInvestmentPlan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5165) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/invest-more` | +| [redeemPwmInvestmentPlan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5174) | :closed_lock_with_key: | POST | `/v5/earn/pwm/investment-plan/redeem` | +| [getPwmInvestmentPlanOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5183) | :closed_lock_with_key: | GET | `/v5/earn/pwm/investment-plan/order` | +| [getPwmSubscribableProductInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5192) | | GET | `/v5/earn/pwm/customize-plan/product` | +| [createPwmCustomizeInvestmentPlan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5201) | :closed_lock_with_key: | POST | `/v5/earn/pwm/customize-plan/create` | +| [getPwmAllFunds()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5216) | :closed_lock_with_key: | GET | `/v5/earn/pwm/asset-manager/all-funds` | +| [settlePwmFundProfit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5225) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/settle-profit` | +| [createPwmFund()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5234) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/create-fund` | +| [createPwmAssetManagerInvestmentPlan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5243) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/create-investment-plan` | +| [getPwmAssetManagerInvestmentPlans()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5257) | :closed_lock_with_key: | GET | `/v5/earn/pwm/asset-manager/get-investment-plan` | +| [managePwmAssetManagerInvestmentPlan()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5269) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/manage-investment-plan` | +| [getPwmAllFundOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5283) | :closed_lock_with_key: | GET | `/v5/earn/pwm/asset-manager/all-order` | +| [managePwmFundOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5292) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/manage-order` | +| [createPwmFundSubAccount()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5301) | :closed_lock_with_key: | POST | `/v5/earn/pwm/asset-manager/create-sub-account` | +| [pwmFundTransfer()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5313) | :closed_lock_with_key: | POST | `/v5/earn/pwm/fund-transfer` | +| [getPwmFundTransferRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5322) | :closed_lock_with_key: | GET | `/v5/earn/pwm/query-fund-transfer-result` | +| [queryCardAssetRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5337) | :closed_lock_with_key: | POST | `/v5/card/transaction/query-asset-records` | +| [queryCardPointsBalance()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5346) | :closed_lock_with_key: | POST | `/v5/card/reward/points/balance` | +| [queryCardPointsRecords()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5353) | :closed_lock_with_key: | POST | `/v5/card/reward/points/records` | +| [queryCardPointsTier()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5362) | :closed_lock_with_key: | POST | `/v5/card/reward/points/tier` | +| [queryCardMallItemList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5369) | :closed_lock_with_key: | POST | `/v5/card/reward/mall/item/list` | +| [queryCardPointCashbackDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5378) | :closed_lock_with_key: | POST | `/v5/card/reward/point/cashback/detail` | +| [createRFQ()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5394) | :closed_lock_with_key: | POST | `/v5/rfq/create-rfq` | +| [getRFQConfig()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5405) | :closed_lock_with_key: | GET | `/v5/rfq/config` | +| [cancelRFQ()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5414) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-rfq` | +| [cancelAllRFQ()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5424) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-all-rfq` | +| [createRFQQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5433) | :closed_lock_with_key: | POST | `/v5/rfq/create-quote` | +| [executeRFQQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5444) | :closed_lock_with_key: | POST | `/v5/rfq/execute-quote` | +| [cancelRFQQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5455) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-quote` | +| [cancelAllRFQQuotes()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5465) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-all-quotes` | +| [getRFQRealtimeInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5479) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-realtime` | +| [getRFQHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5491) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-list` | +| [getRFQRealtimeQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5505) | :closed_lock_with_key: | GET | `/v5/rfq/quote-realtime` | +| [getRFQHistoryQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5520) | :closed_lock_with_key: | GET | `/v5/rfq/quote-list` | +| [getRFQTrades()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5533) | :closed_lock_with_key: | GET | `/v5/rfq/trade-list` | +| [getRFQPublicTrades()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5546) | :closed_lock_with_key: | GET | `/v5/rfq/public-trades` | +| [acceptNonLPQuote()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5562) | :closed_lock_with_key: | POST | `/v5/rfq/accept-other-quote` | +| [getRFQDetails()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5568) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-detail-list` | +| [getP2PAccountCoinsBalance()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5593) | :closed_lock_with_key: | GET | `/v5/asset/transfer/query-account-coins-balance` | +| [getP2POnlineAds()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5610) | :closed_lock_with_key: | POST | `/v5/p2p/item/online` | +| [createP2PAd()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5619) | :closed_lock_with_key: | POST | `/v5/p2p/item/create` | +| [cancelP2PAd()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5628) | :closed_lock_with_key: | POST | `/v5/p2p/item/cancel` | +| [updateP2PAd()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5642) | :closed_lock_with_key: | POST | `/v5/p2p/item/update` | +| [getP2PPersonalAds()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5652) | :closed_lock_with_key: | POST | `/v5/p2p/item/personal/list` | +| [getP2PAdDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5661) | :closed_lock_with_key: | POST | `/v5/p2p/item/info` | +| [getP2POrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5676) | :closed_lock_with_key: | POST | `/v5/p2p/order/simplifyList` | +| [getP2POrderDetail()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5686) | :closed_lock_with_key: | POST | `/v5/p2p/order/info` | +| [getP2PPendingOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5695) | :closed_lock_with_key: | POST | `/v5/p2p/order/pending/simplifyList` | +| [markP2POrderAsPaid()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5704) | :closed_lock_with_key: | POST | `/v5/p2p/order/pay` | +| [releaseP2POrder()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5713) | :closed_lock_with_key: | POST | `/v5/p2p/order/finish` | +| [sendP2POrderMessage()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5722) | :closed_lock_with_key: | POST | `/v5/p2p/order/message/send` | +| [getP2POrderMessages()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5756) | :closed_lock_with_key: | POST | `/v5/p2p/order/message/listpage` | +| [getP2PUserInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5770) | :closed_lock_with_key: | POST | `/v5/p2p/user/personal/info` | +| [getP2PCounterpartyUserInfo()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5777) | :closed_lock_with_key: | POST | `/v5/p2p/user/order/personal/info` | +| [getP2PUserPayments()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5786) | :closed_lock_with_key: | POST | `/v5/p2p/user/payment/list` | +| [setApiRateLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5806) | :closed_lock_with_key: | POST | `/v5/apilimit/set` | +| [queryApiRateLimit()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5835) | :closed_lock_with_key: | GET | `/v5/apilimit/query` | +| [getRateLimitCap()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5854) | :closed_lock_with_key: | GET | `/v5/apilimit/query-cap` | +| [getAllRateLimits()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5873) | :closed_lock_with_key: | GET | `/v5/apilimit/query-all` | +| [getLaunchpoolProjectList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5896) | | GET | `/v5/spot-x/launchpool/project/list` | +| [getLaunchpoolUserActivityLog()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5902) | :closed_lock_with_key: | POST | `/v5/spot-x/launchpool/user/activity-log` | +| [getLaunchpoolCurrentStaking()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5908) | :closed_lock_with_key: | GET | `/v5/spot-x/launchpool/user/current-staking` | +| [getLaunchpoolUserHistory()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5914) | :closed_lock_with_key: | POST | `/v5/spot-x/launchpool/user/history` | +| [getPuzzleProjectList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5920) | | GET | `/v5/spot-x/puzzle/project/list` | +| [getTokenSplashProjectList()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5926) | | GET | `/v5/spot-x/token-splash/project/list` | +| [getTokenSplashUserActivityParams()](https://github.com/sieblyio/bybit-api/blob/master/src/rest-client-v5.ts#L5932) | :closed_lock_with_key: | GET | `/v5/spot-x/token-splash/user/activity-params` | # websocket-api-client.ts @@ -444,9 +458,9 @@ This client provides WebSocket API endpoints which allow for faster interactions | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [submitNewOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-api-client.ts#L95) | :closed_lock_with_key: | WS | `order.create` | -| [amendOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-api-client.ts#L111) | :closed_lock_with_key: | WS | `order.amend` | -| [cancelOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-api-client.ts#L127) | :closed_lock_with_key: | WS | `order.cancel` | -| [batchSubmitOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-api-client.ts#L143) | :closed_lock_with_key: | WS | `order.create-batch` | -| [batchAmendOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-api-client.ts#L171) | :closed_lock_with_key: | WS | `order.amend-batch` | -| [batchCancelOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/websocket-api-client.ts#L199) | :closed_lock_with_key: | WS | `order.cancel-batch` | \ No newline at end of file +| [submitNewOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/websocket-api-client.ts#L95) | :closed_lock_with_key: | WS | `order.create` | +| [amendOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/websocket-api-client.ts#L111) | :closed_lock_with_key: | WS | `order.amend` | +| [cancelOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/websocket-api-client.ts#L127) | :closed_lock_with_key: | WS | `order.cancel` | +| [batchSubmitOrders()](https://github.com/sieblyio/bybit-api/blob/master/src/websocket-api-client.ts#L143) | :closed_lock_with_key: | WS | `order.create-batch` | +| [batchAmendOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/websocket-api-client.ts#L171) | :closed_lock_with_key: | WS | `order.amend-batch` | +| [batchCancelOrder()](https://github.com/sieblyio/bybit-api/blob/master/src/websocket-api-client.ts#L199) | :closed_lock_with_key: | WS | `order.cancel-batch` | \ No newline at end of file diff --git a/examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-available-inventory.js b/examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-available-inventory.js new file mode 100644 index 00000000..06e38eda --- /dev/null +++ b/examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-available-inventory.js @@ -0,0 +1,22 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getFixedLoanAvailableInventory({ + currency: 'USDT', + term: '7', + annualRate: '0.02', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/get-available-inventory.js b/examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/get-available-inventory.js new file mode 100644 index 00000000..c645ee82 --- /dev/null +++ b/examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/get-available-inventory.js @@ -0,0 +1,20 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getFlexibleLoanAvailableInventory({ + currency: 'USDT', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Market/get-full-depth-orderbook.js b/examples/apidoc/V5/Market/get-full-depth-orderbook.js new file mode 100644 index 00000000..80a675ca --- /dev/null +++ b/examples/apidoc/V5/Market/get-full-depth-orderbook.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, +}); + +client + .getFullDepthOrderbook({ + category: 'spot', + symbol: 'BTCUSDT', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/RFQ/get-rfq-details.js b/examples/apidoc/V5/RFQ/get-rfq-details.js new file mode 100644 index 00000000..80ed35f5 --- /dev/null +++ b/examples/apidoc/V5/RFQ/get-rfq-details.js @@ -0,0 +1,21 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getRFQDetails({ + traderType: 'request', + limit: 50, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-fixed-rate-available-inventory.js b/examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-fixed-rate-available-inventory.js new file mode 100644 index 00000000..aa3c4c51 --- /dev/null +++ b/examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-fixed-rate-available-inventory.js @@ -0,0 +1,22 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getFixedRateAvailableInventory({ + currency: 'USDT', + term: '7', + annualRate: '0.02', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-flexible-available-inventory.js b/examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-flexible-available-inventory.js new file mode 100644 index 00000000..2e44b480 --- /dev/null +++ b/examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-flexible-available-inventory.js @@ -0,0 +1,20 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getFlexibleAvailableInventory({ + currency: 'BTC', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-current-staking.js b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-current-staking.js new file mode 100644 index 00000000..f60d7083 --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-current-staking.js @@ -0,0 +1,18 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getLaunchpoolCurrentStaking() + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-project-list.js b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-project-list.js new file mode 100644 index 00000000..d8d9a0bf --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-project-list.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, +}); + +client + .getLaunchpoolProjectList({ + status: 1, + limit: 10, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-user-activity-log.js b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-user-activity-log.js new file mode 100644 index 00000000..fc40f069 --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-user-activity-log.js @@ -0,0 +1,24 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getLaunchpoolUserActivityLog({ + stakeCoin: 'USDT', + type: 0, + status: 1, + pageSize: 10, + current: 1, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-user-history.js b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-user-history.js new file mode 100644 index 00000000..191d62a2 --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Launchpool/get-launchpool-user-history.js @@ -0,0 +1,21 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getLaunchpoolUserHistory({ + pageSize: 10, + current: 1, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Puzzle/get-puzzle-project-list.js b/examples/apidoc/V5/Spot-X/Puzzle/get-puzzle-project-list.js new file mode 100644 index 00000000..22a04267 --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Puzzle/get-puzzle-project-list.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, +}); + +client + .getPuzzleProjectList({ + status: 1, + limit: 10, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Token-Splash/get-token-splash-project-list.js b/examples/apidoc/V5/Spot-X/Token-Splash/get-token-splash-project-list.js new file mode 100644 index 00000000..48f749d2 --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Token-Splash/get-token-splash-project-list.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, +}); + +client + .getTokenSplashProjectList({ + status: 1, + limit: 10, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Spot-X/Token-Splash/get-token-splash-user-activity-params.js b/examples/apidoc/V5/Spot-X/Token-Splash/get-token-splash-user-activity-params.js new file mode 100644 index 00000000..a611e145 --- /dev/null +++ b/examples/apidoc/V5/Spot-X/Token-Splash/get-token-splash-user-activity-params.js @@ -0,0 +1,20 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getTokenSplashUserActivityParams({ + activityCoin: 'BTC', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/User/get-referral-code.js b/examples/apidoc/V5/User/get-referral-code.js new file mode 100644 index 00000000..ab5a3fec --- /dev/null +++ b/examples/apidoc/V5/User/get-referral-code.js @@ -0,0 +1,18 @@ +import { RestClientV5 } from 'bybit-api'; +// or, if require is preferred: +// const { RestClientV5 } = require('bybit-api'); + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getReferralCode() + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index 9ad57953..766890c7 100644 --- a/llms.txt +++ b/llms.txt @@ -114,6 +114,7 @@ src/ v5-rfq.ts v5-rwa.ts v5-spot-leverage-token.ts + v5-spot-x.ts v5-spreadtrading.ts v5-strategy.ts v5-trade.ts @@ -147,6 +148,7 @@ src/ v5-rfq.ts v5-rwa.ts v5-spot-leverage-token.ts + v5-spot-x.ts v5-spreadtrading.ts v5-strategy.ts v5-trade.ts @@ -1555,169 +1557,6 @@ export interface USDCPositionsRequest { cursor?: string; } -================ -File: src/types/request/v5-alpha-lp.ts -================ -/** - * V5 private Alpha LP requests. - */ -⋮---- -export interface GetAlphaLPPoolListParamsV5 { - tokenSymbol?: string; -} -⋮---- -export interface GetAlphaLPPoolInfoParamsV5 { - poolAddress: string; -} -⋮---- -export interface ExecuteAlphaLPStakeParamsV5 { - positionId: number; - poolAddress: string; - payTokenAmount: string; - payTokenCode: string; - rangeUpper?: string; - rangeLower?: string; - priceUpper?: string; - priceLower?: string; -} -⋮---- -export interface ExecuteAlphaLPRedeemParamsV5 { - positionId: number; - poolAddress: string; - dercRatio: string; - receiveTokenCode?: string; -} -⋮---- -export interface GetAlphaLPOrderListParamsV5 { - orderType?: 0 | 1 | 2; - tokenCode?: string; - orderStatus?: number[]; - days?: number; - limit?: number; - pageIndex?: number; - poolAddress?: string; -} -⋮---- -export interface GetAlphaLPPayTokenListParamsV5 { - chainCode?: string; - tokenAddress?: string; -} -⋮---- -export interface GetAlphaLPPayTokenPriceParamsV5 { - tokenCode: string[]; - chainCode?: string; -} - -================ -File: src/types/request/v5-alpha-prediction.ts -================ -/** - * V5 private Alpha prediction market requests. - */ -⋮---- -export interface GetAlphaPredictionEventDetailParamsV5 { - eventId?: string; - slug?: string; - hasMoreMarkets?: boolean; -} -⋮---- -export interface GetAlphaPredictionOrderEstimateParamsV5 { - tokenId: string; - side: 1 | 2; - eventId: string; - amount: string; - orderType: 1; - payTokenCode?: string; -} -⋮---- -export interface ExecuteAlphaPredictionBuyParamsV5 { - tokenId: string; - amount: string; - payTokenCode: string; - orderType: 1; - slippage: string; - eventId: string; -} -⋮---- -export interface ExecuteAlphaPredictionSellParamsV5 { - tokenId: string; - size: string; - orderType: 1; - slippage: string; - eventId: string; - toTokenCode?: string; -} -⋮---- -export interface GetAlphaPredictionOrderListParamsV5 { - status?: number; - tokenId?: string; - eventId?: string; - side?: 1 | 2; - days?: number; - limit?: number; - pageIndex?: number; -} -⋮---- -export interface GetAlphaPredictionOrderBookParamsV5 { - tokenIds: string[]; -} -⋮---- -export interface GetAlphaPredictionTokenPriceParamsV5 { - tokenIds: string[]; -} -⋮---- -export interface GetAlphaPredictionPriceHistoryParamsV5 { - tokenId: string; - interval: string; -} -⋮---- -export interface GetAlphaPredictionPositionListParamsV5 { - tokenId?: string; - eventId?: string; - limit?: number; - pageIndex?: number; -} -⋮---- -export interface GetAlphaPredictionPositionHistoryParamsV5 { - tokenId?: string; - eventId?: string; - result?: number; - days?: number; - limit?: number; - pageIndex?: number; -} -⋮---- -export interface GetAlphaPredictionPortfolioSummaryParamsV5 { - eventType?: number; -} -⋮---- -export interface GetAlphaPredictionSideMarketListParamsV5 { - eventId: string; - sortBy?: string; - marketType?: number; - limit?: number; - pageIndex?: number; -} -⋮---- -export interface GetAlphaPredictionSportsMatchListParamsV5 { - eventType: number; - status?: number; - startTime?: number; - endTime?: number; - stageCode?: string; - limit?: number; - pageIndex?: number; -} -⋮---- -export interface GetAlphaPredictionSportsTimelineStagesParamsV5 { - eventType: number; -} -⋮---- -export interface GetAlphaPredictionSportsGroupStageDetailParamsV5 { - eventType: number; - groupName?: string; -} - ================ File: src/types/request/v5-p2p-trading.ts ================ @@ -1919,44 +1758,6 @@ export interface GetPreUpgradeUSDCSessionParamsV5 { cursor?: string; } -================ -File: src/types/request/v5-rwa.ts -================ -/** - * V5 RWA (Real World Assets) earn requests. - */ -⋮---- -export interface GetRWAProductListParamsV5 { - coin?: string; -} -⋮---- -export interface PlaceRWAOrderParamsV5 { - productId: number; - orderType: 'Stake' | 'Redeem'; - coin: string; - orderLinkId: string; - stakeAmount?: string; - redeemShares?: string; - accountType?: 'FUND' | 'UNIFIED'; -} -⋮---- -export interface GetRWAOrderListParamsV5 { - orderId?: string; - orderLinkId?: string; - orderType?: 'Stake' | 'Redeem'; - productId?: number; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetRWANavChartParamsV5 { - productId: number; - startTime?: number; - endTime?: number; -} - ================ File: src/types/response/account-asset.ts ================ @@ -2198,123 +1999,45 @@ export interface APIKeyInfoV3 { } ================ -File: src/types/response/contract.ts +File: src/types/response/shared.ts ================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -export interface PaginatedResult { - nextPageCursor: string; - list: TList[]; +export interface SymbolWalletBalance { + equity: number; + available_balance: number; + used_margin: number; + order_margin: number; + position_margin: number; + occ_closing_fee: number; + occ_funding_fee: number; + wallet_balance: number; + realised_pnl: number; + unrealised_pnl: number; + cum_realised_pnl: number; + given_cash: number; + service_cash: number; } -export interface ContractListResult { - category: string; - list: TList[]; +⋮---- +export interface WalletBalances { + [symbol: string]: SymbolWalletBalance | undefined; +} + +================ +File: src/types/response/spot.ts +================ +export interface SpotBalance { + coin: string; + coinId: string; + coinName: string; + total: string; + free: string; + locked: string; } ⋮---- -export interface ContractHistoricOrder { - symbol: string; - orderId: string; - orderLinkId: string; - side: string; - orderType: string; - price: string; - iv: string; - qty: string; - timeInForce: string; - orderStatus: string; - positionIdx: number; - lastPriceOnCreated: string; - createdTime: string; - updatedTime: string; - cancelType: string; - rejectReason: string; - stopOrderType: string; - triggerDirection: number; - triggerBy: string; - triggerPrice: string; - cumExecValue: string; - cumExecFee: string; - cumExecQty: string; - leavesValue: string; - leavesQty: string; - takeProfit: string; - stopLoss: string; - tpslMode: string; - tpLimitPrice: string; - slLimitPrice: string; - tpTriggerBy: string; - slTriggerBy: string; - reduceOnly: boolean; - closeOnTrigger: boolean; - blockTradeId: string; - smpType: string; - smpGroup: number; - smpOrderId: string; -} -⋮---- -export interface ContractSymbolTicker { - symbol: string; - bidPrice: string; - askPrice: string; - lastPrice: string; - lastTickDirection: string; - prevPrice24h: string; - price24hPcnt: string; - highPrice24h: string; - lowPrice24h: string; - prevPrice1h: string; - markPrice: string; - indexPrice: string; - openInterest: string; - turnover24h: string; - volume24h: string; - fundingRate: string; - nextFundingTime: string; - predictedDeliveryPrice: string; - basisRate: string; - deliveryFeeRate: string; - deliveryTime: string; -} - -================ -File: src/types/response/shared.ts -================ -export interface SymbolWalletBalance { - equity: number; - available_balance: number; - used_margin: number; - order_margin: number; - position_margin: number; - occ_closing_fee: number; - occ_funding_fee: number; - wallet_balance: number; - realised_pnl: number; - unrealised_pnl: number; - cum_realised_pnl: number; - given_cash: number; - service_cash: number; -} -⋮---- -export interface WalletBalances { - [symbol: string]: SymbolWalletBalance | undefined; -} - -================ -File: src/types/response/spot.ts -================ -export interface SpotBalance { - coin: string; - coinId: string; - coinName: string; - total: string; - free: string; - locked: string; -} -⋮---- -export interface SpotBalances { - balances: SpotBalance[]; -} -⋮---- -export interface SpotLastPrice { +export interface SpotBalances { + balances: SpotBalance[]; +} +⋮---- +export interface SpotLastPrice { symbol: string; price: string; } @@ -2457,1496 +2180,1228 @@ export interface LinearOrder { } ================ -File: src/types/response/v5-alpha-lp.ts +File: src/types/response/v5-p2p-trading.ts ================ -/** - * V5 private Alpha LP responses. - */ +import { P2PTradingPreferenceSetV5 } from '../request/v5-p2p-trading'; ⋮---- -export interface AlphaLPPoolV5 { - poolAddress: string; - poolName: string; - poolTag: string; - apy: string; - tvl: string; - token0Symbol: string; - token0IconUrlDay: string; - token0IconUrlNight: string; - token1Symbol: string; - token1IconUrlDay: string; - token1IconUrlNight: string; - chainCode: string; - chainIconUrl: string; +export interface P2PCoinBalanceV5 { + coin: string; + transferBalance: string; + walletBalance: string; + bonus: string; } ⋮---- -export interface AlphaLPPoolListResultV5 { - pools: AlphaLPPoolV5[]; +export interface P2PAccountCoinsBalanceV5 { + memberId: string; + accountType: string; + balance: P2PCoinBalanceV5[]; } ⋮---- -export interface AlphaLPPoolInfoV5 { - poolAddress: string; - poolName: string; - apy: string; - tvl: string; - feeRate: string; - token0Symbol: string; - token0Reserve: string; - token1Symbol: string; - token1Reserve: string; - priceRangeLower: string; - priceRangeUpper: string; - currentPrice: string; +export interface P2POnlineAdV5 { + id: string; + nickName: string; + tokenId: string; + currencyId: string; + side: string; + price: string; + lastQuantity: string; + minAmount: string; + maxAmount: string; + payments: string[]; + recentOrderNum: number; + recentExecuteRate: number; + isOnline: boolean; + authTag: string[]; + paymentPeriod: number; + accountId: number; + userId: number; + priceType: number; + premium: string; + quantity: string; + frozenQuantity: string; + executedQuantity: string; + remark: string; + status: number; + createDate: string; + orderNum: string; + finishNum: string; + fee: string; + lastLogoutTime: string; + blocked: string; + makerContact: boolean; + symbolInfo: { + id: string; + exchangeId: string; + orgId: string; + tokenId: string; + currencyId: string; + status: string; + lowerLimitAlarm: number; + upperLimitAlarm: number; + itemDownRange: string; + itemUpRange: string; + currencyMinQuote: string; + currencyMaxQuote: string; + currencyLowerMaxQuote: string; + tokenMinQuote: string; + tokenMaxQuote: string; + kycCurrencyLimit: string; + itemSideLimit: string; + buyFeeRate: string; + sellFeeRate: string; + orderAutoCancelMinute: number; + orderFinishMinute: number; + tradeSide: number; + currency: { + id: string; + exchangeId: string; + orgId: string; + currencyId: string; + scale: number; + }; + token: { + id: string; + exchangeId: string; + orgId: string; + tokenId: string; + scale: number; + sequence: number; + }; + buyAd: number; + sellAd: number; + }; + tradingPreferenceSet: { + hasUnPostAd: number; + isKyc: number; + isEmail: number; + isMobile: number; + hasRegisterTime: number; + registerTimeThreshold: number; + orderFinishNumberDay30: number; + completeRateDay30: number; + nationalLimit: number; + hasOrderFinishNumberDay30: number; + hasCompleteRateDay30: number; + hasNationalLimit: number; + }; + version: number; + authStatus: number; + recommend: boolean; + recommendTag: string; + userType: string; + itemType: string; } ⋮---- -export interface ExecuteAlphaLPStakeResultV5 { - positionId: number; - orderNo: string; +export interface P2POnlineAdsResponseV5 { + count: number; + items: P2POnlineAdV5[]; } ⋮---- -export interface ExecuteAlphaLPRedeemResultV5 { - orderNo: string; +export interface P2PCreateAdResponseV5 { + itemId: string; + securityRiskToken: string; + riskTokenType: string; + riskVersion: string; + needSecurityRisk: boolean; } ⋮---- -export interface AlphaLPOrderV5 { - orderType: number; - orderNo: string; - orderStatus: number; - poolAddress: string; - poolName: string; - positionId: number; - tokenCode: string; - tokenSymbol: string; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - amount: string; - chainCode: string; - chainIconUrl: string; - gasTokenSymbol: string; - gasOnchain: string; - gasUsd: string | null; - platformFee: string; - platformFeeUsd: string | null; - createTime: number; - executionTime: number; - failureReason?: string; - dercRatio?: string; -} -⋮---- -export interface AlphaLPOrderListResultV5 { - total: number; - pageIndex: number; - orders: AlphaLPOrderV5[]; -} -⋮---- -export interface AlphaLPPayTokenV5 { - tokenCode: string; - tokenSymbol: string; - chainCode: string; - chainIconUrl: string; - decimals: number; - availableBalance: string; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - minStakeAmount: string; - maxStakeAmount: string; +export interface P2PPaymentTermV5 { + id: string; + realName: string; + paymentType: number; + bankName: string; + branchName: string; + accountNo: string; + qrcode: string; + visible: number; + payMessage: string; + firstName: string; + lastName: string; + secondLastName: string; + clabe: string; + debitCardNumber: string; + mobile: string; + businessName: string; + concept: string; + paymentExt1: string; + paymentExt2: string; + paymentExt3: string; + paymentExt4: string; + paymentExt5: string; + paymentExt6: string; + paymentTemplateVersion: number; + paymentConfig: { + paymentType: number; + paymentName: string; + paymentDialect: string; + }; + realNameVerified: boolean; } ⋮---- -export interface AlphaLPPayTokenListResultV5 { - tokens: AlphaLPPayTokenV5[]; +export interface P2PAdDetailV5 { + id: string; + accountId: string; + userId: string; + nickName: string; + tokenId: string; + tokenName: string; + currencyId: string; + side: number; + priceType: number; + price: string; + premium: string; + lastQuantity: string; + quantity: string; + frozenQuantity: string; + executedQuantity: string; + minAmount: string; + maxAmount: string; + remark: string; + status: number; + createDate: string; + payments: string[]; + orderNum: number; + finishNum: number; + recentOrderNum: number; + recentExecuteRate: number; + fee: string; + isOnline: boolean; + lastLogoutTime: string; + symbolInfo: { + id: string; + exchangeId: string; + orgId: string; + tokenId: string; + currencyId: string; + status: number; + lowerLimitAlarm: number; + upperLimitAlarm: number; + itemDownRange: string; + itemUpRange: string; + currencyMinQuote: string; + currencyMaxQuote: string; + currencyLowerMaxQuote: string; + tokenMinQuote: string; + tokenMaxQuote: string; + kycCurrencyLimit: string; + itemSideLimit: number; + buyFeeRate: string; + sellFeeRate: string; + orderAutoCancelMinute: number; + orderFinishMinute: number; + tradeSide: number; + currency: { + id: string; + exchangeId: string; + orgId: string; + currencyId: string; + scale: number; + }; + token: { + id: string; + exchangeId: string; + orgId: string; + tokenId: string; + scale: number; + sequence: number; + }; + buyAd: { + paymentPeriods: number[]; + }; + sellAd: { + paymentPeriods: number[]; + }; + }; + tradingPreferenceSet: P2PTradingPreferenceSetV5; + paymentTerms: P2PPaymentTermV5[]; + version: number; + updateDate: string; + feeRate: string; + paymentPeriod: number; + itemType: string; } ⋮---- -export interface AlphaLPPayTokenPriceV5 { - tokenCode: string; - tokenSymbol: string; - priceUsd: string; - chainCode: string; - updateTime: number; +export interface P2PPersonalAdsResponseV5 { + count: number; + items: P2PAdDetailV5[]; + hiddenFlag: boolean; } ⋮---- -export interface AlphaLPPayTokenPriceResultV5 { - prices: AlphaLPPayTokenPriceV5[]; +export interface P2POrderExtensionV5 { + isDelayWithdraw: boolean; + delayTime: string; + startTime: string; } ⋮---- -export interface AlphaLPPositionV5 { - positionId: number; - poolAddress: string; - poolName: string; - stakedAmount: string; - stakedTokenCode: string; - stakedTokenSymbol: string; - currentValueUsd: string; - earnedRewardsUsd: string; - unrealizedPnl: string; - realizedPnl: string; - apy: string; - token0Amount: string; - token0Symbol: string; - token1Amount: string; - token1Symbol: string; - rangeUpper: string; - rangeLower: string; - createTime: number; - updateTime: number; +export interface P2POrderV5 { + id: string; + side: number; + tokenId: string; + orderType: string; + amount: string; + currencyId: string; + price: string; + notifyTokenQuantity?: string; + notifyTokenId?: string; + fee: string; + targetNickName: string; + targetUserId: string; status: number; + selfUnreadMsgCount: string; + createDate: string; + transferLastSeconds: string; + appealLastSeconds: string; + userId: string; + sellerRealName: string; + buyerRealName: string; + judgeInfo: { + autoJudgeUnlockTime: string; + dissentResult: string; + preDissent: string; + postDissent: string; + }; + unreadMsgCount: string; + extension: P2POrderExtensionV5; + bulkOrderFlag: boolean; } ⋮---- -export interface AlphaLPPositionListResultV5 { - positions: AlphaLPPositionV5[]; -} - -================ -File: src/types/response/v5-alpha-prediction.ts -================ -/** - * V5 private Alpha prediction market responses. - */ -⋮---- -export interface AlphaPredictionEngineStatusV5 { - available: boolean; +export interface P2POrdersResponseV5 { + count: number; + items: P2POrderV5[]; } ⋮---- -export interface AlphaPredictionPayTokenV5 { - tokenCode: string; - symbol: string; - tokenDecimals: number; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - supportChains: string[]; +export interface P2PPaymentConfigItemV5 { + view: boolean; + name: string; + label: string; + placeholder: string; + type: string; + maxLength: string; + required: boolean; } ⋮---- -export interface AlphaPredictionMarketV5 { - tokenId: string; - outcome: string; - price: string; - side: number; - volume: string; - liquidity: string; +export interface P2PPaymentConfigV5 { + paymentType: string; + checkType: number; + sort: number; + paymentName: string; + addTips: string; + itemTips: string; + online: number; + items: P2PPaymentConfigItemV5[]; } ⋮---- -export interface AlphaPredictionEventDetailV5 { - eventId: string; - slug: string; - title: string; - description: string; - category: string; - endDate: number; - resolved: boolean; - volume: string; - liquidity: string; - markets: AlphaPredictionMarketV5[]; -} -⋮---- -export interface AlphaPredictionOrderEstimateFeeDetailV5 { - serverFee: string; - polymarketFee: string; +export interface P2PPaymentTermDetailV5 { + id: string; + realName: string; + paymentType: number; + bankName: string; + branchName: string; + accountNo: string; + qrcode: string; + visible: number; + payMessage: string; + firstName: string; + lastName: string; + secondLastName: string; + clabe: string; + debitCardNumber: string; + mobile: string; + businessName: string; + concept: string; + online: string; + paymentExt1: string; + paymentExt2: string; + paymentExt3: string; + paymentExt4: string; + paymentExt5: string; + paymentExt6: string; + paymentTemplateVersion: number; + paymentConfigVo: P2PPaymentConfigV5; + ruPaymentPrompt: boolean; } ⋮---- -export interface AlphaPredictionOrderEstimateV5 { - avgPrice: string; - estimatedCost: string; - estimatedReceive: string; - toWin?: string; - feeAmount: string; - feeDetail: AlphaPredictionOrderEstimateFeeDetailV5; - slippage: string; +export interface P2PAppraiseInfoV5 { + anonymous: string; + appraiseContent: string; + appraiseId: string; + appraiseType: string; + modifyFlag: string; + updateDate: string; } ⋮---- -export interface ExecuteAlphaPredictionOrderResultV5 { - orderNo: string; +export interface P2PJudgeInfoV5 { + autoJudgeUnlockTime: string; + dissentResult: string; + preDissent: string; + postDissent: string; } ⋮---- -export interface AlphaPredictionOrderV5 { - orderNo: string; - tokenId: string; - eventId: string; +export interface P2POrderDetailV5 { + id: string; side: number; - orderType: number; - orderAmount: string; - filledSize: string; - filledPrice: string; - totalFee: string; - status: number; - createdAt: number; - updatedAt: number; -} -⋮---- -export interface AlphaPredictionOrderListResultV5 { - orders: AlphaPredictionOrderV5[]; - total: number; - pageIndex: number; -} -⋮---- -export interface AlphaPredictionOrderBookLevelV5 { + itemId: string; + accountId: string; + userId: string; + nickName: string; + makerUserId: string; + targetAccountId: string; + targetUserId: string; + targetNickName: string; + targetFirstName: string; + targetSecondName: string; + targetUserAuthStatus: number; + targetConnectInformation: string; + payerRealName: string; + sellerRealName: string; + buyerRealName: string; + tokenId: string; + tokenName: string; + currencyId: string; price: string; - size: string; + quantity: string; + amount: string; + payCode: string; + paymentType: number; + transferDate: string; + status: number; + createDate: string; + paymentTermList: P2PPaymentTermDetailV5[]; + remark: string; + transferLastSeconds: string; + recentOrderNum: number; + recentExecuteRate: number; + appealLastSeconds: string; + appealContent: string; + appealType: number; + appealNickName: string; + canAppeal: string; + totalAppealTimes: string; + appealedTimes: string; + paymentTermResult: P2PPaymentTermDetailV5; + orderFinishMinute: number; + confirmedPayTerm: P2PPaymentTermDetailV5; + makerFee: string; + takerFee: string; + fee: string; + showContact: boolean; + tokenBalance: string; + fiatBalance: string; + unreadMsgCount: string; + updateDate: string; + extension: P2POrderExtensionV5; + selfUnreadMsgCount: string; + judgeType: string; + canReport: boolean; + canReportDisagree: boolean; + canReportType: string[]; + canReportDisagreeType: string[]; + appraiseStatus: string; + appraiseInfo: P2PAppraiseInfoV5; + canReportDisagreeTypes: string[]; + canReportTypes: string[]; + orderType: string; + middleToken: string; + beforePrice: string; + beforeQuantity: string; + beforeToken: string; + alternative: string; + appealUserId: string; + notifyTokenId: string; + notifyTokenQuantity: string; + cancelResponsible: string; + chainType: string; + chainAddress: string; + tradeHashCode: string; + estimatedGasFee: string; + gasFeeTokenId: string; + tradingFeeTokenId: string; + onChainInfo: string; + transactionId: string; + displayRefund: string; + chainWithdrawLastSeconds: string; + chainTransferLastSeconds: string; + orderSource: string; + cancelReason: string; + sellerCancelExamineRemainTime: string; + needSellerExamineCancel: boolean; + couponCurrencyAmount: string; + totalCurrencyAmount: string; + usedCoupon: boolean; + couponTokenId: string; + couponQuantity: string; + completedOrderAppealCount: number; + totalCompletedOrderAppealCount: number; + realOrderStatus: number; + appealVersion: number; + judgeInfo: P2PJudgeInfoV5; + helpType: string; + appealFlowStatus: string; + appealSubStatus: string; + bulkOrderFlag: boolean; + targetUserType: string; + targetUserDisplays: string[]; + appealProcessChangeFlag: boolean; + appealNegotiationNode: number; } ⋮---- -export interface AlphaPredictionOrderBookV5 { - tokenId: string; - bids: AlphaPredictionOrderBookLevelV5[]; - asks: AlphaPredictionOrderBookLevelV5[]; +export interface P2POrderMessageV5 { + id: string; + message: string; + userId: string; + msgType: number; + msgCode: number; + createDate: string; + contentType: string; + orderId: string; + msgUuid: string; + nickName: string; + fileName: string; + accountId: string; + isRead: number; + read: number; + roleType: string; + onlyForCustomer: number; } ⋮---- -export interface AlphaPredictionTokenPriceV5 { - tokenId: string; - bestBid: string; - bestAsk: string; - lastPrice: string; - volume24h: string; - updateTime: number; +export interface P2PUserInfoV5 { + nickName: string; + defaultNickName: boolean; + isOnline: boolean; + kycLevel: string; + email: string; + mobile: string; + lastLogoutTime: string; + recentRate: string; + totalFinishCount: number; + totalFinishSellCount: number; + totalFinishBuyCount: number; + recentFinishCount: number; + averageReleaseTime: string; + averageTransferTime: string; + accountCreateDays: number; + firstTradeDays: number; + realName: string; + recentTradeAmount: string; + totalTradeAmount: string; + registerTime: string; + authStatus: number; + kycCountryCode: string; + blocked: string; + goodAppraiseRate: string; + goodAppraiseCount: number; + badAppraiseCount: number; + accountId: number; + paymentCount: number; + contactCount: number; + vipLevel: number; + userCancelCountLimit: number; + paymentRealNameUneditable: boolean; + userId: string; + realNameEn: string; } ⋮---- -export interface AlphaPredictionPriceHistoryCandleV5 { - openTime: number; - open: string; - high: string; - low: string; - close: string; - volume: string; +export interface P2PCounterpartyUserInfoV5 { + nickName: string; + defaultNickName: boolean; + whiteFlag: number; + contactConfig: boolean; + isOnline: boolean; + email: string; + mobile: string; + kycLevel: number; + lastLogoutTime: string; + recentRate: number; + totalFinishCount: number; + totalFinishSellCount: number; + totalFinishBuyCount: number; + recentFinishCount: number; + averageReleaseTime: string; + averageTransferTime: string; + accountCreateDays: number; + firstTradeDays: number; + realName: string; + recentTradeAmount: string; + totalTradeAmount: string; + executeNum: number; + orderNum: number; + hasUnPostAd: number; + registerTime: string; + authStatus: number; + kycCountryCode: string; + blocked: string; + goodAppraiseRate: string; + goodAppraiseCount: number; + badAppraiseCount: number; + accountId: string; + paymentCount: number; + contactCount: number; + realNameMask: string; + vipLevel: number; + vipProfit: []; + userTag: []; + userCancelCountLimit: number; + paymentRealNameUneditable: boolean; + lostRoleAffected: boolean; + userCurPrivilege: string[]; + userType: string; + userId: string; + realNameEn: string; + canSubOnline: boolean; + curPrivilegeInfo: []; + openApiSwitch: number; } ⋮---- -export interface AlphaPredictionPriceHistoryV5 { - tokenId: string; - interval: string; - list: AlphaPredictionPriceHistoryCandleV5[]; +export interface P2PUserPaymentV5 { + id: string; + realName: string; + paymentType: string; + bankName: string; + branchName: string; + accountNo: string; + qrcode: string; + visible: number; + payMessage: string; + firstName: string; + lastName: string; + secondLastName: string; + clabe: string; + debitCardNumber: string; + mobile: string; + businessName: string; + concept: string; + online: string; + countNo: string; + paymentExt1: string; + paymentExt2: string; + paymentExt3: string; + paymentExt4: string; + paymentExt5: string; + paymentExt6: string; + paymentTemplateVersion: number; + hasPaymentTemplateChanged: boolean; + paymentConfigVo: P2PPaymentConfigV5; + realNameVerified: boolean; + channel: string; + currencyBalance: string[]; } -⋮---- -export interface AlphaPredictionPositionV5 { - positionId: string; - tokenId: string; - eventId: string; - outcomeName: string; - shares: string; - cost: string; - avgPrice: string; - currentPrice: string; - value: string; - unrealizedPnl: string; - unrealizedPnlRate: string; - createdAt: number; - finished: boolean; + +================ +File: src/types/response/v5-preupgrade.ts +================ +export interface PreUpgradeTransaction { + symbol: string; + category: string; + side: 'Buy' | 'Sell' | 'None'; + transactionTime: string; + type: string; + qty: string; + size: string; + currency: 'USDC' | 'USDT' | 'BTC' | 'ETH'; + tradePrice: string; + funding: string; + fee: string; + cashFlow: string; + change: string; + cashBalance: string; + feeRate: string; + bonusChange: string; + tradeId: string; + orderId: string; + orderLinkId: string; + extraFees: string; } ⋮---- -export interface AlphaPredictionPositionListResultV5 { - positions: AlphaPredictionPositionV5[]; - total: number; - totalAssetUsd: string; +export interface PreUpgradeOptionsDelivery { + deliveryTime: number; + symbol: string; + side: 'Buy' | 'Sell'; + position: string; + deliveryPrice: string; + strike: string; + fee: string; + deliveryRpl: string; } ⋮---- -export interface AlphaPredictionPositionHistoryV5 { - positionId: string; - tokenId: string; - eventId: string; - outcomeName: string; - shares: string; - cost: string; - avgPrice: string; - exitPrice: string; - realizedPnl: string; - realizedPnlRate: string; - result: number; - closedAt: number; +export interface PreUpgradeUSDCSessionSettlement { + symbol: string; + side: 'Buy' | 'Sell'; + size: string; + sessionAvgPrice: string; + markPrice: string; + realisedPnl: string; + createdTime: string; } + +================ +File: src/types/websockets/index.ts +================ + + +================ +File: src/types/websockets/ws-api.ts +================ +import { APIID, WS_KEY_MAP } from '../../util'; +import { + AmendOrderParamsV5, + BatchAmendOrderParamsV5, + BatchCancelOrderParamsV5, + BatchOrderParamsV5, + CancelOrderParamsV5, + OrderParamsV5, +} from '../request'; +import { + BatchAmendOrderResultV5, + BatchCancelOrderResultV5, + BatchCreateOrderResultV5, + BatchOrdersRetExtInfoV5, + OrderResultV5, +} from '../response'; +import { WsKey } from './ws-general'; ⋮---- -export interface AlphaPredictionPositionHistoryResultV5 { - positions: AlphaPredictionPositionHistoryV5[]; - total: number; -} +// When new WS API operations are added, make sure to also update WS_API_Operations[] below +export type WSAPIOperation = + | 'order.create' + | 'order.amend' + | 'order.cancel' + | 'order.create-batch' + | 'order.amend-batch' + | 'order.cancel-batch'; ⋮---- -export interface AlphaPredictionPortfolioSummaryV5 { - positionValue: string; - positionValueUsd: string; - biggestWin: string; - winRate: string; - winCount: number; - lossCount: number; -} +export type WsOperation = + | 'subscribe' + | 'unsubscribe' + | 'auth' + | 'ping' + | 'pong'; ⋮---- -export interface AlphaPredictionSideMarketTokenV5 { - tokenId: string; - outcome: string; - price: string; - liquidity: string; +export interface WsRequestOperationBybit { + req_id: string; + op: WsOperation; + args?: (TWSTopic | string | number)[]; } ⋮---- -export interface AlphaPredictionSideMarketV5 { - marketId: string; - eventId: string; - marketType: number; - question: string; - tokens: AlphaPredictionSideMarketTokenV5[]; - volume24h: string; - endDate: number; - status: number; +export interface WSAPIRequest< + TRequestParams = undefined, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + TWSOperation extends WSAPIOperation = any, +> { + reqId: string; + op: TWSOperation; + header: { + 'X-BAPI-TIMESTAMP': string; + 'X-BAPI-RECV-WINDOW': string; + Referer: typeof APIID; + }; + args: [TRequestParams]; } ⋮---- -export interface AlphaPredictionSideMarketListResultV5 { - list: AlphaPredictionSideMarketV5[]; - total: number; - pageIndex: number; - pageSize: number; -} +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -export interface AlphaPredictionSportsMatchV5 { - matchId: string; - eventType: number; - stageCode: string; - homeTeam: string; - awayTeam: string; - matchTime: number; - status: number; - eventId: string; +export interface WSAPIResponse< + TResponseData extends object = object, + TOperation extends WSAPIOperation = WSAPIOperation, + TResponseExtInfo = {}, // added as optional for batch calls +> { + wsKey: WsKey; + /** Auto-generated */ + reqId: string; + retCode: 0 | number; + retMsg: 'OK' | string; + op: TOperation; + data: TResponseData; + retExtInfo: TResponseExtInfo; + header?: { + 'X-Bapi-Limit': string; + 'X-Bapi-Limit-Status': string; + 'X-Bapi-Limit-Reset-Timestamp': string; + Traceid: string; + Timenow: string; + }; + connId: string; } ⋮---- -export interface AlphaPredictionSportsMatchListResultV5 { - list: AlphaPredictionSportsMatchV5[]; - total: number; - pageIndex: number; - pageSize: number; -} +TResponseExtInfo = {}, // added as optional for batch calls ⋮---- -export interface AlphaPredictionSportsTimelineStageV5 { - stageCode: string; - stageName: string; - status: number; - matchCount: number; - startTime: number; - endTime: number; -} +/** Auto-generated */ ⋮---- -export interface AlphaPredictionSportsTimelineStagesV5 { - eventType: number; - stages: AlphaPredictionSportsTimelineStageV5[]; -} +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 interface AlphaPredictionSportsGroupStandingV5 { - rank: number; - teamName: string; - played: number; - won: number; - drawn: number; - lost: number; - goalsFor: number; - goalsAgainst: number; - goalDifference: number; - points: number; -} +// This part says: if there's any key that's not in T, it's an error ⋮---- -export interface AlphaPredictionSportsGroupMatchV5 { - matchId: string; - homeTeam: string; - awayTeam: string; - matchTime: number; - status: number; - homeScore: number; - awayScore: number; - eventId: string; +/** + * List of operations supported for this WsKey (connection) + */ +export interface WsAPIWsKeyTopicMap { + [WS_KEY_MAP.v5PrivateTrade]: WSAPIOperation; } ⋮---- -export interface AlphaPredictionSportsGroupV5 { - groupName: string; - standings: AlphaPredictionSportsGroupStandingV5[]; - matches: AlphaPredictionSportsGroupMatchV5[]; +/** + * Request parameters expected per operation + */ +export interface WsAPITopicRequestParamMap { + 'order.create': OrderParamsV5; + 'order.amend': AmendOrderParamsV5; + 'order.cancel': CancelOrderParamsV5; + + 'order.create-batch': { + category: 'option' | 'linear'; + request: BatchOrderParamsV5[]; + }; + 'order.amend-batch': { + category: 'option' | 'linear'; + request: BatchAmendOrderParamsV5[]; + }; + 'order.cancel-batch': { + category: 'option' | 'linear'; + request: BatchCancelOrderParamsV5[]; + }; } ⋮---- -export interface AlphaPredictionSportsGroupStageDetailV5 { - groups: AlphaPredictionSportsGroupV5[]; +/** + * Response structure expected for each operation + */ +export interface WsAPIOperationResponseMap { + 'order.create': WSAPIResponse; + 'order.amend': WSAPIResponse; + 'order.cancel': WSAPIResponse; + + 'order.create-batch': WSAPIResponse< + { list: BatchCreateOrderResultV5[] }, + 'order.create-batch' + > & { + retExtInfo: BatchOrdersRetExtInfoV5; + }; + 'order.amend-batch': WSAPIResponse< + { list: BatchAmendOrderResultV5[] }, + 'order.amend-batch' + > & { + retExtInfo: BatchOrdersRetExtInfoV5; + }; + 'order.cancel-batch': WSAPIResponse< + { list: BatchCancelOrderResultV5[] }, + 'order.cancel-batch' + > & { + retExtInfo: BatchOrdersRetExtInfoV5; + }; + + ping: { + retCode: 0 | number; + retMsg: 'OK' | string; + op: 'pong'; + data: [string]; + connId: string; + }; } ================ -File: src/types/response/v5-p2p-trading.ts +File: src/types/websockets/ws-confirmations.ts ================ -import { P2PTradingPreferenceSetV5 } from '../request/v5-p2p-trading'; +export interface WebsocketTopicSubscriptionConfirmationEvent { + op: 'subscribe'; + req_id: string; + conn_id: string; + ret_msg: string; + success: boolean; +} ⋮---- -export interface P2PCoinBalanceV5 { - coin: string; - transferBalance: string; - walletBalance: string; - bonus: string; +export interface WebsocketSucceededTopicSubscriptionConfirmationEvent + extends WebsocketTopicSubscriptionConfirmationEvent { + success: true; } ⋮---- -export interface P2PAccountCoinsBalanceV5 { - memberId: string; - accountType: string; - balance: P2PCoinBalanceV5[]; +export interface WebsocketFailedTopicSubscriptionConfirmationEvent + extends WebsocketTopicSubscriptionConfirmationEvent { + success: false; } + +================ +File: src/types/index.ts +================ + + +================ +File: src/index.ts +================ + + +================ +File: src/spot-client-v3.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { APIResponseV3, numberInString } from './types'; +import { REST_CLIENT_TYPE_ENUM } from './util'; +import BaseRestClient from './util/BaseRestClient'; ⋮---- -export interface P2POnlineAdV5 { - id: string; - nickName: string; - tokenId: string; - currencyId: string; - side: string; - price: string; - lastQuantity: string; - minAmount: string; - maxAmount: string; - payments: string[]; - recentOrderNum: number; - recentExecuteRate: number; - isOnline: boolean; - authTag: string[]; - paymentPeriod: number; - accountId: number; - userId: number; - priceType: number; - premium: string; - quantity: string; - frozenQuantity: string; - executedQuantity: string; - remark: string; - status: number; - createDate: string; - orderNum: string; - finishNum: string; - fee: string; - lastLogoutTime: string; - blocked: string; - makerContact: boolean; - symbolInfo: { - id: string; - exchangeId: string; - orgId: string; - tokenId: string; - currencyId: string; - status: string; - lowerLimitAlarm: number; - upperLimitAlarm: number; - itemDownRange: string; - itemUpRange: string; - currencyMinQuote: string; - currencyMaxQuote: string; - currencyLowerMaxQuote: string; - tokenMinQuote: string; - tokenMaxQuote: string; - kycCurrencyLimit: string; - itemSideLimit: string; - buyFeeRate: string; - sellFeeRate: string; - orderAutoCancelMinute: number; - orderFinishMinute: number; - tradeSide: number; - currency: { - id: string; - exchangeId: string; - orgId: string; - currencyId: string; - scale: number; - }; - token: { - id: string; - exchangeId: string; - orgId: string; - tokenId: string; - scale: number; - sequence: number; - }; - buyAd: number; - sellAd: number; - }; - tradingPreferenceSet: { - hasUnPostAd: number; - isKyc: number; - isEmail: number; - isMobile: number; - hasRegisterTime: number; - registerTimeThreshold: number; - orderFinishNumberDay30: number; - completeRateDay30: number; - nationalLimit: number; - hasOrderFinishNumberDay30: number; - hasCompleteRateDay30: number; - hasNationalLimit: number; - }; - version: number; - authStatus: number; - recommend: boolean; - recommendTag: string; - userType: string; - itemType: string; -} +/** + * REST API client for newer Spot V3 APIs. + * @deprecated WARNING + * These endpoints are being switched off gradually and are expected to be completely turned off by the end of 2024. + * They may stop working at any point before then. + * Please update your code as soon as possible to use the V5 APIs instead. + */ +export class SpotClientV3 extends BaseRestClient ⋮---- -export interface P2POnlineAdsResponseV5 { - count: number; - items: P2POnlineAdV5[]; -} +getClientType() ⋮---- -export interface P2PCreateAdResponseV5 { - itemId: string; - securityRiskToken: string; - riskTokenType: string; - riskVersion: string; - needSecurityRisk: boolean; -} +// Doesn't really matter here, since the only remaining endpoint does not require auth. ⋮---- -export interface P2PPaymentTermV5 { - id: string; - realName: string; - paymentType: number; - bankName: string; - branchName: string; - accountNo: string; - qrcode: string; - visible: number; - payMessage: string; - firstName: string; - lastName: string; - secondLastName: string; - clabe: string; - debitCardNumber: string; - mobile: string; - businessName: string; - concept: string; - paymentExt1: string; - paymentExt2: string; - paymentExt3: string; - paymentExt4: string; - paymentExt5: string; - paymentExt6: string; - paymentTemplateVersion: number; - paymentConfig: { - paymentType: number; - paymentName: string; - paymentDialect: string; - }; - realNameVerified: boolean; -} +async fetchServerTime(): Promise ⋮---- -export interface P2PAdDetailV5 { - id: string; - accountId: string; - userId: string; - nickName: string; - tokenId: string; - tokenName: string; - currencyId: string; - side: number; - priceType: number; - price: string; - premium: string; - lastQuantity: string; - quantity: string; - frozenQuantity: string; - executedQuantity: string; - minAmount: string; - maxAmount: string; - remark: string; - status: number; - createDate: string; - payments: string[]; - orderNum: number; - finishNum: number; - recentOrderNum: number; - recentExecuteRate: number; - fee: string; - isOnline: boolean; - lastLogoutTime: string; - symbolInfo: { - id: string; - exchangeId: string; - orgId: string; - tokenId: string; - currencyId: string; - status: number; - lowerLimitAlarm: number; - upperLimitAlarm: number; - itemDownRange: string; - itemUpRange: string; - currencyMinQuote: string; - currencyMaxQuote: string; - currencyLowerMaxQuote: string; - tokenMinQuote: string; - tokenMaxQuote: string; - kycCurrencyLimit: string; - itemSideLimit: number; - buyFeeRate: string; - sellFeeRate: string; - orderAutoCancelMinute: number; - orderFinishMinute: number; - tradeSide: number; - currency: { - id: string; - exchangeId: string; - orgId: string; - currencyId: string; - scale: number; - }; - token: { - id: string; - exchangeId: string; - orgId: string; - tokenId: string; - scale: number; - sequence: number; - }; - buyAd: { - paymentPeriods: number[]; - }; - sellAd: { - paymentPeriods: number[]; - }; - }; - tradingPreferenceSet: P2PTradingPreferenceSetV5; - paymentTerms: P2PPaymentTermV5[]; - version: number; - updateDate: string; - feeRate: string; - paymentPeriod: number; - itemType: string; -} +/** + * + * Market Data Endpoints + * + */ ⋮---- -export interface P2PPersonalAdsResponseV5 { - count: number; - items: P2PAdDetailV5[]; - hiddenFlag: boolean; -} +/** + * Get merged orderbook for symbol + * + * This is the only known pre-V5 endpoint to still be online. + */ +getMergedOrderBook( + symbol: string, + scale?: number, + limit?: number, +): Promise> ⋮---- -export interface P2POrderExtensionV5 { - isDelayWithdraw: boolean; - delayTime: string; - startTime: string; -} +/** + * + * API Data Endpoints + * + */ ⋮---- -export interface P2POrderV5 { - id: string; - side: number; - tokenId: string; - orderType: string; - amount: string; - currencyId: string; - price: string; - notifyTokenQuantity?: string; - notifyTokenId?: string; - fee: string; - targetNickName: string; - targetUserId: string; - status: number; - selfUnreadMsgCount: string; - createDate: string; - transferLastSeconds: string; - appealLastSeconds: string; - userId: string; - sellerRealName: string; - buyerRealName: string; - judgeInfo: { - autoJudgeUnlockTime: string; - dissentResult: string; - preDissent: string; - postDissent: string; - }; - unreadMsgCount: string; - extension: P2POrderExtensionV5; - bulkOrderFlag: boolean; +getServerTime(): Promise< + +================ +File: src/websocket-api-client.ts +================ +import { + AmendOrderParamsV5, + BatchAmendOrderParamsV5, + BatchAmendOrderResultV5, + BatchCancelOrderParamsV5, + BatchCancelOrderResultV5, + BatchCreateOrderResultV5, + BatchOrderParamsV5, + BatchOrdersRetExtInfoV5, + CancelOrderParamsV5, + OrderParamsV5, + OrderResultV5, +} from './types'; +import { WSAPIResponse } from './types/websockets/ws-api'; +import { WSClientConfigurableOptions } from './types/websockets/ws-general'; +import { DefaultLogger } from './util'; +import { WS_KEY_MAP } from './util/websockets/websocket-util'; +import { WebsocketClient } from './websocket-client'; +⋮---- +/** + * 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 P2POrdersResponseV5 { - count: number; - items: P2POrderV5[]; -} +/** + * 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 P2PPaymentConfigItemV5 { - view: boolean; - name: string; - label: string; - placeholder: string; - type: string; - maxLength: string; - required: boolean; -} +/** + * This is a minimal Websocket API wrapper around the WebsocketClient. + * + * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should + * be used to transmit that message. This is only useful if you wish to use an alternative wss + * domain that is supported by the SDK. + * + * Note: To use testnet, don't set the wsKey - use `testnet: true` in + * the constructor instead. + * + * 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/bybit-api/blob/master/examples/ws-api-raw-promises.ts + */ +export class WebsocketAPIClient ⋮---- -export interface P2PPaymentConfigV5 { - paymentType: string; - checkType: number; - sort: number; - paymentName: string; - addTips: string; - itemTips: string; - online: number; - items: P2PPaymentConfigItemV5[]; -} +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -export interface P2PPaymentTermDetailV5 { - id: string; - realName: string; - paymentType: number; - bankName: string; - branchName: string; - accountNo: string; - qrcode: string; - visible: number; - payMessage: string; - firstName: string; - lastName: string; - secondLastName: string; - clabe: string; - debitCardNumber: string; - mobile: string; - businessName: string; - concept: string; - online: string; - paymentExt1: string; - paymentExt2: string; - paymentExt3: string; - paymentExt4: string; - paymentExt5: string; - paymentExt6: string; - paymentTemplateVersion: number; - paymentConfigVo: P2PPaymentConfigV5; - ruPaymentPrompt: boolean; -} +public getWSClient(): WebsocketClient ⋮---- -export interface P2PAppraiseInfoV5 { - anonymous: string; - appraiseContent: string; - appraiseId: string; - appraiseType: string; - modifyFlag: string; - updateDate: string; -} +public setTimeOffsetMs(newOffset: number): void ⋮---- -export interface P2PJudgeInfoV5 { - autoJudgeUnlockTime: string; - dissentResult: string; - preDissent: string; - postDissent: string; -} +/* + * Bybit WebSocket API Methods + * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline + */ ⋮---- -export interface P2POrderDetailV5 { - id: string; - side: number; - itemId: string; - accountId: string; - userId: string; - nickName: string; - makerUserId: string; - targetAccountId: string; - targetUserId: string; - targetNickName: string; - targetFirstName: string; - targetSecondName: string; - targetUserAuthStatus: number; - targetConnectInformation: string; - payerRealName: string; - sellerRealName: string; - buyerRealName: string; - tokenId: string; - tokenName: string; - currencyId: string; - price: string; - quantity: string; - amount: string; - payCode: string; - paymentType: number; - transferDate: string; - status: number; - createDate: string; - paymentTermList: P2PPaymentTermDetailV5[]; - remark: string; - transferLastSeconds: string; - recentOrderNum: number; - recentExecuteRate: number; - appealLastSeconds: string; - appealContent: string; - appealType: number; - appealNickName: string; - canAppeal: string; - totalAppealTimes: string; - appealedTimes: string; - paymentTermResult: P2PPaymentTermDetailV5; - orderFinishMinute: number; - confirmedPayTerm: P2PPaymentTermDetailV5; - makerFee: string; - takerFee: string; - fee: string; - showContact: boolean; - tokenBalance: string; - fiatBalance: string; - unreadMsgCount: string; - updateDate: string; - extension: P2POrderExtensionV5; - selfUnreadMsgCount: string; - judgeType: string; - canReport: boolean; - canReportDisagree: boolean; - canReportType: string[]; - canReportDisagreeType: string[]; - appraiseStatus: string; - appraiseInfo: P2PAppraiseInfoV5; - canReportDisagreeTypes: string[]; - canReportTypes: string[]; - orderType: string; - middleToken: string; - beforePrice: string; - beforeQuantity: string; - beforeToken: string; - alternative: string; - appealUserId: string; - notifyTokenId: string; - notifyTokenQuantity: string; - cancelResponsible: string; - chainType: string; - chainAddress: string; - tradeHashCode: string; - estimatedGasFee: string; - gasFeeTokenId: string; - tradingFeeTokenId: string; - onChainInfo: string; - transactionId: string; - displayRefund: string; - chainWithdrawLastSeconds: string; - chainTransferLastSeconds: string; - orderSource: string; - cancelReason: string; - sellerCancelExamineRemainTime: string; - needSellerExamineCancel: boolean; - couponCurrencyAmount: string; - totalCurrencyAmount: string; - usedCoupon: boolean; - couponTokenId: string; - couponQuantity: string; - completedOrderAppealCount: number; - totalCompletedOrderAppealCount: number; - realOrderStatus: number; - appealVersion: number; - judgeInfo: P2PJudgeInfoV5; - helpType: string; - appealFlowStatus: string; - appealSubStatus: string; - bulkOrderFlag: boolean; - targetUserType: string; - targetUserDisplays: string[]; - appealProcessChangeFlag: boolean; - appealNegotiationNode: number; -} +/** + * Submit a new order + * + * @param params + * @returns + */ +submitNewOrder( + params: OrderParamsV5, +): Promise> ⋮---- -export interface P2POrderMessageV5 { - id: string; - message: string; - userId: string; - msgType: number; - msgCode: number; - createDate: string; - contentType: string; - orderId: string; - msgUuid: string; - nickName: string; - fileName: string; - accountId: string; - isRead: number; - read: number; - roleType: string; - onlyForCustomer: number; -} +/** + * Amend an order + * + * @param params + * @returns + */ +amendOrder( + params: AmendOrderParamsV5, +): Promise> ⋮---- -export interface P2PUserInfoV5 { - nickName: string; - defaultNickName: boolean; - isOnline: boolean; - kycLevel: string; - email: string; - mobile: string; - lastLogoutTime: string; - recentRate: string; - totalFinishCount: number; - totalFinishSellCount: number; - totalFinishBuyCount: number; - recentFinishCount: number; - averageReleaseTime: string; - averageTransferTime: string; - accountCreateDays: number; - firstTradeDays: number; - realName: string; - recentTradeAmount: string; - totalTradeAmount: string; - registerTime: string; - authStatus: number; - kycCountryCode: string; - blocked: string; - goodAppraiseRate: string; - goodAppraiseCount: number; - badAppraiseCount: number; - accountId: number; - paymentCount: number; - contactCount: number; - vipLevel: number; - userCancelCountLimit: number; - paymentRealNameUneditable: boolean; - userId: string; - realNameEn: string; -} +/** + * Cancel an order + * + * @param params + * @returns + */ +cancelOrder( + params: CancelOrderParamsV5, +): Promise> ⋮---- -export interface P2PCounterpartyUserInfoV5 { - nickName: string; - defaultNickName: boolean; - whiteFlag: number; - contactConfig: boolean; - isOnline: boolean; - email: string; - mobile: string; - kycLevel: number; - lastLogoutTime: string; - recentRate: number; - totalFinishCount: number; - totalFinishSellCount: number; - totalFinishBuyCount: number; - recentFinishCount: number; - averageReleaseTime: string; - averageTransferTime: string; - accountCreateDays: number; - firstTradeDays: number; - realName: string; - recentTradeAmount: string; - totalTradeAmount: string; - executeNum: number; - orderNum: number; - hasUnPostAd: number; - registerTime: string; - authStatus: number; - kycCountryCode: string; - blocked: string; - goodAppraiseRate: string; - goodAppraiseCount: number; - badAppraiseCount: number; - accountId: string; - paymentCount: number; - contactCount: number; - realNameMask: string; - vipLevel: number; - vipProfit: []; - userTag: []; - userCancelCountLimit: number; - paymentRealNameUneditable: boolean; - lostRoleAffected: boolean; - userCurPrivilege: string[]; - userType: string; - userId: string; - realNameEn: string; - canSubOnline: boolean; - curPrivilegeInfo: []; - openApiSwitch: number; -} +/** + * Batch submit orders + * + * @param params + * @returns + */ +batchSubmitOrders( + category: 'option' | 'linear', + orders: BatchOrderParamsV5[], + ): Promise< + WSAPIResponse< + { + list: BatchCreateOrderResultV5[]; + }, + 'order.create-batch', + BatchOrdersRetExtInfoV5 + > + > { + return this.wsClient.sendWSAPIRequest( + WS_KEY_MAP.v5PrivateTrade, + 'order.create-batch', + { + category, + request: orders, + }, + ); ⋮---- -export interface P2PUserPaymentV5 { - id: string; - realName: string; - paymentType: string; - bankName: string; - branchName: string; - accountNo: string; - qrcode: string; - visible: number; - payMessage: string; - firstName: string; - lastName: string; - secondLastName: string; - clabe: string; - debitCardNumber: string; - mobile: string; - businessName: string; - concept: string; - online: string; - countNo: string; - paymentExt1: string; - paymentExt2: string; - paymentExt3: string; - paymentExt4: string; - paymentExt5: string; - paymentExt6: string; - paymentTemplateVersion: number; - hasPaymentTemplateChanged: boolean; - paymentConfigVo: P2PPaymentConfigV5; - realNameVerified: boolean; - channel: string; - currencyBalance: string[]; -} +/** + * Batch amend orders + * + * @param params + * @returns + */ +batchAmendOrder( + category: 'option' | 'linear', + orders: BatchAmendOrderParamsV5[], + ): Promise< + WSAPIResponse< + { + list: BatchAmendOrderResultV5[]; + }, + 'order.amend-batch', + BatchOrdersRetExtInfoV5 + > + > { + return this.wsClient.sendWSAPIRequest( + WS_KEY_MAP.v5PrivateTrade, + 'order.amend-batch', + { + category, + request: orders, + }, + ); +⋮---- +/** + * Batch cancel orders + * + * @param params + * @returns + */ +batchCancelOrder( + category: 'option' | 'linear', + orders: BatchCancelOrderParamsV5[], + ): Promise< + WSAPIResponse< + { + list: BatchCancelOrderResultV5[]; + }, + 'order.cancel-batch', + BatchOrdersRetExtInfoV5 + > + > { + return this.wsClient.sendWSAPIRequest( + WS_KEY_MAP.v5PrivateTrade, + 'order.cancel-batch', + { + category, + request: orders, + }, + ); +⋮---- +/** + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * + */ +⋮---- +private setupDefaultEventListeners() +⋮---- +/** + * General event handlers for monitoring the WebsocketClient + */ +⋮---- +// Blind JSON.stringify can fail on circular references +⋮---- +// JSON.stringify({ ...data, target: 'WebSocket' }), ================ -File: src/types/response/v5-preupgrade.ts +File: .eslintrc.cjs ================ -export interface PreUpgradeTransaction { - symbol: string; - category: string; - side: 'Buy' | 'Sell' | 'None'; - transactionTime: string; - type: string; - qty: string; - size: string; - currency: 'USDC' | 'USDT' | 'BTC' | 'ETH'; - tradePrice: string; - funding: string; - fee: string; - cashFlow: string; - change: string; - cashBalance: string; - feeRate: string; - bonusChange: string; - tradeId: string; - orderId: string; - orderLinkId: string; - extraFees: string; -} +// 'require-extensions', // only once moved to ESM ⋮---- -export interface PreUpgradeOptionsDelivery { - deliveryTime: number; - symbol: string; - side: 'Buy' | 'Sell'; - position: string; - deliveryPrice: string; - strike: string; - fee: string; - deliveryRpl: string; -} +// 'plugin:require-extensions/recommended', // only once moved to ESM ⋮---- -export interface PreUpgradeUSDCSessionSettlement { - symbol: string; - side: 'Buy' | 'Sell'; - size: string; - sessionAvgPrice: string; - markPrice: string; - realisedPnl: string; - createdTime: string; +// 'no-unused-vars': ['warn'], + +================ +File: .jshintrc +================ +{ + "esversion": 8, + "asi": true, + "laxbreak": true, + "predef": [ "-Promise" ] } ================ -File: src/types/response/v5-rwa.ts +File: .prettierrc +================ +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" +} + +================ +File: index.js +================ + + +================ +File: jest.config.ts ================ /** - * V5 RWA (Real World Assets) earn responses. + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration */ ⋮---- -export interface RWAProductV5 { - productId: number; - coin: string; - assetSymbol: string; - manager: string; - baseApr: string; - bonusApr: string; - savingType: 'Flexible' | 'Fixed' | string; - duration: number; - nav: string; - minStakeAmount: string; - maxStakeAmount: string; - userMaxAmount: string; - userQuota: string; - minRedeemShare: string; - redeemFeeRate: string; - subscriptionFee: string; - extLink: string; - amountPrecision: number; - sharePrecision: number; -} +import type { Config } from 'jest'; ⋮---- -export interface RWAProductListResultV5 { - list: RWAProductV5[]; -} +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- -export interface PlaceRWAOrderResultV5 { - orderId: string; - orderLinkId: string; -} +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, ⋮---- -export interface RWAPositionV5 { - productId: number; - coin: string; - assetSymbol: string; - effectiveShare: string; - processingStakeAmount: string; - processingRedeemShare: string; - bonusEarned: string; - nav: string; - holdAmount: string; - duration: number; -} +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- -export interface RWAPositionListResultV5 { - list: RWAPositionV5[]; -} +// Automatically clear mock calls, instances, contexts and results before every test ⋮---- -export interface RWAOrderV5 { - orderId: string; - orderLinkId: string; - orderType: 'Stake' | 'Redeem'; - productId: number; - coin: string; - stakeAmount?: string; - redeemShares?: string; - status: 'Processing' | 'Success' | 'Failed' | string; - accountType: 'FUND' | 'UNIFIED' | string; - createdTime: number; - updatedTime: number; - settledShares?: string; - settledAmount?: string; -} +// Indicates whether the coverage information should be collected while executing the test ⋮---- -export interface RWAOrderListResultV5 { - list: RWAOrderV5[]; - nextPageCursor: string; -} +// An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- -export interface RWANavChartPointV5 { - date: string; - nav: string; -} +// The directory where Jest should output its coverage files ⋮---- -export interface RWANavChartResultV5 { - productId: number; - list: RWANavChartPointV5[]; -} - -================ -File: src/types/websockets/index.ts -================ - - -================ -File: src/types/websockets/ws-api.ts -================ -import { APIID, WS_KEY_MAP } from '../../util'; -import { - AmendOrderParamsV5, - BatchAmendOrderParamsV5, - BatchCancelOrderParamsV5, - BatchOrderParamsV5, - CancelOrderParamsV5, - OrderParamsV5, -} from '../request'; -import { - BatchAmendOrderResultV5, - BatchCancelOrderResultV5, - BatchCreateOrderResultV5, - BatchOrdersRetExtInfoV5, - OrderResultV5, -} from '../response'; -import { WsKey } from './ws-general'; +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// When new WS API operations are added, make sure to also update WS_API_Operations[] below -export type WSAPIOperation = - | 'order.create' - | 'order.amend' - | 'order.cancel' - | 'order.create-batch' - | 'order.amend-batch' - | 'order.cancel-batch'; +// Indicates which provider should be used to instrument code for coverage ⋮---- -export type WsOperation = - | 'subscribe' - | 'unsubscribe' - | 'auth' - | 'ping' - | 'pong'; +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], ⋮---- -export interface WsRequestOperationBybit { - req_id: string; - op: WsOperation; - args?: (TWSTopic | string | number)[]; -} +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, ⋮---- -export interface WSAPIRequest< - TRequestParams = undefined, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - TWSOperation extends WSAPIOperation = any, -> { - reqId: string; - op: TWSOperation; - header: { - 'X-BAPI-TIMESTAMP': string; - 'X-BAPI-RECV-WINDOW': string; - Referer: typeof APIID; - }; - args: [TRequestParams]; -} +// A path to a custom dependency extractor +// dependencyExtractor: undefined, ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, ⋮---- -export interface WSAPIResponse< - TResponseData extends object = object, - TOperation extends WSAPIOperation = WSAPIOperation, - TResponseExtInfo = {}, // added as optional for batch calls -> { - wsKey: WsKey; - /** Auto-generated */ - reqId: string; - retCode: 0 | number; - retMsg: 'OK' | string; - op: TOperation; - data: TResponseData; - retExtInfo: TResponseExtInfo; - header?: { - 'X-Bapi-Limit': string; - 'X-Bapi-Limit-Status': string; - 'X-Bapi-Limit-Reset-Timestamp': string; - Traceid: string; - Timenow: string; - }; - connId: string; -} +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, ⋮---- -TResponseExtInfo = {}, // added as optional for batch calls +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], ⋮---- -/** Auto-generated */ +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, ⋮---- -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]; -}; +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, ⋮---- -// This part says: if there's any key that's not in T, it's an error +// A set of global variables that need to be available in all test environments +// globals: {}, ⋮---- -/** - * List of operations supported for this WsKey (connection) - */ -export interface WsAPIWsKeyTopicMap { - [WS_KEY_MAP.v5PrivateTrade]: WSAPIOperation; -} -⋮---- -/** - * Request parameters expected per operation - */ -export interface WsAPITopicRequestParamMap { - 'order.create': OrderParamsV5; - 'order.amend': AmendOrderParamsV5; - 'order.cancel': CancelOrderParamsV5; - - 'order.create-batch': { - category: 'option' | 'linear'; - request: BatchOrderParamsV5[]; - }; - 'order.amend-batch': { - category: 'option' | 'linear'; - request: BatchAmendOrderParamsV5[]; - }; - 'order.cancel-batch': { - category: 'option' | 'linear'; - request: BatchCancelOrderParamsV5[]; - }; -} -⋮---- -/** - * Response structure expected for each operation - */ -export interface WsAPIOperationResponseMap { - 'order.create': WSAPIResponse; - 'order.amend': WSAPIResponse; - 'order.cancel': WSAPIResponse; - - 'order.create-batch': WSAPIResponse< - { list: BatchCreateOrderResultV5[] }, - 'order.create-batch' - > & { - retExtInfo: BatchOrdersRetExtInfoV5; - }; - 'order.amend-batch': WSAPIResponse< - { list: BatchAmendOrderResultV5[] }, - 'order.amend-batch' - > & { - retExtInfo: BatchOrdersRetExtInfoV5; - }; - 'order.cancel-batch': WSAPIResponse< - { list: BatchCancelOrderResultV5[] }, - 'order.cancel-batch' - > & { - retExtInfo: BatchOrdersRetExtInfoV5; - }; - - ping: { - retCode: 0 | number; - retMsg: 'OK' | string; - op: 'pong'; - data: [string]; - connId: string; - }; -} - -================ -File: src/types/websockets/ws-confirmations.ts -================ -export interface WebsocketTopicSubscriptionConfirmationEvent { - op: 'subscribe'; - req_id: string; - conn_id: string; - ret_msg: string; - success: boolean; -} -⋮---- -export interface WebsocketSucceededTopicSubscriptionConfirmationEvent - extends WebsocketTopicSubscriptionConfirmationEvent { - success: true; -} -⋮---- -export interface WebsocketFailedTopicSubscriptionConfirmationEvent - extends WebsocketTopicSubscriptionConfirmationEvent { - success: false; -} - -================ -File: src/types/index.ts -================ - - -================ -File: src/index.ts -================ - - -================ -File: src/spot-client-v3.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { APIResponseV3, numberInString } from './types'; -import { REST_CLIENT_TYPE_ENUM } from './util'; -import BaseRestClient from './util/BaseRestClient'; -⋮---- -/** - * REST API client for newer Spot V3 APIs. - * @deprecated WARNING - * These endpoints are being switched off gradually and are expected to be completely turned off by the end of 2024. - * They may stop working at any point before then. - * Please update your code as soon as possible to use the V5 APIs instead. - */ -export class SpotClientV3 extends BaseRestClient -⋮---- -getClientType() -⋮---- -// Doesn't really matter here, since the only remaining endpoint does not require auth. -⋮---- -async fetchServerTime(): Promise -⋮---- -/** - * - * Market Data Endpoints - * - */ -⋮---- -/** - * Get merged orderbook for symbol - * - * This is the only known pre-V5 endpoint to still be online. - */ -getMergedOrderBook( - symbol: string, - scale?: number, - limit?: number, -): Promise> -⋮---- -/** - * - * API Data Endpoints - * - */ -⋮---- -getServerTime(): Promise< - -================ -File: .eslintrc.cjs -================ -// 'require-extensions', // only once moved to ESM -⋮---- -// 'plugin:require-extensions/recommended', // only once moved to ESM -⋮---- -// 'no-unused-vars': ['warn'], - -================ -File: .jshintrc -================ -{ - "esversion": 8, - "asi": true, - "laxbreak": true, - "predef": [ "-Promise" ] -} - -================ -File: .nvmrc -================ -v22.11.0 - -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" -} - -================ -File: index.js -================ - - -================ -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, -bail: false, // enable to stop test when an error occur, -⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", -⋮---- -// Automatically clear mock calls, instances, contexts and results before every test -⋮---- -// Indicates whether the coverage information should be collected while executing the test -⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected -⋮---- -// The directory where Jest should output its coverage files -⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], -⋮---- -// Indicates which provider should be used to instrument code for coverage -⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], -⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, -⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, -⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, -⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, -⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], -⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, -⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, -⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, -⋮---- -// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. -// maxWorkers: "50%", +// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. +// maxWorkers: "50%", ⋮---- // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ @@ -4790,21 +4245,184 @@ export enum LinearPositionIdx { } ================ -File: src/types/request/v5-alpha-trade.ts +File: src/types/request/v5-alpha-lp.ts ================ /** - * V5 private Alpha / on-chain (Web3) trade requests. + * V5 private Alpha LP requests. */ ⋮---- -export interface GetAlphaTradeQuoteParamsV5 { - tradeType: 1 | 2; - fromTokenCode: string; - fromTokenAmount: string; - toTokenCode: string; - quoteMode?: 0 | 1 | 2; +export interface GetAlphaLPPoolListParamsV5 { + tokenSymbol?: string; } ⋮---- -export interface ExecuteAlphaTradeParamsV5 { +export interface GetAlphaLPPoolInfoParamsV5 { + poolAddress: string; +} +⋮---- +export interface ExecuteAlphaLPStakeParamsV5 { + positionId: number; + poolAddress: string; + payTokenAmount: string; + payTokenCode: string; + rangeUpper?: string; + rangeLower?: string; + priceUpper?: string; + priceLower?: string; +} +⋮---- +export interface ExecuteAlphaLPRedeemParamsV5 { + positionId: number; + poolAddress: string; + dercRatio: string; + receiveTokenCode?: string; +} +⋮---- +export interface GetAlphaLPOrderListParamsV5 { + orderType?: 0 | 1 | 2; + tokenCode?: string; + orderStatus?: number[]; + days?: number; + limit?: number; + pageIndex?: number; + poolAddress?: string; +} +⋮---- +export interface GetAlphaLPPayTokenListParamsV5 { + chainCode?: string; + tokenAddress?: string; +} +⋮---- +export interface GetAlphaLPPayTokenPriceParamsV5 { + tokenCode: string[]; + chainCode?: string; +} + +================ +File: src/types/request/v5-alpha-prediction.ts +================ +/** + * V5 private Alpha prediction market requests. + */ +⋮---- +export interface GetAlphaPredictionEventDetailParamsV5 { + eventId?: string; + slug?: string; + hasMoreMarkets?: boolean; +} +⋮---- +export interface GetAlphaPredictionOrderEstimateParamsV5 { + tokenId: string; + side: 1 | 2; + eventId: string; + amount: string; + orderType: 1; + payTokenCode?: string; +} +⋮---- +export interface ExecuteAlphaPredictionBuyParamsV5 { + tokenId: string; + amount: string; + payTokenCode: string; + orderType: 1; + slippage: string; + eventId: string; +} +⋮---- +export interface ExecuteAlphaPredictionSellParamsV5 { + tokenId: string; + size: string; + orderType: 1; + slippage: string; + eventId: string; + toTokenCode?: string; +} +⋮---- +export interface GetAlphaPredictionOrderListParamsV5 { + status?: number; + tokenId?: string; + eventId?: string; + side?: 1 | 2; + days?: number; + limit?: number; + pageIndex?: number; +} +⋮---- +export interface GetAlphaPredictionOrderBookParamsV5 { + tokenIds: string[]; +} +⋮---- +export interface GetAlphaPredictionTokenPriceParamsV5 { + tokenIds: string[]; +} +⋮---- +export interface GetAlphaPredictionPriceHistoryParamsV5 { + tokenId: string; + interval: string; +} +⋮---- +export interface GetAlphaPredictionPositionListParamsV5 { + tokenId?: string; + eventId?: string; + limit?: number; + pageIndex?: number; +} +⋮---- +export interface GetAlphaPredictionPositionHistoryParamsV5 { + tokenId?: string; + eventId?: string; + result?: number; + days?: number; + limit?: number; + pageIndex?: number; +} +⋮---- +export interface GetAlphaPredictionPortfolioSummaryParamsV5 { + eventType?: number; +} +⋮---- +export interface GetAlphaPredictionSideMarketListParamsV5 { + eventId: string; + sortBy?: string; + marketType?: number; + limit?: number; + pageIndex?: number; +} +⋮---- +export interface GetAlphaPredictionSportsMatchListParamsV5 { + eventType: number; + status?: number; + startTime?: number; + endTime?: number; + stageCode?: string; + limit?: number; + pageIndex?: number; +} +⋮---- +export interface GetAlphaPredictionSportsTimelineStagesParamsV5 { + eventType: number; +} +⋮---- +export interface GetAlphaPredictionSportsGroupStageDetailParamsV5 { + eventType: number; + groupName?: string; +} + +================ +File: src/types/request/v5-alpha-trade.ts +================ +/** + * V5 private Alpha / on-chain (Web3) trade requests. + */ +⋮---- +export interface GetAlphaTradeQuoteParamsV5 { + tradeType: 1 | 2; + fromTokenCode: string; + fromTokenAmount: string; + toTokenCode: string; + quoteMode?: 0 | 1 | 2; +} +⋮---- +export interface ExecuteAlphaTradeParamsV5 { fromTokenCode: string; fromTokenAmount: string; toTokenCode: string; @@ -5427,155 +5045,155 @@ export interface GetEarnTokenHistoryAprParamsV5 { /** 1 = 7d, 2 = 30d, 3 = 180d */ ================ -File: src/types/request/v5-position.ts +File: src/types/request/v5-rwa.ts ================ -import { - CategoryV5, - ExecTypeV5, - OrderTriggerByV5, - OrderTypeV5, - PositionIdx, - TPSLModeV5, -} from '../shared-v5'; +/** + * V5 RWA (Real World Assets) earn requests. + */ ⋮---- -export interface GetFuturesLeverageParamsV5 { - category: 'linear' | 'inverse'; - symbol?: string; +export interface GetRWAProductListParamsV5 { + coin?: string; } ⋮---- -export interface PositionInfoParamsV5 { - category: CategoryV5; - symbol?: string; - baseCoin?: string; - settleCoin?: string; +export interface PlaceRWAOrderParamsV5 { + productId: number; + orderType: 'Stake' | 'Redeem'; + coin: string; + orderLinkId: string; + stakeAmount?: string; + redeemShares?: string; + accountType?: 'FUND' | 'UNIFIED'; +} +⋮---- +export interface GetRWAOrderListParamsV5 { + orderId?: string; + orderLinkId?: string; + orderType?: 'Stake' | 'Redeem'; + productId?: number; + startTime?: number; + endTime?: number; limit?: number; cursor?: string; } ⋮---- -export interface SetLeverageParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - buyLeverage: string; - sellLeverage: string; +export interface GetRWANavChartParamsV5 { + productId: number; + startTime?: number; + endTime?: number; } -⋮---- -export interface SwitchIsolatedMarginParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - tradeMode: 0 | 1; - buyLeverage: string; - sellLeverage: string; + +================ +File: src/types/request/v5-spot-x.ts +================ +export interface GetLaunchpoolProjectListParamsV5 { + status: number; + activityCoin?: string; + projectId?: string; + cursor?: string; + limit?: number; } ⋮---- -export interface SetTPSLModeParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - tpSlMode: TPSLModeV5; +export interface GetLaunchpoolUserActivityLogParamsV5 { + stakeCoin?: string; + type?: number; + status?: number; + startTime?: string; + endTime?: string; + pageSize?: number; + current?: number; } ⋮---- -export interface SwitchPositionModeParamsV5 { - category: 'linear' | 'inverse'; - symbol?: string; - coin?: string; - mode: 0 | 3; +export interface GetLaunchpoolUserHistoryParamsV5 { + stakeCoin?: string; + rewardCoin?: string; + startTime?: string; + endTime?: string; + pageSize?: number; + current?: number; } ⋮---- -export interface SetRiskLimitParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - riskId: number; - positionIdx?: PositionIdx; +export interface GetPuzzleProjectListParamsV5 { + status: number; + projectId?: string; + activityCoin?: string; + cursor?: string; + limit?: number; } ⋮---- -export interface SetTradingStopParamsV5 { - category: CategoryV5; - symbol: string; - takeProfit?: string; - stopLoss?: string; - trailingStop?: string; - tpTriggerBy?: OrderTriggerByV5; - slTriggerBy?: OrderTriggerByV5; - activePrice?: string; - tpslMode?: TPSLModeV5; - tpSize?: string; - slSize?: string; - tpLimitPrice?: string; - slLimitPrice?: string; - tpOrderType?: OrderTypeV5; - slOrderType?: OrderTypeV5; - positionIdx: PositionIdx; +export interface GetTokenSplashProjectListParamsV5 { + status: number; + projectId?: string; + activityCoin?: string; + cursor?: string; + limit?: number; } ⋮---- -export interface SetAutoAddMarginParamsV5 { - category: 'linear'; +export interface GetTokenSplashUserActivityParamsV5 { + projectId?: string; + activityCoin?: string; +} + +================ +File: src/types/request/v5-spreadtrading.ts +================ +export interface GetSpreadInstrumentsInfoParamsV5 { + symbol?: string; + baseCoin?: string; + limit?: number; + cursor?: string; +} +⋮---- +/** GET /v5/spread/max-qty */ +export interface GetSpreadMaxQtyParamsV5 { symbol: string; - autoAddMargin: 0 | 1; - positionIdx?: PositionIdx; + /** 1: Buy, 2: Sell */ + side: '1' | '2'; + orderPrice: string; } ⋮---- -export interface AddOrReduceMarginParamsV5 { - category: 'linear' | 'inverse'; +/** 1: Buy, 2: Sell */ +⋮---- +export interface SubmitSpreadOrderParamsV5 { symbol: string; - margin: string; - positionIDex?: PositionIdx; + side: 'Buy' | 'Sell'; + orderType: 'Limit' | 'Market'; + qty: string; + price: string; + orderLinkId: string; + timeInForce: 'IOC' | 'FOK' | 'GTC' | 'PostOnly'; } ⋮---- -export interface GetExecutionListParamsV5 { - category: CategoryV5; - symbol?: string; +export interface AmendSpreadOrderParamsV5 { + symbol: string; orderId?: string; orderLinkId?: string; - baseCoin?: string; - settleCoin?: string; // Settle coin, uppercase only. For linear, inverse, option - startTime?: number; - endTime?: number; - execType?: ExecTypeV5; - limit?: number; - cursor?: string; + qty?: string; + price?: string; } ⋮---- -settleCoin?: string; // Settle coin, uppercase only. For linear, inverse, option -⋮---- -export interface GetClosedPnLParamsV5 { - category: CategoryV5; +export interface GetSpreadOpenOrdersParamsV5 { symbol?: string; - startTime?: number; - endTime?: number; + baseCoin?: string; + orderId?: string; + orderLinkId?: string; limit?: number; cursor?: string; } -⋮---- -export interface MovePositionParamsV5 { - fromUid: string; - toUid: string; - list: { - category: 'linear' | 'spot' | 'option' | 'inverse'; - symbol: string; - price: string; - side: 'Buy' | 'Sell'; - qty: string; - }[]; -} -⋮---- -export interface GetMovePositionHistoryParamsV5 { - category?: 'linear' | 'spot' | 'option'; +export interface GetSpreadOrderHistoryParamsV5 { symbol?: string; + baseCoin?: string; + orderId?: string; + orderLinkId?: string; startTime?: number; endTime?: number; - status?: 'Processing' | 'Filled' | 'Rejected'; - blockTradeId?: string; - limit?: string; + limit?: number; cursor?: string; } ⋮---- -export interface ConfirmNewRiskLimitParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; -} -⋮---- -export interface GetClosedOptionsPositionsParamsV5 { - category: 'option'; +export interface GetSpreadTradeHistoryParamsV5 { symbol?: string; + orderId?: string; + orderLinkId?: string; startTime?: number; endTime?: number; limit?: number; @@ -5583,351 +5201,91 @@ export interface GetClosedOptionsPositionsParamsV5 { } ================ -File: src/types/request/v5-rfq.ts +File: src/types/request/v5-strategy.ts ================ -export interface RFQTransactionV5 { - category: 'spot' | 'linear' | 'inverse' | 'option'; // Product type - symbol: string; // Name of the trading contract - side: 'buy' | 'sell'; // Inquiry transaction direction - qty: string; // Transaction quantity - isLeverage?: boolean; // For spot lending, default false -} -⋮---- -category: 'spot' | 'linear' | 'inverse' | 'option'; // Product type -symbol: string; // Name of the trading contract -side: 'buy' | 'sell'; // Inquiry transaction direction -qty: string; // Transaction quantity -isLeverage?: boolean; // For spot lending, default false +import { + OrderSideV5, + PositionIdx, + PovModeV5, + StrategyCategoryV5, + StrategyPreferV5, + StrategyTypeV5, +} from '../shared-v5'; ⋮---- -export interface CreateRFQParamsV5 { - counterparties: string[]; // Array of deskCode - rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters - anonymous?: boolean; // Whether it is anonymous inquiry, default false - strategyType?: string; // Inquiry label, max 36 characters - list: RFQTransactionV5[]; // Transaction list, up to 10 sets +/** POST /v5/strategy/create */ +export interface CreateStrategyOrderParamsV5 { + category: StrategyCategoryV5; + symbol: string; + side: OrderSideV5; + strategyType: StrategyTypeV5; + /** Total order quantity (coin). Either size or positionValue is required */ + size?: string; + /** Total order quantity (value). Either size or positionValue is required */ + positionValue?: string; + reduceOnly?: boolean; + positionIdx?: PositionIdx; + /** Spot leverage type. 0: normal, 1: borrow to trade (UTA_SPOT only) */ + leverageType?: 0 | 1; + /** TWAP / POV: total execution duration (seconds). Range [300, 86400]; TWAP must be divisible by interval */ + duration?: number; + /** TWAP / POV: sub-order placement interval (seconds) */ + interval?: 5 | 10 | 15 | 30 | 60 | 120; + /** TWAP: randomize each sub-order quantity by ±20% */ + isRandom?: boolean; + /** Advanced: activate when market price reaches this value */ + triggerPrice?: string; + /** Advanced: terminate when last traded price reaches this value */ + maxChasePrice?: string; + /** Limit chase: absolute distance from best bid/ask. Mutually exclusive with chasePercentE4 */ + chaseDistance?: string; + /** Limit chase: offset in basis points (1/10000). Mutually exclusive with chaseDistance */ + chasePercentE4?: number; + /** Chase / Iceberg: reference price side, e.g. Bid1, Ask1 */ + chasePrice?: string; + strategyPrefer?: StrategyPreferV5; + limitPrice?: string; + strategySl?: string; + strategyTp?: string; + /** Iceberg: 0 = taker allowed, 1 = post-only */ + postOnly?: 0 | 1; + isRebalance?: boolean; + /** 1: market, 2: limit */ + orderType?: 1 | 2; + orderPriceOffset?: string; + strategyName?: string; + /** POV execution mode */ + mode?: PovModeV5; + /** POV participation rate */ + participationRate?: string; + /** POV: historical traded volume window (seconds), range [60, 14400] */ + referenceWindow?: string; + /** POV: book depth reference levels [1, 10] */ + depthReference?: string; } ⋮---- -counterparties: string[]; // Array of deskCode -rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters -anonymous?: boolean; // Whether it is anonymous inquiry, default false -strategyType?: string; // Inquiry label, max 36 characters -list: RFQTransactionV5[]; // Transaction list, up to 10 sets +/** Total order quantity (coin). Either size or positionValue is required */ ⋮---- -export interface CancelRFQParamsV5 { - rfqId?: string; // Inquiry ID - rfqLinkId?: string; // Inquiry Custom ID -} +/** Total order quantity (value). Either size or positionValue is required */ ⋮---- -rfqId?: string; // Inquiry ID -rfqLinkId?: string; // Inquiry Custom ID +/** Spot leverage type. 0: normal, 1: borrow to trade (UTA_SPOT only) */ ⋮---- -export interface RFQQuoteV5 { - category: 'spot' | 'linear' | 'option'; // Product type - symbol: string; // Name of the trading contract - price: string; // Quote price - isLeverage?: boolean; // For spot lending, default false -} +/** TWAP / POV: total execution duration (seconds). Range [300, 86400]; TWAP must be divisible by interval */ ⋮---- -category: 'spot' | 'linear' | 'option'; // Product type -symbol: string; // Name of the trading contract -price: string; // Quote price -isLeverage?: boolean; // For spot lending, default false +/** TWAP / POV: sub-order placement interval (seconds) */ ⋮---- -export interface CreateRFQQuoteParamsV5 { - rfqId: string; // Inquiry ID - quoteLinkId?: string; // Quotation custom ID, 1-32 characters - anonymous?: boolean; // Whether it is anonymous quotation, default false - expiresIn?: number; // Validity period in seconds, default 60 - quoteBuyList?: RFQQuoteV5[]; // Quotation buy direction - quoteSellList?: RFQQuoteV5[]; // Quotation sell direction -} +/** TWAP: randomize each sub-order quantity by ±20% */ ⋮---- -rfqId: string; // Inquiry ID -quoteLinkId?: string; // Quotation custom ID, 1-32 characters -anonymous?: boolean; // Whether it is anonymous quotation, default false -expiresIn?: number; // Validity period in seconds, default 60 -quoteBuyList?: RFQQuoteV5[]; // Quotation buy direction -quoteSellList?: RFQQuoteV5[]; // Quotation sell direction +/** Advanced: activate when market price reaches this value */ ⋮---- -export interface ExecuteRFQQuoteParamsV5 { - rfqId: string; // Inquiry ID - quoteId: string; // Quotation ID - quoteSide: 'buy' | 'sell'; // The direction of the quote -} +/** Advanced: terminate when last traded price reaches this value */ ⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Quotation ID -quoteSide: 'buy' | 'sell'; // The direction of the quote +/** Limit chase: absolute distance from best bid/ask. Mutually exclusive with chasePercentE4 */ ⋮---- -export interface CancelRFQQuoteParamsV5 { - quoteId?: string; // Quotation ID - rfqId?: string; // Inquiry ID - quoteLinkId?: string; // Quotation Custom ID -} +/** Limit chase: offset in basis points (1/10000). Mutually exclusive with chaseDistance */ ⋮---- -quoteId?: string; // Quotation ID -rfqId?: string; // Inquiry ID -quoteLinkId?: string; // Quotation Custom ID +/** Chase / Iceberg: reference price side, e.g. Bid1, Ask1 */ ⋮---- -export interface GetRFQRealtimeParamsV5 { - rfqId?: string; // Inquiry ID - rfqLinkId?: string; // Inquiry Custom ID - traderType?: 'quote' | 'request'; // Trader type, default 'request' -} -⋮---- -rfqId?: string; // Inquiry ID -rfqLinkId?: string; // Inquiry Custom ID -traderType?: 'quote' | 'request'; // Trader type, default 'request' -⋮---- -export interface GetRFQListParamsV5 { - rfqId?: string; // Inquiry ID - rfqLinkId?: string; // Custom ID for inquiry form - traderType?: 'quoter' | 'request'; // Trader type, default 'request' - status?: - | 'Active' - | 'Canceled' - | 'PendingFill' - | 'Filled' - | 'Expired' - | 'Failed'; // Status of the inquiry form - limit?: number; // Return number of items, max 100, default 50 - cursor?: string; // Page turning mark -} -⋮---- -rfqId?: string; // Inquiry ID -rfqLinkId?: string; // Custom ID for inquiry form -traderType?: 'quoter' | 'request'; // Trader type, default 'request' -⋮---- -| 'Failed'; // Status of the inquiry form -limit?: number; // Return number of items, max 100, default 50 -cursor?: string; // Page turning mark -⋮---- -export interface GetRFQQuoteRealtimeParamsV5 { - rfqId?: string; // Inquiry ID - quoteId?: string; // Quotation ID - quoteLinkId?: string; // Quotation Custom ID - traderType?: 'quote' | 'request'; // Trader type, default 'quote' -} -⋮---- -rfqId?: string; // Inquiry ID -quoteId?: string; // Quotation ID -quoteLinkId?: string; // Quotation Custom ID -traderType?: 'quote' | 'request'; // Trader type, default 'quote' -⋮---- -export interface GetRFQHistoryParamsV5 { - rfqId?: string; // Inquiry ID - quoteId?: string; // Quotation ID - quoteLinkId?: string; // Quotation custom ID, can only check last 3 months - traderType?: 'quote' | 'request'; // Trader type, default 'quote' - status?: - | 'Active' - | 'Canceled' - | 'PendingFill' - | 'Filled' - | 'Expired' - | 'Failed'; // Status of quotation - limit?: number; // Return number of items, max 100, default 50 - cursor?: string; // Page turning mark -} -⋮---- -rfqId?: string; // Inquiry ID -quoteId?: string; // Quotation ID -quoteLinkId?: string; // Quotation custom ID, can only check last 3 months -traderType?: 'quote' | 'request'; // Trader type, default 'quote' -⋮---- -| 'Failed'; // Status of quotation -limit?: number; // Return number of items, max 100, default 50 -cursor?: string; // Page turning mark -⋮---- -export interface GetRFQTradeListParamsV5 { - rfqId?: string; // Inquiry ID - rfqLinkId?: string; // Custom ID for inquiry form, can only check last 3 months - quoteId?: string; // Quotation ID - quoteLinkId?: string; // Quotation custom ID, can only check last 3 months - status?: 'Filled' | 'Rejected'; // Status - limit?: number; // Return number of items, max 100, default 50 - cursor?: string; // Page turning mark -} -⋮---- -rfqId?: string; // Inquiry ID -rfqLinkId?: string; // Custom ID for inquiry form, can only check last 3 months -quoteId?: string; // Quotation ID -quoteLinkId?: string; // Quotation custom ID, can only check last 3 months -status?: 'Filled' | 'Rejected'; // Status -limit?: number; // Return number of items, max 100, default 50 -cursor?: string; // Page turning mark -⋮---- -export interface GetRFQPublicTradesParamsV5 { - startTime?: number; // Timestamp in milliseconds, time range is 7 days - endTime?: number; // Timestamp in milliseconds, time range is 7 days - limit?: number; // Return number of items, max 100, default 50 - cursor?: string; // Page turning mark -} -⋮---- -startTime?: number; // Timestamp in milliseconds, time range is 7 days -endTime?: number; // Timestamp in milliseconds, time range is 7 days -limit?: number; // Return number of items, max 100, default 50 -cursor?: string; // Page turning mark -⋮---- -export interface AcceptNonLPQuoteParamsV5 { - rfqId: string; // Inquiry ID -} -⋮---- -rfqId: string; // Inquiry ID - -================ -File: src/types/request/v5-spreadtrading.ts -================ -export interface GetSpreadInstrumentsInfoParamsV5 { - symbol?: string; - baseCoin?: string; - limit?: number; - cursor?: string; -} -⋮---- -/** GET /v5/spread/max-qty */ -export interface GetSpreadMaxQtyParamsV5 { - symbol: string; - /** 1: Buy, 2: Sell */ - side: '1' | '2'; - orderPrice: string; -} -⋮---- -/** 1: Buy, 2: Sell */ -⋮---- -export interface SubmitSpreadOrderParamsV5 { - symbol: string; - side: 'Buy' | 'Sell'; - orderType: 'Limit' | 'Market'; - qty: string; - price: string; - orderLinkId: string; - timeInForce: 'IOC' | 'FOK' | 'GTC' | 'PostOnly'; -} -⋮---- -export interface AmendSpreadOrderParamsV5 { - symbol: string; - orderId?: string; - orderLinkId?: string; - qty?: string; - price?: string; -} -⋮---- -export interface GetSpreadOpenOrdersParamsV5 { - symbol?: string; - baseCoin?: string; - orderId?: string; - orderLinkId?: string; - limit?: number; - cursor?: string; -} -export interface GetSpreadOrderHistoryParamsV5 { - symbol?: string; - baseCoin?: string; - orderId?: string; - orderLinkId?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetSpreadTradeHistoryParamsV5 { - symbol?: string; - orderId?: string; - orderLinkId?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} - -================ -File: src/types/request/v5-strategy.ts -================ -import { - OrderSideV5, - PositionIdx, - PovModeV5, - StrategyCategoryV5, - StrategyPreferV5, - StrategyTypeV5, -} from '../shared-v5'; -⋮---- -/** POST /v5/strategy/create */ -export interface CreateStrategyOrderParamsV5 { - category: StrategyCategoryV5; - symbol: string; - side: OrderSideV5; - strategyType: StrategyTypeV5; - /** Total order quantity (coin). Either size or positionValue is required */ - size?: string; - /** Total order quantity (value). Either size or positionValue is required */ - positionValue?: string; - reduceOnly?: boolean; - positionIdx?: PositionIdx; - /** Spot leverage type. 0: normal, 1: borrow to trade (UTA_SPOT only) */ - leverageType?: 0 | 1; - /** TWAP / POV: total execution duration (seconds). Range [300, 86400]; TWAP must be divisible by interval */ - duration?: number; - /** TWAP / POV: sub-order placement interval (seconds) */ - interval?: 5 | 10 | 15 | 30 | 60 | 120; - /** TWAP: randomize each sub-order quantity by ±20% */ - isRandom?: boolean; - /** Advanced: activate when market price reaches this value */ - triggerPrice?: string; - /** Advanced: terminate when last traded price reaches this value */ - maxChasePrice?: string; - /** Limit chase: absolute distance from best bid/ask. Mutually exclusive with chasePercentE4 */ - chaseDistance?: string; - /** Limit chase: offset in basis points (1/10000). Mutually exclusive with chaseDistance */ - chasePercentE4?: number; - /** Chase / Iceberg: reference price side, e.g. Bid1, Ask1 */ - chasePrice?: string; - strategyPrefer?: StrategyPreferV5; - limitPrice?: string; - strategySl?: string; - strategyTp?: string; - /** Iceberg: 0 = taker allowed, 1 = post-only */ - postOnly?: 0 | 1; - isRebalance?: boolean; - /** 1: market, 2: limit */ - orderType?: 1 | 2; - orderPriceOffset?: string; - strategyName?: string; - /** POV execution mode */ - mode?: PovModeV5; - /** POV participation rate */ - participationRate?: string; - /** POV: historical traded volume window (seconds), range [60, 14400] */ - referenceWindow?: string; - /** POV: book depth reference levels [1, 10] */ - depthReference?: string; -} -⋮---- -/** Total order quantity (coin). Either size or positionValue is required */ -⋮---- -/** Total order quantity (value). Either size or positionValue is required */ -⋮---- -/** Spot leverage type. 0: normal, 1: borrow to trade (UTA_SPOT only) */ -⋮---- -/** TWAP / POV: total execution duration (seconds). Range [300, 86400]; TWAP must be divisible by interval */ -⋮---- -/** TWAP / POV: sub-order placement interval (seconds) */ -⋮---- -/** TWAP: randomize each sub-order quantity by ±20% */ -⋮---- -/** Advanced: activate when market price reaches this value */ -⋮---- -/** Advanced: terminate when last traded price reaches this value */ -⋮---- -/** Limit chase: absolute distance from best bid/ask. Mutually exclusive with chasePercentE4 */ -⋮---- -/** Limit chase: offset in basis points (1/10000). Mutually exclusive with chaseDistance */ -⋮---- -/** Chase / Iceberg: reference price side, e.g. Bid1, Ask1 */ -⋮---- -/** Iceberg: 0 = taker allowed, 1 = post-only */ +/** Iceberg: 0 = taker allowed, 1 = post-only */ ⋮---- /** 1: market, 2: limit */ ⋮---- @@ -6146,7190 +5504,4907 @@ export interface BatchCancelOrderParamsV5 { } ================ -File: src/types/response/v5-alpha-trade.ts +File: src/types/response/contract.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +export interface PaginatedResult { + nextPageCursor: string; + list: TList[]; +} +export interface ContractListResult { + category: string; + list: TList[]; +} +⋮---- +export interface ContractHistoricOrder { + symbol: string; + orderId: string; + orderLinkId: string; + side: string; + orderType: string; + price: string; + iv: string; + qty: string; + timeInForce: string; + orderStatus: string; + positionIdx: number; + lastPriceOnCreated: string; + createdTime: string; + updatedTime: string; + cancelType: string; + rejectReason: string; + stopOrderType: string; + triggerDirection: number; + triggerBy: string; + triggerPrice: string; + cumExecValue: string; + cumExecFee: string; + cumExecQty: string; + leavesValue: string; + leavesQty: string; + takeProfit: string; + stopLoss: string; + tpslMode: string; + tpLimitPrice: string; + slLimitPrice: string; + tpTriggerBy: string; + slTriggerBy: string; + reduceOnly: boolean; + closeOnTrigger: boolean; + blockTradeId: string; + smpType: string; + smpGroup: string; + smpOrderId: string; +} +⋮---- +export interface ContractSymbolTicker { + symbol: string; + bidPrice: string; + askPrice: string; + lastPrice: string; + lastTickDirection: string; + prevPrice24h: string; + price24hPcnt: string; + highPrice24h: string; + lowPrice24h: string; + prevPrice1h: string; + markPrice: string; + indexPrice: string; + openInterest: string; + turnover24h: string; + volume24h: string; + fundingRate: string; + nextFundingTime: string; + predictedDeliveryPrice: string; + basisRate: string; + deliveryFeeRate: string; + deliveryTime: string; +} + +================ +File: src/types/response/v5-alpha-lp.ts ================ /** - * V5 private Alpha / on-chain (Web3) trade responses. + * V5 private Alpha LP responses. */ ⋮---- -export interface AlphaTradeQuoteModeEstimationV5 { - quoteMode: number; - estimatedGas: string; - estimatedGasUsd: string; - estimatedSlippage: string; +export interface AlphaLPPoolV5 { + poolAddress: string; + poolName: string; + poolTag: string; + apy: string; + tvl: string; + token0Symbol: string; + token0IconUrlDay: string; + token0IconUrlNight: string; + token1Symbol: string; + token1IconUrlDay: string; + token1IconUrlNight: string; + chainCode: string; + chainIconUrl: string; } ⋮---- -export interface AlphaTradeQuoteResultV5 { - tradeType: number; - fromTokenCode: string; - fromTokenAmount: string; - fromTokenAmountUsd: string; - toTokenCode: string; - toTokenAmount: string; - toTokenAmountUsd: string; - minToTokenAmount: string; - slippage: string; - gas: string; - gasUsd: string; - platformFee: string; - platformFeeUsd: string; - swapRate: string; - lossRate: string; - quoteData: string; - correctingCode: string; - quoteMode: number; - quoteDataId: string; - expireTime: number; - modeEstimations: AlphaTradeQuoteModeEstimationV5[]; - chargeAmount?: string; - timestamp?: number; +export interface AlphaLPPoolListResultV5 { + pools: AlphaLPPoolV5[]; } ⋮---- -export interface ExecuteAlphaTradeResultV5 { +export interface AlphaLPPoolInfoV5 { + poolAddress: string; + poolName: string; + apy: string; + tvl: string; + feeRate: string; + token0Symbol: string; + token0Reserve: string; + token1Symbol: string; + token1Reserve: string; + priceRangeLower: string; + priceRangeUpper: string; + currentPrice: string; +} +⋮---- +export interface ExecuteAlphaLPStakeResultV5 { + positionId: number; orderNo: string; } ⋮---- -export interface AlphaPayTokenV5 { - tokenCode: string; - symbol: string; - tokenDecimals: number; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - limit: string; - supportChains: string[]; +export interface ExecuteAlphaLPRedeemResultV5 { + orderNo: string; } ⋮---- -export interface AlphaTradeOrderV5 { +export interface AlphaLPOrderV5 { orderType: number; - tradeType: number; orderNo: string; orderStatus: number; - fromTokenCode: string; - fromTokenAmount: string; - fromTokenSymbol: string; - fromTokenDecimals: number; - fromTokenIconUrlDay?: string; - fromTokenIconUrlNight?: string; - fromChainCode: string; - fromChainIconUrl?: string; - toTokenCode: string; - toTokenAmount: string; - toTokenSymbol: string; - toTokenDecimals: number; - toTokenIconUrlDay?: string; - toTokenIconUrlNight?: string; - toChainCode: string; - toChainIconUrl?: string; + poolAddress: string; + poolName: string; + positionId: number; + tokenCode: string; + tokenSymbol: string; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + amount: string; + chainCode: string; + chainIconUrl: string; gasTokenSymbol: string; gasOnchain: string; gasUsd: string | null; platformFee: string; platformFeeUsd: string | null; - quoteMode: number; createTime: number; - executionTime?: number; - failureReasonCode?: string; - source?: string; - swapRate: string; - actualFromTokenAmount: string; + executionTime: number; + failureReason?: string; + dercRatio?: string; } ⋮---- -export interface AlphaTradeOrderListResultV5 { +export interface AlphaLPOrderListResultV5 { total: number; pageIndex: number; - orders: AlphaTradeOrderV5[]; + orders: AlphaLPOrderV5[]; } ⋮---- -export interface AlphaBizTokenV5 { +export interface AlphaLPPayTokenV5 { tokenCode: string; + tokenSymbol: string; chainCode: string; chainIconUrl: string; - tokenAddress: string; - symbol: string; - tokenDecimals: number; + decimals: number; + availableBalance: string; tokenIconUrlDay: string; tokenIconUrlNight: string; - createTime: number; - createTimeOnchain: number; - riskFlag: number; - minOrderQuantity: number; - maxOrderQuantity: number; - tokenTags: number[]; - payTokenCodes: string[]; -} -⋮---- -export interface AlphaBizTokenPriceV5 { - chainCode: string; - tokenAddress: string; - price: string; - change24h: string; - vol24h: string; - marketCap: string; - liquidity: string; - holders: string; + minStakeAmount: string; + maxStakeAmount: string; } ⋮---- -export interface AlphaBizTokenPriceListResultV5 { - tokenPriceInfoList: AlphaBizTokenPriceV5[]; +export interface AlphaLPPayTokenListResultV5 { + tokens: AlphaLPPayTokenV5[]; } ⋮---- -export interface AlphaBizTokenDetailsV5 { +export interface AlphaLPPayTokenPriceV5 { tokenCode: string; + tokenSymbol: string; + priceUsd: string; chainCode: string; - chainIconUrl: string; - tokenAddress: string; - symbol: string; - tokenDecimals: number; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - minOrderQuantity: string; - maxOrderQuantity: string; - maxPositionQuantity: string; - tokenDesc: string; - xUrl: string; - officialUrl: string; - whitePaperUrl: string; - tokenTag: number; - riskFlag: number; - createTimeOnchain: number; - status: number; - tokenTags: number[]; - showMessage: number; - content?: string; - linkName?: string; - linkAddress?: string; + updateTime: number; } ⋮---- -export interface AlphaAssetV5 { - chainCode: string; - chainIconUrl: string; - tokenAddress: string; - tokenCode: string; - tokenSymbol: string; - tokenDecimals: number; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - tokenAmount: string; - tokenAmountUsd: string; - tradeFlag: number; - pnl: string | null; - pnlRatio: string | null; - costPrice: string | null; - lastPrice: string; - costTotalValue: string | null; - assetStatus: number; - announcementUrl?: string; - estimatedOfflineTime?: number; - delistingTime?: number; +export interface AlphaLPPayTokenPriceResultV5 { + prices: AlphaLPPayTokenPriceV5[]; } ⋮---- -export interface AlphaAssetListResultV5 { - totalAssetUsd: string; - assetList: AlphaAssetV5[]; +export interface AlphaLPPositionV5 { + positionId: number; + poolAddress: string; + poolName: string; + stakedAmount: string; + stakedTokenCode: string; + stakedTokenSymbol: string; + currentValueUsd: string; + earnedRewardsUsd: string; + unrealizedPnl: string; + realizedPnl: string; + apy: string; + token0Amount: string; + token0Symbol: string; + token1Amount: string; + token1Symbol: string; + rangeUpper: string; + rangeLower: string; + createTime: number; + updateTime: number; + status: number; } ⋮---- -export interface AlphaAssetDetailResultV5 { - assetList: AlphaAssetV5[]; +export interface AlphaLPPositionListResultV5 { + positions: AlphaLPPositionV5[]; } ================ -File: src/types/response/v5-broker.ts +File: src/types/response/v5-alpha-prediction.ts ================ -interface EarningDetailV5 { - userId: string; - bizType: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; - symbol: string; - coin: string; - earning: string; - markupEarning: string; - baseFeeEarning: string; - orderId: string; - execTime: string; -} +/** + * V5 private Alpha prediction market responses. + */ ⋮---- -interface TotalEarningCategoryV5 { - coin: string; - earning: string; +export interface AlphaPredictionEngineStatusV5 { + available: boolean; } ⋮---- -export interface ExchangeBrokerEarningResultV5 { - totalEarningCat: { - spot: TotalEarningCategoryV5[]; - derivatives: TotalEarningCategoryV5[]; - options: TotalEarningCategoryV5[]; - convert: TotalEarningCategoryV5[]; - total: TotalEarningCategoryV5[]; - }; - details: EarningDetailV5[]; - nextPageCursor: string; +export interface AlphaPredictionPayTokenV5 { + tokenCode: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + supportChains: string[]; } ⋮---- -export interface ExchangeBrokerAccountInfoV5 { - subAcctQty: string; - maxSubAcctQty: string; - baseFeeRebateRate: { - spot: string; - derivatives: string; - }; - markupFeeRebateRate: { - spot: string; - derivatives: string; - convert: string; - }; - ts: string; +export interface AlphaPredictionMarketV5 { + tokenId: string; + outcome: string; + price: string; + side: number; + volume: string; + liquidity: string; } ⋮---- -export interface ExchangeBrokerSubAccountDepositRecordV5 { - id: string; - subMemberId: string; - coin: string; - chain: string; - amount: string; - txID: string; - status: number; - toAddress: string; - tag: string; - depositFee: string; - successAt: string; - confirmations: string; - txIndex: string; - blockHash: string; - batchReleaseLimit: string; - depositType: string; +export interface AlphaPredictionEventDetailV5 { + eventId: string; + slug: string; + title: string; + description: string; + category: string; + endDate: number; + resolved: boolean; + volume: string; + liquidity: string; + markets: AlphaPredictionMarketV5[]; } ⋮---- -export interface BrokerVoucherSpecV5 { - id: string; - coin: string; - amountUnit: 'AWARD_AMOUNT_UNIT_USD' | 'AWARD_AMOUNT_UNIT_COIN'; - productLine: string; - subProductLine: string; - totalAmount: { - [key: string]: string; - }; - usedAmount: string; +export interface AlphaPredictionOrderEstimateFeeDetailV5 { + serverFee: string; + polymarketFee: string; } ⋮---- -export interface BrokerIssuedVoucherV5 { - accountId: string; - awardId: string; - specCode: string; - amount: string; - isClaimed: boolean; - startAt: string; - endAt: string; - effectiveAt: string; - ineffectiveAt: string; - usedAmount: string; +export interface AlphaPredictionOrderEstimateV5 { + avgPrice: string; + estimatedCost: string; + estimatedReceive: string; + toWin?: string; + feeAmount: string; + feeDetail: AlphaPredictionOrderEstimateFeeDetailV5; + slippage: string; } ⋮---- -export interface BrokerRateLimitSetResultItemV5 { - uids: string; - bizType: string; - rate: number; - success: boolean; - msg: string; +export interface ExecuteAlphaPredictionOrderResultV5 { + orderNo: string; } ⋮---- -export interface BrokerRateLimitCapItemV5 { - bizType: string; - totalRate: string; - ebCap: string; - uidCap: string; +export interface AlphaPredictionOrderV5 { + orderNo: string; + tokenId: string; + eventId: string; + side: number; + orderType: number; + orderAmount: string; + filledSize: string; + filledPrice: string; + totalFee: string; + status: number; + createdAt: number; + updatedAt: number; } ⋮---- -export interface BrokerRateLimitAllItemV5 { - uids: string; - bizType: string; - rate: number; -} - -================ -File: src/types/response/v5-card.ts -================ -export interface CardAssetRecordV5 { - pan4: string; - pan6: string; - tradeStatus: string; - side: string; - basicAmount: string; - basicCurrency: string; - transactionAmount: string; - transactionCurrency: string; - txnCreate: number; - merchCountry: string; - merchCity: string; - merchName: string; - txnId: string; - declinedReason: string; - totalFees: string; - uid: number; - transactionCurrencyAmount: string; - fxPad: string; - interchangeFee: string; - billAmount: string; - paidAmount: string; - paidCurrency: string; - bonusAmount: string; - foreignTransactionFee: string; - totalTax: string; - paidFiat: string; - withdrawalFee: string; - status: string; - orderNo: string; - mccCode: string; - merchCategoryDesc: string; +export interface AlphaPredictionOrderListResultV5 { + orders: AlphaPredictionOrderV5[]; + total: number; + pageIndex: number; } ⋮---- -export interface CardAssetRecordsResultV5 { - pageSize: number; - pageNo: number; - totalCount: number; - data: CardAssetRecordV5[]; +export interface AlphaPredictionOrderBookLevelV5 { + price: string; + size: string; } ⋮---- -export interface CardPointBalanceV5 { - accountId: string; - availablePoint: string | number; - pendingPoint: string | number; - status: string; - updateTime: string | number; - settlementPeriod: number; +export interface AlphaPredictionOrderBookV5 { + tokenId: string; + bids: AlphaPredictionOrderBookLevelV5[]; + asks: AlphaPredictionOrderBookLevelV5[]; } ⋮---- -export interface CardPointRecordV5 { - outOrderId: string; - point: number; - side: string; - type: string; - subType: string; - createTime: number; +export interface AlphaPredictionTokenPriceV5 { + tokenId: string; + bestBid: string; + bestAsk: string; + lastPrice: string; + volume24h: string; updateTime: number; - bizId: string; - bizTxnId: string; - transactionDate: string; - transactionId: string; - transactionAmount: string; - basicCurrency: string; - merchCategoryDesc: string; - merchName: string; - merchCountry: string; - merchCity: string; - pan4: string; - payFiatAmount: string; - transactionCurrencyAmount: string; } ⋮---- -export interface CardPointRecordsResultV5 { - pageSize: number; - pageNo: number; - totalCount: number; - data: CardPointRecordV5[]; +export interface AlphaPredictionPriceHistoryCandleV5 { + openTime: number; + open: string; + high: string; + low: string; + close: string; + volume: string; } ⋮---- -export interface CardPointTierInfoV5 { - usedLimit: string; - limit: string; - unit: string; - tier: string; - autoCashback: boolean; +export interface AlphaPredictionPriceHistoryV5 { + tokenId: string; + interval: string; + list: AlphaPredictionPriceHistoryCandleV5[]; } ⋮---- -export interface CardMallItemV5 { - itemId: string; - itemName: string; - priority: number; - onTime: string; - offTime: string; - price: string; - discountPrice: string; - totalNum: number; - redeemNum: number; - picPath: string; - currency: string; - currencyType: number; - itemType: number; - itemBizType: number; +export interface AlphaPredictionPositionV5 { + positionId: string; + tokenId: string; + eventId: string; + outcomeName: string; + shares: string; + cost: string; + avgPrice: string; + currentPrice: string; + value: string; + unrealizedPnl: string; + unrealizedPnlRate: string; + createdAt: number; + finished: boolean; } ⋮---- -export interface CardMallItemListResultV5 { - pageNo: number; - pageSize: number; - totalCount: number; - data: CardMallItemV5[]; +export interface AlphaPredictionPositionListResultV5 { + positions: AlphaPredictionPositionV5[]; + total: number; + totalAssetUsd: string; } ⋮---- -export interface CardPointCashbackDetailV5 { - points: string; - amt: string; - ccy: string; - ccyType: string; - createTime: string; - bizTxnId: string; - sourceId: number; - sourceCode: string; - orderStatus: number; - orderSubStatus: number; - orderShowStatus: string; - failedBizCode: string; -} - -================ -File: src/types/response/v5-earn-advance-discount.ts -================ -export interface AdvanceEarnDiscountBuyOfferV5 { - productId: string; - currentPrice: string; - purchasePrice: string; - knockoutPrice: string; - knockoutCouponE8: string; - maxInvestmentAmount: string; - instUid: string; - expiredAt: string; - category: string; +export interface AlphaPredictionPositionHistoryV5 { + positionId: string; + tokenId: string; + eventId: string; + outcomeName: string; + shares: string; + cost: string; + avgPrice: string; + exitPrice: string; + realizedPnl: string; + realizedPnlRate: string; + result: number; + closedAt: number; } ⋮---- -/** GET /v5/earn/advance/product-extra-info?category=DiscountBuy */ -export interface AdvanceEarnProductExtraInfoDiscountBuyV5 { - offers: AdvanceEarnDiscountBuyOfferV5[]; +export interface AlphaPredictionPositionHistoryResultV5 { + positions: AlphaPredictionPositionHistoryV5[]; + total: number; } ⋮---- -export interface AdvanceEarnDualAssetQuoteLevelV5 { - selectPrice: string; - apyE8: string; - maxInvestmentAmount: string; - expiredAt: string; +export interface AlphaPredictionPortfolioSummaryV5 { + positionValue: string; + positionValueUsd: string; + biggestWin: string; + winRate: string; + winCount: number; + lossCount: number; } ⋮---- -export interface AdvanceEarnDualAssetQuoteProductV5 { - productId: string; - currentPrice: string; - buyLowPrice: AdvanceEarnDualAssetQuoteLevelV5[]; - sellHighPrice: AdvanceEarnDualAssetQuoteLevelV5[]; +export interface AlphaPredictionSideMarketTokenV5 { + tokenId: string; + outcome: string; + price: string; + liquidity: string; } ⋮---- -/** GET /v5/earn/advance/product-extra-info?category=DualAssets&productId= */ -export interface AdvanceEarnProductExtraInfoDualAssetsV5 { - category: 'DualAssets'; - list: AdvanceEarnDualAssetQuoteProductV5[]; +export interface AlphaPredictionSideMarketV5 { + marketId: string; + eventId: string; + marketType: number; + question: string; + tokens: AlphaPredictionSideMarketTokenV5[]; + volume24h: string; + endDate: number; + status: number; } ⋮---- -export type AdvanceEarnProductExtraInfoV5 = - | AdvanceEarnProductExtraInfoDiscountBuyV5 - | AdvanceEarnProductExtraInfoDualAssetsV5; +export interface AlphaPredictionSideMarketListResultV5 { + list: AlphaPredictionSideMarketV5[]; + total: number; + pageIndex: number; + pageSize: number; +} ⋮---- -export interface AdvanceEarnPlaceOrderResultV5 { - orderId: string; - orderLinkId: string; +export interface AlphaPredictionSportsMatchV5 { + matchId: string; + eventType: number; + stageCode: string; + homeTeam: string; + awayTeam: string; + matchTime: number; + status: number; + eventId: string; } ⋮---- -export interface AdvanceEarnDiscountBuyPositionV5 { - positionId: string; - productId: string; - category: string; - coin: string; - underlyingAsset: string; - amount: string; - purchasePrice: string; - knockoutPrice: string; - knockoutCouponE8: string; - status: string; - orderId: string; - duration: string; - settlementTime: string; - accountType: string; - toAccountType: string; - settleType: string; - expectReceiveAt: string; +export interface AlphaPredictionSportsMatchListResultV5 { + list: AlphaPredictionSportsMatchV5[]; + total: number; + pageIndex: number; + pageSize: number; } ⋮---- -export interface AdvanceEarnDualAssetsPositionV5 { - positionId: string; - productId: string; - category: string; - baseCoin: string; - quoteCoin: string; - investCoin: string; - amount: string; - apyE8: string; - direction: 'BuyLow' | 'SellHigh' | string; - targetPrice: string; - settlementTime: string; - status: string; - orderId: string; - duration: string; - expectReturnCoin: string; - expectReturnAmount: string; - accountType: string; - toAccountType: string; - yieldStartAt: string | number; - yieldEndAt: string | number; +export interface AlphaPredictionSportsTimelineStageV5 { + stageCode: string; + stageName: string; + status: number; + matchCount: number; + startTime: number; + endTime: number; } ⋮---- -export interface AdvanceEarnPositionListV5 { - category: string; - list: (AdvanceEarnDiscountBuyPositionV5 | AdvanceEarnDualAssetsPositionV5)[]; - nextPageCursor: string; +export interface AlphaPredictionSportsTimelineStagesV5 { + eventType: number; + stages: AlphaPredictionSportsTimelineStageV5[]; } ⋮---- -export interface AdvanceEarnDiscountBuyOrderV5 { - orderId: string; - orderLinkId: string; - productId: string; - category: string; - orderType: string; - amount: string; - coin: string; - underlyingAsset: string; - status: string; - createdTime: string; - purchasePrice: string; - knockoutPrice: string; - knockoutCouponE8: string; - duration: string; - settlementTime: string; - accountType: string; - toAccountType: string; - settleType: string; - settlementPrice: string; - settlementCoin: string; - settlementAmount: string; - isVip: boolean; - refundStatus: string; +export interface AlphaPredictionSportsGroupStandingV5 { + rank: number; + teamName: string; + played: number; + won: number; + drawn: number; + lost: number; + goalsFor: number; + goalsAgainst: number; + goalDifference: number; + points: number; } ⋮---- -export interface AdvanceEarnDualAssetsOrderV5 { - orderId: string; - orderLinkId: string; - productId: string; - category: string; - orderType: string; - amount: string; - coin: string; - baseCoin: string; - quoteCoin: string; - status: string; - createdTime: string; - updatedTime: string; - direction: 'BuyLow' | 'SellHigh' | string; - targetPrice: string; - settlementTime: string | number; - estimateApyE8: string | number; - duration: string; - accountType: string; - toAccountType: string; - selectApyE8: string | number; - isVip: boolean; - settlementCoin: string; - settlementAmount: string; - orderMode: string; - settlementPrice: string; - refundStatus: string; - trialBonusAmount: string; - trialBonusPnl: string; +export interface AlphaPredictionSportsGroupMatchV5 { + matchId: string; + homeTeam: string; + awayTeam: string; + matchTime: number; + status: number; + homeScore: number; + awayScore: number; + eventId: string; } ⋮---- -export interface AdvanceEarnOrderListV5 { - category: string; - list: (AdvanceEarnDiscountBuyOrderV5 | AdvanceEarnDualAssetsOrderV5)[]; - nextPageCursor: string; +export interface AlphaPredictionSportsGroupV5 { + groupName: string; + standings: AlphaPredictionSportsGroupStandingV5[]; + matches: AlphaPredictionSportsGroupMatchV5[]; +} +⋮---- +export interface AlphaPredictionSportsGroupStageDetailV5 { + groups: AlphaPredictionSportsGroupV5[]; } ================ -File: src/types/response/v5-earn-fixed-term.ts +File: src/types/response/v5-alpha-trade.ts ================ -export interface FixedTermEarnTieredApyV5 { - min: string; - max: string; - apy: string; -} +/** + * V5 private Alpha / on-chain (Web3) trade responses. + */ ⋮---- -export interface FixedTermEarnInterestCoinApyV5 { - coin: string; - apy: string; - expectUnitEarning: string; - currentPrice: string; +export interface AlphaTradeQuoteModeEstimationV5 { + quoteMode: number; + estimatedGas: string; + estimatedGasUsd: string; + estimatedSlippage: string; } ⋮---- -export interface FixedTermEarnProductV5 { - productId: string; - category: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium' | string; - coin: string; - duration: string; - status: 'Available' | 'SoldOut' | 'NotStarted' | string; - tieredApyList: FixedTermEarnTieredApyV5[]; - minStakeAmount: string; - maxStakeAmount: string; - precision: number; - subscribeStartAt: string; - subscribeEndAt: string; - allowEarlyRedemption: boolean; - earlyRedemptionApy: string; - redemptionLimitDuration: string; - allowAutoReinvest: boolean; - interestCoinApyList: FixedTermEarnInterestCoinApyV5[]; - isVip: boolean; - creditTime: string; - specialUserGroupRequired: boolean; - specialUserGroupInfo: string; +export interface AlphaTradeQuoteResultV5 { + tradeType: number; + fromTokenCode: string; + fromTokenAmount: string; + fromTokenAmountUsd: string; + toTokenCode: string; + toTokenAmount: string; + toTokenAmountUsd: string; + minToTokenAmount: string; + slippage: string; + gas: string; + gasUsd: string; + platformFee: string; + platformFeeUsd: string; + swapRate: string; + lossRate: string; + quoteData: string; + correctingCode: string; + quoteMode: number; + quoteDataId: string; + expireTime: number; + modeEstimations: AlphaTradeQuoteModeEstimationV5[]; + chargeAmount?: string; + timestamp?: number; } ⋮---- -export interface FixedTermEarnProductListV5 { - list: FixedTermEarnProductV5[]; +export interface ExecuteAlphaTradeResultV5 { + orderNo: string; } ⋮---- -export interface FixedTermEarnPlaceOrderResultV5 { - orderId: string; - orderLinkId: string; +export interface AlphaPayTokenV5 { + tokenCode: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + limit: string; + supportChains: string[]; } ⋮---- -export interface RedeemFixedTermEarnResultV5 { - redeemAmount: string; - estEarnings: string; +export interface AlphaTradeOrderV5 { + orderType: number; + tradeType: number; + orderNo: string; + orderStatus: number; + fromTokenCode: string; + fromTokenAmount: string; + fromTokenSymbol: string; + fromTokenDecimals: number; + fromTokenIconUrlDay?: string; + fromTokenIconUrlNight?: string; + fromChainCode: string; + fromChainIconUrl?: string; + toTokenCode: string; + toTokenAmount: string; + toTokenSymbol: string; + toTokenDecimals: number; + toTokenIconUrlDay?: string; + toTokenIconUrlNight?: string; + toChainCode: string; + toChainIconUrl?: string; + gasTokenSymbol: string; + gasOnchain: string; + gasUsd: string | null; + platformFee: string; + platformFeeUsd: string | null; + quoteMode: number; + createTime: number; + executionTime?: number; + failureReasonCode?: string; + source?: string; + swapRate: string; + actualFromTokenAmount: string; } ⋮---- -export interface FixedTermEarnEarlyRedeemInfoV5 { - allowEarlyRedeem: boolean; - earlyRedeemEarning: string; - returnCoin: string; - redemptionLimitDuration: string; +export interface AlphaTradeOrderListResultV5 { + total: number; + pageIndex: number; + orders: AlphaTradeOrderV5[]; } ⋮---- -export interface FixedTermEarnPositionInterestV5 { - coin: string; - apy: string; - expectReturnEarning: string; - price: string; +export interface AlphaBizTokenV5 { + tokenCode: string; + chainCode: string; + chainIconUrl: string; + tokenAddress: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + createTime: number; + createTimeOnchain: number; + riskFlag: number; + minOrderQuantity: number; + maxOrderQuantity: number; + tokenTags: number[]; + payTokenCodes: string[]; } ⋮---- -export interface FixedTermEarnPositionV5 { - positionId: string; - productId: string; - category: string; - coin: string; - amount: string; - effectiveAmount: string; - duration: string; - status: string; - settlementTime: string; - createdAt: string; - orderId: string; - earlyRedeemInfo: FixedTermEarnEarlyRedeemInfoV5 | null; - allowAutoReinvest: boolean; - autoReinvest: string; - interestCoinApyList: FixedTermEarnPositionInterestV5[]; +export interface AlphaBizTokenPriceV5 { + chainCode: string; + tokenAddress: string; + price: string; + change24h: string; + vol24h: string; + marketCap: string; + liquidity: string; + holders: string; } ⋮---- -export interface FixedTermEarnPositionListV5 { - list: FixedTermEarnPositionV5[]; +export interface AlphaBizTokenPriceListResultV5 { + tokenPriceInfoList: AlphaBizTokenPriceV5[]; } ⋮---- -export interface FixedTermEarnOrderYieldInfoV5 { - coin: string; - amount: string; - status: string; - createdAt: string; - apy: string; -} -⋮---- -export interface FixedTermEarnOrderV5 { - orderId: string; - orderLinkId: string; - orderType: string; - status: string; - productId: string; - category: string; - coin: string; - amount: string; - duration: string; - accountType: string; - settlementTime: string; - createdAt: string; - yieldInfoList: FixedTermEarnOrderYieldInfoV5[]; +export interface AlphaBizTokenDetailsV5 { + tokenCode: string; + chainCode: string; + chainIconUrl: string; + tokenAddress: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + minOrderQuantity: string; + maxOrderQuantity: string; + maxPositionQuantity: string; + tokenDesc: string; + xUrl: string; + officialUrl: string; + whitePaperUrl: string; + tokenTag: number; + riskFlag: number; + createTimeOnchain: number; + status: number; + tokenTags: number[]; + showMessage: number; + content?: string; + linkName?: string; + linkAddress?: string; } ⋮---- -export interface FixedTermEarnOrderListV5 { - list: FixedTermEarnOrderV5[]; - nextPageCursor: string; -} - -================ -File: src/types/response/v5-earn-liquidity-mining.ts -================ -export interface LiquidityMiningApyBreakdownV5 { - coin: string; - apy: string; +export interface AlphaAssetV5 { + chainCode: string; + chainIconUrl: string; + tokenAddress: string; + tokenCode: string; + tokenSymbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + tokenAmount: string; + tokenAmountUsd: string; + tradeFlag: number; + pnl: string | null; + pnlRatio: string | null; + costPrice: string | null; + lastPrice: string; + costTotalValue: string | null; + assetStatus: number; + announcementUrl?: string; + estimatedOfflineTime?: number; + delistingTime?: number; } ⋮---- -export interface LiquidityMiningProductV5 { - productId: string; - baseCoin: string; - quoteCoin: string; - status: 'Available' | 'NotAvailable' | string; - maxLeverage: number; - minInvestmentQuote: string; - minInvestmentBase: string; - maxInvestmentQuote: string; - maxInvestmentBase: string; - minWithdrawalAmount: string; - minReinvestAmount: string; - baseCoinPrecision: number; - quoteCoinPrecision: number; - yieldCoins: string[]; - apyE8: string; - apy7dE8: string; - poolLiquidityValue: string; - dailyYield: string; - slippageRateE8List: string[]; - apyBreakdown: LiquidityMiningApyBreakdownV5[]; - apy7dBreakdown: LiquidityMiningApyBreakdownV5[]; - slippage_levels?: string[]; +export interface AlphaAssetListResultV5 { + totalAssetUsd: string; + assetList: AlphaAssetV5[]; } ⋮---- -export interface LiquidityMiningProductResultV5 { - products: LiquidityMiningProductV5[]; +export interface AlphaAssetDetailResultV5 { + assetList: AlphaAssetV5[]; } ================ -File: src/types/response/v5-earn-pwm.ts +File: src/types/response/v5-broker.ts ================ -export interface PwmCoinAmountV5 { +interface EarningDetailV5 { + userId: string; + bizType: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; + symbol: string; coin: string; - amount: string; + earning: string; + markupEarning: string; + baseFeeEarning: string; + orderId: string; + execTime: string; } ⋮---- -export interface PwmMultiCoinsEarningPositionItemV5 { - category: string; - productId: string; +interface TotalEarningCategoryV5 { coin: string; - currentAmount: string; - accumulateYield: string; - apr: string; - positionId: string; - status?: string; + earning: string; } ⋮---- -export interface PwmMultiCoinsEarningPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - items: PwmMultiCoinsEarningPositionItemV5[]; +export interface ExchangeBrokerEarningResultV5 { + totalEarningCat: { + spot: TotalEarningCategoryV5[]; + derivatives: TotalEarningCategoryV5[]; + options: TotalEarningCategoryV5[]; + convert: TotalEarningCategoryV5[]; + total: TotalEarningCategoryV5[]; + }; + details: EarningDetailV5[]; + nextPageCursor: string; } ⋮---- -export interface PwmFixedYieldPositionItemV5 { - category: string; - productId: string; - coin: string; - currentAmount: string; - accumulateYield: string; - apr: string; - duration: number; - maturityTime: string; - autoReinvest: boolean; - positionId: string; - status?: string; +export interface ExchangeBrokerAccountInfoV5 { + subAcctQty: string; + maxSubAcctQty: string; + baseFeeRebateRate: { + spot: string; + derivatives: string; + }; + markupFeeRebateRate: { + spot: string; + derivatives: string; + convert: string; + }; + ts: string; } ⋮---- -export interface PwmFixedYieldPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - items: PwmFixedYieldPositionItemV5[]; +export interface ExchangeBrokerSubAccountDepositRecordV5 { + id: string; + subMemberId: string; + coin: string; + chain: string; + amount: string; + txID: string; + status: number; + toAddress: string; + tag: string; + depositFee: string; + successAt: string; + confirmations: string; + txIndex: string; + blockHash: string; + batchReleaseLimit: string; + depositType: string; } ⋮---- -export interface PwmEquityFundPositionItemV5 { - category: string; - productId: string; - fundName: string; +export interface BrokerVoucherSpecV5 { + id: string; coin: string; - tags: string[]; - nav: string; - userShares: string; - shareValue: string; - holdingValue: string; - accumulateYield: string; - apr30d: string; - aprTotal: string; - sharpRatio: string; - maxDrawdown: string; - createdTime: string; - runningDays: number; - positionId?: string; - status?: string; + amountUnit: 'AWARD_AMOUNT_UNIT_USD' | 'AWARD_AMOUNT_UNIT_COIN'; + productLine: string; + subProductLine: string; + totalAmount: { + [key: string]: string; + }; + usedAmount: string; } ⋮---- -export interface PwmEquityFundsPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - items: PwmEquityFundPositionItemV5[]; +export interface BrokerIssuedVoucherV5 { + accountId: string; + awardId: string; + specCode: string; + amount: string; + isClaimed: boolean; + startAt: string; + endAt: string; + effectiveAt: string; + ineffectiveAt: string; + usedAmount: string; } ⋮---- -export interface PwmOnchainEarnPositionItemV5 { - category: string; - productId: string; - coin: string; - stakeAmount: string; - apr: string; - positionId: string; - status?: string; +export interface BrokerRateLimitSetResultItemV5 { + uids: string; + bizType: string; + rate: number; + success: boolean; + msg: string; } ⋮---- -export interface PwmOnchainEarnPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - items: PwmOnchainEarnPositionItemV5[]; +export interface BrokerRateLimitCapItemV5 { + bizType: string; + totalRate: string; + ebCap: string; + uidCap: string; } ⋮---- -export interface PwmInvestmentPlanPositionsV5 { - multiCoinsEarning?: PwmMultiCoinsEarningPositionsV5; - fixedYield?: PwmFixedYieldPositionsV5; - equityFunds?: PwmEquityFundsPositionsV5; - onchainEarn?: PwmOnchainEarnPositionsV5; - fundingAccount?: PwmCoinAmountV5[]; +export interface BrokerRateLimitAllItemV5 { + uids: string; + bizType: string; + rate: number; } -⋮---- -/** GET /v5/earn/pwm/investment-plan/list */ -export interface PwmInvestmentPlanSummaryV5 { - planId: string; - planName: string; - planType: string; + +================ +File: src/types/response/v5-card.ts +================ +export interface CardAssetRecordV5 { + pan4: string; + pan6: string; + tradeStatus: string; + side: string; + basicAmount: string; + basicCurrency: string; + transactionAmount: string; + transactionCurrency: string; + txnCreate: number; + merchCountry: string; + merchCity: string; + merchName: string; + txnId: string; + declinedReason: string; + totalFees: string; + uid: number; + transactionCurrencyAmount: string; + fxPad: string; + interchangeFee: string; + billAmount: string; + paidAmount: string; + paidCurrency: string; + bonusAmount: string; + foreignTransactionFee: string; + totalTax: string; + paidFiat: string; + withdrawalFee: string; status: string; - currentAssetUsd?: string; - accumulateYieldUsd?: string; - weightedAvgApr?: string; - createdTime?: string; + orderNo: string; + mccCode: string; + merchCategoryDesc: string; } ⋮---- -export interface PwmInvestmentPlanListResultV5 { - list: PwmInvestmentPlanSummaryV5[]; +export interface CardAssetRecordsResultV5 { + pageSize: number; + pageNo: number; + totalCount: number; + data: CardAssetRecordV5[]; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/detail */ -export interface PwmInvestmentPlanDetailV5 { - planId: string; - planName: string; - planType: string; +export interface CardPointBalanceV5 { + accountId: string; + availablePoint: string | number; + pendingPoint: string | number; status: string; - currentAssetUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - currentAssets: PwmCoinAmountV5[]; - positions: PwmInvestmentPlanPositionsV5; - createdTime: string; + updateTime: string | number; + settlementPeriod: number; } ⋮---- -export interface PwmEquityFundIntroductionV5 { - description: string; - historicalYieldRateMax: string; - historicalYieldRateMin: string; - sharpRatio: string; - maxDrawback: string; - lockupPeriod: string; +export interface CardPointRecordV5 { + outOrderId: string; + point: number; + side: string; + type: string; + subType: string; + createTime: number; + updateTime: number; + bizId: string; + bizTxnId: string; + transactionDate: string; + transactionId: string; + transactionAmount: string; + basicCurrency: string; + merchCategoryDesc: string; + merchName: string; + merchCountry: string; + merchCity: string; + pan4: string; + payFiatAmount: string; + transactionCurrencyAmount: string; } ⋮---- -export interface PwmPendingMultiCoinsEarningItemV5 { - category: string; - productId: string; - coin: string; - configuredAmount: string; - apr: string; +export interface CardPointRecordsResultV5 { + pageSize: number; + pageNo: number; + totalCount: number; + data: CardPointRecordV5[]; } ⋮---- -export interface PwmPendingFixedYieldItemV5 { - category: string; - productId: string; - coin: string; - configuredAmount: string; - apr: string; - duration: number; +export interface CardPointTierInfoV5 { + usedLimit: string; + limit: string; + unit: string; + tier: string; + autoCashback: boolean; } ⋮---- -export interface PwmPendingEquityFundItemV5 { - category: string; - productId: string; - fundName: string; - coin: string; - configuredAmount: string; - tags: string[]; - introduction: PwmEquityFundIntroductionV5; +export interface CardMallItemV5 { + itemId: string; + itemName: string; + priority: number; + onTime: string; + offTime: string; + price: string; + discountPrice: string; + totalNum: number; + redeemNum: number; + picPath: string; + currency: string; + currencyType: number; + itemType: number; + itemBizType: number; } ⋮---- -export interface PwmPendingOnchainEarnItemV5 { - category: string; - productId: string; - coin: string; - configuredAmount: string; - apr: string; +export interface CardMallItemListResultV5 { + pageNo: number; + pageSize: number; + totalCount: number; + data: CardMallItemV5[]; } ⋮---- -export interface PwmPendingInvestmentPlanProductsV5 { - multiCoinsEarning?: { - configuredAmountUsd: string; - items: PwmPendingMultiCoinsEarningItemV5[]; - }; - fixedYield?: { - configuredAmountUsd: string; - items: PwmPendingFixedYieldItemV5[]; - }; - equityFunds?: { - configuredAmountUsd: string; - items: PwmPendingEquityFundItemV5[]; - }; - onchainEarn?: { - configuredAmountUsd: string; - items: PwmPendingOnchainEarnItemV5[]; - }; +export interface CardPointCashbackDetailV5 { + points: string; + amt: string; + ccy: string; + ccyType: string; + createTime: string; + bizTxnId: string; + sourceId: number; + sourceCode: string; + orderStatus: number; + orderSubStatus: number; + orderShowStatus: string; + failedBizCode: string; } -⋮---- -/** GET /v5/earn/pwm/investment-plan/new-plan */ -export interface PwmPendingInvestmentPlanDetailV5 { - planId: string; - planName: string; - planType: string; - status: string; - source: string; - totalConfiguredAmountUsd: string; - products: PwmPendingInvestmentPlanProductsV5; - createdTime: string; + +================ +File: src/types/response/v5-earn-advance-discount.ts +================ +export interface AdvanceEarnDiscountBuyOfferV5 { + productId: string; + currentPrice: string; + purchasePrice: string; + knockoutPrice: string; + knockoutCouponE8: string; + maxInvestmentAmount: string; + instUid: string; + expiredAt: string; + category: string; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/claim */ -export interface ClaimPwmWithdrawableFundsResultV5 { - planId: string; - toAccountType: number; - status: string; - createdTime: string; +/** GET /v5/earn/advance/product-extra-info?category=DiscountBuy */ +export interface AdvanceEarnProductExtraInfoDiscountBuyV5 { + offers: AdvanceEarnDiscountBuyOfferV5[]; } ⋮---- -export interface PwmAssetTrendDataPointV5 { - date: string; - assetValueUsd: string; +export interface AdvanceEarnDualAssetQuoteLevelV5 { + selectPrice: string; + apyE8: string; + maxInvestmentAmount: string; + expiredAt: string; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/asset-trend */ -export interface PwmInvestmentPlanAssetTrendResultV5 { - planId: string; - dataPoints: PwmAssetTrendDataPointV5[]; +export interface AdvanceEarnDualAssetQuoteProductV5 { + productId: string; + currentPrice: string; + buyLowPrice: AdvanceEarnDualAssetQuoteLevelV5[]; + sellHighPrice: AdvanceEarnDualAssetQuoteLevelV5[]; } ⋮---- -export interface PwmFundNavDataPointV5 { - date: string; - nav: string; +/** GET /v5/earn/advance/product-extra-info?category=DualAssets&productId= */ +export interface AdvanceEarnProductExtraInfoDualAssetsV5 { + category: 'DualAssets'; + list: AdvanceEarnDualAssetQuoteProductV5[]; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/fund-nav */ -export interface PwmFundHistoricalNavResultV5 { - fundId: string; - fundName: string; - coin: string; - currentNav: string; - dataPoints: PwmFundNavDataPointV5[]; -} +export type AdvanceEarnProductExtraInfoV5 = + | AdvanceEarnProductExtraInfoDiscountBuyV5 + | AdvanceEarnProductExtraInfoDualAssetsV5; ⋮---- -/** POST /v5/earn/pwm/investment-plan/subscribe */ -export interface SubscribePwmInvestmentPlanResultV5 { - planId: string; - status: string; +export interface AdvanceEarnPlaceOrderResultV5 { + orderId: string; orderLinkId: string; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/invest-more */ -export interface InvestMorePwmInvestmentPlanResultV5 { - planId: string; - category: string; +export interface AdvanceEarnDiscountBuyPositionV5 { + positionId: string; productId: string; + category: string; coin: string; + underlyingAsset: string; amount: string; + purchasePrice: string; + knockoutPrice: string; + knockoutCouponE8: string; status: string; - orderLinkId: string; orderId: string; + duration: string; + settlementTime: string; + accountType: string; + toAccountType: string; + settleType: string; + expectReceiveAt: string; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/redeem */ -export interface RedeemPwmInvestmentPlanResultV5 { +export interface AdvanceEarnDualAssetsPositionV5 { + positionId: string; + productId: string; + category: string; + baseCoin: string; + quoteCoin: string; + investCoin: string; + amount: string; + apyE8: string; + direction: 'BuyLow' | 'SellHigh' | string; + targetPrice: string; + settlementTime: string; + status: string; orderId: string; - planId: string; + duration: string; + expectReturnCoin: string; + expectReturnAmount: string; + accountType: string; + toAccountType: string; + yieldStartAt: string | number; + yieldEndAt: string | number; +} +⋮---- +export interface AdvanceEarnPositionListV5 { category: string; + list: (AdvanceEarnDiscountBuyPositionV5 | AdvanceEarnDualAssetsPositionV5)[]; + nextPageCursor: string; +} +⋮---- +export interface AdvanceEarnDiscountBuyOrderV5 { + orderId: string; + orderLinkId: string; productId: string; - shares?: string; - amount?: string; - estimatedAmount?: string; + category: string; + orderType: string; + amount: string; coin: string; + underlyingAsset: string; status: string; - orderLinkId: string; + createdTime: string; + purchasePrice: string; + knockoutPrice: string; + knockoutCouponE8: string; + duration: string; + settlementTime: string; + accountType: string; + toAccountType: string; + settleType: string; + settlementPrice: string; + settlementCoin: string; + settlementAmount: string; + isVip: boolean; + refundStatus: string; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/order */ -export interface PwmInvestmentPlanOrderV5 { +export interface AdvanceEarnDualAssetsOrderV5 { orderId: string; - planId: string; - type: string; - accountType: string; - coin: string; - amount: string; - category: string; + orderLinkId: string; productId: string; + category: string; + orderType: string; + amount: string; + coin: string; + baseCoin: string; + quoteCoin: string; status: string; - orderTime: string; + createdTime: string; + updatedTime: string; + direction: 'BuyLow' | 'SellHigh' | string; + targetPrice: string; + settlementTime: string | number; + estimateApyE8: string | number; + duration: string; + accountType: string; + toAccountType: string; + selectApyE8: string | number; + isVip: boolean; + settlementCoin: string; + settlementAmount: string; + orderMode: string; + settlementPrice: string; + refundStatus: string; + trialBonusAmount: string; + trialBonusPnl: string; } ⋮---- -export interface PwmInvestmentPlanOrdersResultV5 { - list: PwmInvestmentPlanOrderV5[]; +export interface AdvanceEarnOrderListV5 { + category: string; + list: (AdvanceEarnDiscountBuyOrderV5 | AdvanceEarnDualAssetsOrderV5)[]; nextPageCursor: string; } + +================ +File: src/types/response/v5-earn-fixed-term.ts +================ +export interface FixedTermEarnTieredApyV5 { + min: string; + max: string; + apy: string; +} ⋮---- -/** GET /v5/earn/pwm/customize-plan/product */ -export interface PwmSubscribableProductCardV5 { - category: string; - productId?: string; - fundName?: string; +export interface FixedTermEarnInterestCoinApyV5 { coin: string; - apr?: string; - aprRangeLow?: string; - aprRangeHigh?: string; - tags?: string[]; - introduction?: string; - aum?: string; - minInvestmentAmount?: string; - maxInvestmentAmount?: string; - duration?: number; - maxDrawdown?: string; - sharpRatio?: string; - estAPR?: string; + apy: string; + expectUnitEarning: string; + currentPrice: string; } ⋮---- -export interface PwmSubscribableProductGroupV5 { - type: string; - cards: PwmSubscribableProductCardV5[]; +export interface FixedTermEarnProductV5 { + productId: string; + category: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium' | string; + coin: string; + duration: string; + status: 'Available' | 'SoldOut' | 'NotStarted' | string; + tieredApyList: FixedTermEarnTieredApyV5[]; + minStakeAmount: string; + maxStakeAmount: string; + precision: number; + subscribeStartAt: string; + subscribeEndAt: string; + allowEarlyRedemption: boolean; + earlyRedemptionApy: string; + redemptionLimitDuration: string; + allowAutoReinvest: boolean; + interestCoinApyList: FixedTermEarnInterestCoinApyV5[]; + isVip: boolean; + creditTime: string; + specialUserGroupRequired: boolean; + specialUserGroupInfo: string; } ⋮---- -export interface PwmSubscribableProductInfoResultV5 { - products: PwmSubscribableProductGroupV5[]; +export interface FixedTermEarnProductListV5 { + list: FixedTermEarnProductV5[]; } ⋮---- -/** POST /v5/earn/pwm/customize-plan/create */ -export interface CreatePwmCustomizeInvestmentPlanResultV5 { - planId: string; - planName: string; - status: string; - orderLinkId?: string; +export interface FixedTermEarnPlaceOrderResultV5 { + orderId: string; + orderLinkId: string; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/all-funds */ -export interface PwmAssetManagerFundV5 { - fundId: string; - fundName: string; - coin: string; - status: string; - totalEquity: string; - totalShares: string; - currentNav: string; - currentAPR?: string; - accountUid: string; - subAccountList: string[]; - profitShareRate: string; - managementFeeRate: string; - uncollectedProfit: string; - collectedProfit: string; - totalLoan: string; - createdTime: string; +export interface RedeemFixedTermEarnResultV5 { + redeemAmount: string; + estEarnings: string; } ⋮---- -export interface PwmAllFundsResultV5 { - list: PwmAssetManagerFundV5[]; - nextPageCursor: string; +export interface FixedTermEarnEarlyRedeemInfoV5 { + allowEarlyRedeem: boolean; + earlyRedeemEarning: string; + returnCoin: string; + redemptionLimitDuration: string; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/settle-profit */ -export interface SettlePwmFundProfitResultV5 { - fundId: string; - status: string; - totalProfitShared: string; - instIncome: string; +export interface FixedTermEarnPositionInterestV5 { coin: string; - createdTime: string; + apy: string; + expectReturnEarning: string; + price: string; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/create-fund */ -export interface CreatePwmFundResultV5 { - fundId: string; - fundName: string; +export interface FixedTermEarnPositionV5 { + positionId: string; + productId: string; + category: string; coin: string; + amount: string; + effectiveAmount: string; + duration: string; status: string; - profitShareRate: string; - managementFeeRate: string; - accountUid: string; - createdTime: string; + settlementTime: string; + createdAt: string; + orderId: string; + earlyRedeemInfo: FixedTermEarnEarlyRedeemInfoV5 | null; + allowAutoReinvest: boolean; + autoReinvest: string; + interestCoinApyList: FixedTermEarnPositionInterestV5[]; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/create-investment-plan */ -export interface CreatePwmAssetManagerInvestmentPlanResultV5 { - planId: string; - planType: string; - accountUid: string; - status: string; - createdTime: string; +export interface FixedTermEarnPositionListV5 { + list: FixedTermEarnPositionV5[]; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/get-investment-plan */ -export interface PwmAssetManagerInvestmentPlanDistributionV5 { - category: string; +export interface FixedTermEarnOrderYieldInfoV5 { coin: string; - productId: string; - currentAmount: string; -} -⋮---- -export interface PwmAssetManagerInvestmentPlanV5 { - planId: string; - planName: string; - planType: string; - subscriptionUid: string; - status: string; - source: string; - currentAssetUsd: string; - accumulateYieldUsd: string; - investmentDistribution: PwmAssetManagerInvestmentPlanDistributionV5[]; - createdTime: string; -} -⋮---- -export interface PwmAssetManagerInvestmentPlansResultV5 { - list: PwmAssetManagerInvestmentPlanV5[]; - nextPageCursor: string; -} -⋮---- -/** POST /v5/earn/pwm/asset-manager/manage-investment-plan */ -export interface ManagePwmAssetManagerInvestmentPlanFundResultV5 { - fundId: string; amount: string; -} -⋮---- -export interface ManagePwmAssetManagerInvestmentPlanResultV5 { - planId: string; status: string; - updatedTime: string; - updateFunds: ManagePwmAssetManagerInvestmentPlanFundResultV5[]; + createdAt: string; + apy: string; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/all-order */ -export interface PwmAssetManagerFundOrderV5 { +export interface FixedTermEarnOrderV5 { orderId: string; - fundId: string; - fundName: string; - accountUid: string; + orderLinkId: string; orderType: string; + status: string; + productId: string; + category: string; coin: string; amount: string; - shares: string; - status: string; - createdTime: string; + duration: string; + accountType: string; + settlementTime: string; + createdAt: string; + yieldInfoList: FixedTermEarnOrderYieldInfoV5[]; } ⋮---- -export interface PwmAllFundOrdersResultV5 { - list: PwmAssetManagerFundOrderV5[]; +export interface FixedTermEarnOrderListV5 { + list: FixedTermEarnOrderV5[]; nextPageCursor: string; } -⋮---- -/** POST /v5/earn/pwm/asset-manager/manage-order */ -export interface ManagePwmFundOrderResultV5 { - orderId: string; - fundId: string; - accountUid: string; - orderStatus: string; - orderType: string; - action: string; + +================ +File: src/types/response/v5-earn-liquidity-mining.ts +================ +export interface LiquidityMiningApyBreakdownV5 { coin: string; - amount: string; - shares: string; - updatedTime: string; -} -⋮---- -/** POST /v5/earn/pwm/asset-manager/create-sub-account */ -export interface CreatePwmFundSubAccountResultV5 { - fundId: string; - subAccountUid: string; - createdTime: string; - status: string; + apy: string; } ⋮---- -/** POST /v5/earn/pwm/fund-transfer */ -export interface PwmFundTransferResultV5 { - transferId: string; - status: string; +export interface LiquidityMiningProductV5 { + productId: string; + baseCoin: string; + quoteCoin: string; + status: 'Available' | 'NotAvailable' | string; + maxLeverage: number; + minInvestmentQuote: string; + minInvestmentBase: string; + maxInvestmentQuote: string; + maxInvestmentBase: string; + minWithdrawalAmount: string; + minReinvestAmount: string; + baseCoinPrecision: number; + quoteCoinPrecision: number; + yieldCoins: string[]; + apyE8: string; + apy7dE8: string; + poolLiquidityValue: string; + dailyYield: string; + slippageRateE8List: string[]; + apyBreakdown: LiquidityMiningApyBreakdownV5[]; + apy7dBreakdown: LiquidityMiningApyBreakdownV5[]; + slippage_levels?: string[]; } ⋮---- -/** GET /v5/earn/pwm/query-fund-transfer-result */ -export interface PwmFundTransferRecordV5 { - transferId: string; - status: string; - fromUserId: number; - toUserId: number; - amount: string; - coin: string; +export interface LiquidityMiningProductResultV5 { + products: LiquidityMiningProductV5[]; } ================ -File: src/types/response/v5-earn-token.ts +File: src/types/response/v5-earn-pwm.ts ================ -/** - * Earn token product (e.g. BYUSDT) — /v5/earn/token/* - */ +export interface PwmCoinAmountV5 { + coin: string; + amount: string; +} ⋮---- -export interface EarnTokenProductV5 { +export interface PwmMultiCoinsEarningPositionItemV5 { + category: string; productId: string; coin: string; - mintFeeRateE8: string; - redeemFeeRateE8: string; - minInvestment: string; - userHolding: string; - leftQuota: string; - canMint: boolean; - savingsBalance: string; - aprE8: string; - bonusAprE8: string; - bonusMaxAmount: string; - baseCoinPrecision: number; - tokenPrecision: number; + currentAmount: string; + accumulateYield: string; + apr: string; + positionId: string; + status?: string; } ⋮---- -export interface PlaceEarnTokenOrderResultV5 { - orderId: string; - orderLinkId: string; +export interface PwmMultiCoinsEarningPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + items: PwmMultiCoinsEarningPositionItemV5[]; } ⋮---- -export interface EarnTokenOrderV5 { - orderId: string; - orderLinkId: string; - orderType: 'Mint' | 'Redeem'; - fromCoin: string; - toCoin: string; - fromAmount: string; - toAmount: string; - serviceFee: string; - status: 'Success' | 'Processing' | 'Fail'; - createdTime: string; +export interface PwmFixedYieldPositionItemV5 { + category: string; + productId: string; + coin: string; + currentAmount: string; + accumulateYield: string; + apr: string; + duration: number; + maturityTime: string; + autoReinvest: boolean; + positionId: string; + status?: string; } ⋮---- -export interface EarnTokenPositionV5 { - totalAmount: string; - totalYield: string; - yesterdayYield: string; - aprE8: number; - bonusAprE8: number; - bonusMaxAmount: string; - hasQuota: boolean; +export interface PwmFixedYieldPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + items: PwmFixedYieldPositionItemV5[]; } ⋮---- -export interface EarnTokenDailyYieldRecordV5 { - yield: string; - bonusYield: string; - status: 'Success' | 'Processing'; +export interface PwmEquityFundPositionItemV5 { + category: string; + productId: string; + fundName: string; + coin: string; + tags: string[]; + nav: string; + userShares: string; + shareValue: string; + holdingValue: string; + accumulateYield: string; + apr30d: string; + aprTotal: string; + sharpRatio: string; + maxDrawdown: string; createdTime: string; + runningDays: number; + positionId?: string; + status?: string; } ⋮---- -export interface EarnTokenHourlyYieldRecordV5 { - effectiveAmount: string; - yield: string; - rewardType: 0 | 1; - aprE8: string; - hourlyDate: string; - createdTime: string; +export interface PwmEquityFundsPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + items: PwmEquityFundPositionItemV5[]; } ⋮---- -export interface EarnTokenHistoryAprPointV5 { - timestamp: string; - aprE8: string; +export interface PwmOnchainEarnPositionItemV5 { + category: string; + productId: string; + coin: string; + stakeAmount: string; + apr: string; + positionId: string; + status?: string; } - -================ -File: src/types/response/v5-rfq.ts -================ -export interface RFQConfigV5 { - deskCode: string; // Own deskCode, unique identification code - maxLegs: number; // Maximum number of legs - maxLP: number; // Maximum number of LPs selected in inquiry form - maxActiveRfq: number; // Maximum number of unfinished inquiry orders allowed - minLimitQtySpotOrder: number; // Spot minimum order quantity multiplier - minLimitQtyContractOrder: number; // Contract minimum order quantity multiplier - minLimitQtyOptionOrder: number; // Option minimum order multiplier - strategyTypes: { - strategyName: string; // Policy name - }[]; - counterparties: { - strategyName: string; // Policy name - }[]; -} -⋮---- -deskCode: string; // Own deskCode, unique identification code -maxLegs: number; // Maximum number of legs -maxLP: number; // Maximum number of LPs selected in inquiry form -maxActiveRfq: number; // Maximum number of unfinished inquiry orders allowed -minLimitQtySpotOrder: number; // Spot minimum order quantity multiplier -minLimitQtyContractOrder: number; // Contract minimum order quantity multiplier -minLimitQtyOptionOrder: number; // Option minimum order multiplier -⋮---- -strategyName: string; // Policy name -⋮---- -strategyName: string; // Policy name ⋮---- -export interface RFQCounterpartyV5 { - traderName: string; // Name of the bidder - deskCode: string; // Unique identification code of the quotation party - type: string | null; // Quoter type. LP is automated market maker, null means normal quote party +export interface PwmOnchainEarnPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + items: PwmOnchainEarnPositionItemV5[]; } ⋮---- -traderName: string; // Name of the bidder -deskCode: string; // Unique identification code of the quotation party -type: string | null; // Quoter type. LP is automated market maker, null means normal quote party -⋮---- -export interface CreateRFQResultV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Inquiry Custom ID - status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form - expiresAt: string; // Expiration time in milliseconds Unix timestamp - deskCode: string; // Inquiry party unique identification code +export interface PwmInvestmentPlanPositionsV5 { + multiCoinsEarning?: PwmMultiCoinsEarningPositionsV5; + fixedYield?: PwmFixedYieldPositionsV5; + equityFunds?: PwmEquityFundsPositionsV5; + onchainEarn?: PwmOnchainEarnPositionsV5; + fundingAccount?: PwmCoinAmountV5[]; } ⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Inquiry Custom ID -status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form -expiresAt: string; // Expiration time in milliseconds Unix timestamp -deskCode: string; // Inquiry party unique identification code +/** GET /v5/earn/pwm/investment-plan/list */ +export interface PwmInvestmentPlanSummaryV5 { + planId: string; + planName: string; + planType: string; + status: string; + currentAssetUsd?: string; + accumulateYieldUsd?: string; + weightedAvgApr?: string; + createdTime?: string; +} ⋮---- -export interface CancelRFQResultV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Inquiry Custom ID +export interface PwmInvestmentPlanListResultV5 { + list: PwmInvestmentPlanSummaryV5[]; } ⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Inquiry Custom ID +/** GET /v5/earn/pwm/investment-plan/detail */ +export interface PwmInvestmentPlanDetailV5 { + planId: string; + planName: string; + planType: string; + status: string; + currentAssetUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + currentAssets: PwmCoinAmountV5[]; + positions: PwmInvestmentPlanPositionsV5; + createdTime: string; +} ⋮---- -export interface CancelRFQItemV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Inquiry Custom ID - code: number; // Cancel success or failure, 0 means success - msg: string; // Cancellation failure reason +export interface PwmEquityFundIntroductionV5 { + description: string; + historicalYieldRateMax: string; + historicalYieldRateMin: string; + sharpRatio: string; + maxDrawback: string; + lockupPeriod: string; } ⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Inquiry Custom ID -code: number; // Cancel success or failure, 0 means success -msg: string; // Cancellation failure reason +export interface PwmPendingMultiCoinsEarningItemV5 { + category: string; + productId: string; + coin: string; + configuredAmount: string; + apr: string; +} ⋮---- -export interface CancelAllRFQResultV5 { - data: CancelRFQItemV5[]; // Array of cancellation results +export interface PwmPendingFixedYieldItemV5 { + category: string; + productId: string; + coin: string; + configuredAmount: string; + apr: string; + duration: number; } ⋮---- -data: CancelRFQItemV5[]; // Array of cancellation results +export interface PwmPendingEquityFundItemV5 { + category: string; + productId: string; + fundName: string; + coin: string; + configuredAmount: string; + tags: string[]; + introduction: PwmEquityFundIntroductionV5; +} ⋮---- -export interface CreateRFQQuoteResultV5 { - rfqId: string; // Inquiry ID - quoteId: string; // Quotation ID - quoteLinkId: string; // Quotation Custom ID - expiresAt: string; // Expiration time in milliseconds Unix timestamp - deskCode: string; // Quoter's unique identification code - status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation +export interface PwmPendingOnchainEarnItemV5 { + category: string; + productId: string; + coin: string; + configuredAmount: string; + apr: string; } ⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Quotation ID -quoteLinkId: string; // Quotation Custom ID -expiresAt: string; // Expiration time in milliseconds Unix timestamp -deskCode: string; // Quoter's unique identification code -status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation +export interface PwmPendingInvestmentPlanProductsV5 { + multiCoinsEarning?: { + configuredAmountUsd: string; + items: PwmPendingMultiCoinsEarningItemV5[]; + }; + fixedYield?: { + configuredAmountUsd: string; + items: PwmPendingFixedYieldItemV5[]; + }; + equityFunds?: { + configuredAmountUsd: string; + items: PwmPendingEquityFundItemV5[]; + }; + onchainEarn?: { + configuredAmountUsd: string; + items: PwmPendingOnchainEarnItemV5[]; + }; +} ⋮---- -export interface ExecuteRFQQuoteResultV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Inquiry Custom ID - quoteId: string; // Quotation ID - status: 'Processing' | 'Rejected'; // Order status - rejectParty: string; // Empty means passed, "Taker", "Maker", "Bybit" when rejected +/** GET /v5/earn/pwm/investment-plan/new-plan */ +export interface PwmPendingInvestmentPlanDetailV5 { + planId: string; + planName: string; + planType: string; + status: string; + source: string; + totalConfiguredAmountUsd: string; + products: PwmPendingInvestmentPlanProductsV5; + createdTime: string; } ⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Inquiry Custom ID -quoteId: string; // Quotation ID -status: 'Processing' | 'Rejected'; // Order status -rejectParty: string; // Empty means passed, "Taker", "Maker", "Bybit" when rejected +/** POST /v5/earn/pwm/investment-plan/claim */ +export interface ClaimPwmWithdrawableFundsResultV5 { + planId: string; + toAccountType: number; + status: string; + createdTime: string; +} ⋮---- -export interface CancelRFQQuoteResultV5 { - rfqId: string; // Inquiry ID - quoteId: string; // Quotation ID - quoteLinkId: string; // Quotation Custom ID +export interface PwmAssetTrendDataPointV5 { + date: string; + assetValueUsd: string; } ⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Quotation ID -quoteLinkId: string; // Quotation Custom ID +/** GET /v5/earn/pwm/investment-plan/asset-trend */ +export interface PwmInvestmentPlanAssetTrendResultV5 { + planId: string; + dataPoints: PwmAssetTrendDataPointV5[]; +} ⋮---- -export interface CancelRFQQuoteItemV5 { - rfqId: string; // Inquiry ID - quoteId: string; // Quotation ID - quoteLinkId: string; // Quotation Custom ID - code: number; // Cancel success or failure, 0 means success - msg: string; // Cancellation failure reason +export interface PwmFundNavDataPointV5 { + date: string; + nav: string; } ⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Quotation ID -quoteLinkId: string; // Quotation Custom ID -code: number; // Cancel success or failure, 0 means success -msg: string; // Cancellation failure reason +/** GET /v5/earn/pwm/investment-plan/fund-nav */ +export interface PwmFundHistoricalNavResultV5 { + fundId: string; + fundName: string; + coin: string; + currentNav: string; + dataPoints: PwmFundNavDataPointV5[]; +} ⋮---- -export interface RFQLegV5 { - category: 'linear' | 'option' | 'spot'; // Product category - symbol: string; // The unique instrument ID - side: 'buy' | 'sell'; // Inquiry direction - qty: string; // Order quantity of the instrument - isLeverage?: boolean; // For spot lending +/** POST /v5/earn/pwm/investment-plan/subscribe */ +export interface SubscribePwmInvestmentPlanResultV5 { + planId: string; + status: string; + orderLinkId: string; } ⋮---- -category: 'linear' | 'option' | 'spot'; // Product category -symbol: string; // The unique instrument ID -side: 'buy' | 'sell'; // Inquiry direction -qty: string; // Order quantity of the instrument -isLeverage?: boolean; // For spot lending +/** POST /v5/earn/pwm/investment-plan/invest-more */ +export interface InvestMorePwmInvestmentPlanResultV5 { + planId: string; + category: string; + productId: string; + coin: string; + amount: string; + status: string; + orderLinkId: string; + orderId: string; +} ⋮---- -export interface RFQItemV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Custom ID for inquiry form - counterparties: string[]; // List of bidders - expiresAt: string; // Expiration time in milliseconds Unix timestamp - strategyType: string; // Inquiry label - status: - | 'Active' - | 'Canceled' - | 'PendingFill' - | 'Filled' - | 'Expired' - | 'Failed'; // Status - acceptOtherQuoteStatus?: string; // Whether to accept non-LP quotes. "false": do not accept, "true": accept - deskCode: string; // Unique identification code of the inquiry party - createdAt: number; // Time when the trade is created in epoch - updatedAt: number; // Time when the trade is updated in epoch - legs: RFQLegV5[]; // Combination transaction +/** POST /v5/earn/pwm/investment-plan/redeem */ +export interface RedeemPwmInvestmentPlanResultV5 { + orderId: string; + planId: string; + category: string; + productId: string; + shares?: string; + amount?: string; + estimatedAmount?: string; + coin: string; + status: string; + orderLinkId: string; } ⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Custom ID for inquiry form -counterparties: string[]; // List of bidders -expiresAt: string; // Expiration time in milliseconds Unix timestamp -strategyType: string; // Inquiry label -⋮---- -| 'Failed'; // Status -acceptOtherQuoteStatus?: string; // Whether to accept non-LP quotes. "false": do not accept, "true": accept -deskCode: string; // Unique identification code of the inquiry party -createdAt: number; // Time when the trade is created in epoch -updatedAt: number; // Time when the trade is updated in epoch -legs: RFQLegV5[]; // Combination transaction +/** GET /v5/earn/pwm/investment-plan/order */ +export interface PwmInvestmentPlanOrderV5 { + orderId: string; + planId: string; + type: string; + accountType: string; + coin: string; + amount: string; + category: string; + productId: string; + status: string; + orderTime: string; +} ⋮---- -export interface GetRFQRealtimeResultV5 { - list: RFQItemV5[]; // Array of RFQ items +export interface PwmInvestmentPlanOrdersResultV5 { + list: PwmInvestmentPlanOrderV5[]; + nextPageCursor: string; } ⋮---- -list: RFQItemV5[]; // Array of RFQ items +/** GET /v5/earn/pwm/customize-plan/product */ +export interface PwmSubscribableProductCardV5 { + category: string; + productId?: string; + fundName?: string; + coin: string; + apr?: string; + aprRangeLow?: string; + aprRangeHigh?: string; + tags?: string[]; + introduction?: string; + aum?: string; + minInvestmentAmount?: string; + maxInvestmentAmount?: string; + duration?: number; + maxDrawdown?: string; + sharpRatio?: string; + estAPR?: string; +} ⋮---- -export interface RFQHistory { - cursor: string; // Page turning mark - list: RFQItemV5[]; // Array of RFQ items +export interface PwmSubscribableProductGroupV5 { + type: string; + cards: PwmSubscribableProductCardV5[]; } ⋮---- -cursor: string; // Page turning mark -list: RFQItemV5[]; // Array of RFQ items +export interface PwmSubscribableProductInfoResultV5 { + products: PwmSubscribableProductGroupV5[]; +} ⋮---- -export interface QuoteLegV5 { - category: 'spot' | 'linear' | 'option'; // Product type - symbol: string; // The unique instrument ID or name of trading contract - price: string; // Order price or quote price - qty?: string; // Order quantity - isLeverage?: boolean; // For spot lending +/** POST /v5/earn/pwm/customize-plan/create */ +export interface CreatePwmCustomizeInvestmentPlanResultV5 { + planId: string; + planName: string; + status: string; + orderLinkId?: string; } ⋮---- -category: 'spot' | 'linear' | 'option'; // Product type -symbol: string; // The unique instrument ID or name of trading contract -price: string; // Order price or quote price -qty?: string; // Order quantity -isLeverage?: boolean; // For spot lending +/** GET /v5/earn/pwm/asset-manager/all-funds */ +export interface PwmAssetManagerFundV5 { + fundId: string; + fundName: string; + coin: string; + status: string; + totalEquity: string; + totalShares: string; + currentNav: string; + currentAPR?: string; + accountUid: string; + subAccountList: string[]; + profitShareRate: string; + managementFeeRate: string; + uncollectedProfit: string; + collectedProfit: string; + totalLoan: string; + createdTime: string; +} ⋮---- -export interface RFQQuoteItemV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Custom ID for inquiry form - quoteId: string; // Quotation ID - quoteLinkId: string; // Quotation custom ID - expiresAt: string; // Expiration time in milliseconds Unix timestamp - deskCode: string; // Unique identification code of quotation party - status: - | 'Active' - | 'Canceled' - | 'PendingFill' - | 'Filled' - | 'Expired' - | 'Failed'; // Status - execQuoteSide: string; // Execute quote direction, buy or sell - createdAt: number; // Time when the trade is created in epoch - updatedAt: number; // Time when the trade is updated in epoch - quoteBuyList: QuoteLegV5[]; // Quotation buy direction - quoteSellList: QuoteLegV5[]; // Quotation sell direction +export interface PwmAllFundsResultV5 { + list: PwmAssetManagerFundV5[]; + nextPageCursor: string; } ⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Custom ID for inquiry form -quoteId: string; // Quotation ID -quoteLinkId: string; // Quotation custom ID -expiresAt: string; // Expiration time in milliseconds Unix timestamp -deskCode: string; // Unique identification code of quotation party +/** POST /v5/earn/pwm/asset-manager/settle-profit */ +export interface SettlePwmFundProfitResultV5 { + fundId: string; + status: string; + totalProfitShared: string; + instIncome: string; + coin: string; + createdTime: string; +} ⋮---- -| 'Failed'; // Status -execQuoteSide: string; // Execute quote direction, buy or sell -createdAt: number; // Time when the trade is created in epoch -updatedAt: number; // Time when the trade is updated in epoch -quoteBuyList: QuoteLegV5[]; // Quotation buy direction -quoteSellList: QuoteLegV5[]; // Quotation sell direction +/** POST /v5/earn/pwm/asset-manager/create-fund */ +export interface CreatePwmFundResultV5 { + fundId: string; + fundName: string; + coin: string; + status: string; + profitShareRate: string; + managementFeeRate: string; + accountUid: string; + createdTime: string; +} ⋮---- -export interface RFQTradeLegV5 { - category: 'linear' | 'option' | 'spot'; // Product category - orderId: string; // Bybit order ID - symbol: string; // The unique instrument ID - side: 'buy' | 'sell'; // Direction - price: string; // Execution price - qty: string; // Number of executions - isLeverage?: boolean; // For spot lending - markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot - execFee: string; // Fee for taker or maker in base currency - execId: string; // Unique exec(trade) ID from exchange - resultCode: number; // Status code, 0 means success - resultMessage: string; // Error message about resultCode - rejectParty: string; // Empty if Filled, "Taker"/"Maker"/"bybit" if Rejected +/** POST /v5/earn/pwm/asset-manager/create-investment-plan */ +export interface CreatePwmAssetManagerInvestmentPlanResultV5 { + planId: string; + planType: string; + accountUid: string; + status: string; + createdTime: string; } ⋮---- -category: 'linear' | 'option' | 'spot'; // Product category -orderId: string; // Bybit order ID -symbol: string; // The unique instrument ID -side: 'buy' | 'sell'; // Direction -price: string; // Execution price -qty: string; // Number of executions -isLeverage?: boolean; // For spot lending -markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot -execFee: string; // Fee for taker or maker in base currency -execId: string; // Unique exec(trade) ID from exchange -resultCode: number; // Status code, 0 means success -resultMessage: string; // Error message about resultCode -rejectParty: string; // Empty if Filled, "Taker"/"Maker"/"bybit" if Rejected +/** GET /v5/earn/pwm/asset-manager/get-investment-plan */ +export interface PwmAssetManagerInvestmentPlanDistributionV5 { + category: string; + coin: string; + productId: string; + currentAmount: string; +} ⋮---- -export interface RFQTradeV5 { - rfqId: string; // Inquiry ID - quoteId: string; // Completed inquiry form and executed quotation ID - quoteSide: 'buy' | 'sell'; // Executed quotation direction - strategyType: string; // Inquiry label - status: 'Filled' | 'Rejected'; // Status - rfqDeskCode: string; // Unique identification code of inquiry party - quoteDestCode: string; // Unique identification code of quotation party - createdAt: number; // Time when trade is created in epoch - updatedAt: number; // Time when trade is updated in epoch - legs: RFQTradeLegV5[]; // Combination transaction +export interface PwmAssetManagerInvestmentPlanV5 { + planId: string; + planName: string; + planType: string; + subscriptionUid: string; + status: string; + source: string; + currentAssetUsd: string; + accumulateYieldUsd: string; + investmentDistribution: PwmAssetManagerInvestmentPlanDistributionV5[]; + createdTime: string; } ⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Completed inquiry form and executed quotation ID -quoteSide: 'buy' | 'sell'; // Executed quotation direction -strategyType: string; // Inquiry label -status: 'Filled' | 'Rejected'; // Status -rfqDeskCode: string; // Unique identification code of inquiry party -quoteDestCode: string; // Unique identification code of quotation party -createdAt: number; // Time when trade is created in epoch -updatedAt: number; // Time when trade is updated in epoch -legs: RFQTradeLegV5[]; // Combination transaction +export interface PwmAssetManagerInvestmentPlansResultV5 { + list: PwmAssetManagerInvestmentPlanV5[]; + nextPageCursor: string; +} ⋮---- -export interface RFQPublicTradeLegV5 { - category: 'linear' | 'option' | 'spot'; // Product category - symbol: string; // The unique instrument ID - side: 'buy' | 'sell'; // Inquiry direction - price: string; // Execution price - qty: string; // Number of executions - markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot +/** POST /v5/earn/pwm/asset-manager/manage-investment-plan */ +export interface ManagePwmAssetManagerInvestmentPlanFundResultV5 { + fundId: string; + amount: string; } ⋮---- -category: 'linear' | 'option' | 'spot'; // Product category -symbol: string; // The unique instrument ID -side: 'buy' | 'sell'; // Inquiry direction -price: string; // Execution price -qty: string; // Number of executions -markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot -⋮---- -export interface RFQPublicTradeV5 { - rfqId: string; // Inquiry ID - strategyType: string; // Inquiry label - createdAt: number; // Time when trade is created in epoch - updatedAt: number; // Time when trade is updated in epoch - legs: RFQPublicTradeLegV5[]; // Combination transaction +export interface ManagePwmAssetManagerInvestmentPlanResultV5 { + planId: string; + status: string; + updatedTime: string; + updateFunds: ManagePwmAssetManagerInvestmentPlanFundResultV5[]; } ⋮---- -rfqId: string; // Inquiry ID -strategyType: string; // Inquiry label -createdAt: number; // Time when trade is created in epoch -updatedAt: number; // Time when trade is updated in epoch -legs: RFQPublicTradeLegV5[]; // Combination transaction -⋮---- -export interface AcceptNonLPQuoteResultV5 { - rfqId: string; // Inquiry ID +/** GET /v5/earn/pwm/asset-manager/all-order */ +export interface PwmAssetManagerFundOrderV5 { + orderId: string; + fundId: string; + fundName: string; + accountUid: string; + orderType: string; + coin: string; + amount: string; + shares: string; + status: string; + createdTime: string; } ⋮---- -rfqId: string; // Inquiry ID - -================ -File: src/types/response/v5-spreadtrading.ts -================ -export interface SpreadInstrumentInfoV5 { - symbol: string; - contractType: 'FundingRateArb' | 'CarryTrade' | 'FutureSpread' | 'PerpBasis'; - status: 'Trading' | 'Settling'; - baseCoin: string; - quoteCoin: string; - settleCoin: string; - tickSize: string; - minPrice: string; - maxPrice: string; - lotSize: string; - minSize: string; - maxSize: string; - launchTime: string; - deliveryTime: string; - legs: { - symbol: string; - contractType: 'LinearPerpetual' | 'LinearFutures' | 'Spot'; - }[]; +export interface PwmAllFundOrdersResultV5 { + list: PwmAssetManagerFundOrderV5[]; + nextPageCursor: string; } ⋮---- -export interface SpreadOrderbookResponseV5 { - s: string; // Symbol - b: [string, string][]; // Bids array [price, size] - a: [string, string][]; // Asks array [price, size] - u: number; // Update ID - ts: number; // Timestamp - seq: number; // Sequence - cts: number; // Cross timestamp +/** POST /v5/earn/pwm/asset-manager/manage-order */ +export interface ManagePwmFundOrderResultV5 { + orderId: string; + fundId: string; + accountUid: string; + orderStatus: string; + orderType: string; + action: string; + coin: string; + amount: string; + shares: string; + updatedTime: string; } ⋮---- -s: string; // Symbol -b: [string, string][]; // Bids array [price, size] -a: [string, string][]; // Asks array [price, size] -u: number; // Update ID -ts: number; // Timestamp -seq: number; // Sequence -cts: number; // Cross timestamp -⋮---- -export interface SpreadTickerV5 { - symbol: string; // Spread combination symbol name - bidPrice: string; // Bid 1 price - bidSize: string; // Bid 1 size - askPrice: string; // Ask 1 price - askSize: string; // Ask 1 size - lastPrice: string; // Last trade price - highPrice24h: string; // The highest price in the last 24 hours - lowPrice24h: string; // The lowest price in the last 24 hours - prevPrice24h: string; // Price 24 hours ago - volume24h: string; // Volume for 24h +/** POST /v5/earn/pwm/asset-manager/create-sub-account */ +export interface CreatePwmFundSubAccountResultV5 { + fundId: string; + subAccountUid: string; + createdTime: string; + status: string; } ⋮---- -symbol: string; // Spread combination symbol name -bidPrice: string; // Bid 1 price -bidSize: string; // Bid 1 size -askPrice: string; // Ask 1 price -askSize: string; // Ask 1 size -lastPrice: string; // Last trade price -highPrice24h: string; // The highest price in the last 24 hours -lowPrice24h: string; // The lowest price in the last 24 hours -prevPrice24h: string; // Price 24 hours ago -volume24h: string; // Volume for 24h +/** POST /v5/earn/pwm/fund-transfer */ +export interface PwmFundTransferResultV5 { + transferId: string; + status: string; +} ⋮---- -export interface SpreadRecentTradeV5 { - execId: string; // Execution ID - symbol: string; // Spread combination symbol name - price: string; // Trade price - size: string; // Trade size - side: 'Buy' | 'Sell'; // Side of taker - time: string; // Trade time (ms) - seq?: string; +/** GET /v5/earn/pwm/query-fund-transfer-result */ +export interface PwmFundTransferRecordV5 { + transferId: string; + status: string; + fromUserId: number; + toUserId: number; + amount: string; + coin: string; } + +================ +File: src/types/response/v5-earn-token.ts +================ +/** + * Earn token product (e.g. BYUSDT) — /v5/earn/token/* + */ ⋮---- -execId: string; // Execution ID -symbol: string; // Spread combination symbol name -price: string; // Trade price -size: string; // Trade size -side: 'Buy' | 'Sell'; // Side of taker -time: string; // Trade time (ms) +export interface EarnTokenProductV5 { + productId: string; + coin: string; + mintFeeRateE8: string; + redeemFeeRateE8: string; + minInvestment: string; + userHolding: string; + leftQuota: string; + canMint: boolean; + savingsBalance: string; + aprE8: string; + bonusAprE8: string; + bonusMaxAmount: string; + baseCoinPrecision: number; + tokenPrecision: number; +} ⋮---- -export interface SpreadOpenOrderV5 { - symbol: string; - baseCoin: string; - orderType: 'Market' | 'Limit'; - orderLinkId: string; - side: 'Buy' | 'Sell'; - timeInForce: 'GTC' | 'FOK' | 'IOC' | 'PostOnly'; +export interface PlaceEarnTokenOrderResultV5 { orderId: string; - leavesQty: string; - orderStatus: 'New' | 'PartiallyFilled'; - cumExecQty: string; - price: string; - qty: string; - createdTime: string; - updatedTime: string; + orderLinkId: string; } ⋮---- -export interface SpreadOrderHistoryV5 { - symbol: string; - orderType: 'Market' | 'Limit'; - orderLinkId: string; +export interface EarnTokenOrderV5 { orderId: string; - contractType: 'FundingRateArb' | 'CarryTrade' | 'FutureSpread' | 'PerpBasis'; - orderStatus: 'Rejected' | 'Cancelled' | 'Filled'; - price: string; - orderQty: string; - timeInForce: 'GTC' | 'FOK' | 'IOC' | 'PostOnly'; - baseCoin: string; - createdAt: string; - updatedAt: string; - side: 'Buy' | 'Sell'; - leavesQty: string; - settleCoin: string; - cumExecQty: string; - qty: string; - leg1Symbol: string; - leg1ProdType: 'Futures' | 'Spot'; - leg1OrderId: string; - leg1Side: string; - leg2ProdType: 'Futures' | 'Spot'; - leg2OrderId: string; - leg2Symbol: string; - leg2Side: string; - cxlRejReason: string; - cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee + orderLinkId: string; + orderType: 'Mint' | 'Redeem'; + fromCoin: string; + toCoin: string; + fromAmount: string; + toAmount: string; + serviceFee: string; + status: 'Success' | 'Processing' | 'Fail'; + createdTime: string; } ⋮---- -cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee -⋮---- -export interface SpreadTradeLegV5 { - symbol: string; - side: 'Buy' | 'Sell'; - execPrice: string; - execTime: string; - execValue: string; - execType: string; - category: 'linear' | 'spot'; - execQty: string; - execFee: string; - feeCurrency: string; // Trading fee currency - execId: string; +export interface EarnTokenPositionV5 { + totalAmount: string; + totalYield: string; + yesterdayYield: string; + aprE8: number; + bonusAprE8: number; + bonusMaxAmount: string; + hasQuota: boolean; } ⋮---- -feeCurrency: string; // Trading fee currency -⋮---- -export interface SpreadTradeV5 { - symbol: string; - orderLinkId: string; - side: 'Buy' | 'Sell'; - orderId: string; - execPrice: string; - execTime: string; - execType: 'Trade'; - execQty: string; - execId: string; - legs: SpreadTradeLegV5[]; - extraFees: string; +export interface EarnTokenDailyYieldRecordV5 { + yield: string; + bonusYield: string; + status: 'Success' | 'Processing'; + createdTime: string; } ⋮---- -/** GET /v5/spread/max-qty */ -export interface SpreadMaxQtyResultV5 { - /** Maximum order quantity (available balance for the spread order). */ - ab: string; +export interface EarnTokenHourlyYieldRecordV5 { + effectiveAmount: string; + yield: string; + rewardType: 0 | 1; + aprE8: string; + hourlyDate: string; + createdTime: string; } ⋮---- -/** Maximum order quantity (available balance for the spread order). */ +export interface EarnTokenHistoryAprPointV5 { + timestamp: string; + aprE8: string; +} ================ -File: src/types/response/v5-strategy.ts +File: src/types/response/v5-rwa.ts ================ -import { - OrderSideV5, - PositionIdx, - PovModeV5, - StrategyCategoryV5, - StrategyPreferV5, - StrategyTypeV5, -} from '../shared-v5'; +/** + * V5 RWA (Real World Assets) earn responses. + */ ⋮---- -export interface CreateStrategyOrderResultV5 { - strategyId: string; - /** null when creation succeeded */ - result: string | null; +export interface RWAProductV5 { + productId: number; + coin: string; + assetSymbol: string; + manager: string; + baseApr: string; + bonusApr: string; + savingType: 'Flexible' | 'Fixed' | string; + duration: number; + nav: string; + minStakeAmount: string; + maxStakeAmount: string; + userMaxAmount: string; + userQuota: string; + minRedeemShare: string; + redeemFeeRate: string; + subscriptionFee: string; + extLink: string; + amountPrecision: number; + sharePrecision: number; } ⋮---- -/** null when creation succeeded */ +export interface RWAProductListResultV5 { + list: RWAProductV5[]; +} ⋮---- -export interface StopStrategyResultV5 { - strategyId: string; +export interface PlaceRWAOrderResultV5 { + orderId: string; + orderLinkId: string; } ⋮---- -export interface StrategyListItemV5 { - strategyId: string; - category: StrategyCategoryV5; - symbol: string; - side: OrderSideV5; - size: string; - strategyType: StrategyTypeV5; - /** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ - status: 2 | 3 | 4 | 5 | 6; - executedSize: string; - executedAvgPrice: string; - executedStartTimeE3: string; - executedEndTimeE3: string; - createdTimeE3: string; - updatedTimeE3: string; - reduceOnly: boolean; - triggerPrice: string; - isTriggered: boolean; - leverageType: 0 | 1; - terminateType: number; - terminateRemark: string; - triggerCount: string; - tradingCount: string; - realizedPnl: string; - strategyName: string; - strategyPrefer: StrategyPreferV5 | string; +export interface RWAPositionV5 { + productId: number; + coin: string; + assetSymbol: string; + effectiveShare: string; + processingStakeAmount: string; + processingRedeemShare: string; + bonusEarned: string; + nav: string; + holdAmount: string; duration: number; - executedDuration: number; - isRandom: boolean; - interval: number; - limitPrice: string; - chasePercentE4: string; - chaseDistance: string; - maxChasePrice: string; - chaseOrderPrice: string; - chasePrice: string; - postOnly: number; - isRebalance: boolean; - orderType: string; - orderPriceOffset: string; - strategySl: string; - strategyTp: string; - arbitrageOrders: unknown[]; - positionValue: string; - filledPositionValue: string; - /** POV only */ - mode?: PovModeV5 | string; - participationRate?: string; - referenceWindow?: string; - depthReference?: string; } ⋮---- -/** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ -⋮---- -/** POV only */ -⋮---- -export interface StrategyListResultV5 { - list: StrategyListItemV5[]; - nextCursor: string; - prevCursor: string; +export interface RWAPositionListResultV5 { + list: RWAPositionV5[]; } ⋮---- -export interface StrategyOrderListItemV5 { - strategyId: string; +export interface RWAOrderV5 { orderId: string; - symbol: string; - side: OrderSideV5; - size: string; - price: string; - /** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ - status: string; - executedSize: string; - dealTimeE3: string; - parentOrderId: string; - createdTimeE3: string; - updatedTimeE3: string; - code: number; - msg: string; - category: StrategyCategoryV5; - positionIdx: PositionIdx; - leverageType: 0 | 1; - tpPrice: string; - slPrice: string; - orderType: string; - orderPriceOffset: string; - positionValue: string; - filledPositionValue: string; + orderLinkId: string; + orderType: 'Stake' | 'Redeem'; + productId: number; + coin: string; + stakeAmount?: string; + redeemShares?: string; + status: 'Processing' | 'Success' | 'Failed' | string; + accountType: 'FUND' | 'UNIFIED' | string; + createdTime: number; + updatedTime: number; + settledShares?: string; + settledAmount?: string; } ⋮---- -/** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ +export interface RWAOrderListResultV5 { + list: RWAOrderV5[]; + nextPageCursor: string; +} ⋮---- -export interface StrategyOrderListResultV5 { - list: StrategyOrderListItemV5[]; - nextCursor: string; - prevCursor: string; +export interface RWANavChartPointV5 { + date: string; + nav: string; +} +⋮---- +export interface RWANavChartResultV5 { + productId: number; + list: RWANavChartPointV5[]; } ================ -File: src/types/shared.ts +File: src/types/response/v5-spot-x.ts ================ -import { RestClientV5 } from '../rest-client-v5'; -import { SpotClientV3 } from '../spot-client-v3'; +export interface LaunchpoolPoolV5 { + poolId: string; + stakeCoin: string; + apr: string; + totalStakedAmount: string; + participantCount: string; +} ⋮---- -export type RESTClient = SpotClientV3 | RestClientV5; +export interface LaunchpoolProjectV5 { + projectId: string; + activityCoin: string; + rewardCoin: string; + status: number; + totalReward: string; + stakeStartTime: string; + stakeEndTime: string; + totalParticipantCount: string; + pools: LaunchpoolPoolV5[]; +} ⋮---- -export type numberInString = string; +export interface LaunchpoolProjectListResultV5 { + list: LaunchpoolProjectV5[]; + nextPageCursor: string; +} ⋮---- -export type OrderSide = 'Buy' | 'Sell'; +export interface LaunchpoolActivityLogItemV5 { + stakeCoin: string; + rewardCoin: string; + amount: string; + type: number; + status: number; + createdTime: string; + orderId: string; +} ⋮---- -export type KlineInterval = - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '12h' - | '1d' - | '1w' - | '1M'; +export interface LaunchpoolActivityLogResultV5 { + list: LaunchpoolActivityLogItemV5[]; + total: number; + pageSize: number; + current: number; +} ⋮---- -export type KlineIntervalV3 = - | '1' - | '3' - | '5' - | '15' - | '30' - | '60' - | '120' - | '240' - | '360' - | '720' - | 'D' - | 'W' - | 'M'; +export interface LaunchpoolStakingPositionV5 { + stakeCoin: string; + rewardCoin: string; + stakeAmount: string; + totalReward: string; + autoRedeemDate: string; +} ⋮---- -export interface APIRateLimit { - /** Remaining requests to this endpoint before the next reset */ - remainingRequests: number; - /** Max requests for this endpoint per rollowing window (before next reset) */ - maxRequests: number; - /** - * Timestamp when the rate limit resets if you have exceeded your current maxRequests. - * Otherwise, this is approximately your current timestamp. - */ - resetAtTimestamp: number; +export interface LaunchpoolCurrentStakingResultV5 { + totalInvestmentUsd: string; + totalEarningsUsd: string; + todayEarningsUsd: string; + list: LaunchpoolStakingPositionV5[]; } ⋮---- -/** Remaining requests to this endpoint before the next reset */ -⋮---- -/** Max requests for this endpoint per rollowing window (before next reset) */ -⋮---- -/** - * Timestamp when the rate limit resets if you have exceeded your current maxRequests. - * Otherwise, this is approximately your current timestamp. - */ -⋮---- -export interface APIResponseV3 { - retCode: number; - retMsg: 'OK' | string; - result: TResult; - retExtInfo: TExtInfo; - /** - * These are per-UID per-endpoint rate limits, automatically parsed from response headers if available. - * - * Note: - * - this is primarily for V5 (or newer) APIs. - * - these rate limits are per-endpoint per-account, so will not appear for public API calls - */ - rateLimitApi?: APIRateLimit; +export interface LaunchpoolUserHistoryItemV5 { + stakeCoin: string; + rewardCoin: string; + totalReward: string; + stakeStartTime: string; + stakeEndTime: string; } ⋮---- -/** - * These are per-UID per-endpoint rate limits, automatically parsed from response headers if available. - * - * Note: - * - this is primarily for V5 (or newer) APIs. - * - these rate limits are per-endpoint per-account, so will not appear for public API calls - */ +export interface LaunchpoolUserHistoryResultV5 { + list: LaunchpoolUserHistoryItemV5[]; + total: number; + pageSize: number; + current: number; +} ⋮---- -export type APIResponseV3WithTime = APIResponseV3< - TResult, - TExtInfo -> & { time: number }; +export interface PuzzleProjectV5 { + projectId: string; + activityCoin: string; + rewardCoin: string; + status: number; + startTime: string; + endTime: string; + totalReward: string; + participantCount: string; +} ⋮---- -export interface APIP2PResponse { - ret_code: number; - ret_msg: string; - result: { - result: TResult; - totalRows: string; - totalPages: string; - currentPage: string; - dayLimit: string; - showDayLimit: boolean; - }; - ext_code: string; - ext_info: TExtInfo; - time_now: string; +export interface PuzzleProjectListResultV5 { + list: PuzzleProjectV5[]; + nextPageCursor: string; } ⋮---- -/** - * Request Parameter Types - */ -export interface SymbolParam { - symbol: string; +export interface TokenSplashProjectV5 { + status: number; + projectId: string; + activityCoin: string; + rewardCoin: string; + totalReward: string; + participantCount: string; + registrationStartTime: string; + activityEndTime: string; } ⋮---- -export interface SymbolLimitParam { - symbol: string; - limit?: TLimit; +export interface TokenSplashProjectListResultV5 { + list: TokenSplashProjectV5[]; + nextPageCursor: string; } ⋮---- -export interface SymbolPeriodLimitParam { - symbol: string; - period: string; - limit?: TLimit; +export interface TokenSplashTradeTaskV5 { + tradeRequiredAmount: string; + tradeUnit: string; + tradedAmount: string; + maxRewardAmount: string; + estimatedRewardAmount: string; + rewardCoin: string; } ⋮---- -export interface SymbolFromLimitParam { - symbol: string; - from?: number; - limit?: number; +export interface TokenSplashUserActivityItemV5 { + projectId: string; + activityCoin: string; + tradeTask: TokenSplashTradeTaskV5; } ⋮---- -export interface SymbolIntervalFromLimitParam { +export interface TokenSplashUserActivityResultV5 { + list: TokenSplashUserActivityItemV5[]; +} + +================ +File: src/types/response/v5-spreadtrading.ts +================ +export interface SpreadInstrumentInfoV5 { symbol: string; - interval: string; - from: number; - limit?: number; + contractType: 'FundingRateArb' | 'CarryTrade' | 'FutureSpread' | 'PerpBasis'; + status: 'Trading' | 'Settling'; + baseCoin: string; + quoteCoin: string; + settleCoin: string; + tickSize: string; + minPrice: string; + maxPrice: string; + lotSize: string; + minSize: string; + maxSize: string; + launchTime: string; + deliveryTime: string; + legs: { + symbol: string; + contractType: 'LinearPerpetual' | 'LinearFutures' | 'Spot'; + }[]; } ⋮---- -export interface CoinParam { - coin: string; +export interface SpreadOrderbookResponseV5 { + s: string; // Symbol + b: [string, string][]; // Bids array [price, size] + a: [string, string][]; // Asks array [price, size] + u: number; // Update ID + ts: number; // Timestamp + seq: number; // Sequence + cts: number; // Cross timestamp } ⋮---- -export interface WalletFundRecordsReq { - start_date?: string; - end_date?: string; - currency?: string; - coin?: string; - wallet_fund_type?: string; - page?: number; - limit?: number; -} +s: string; // Symbol +b: [string, string][]; // Bids array [price, size] +a: [string, string][]; // Asks array [price, size] +u: number; // Update ID +ts: number; // Timestamp +seq: number; // Sequence +cts: number; // Cross timestamp ⋮---- -export interface WithdrawRecordsReq { - start_date?: string; - end_date?: string; - coin?: string; - status?: string; - page?: number; - limit?: number; +export interface SpreadTickerV5 { + symbol: string; // Spread combination symbol name + bidPrice: string; // Bid 1 price + bidSize: string; // Bid 1 size + askPrice: string; // Ask 1 price + askSize: string; // Ask 1 size + lastPrice: string; // Last trade price + highPrice24h: string; // The highest price in the last 24 hours + lowPrice24h: string; // The lowest price in the last 24 hours + prevPrice24h: string; // Price 24 hours ago + volume24h: string; // Volume for 24h } ⋮---- -export interface AssetExchangeRecordsReq { - limit?: number; - from?: number; - direction?: string; +symbol: string; // Spread combination symbol name +bidPrice: string; // Bid 1 price +bidSize: string; // Bid 1 size +askPrice: string; // Ask 1 price +askSize: string; // Ask 1 size +lastPrice: string; // Last trade price +highPrice24h: string; // The highest price in the last 24 hours +lowPrice24h: string; // The lowest price in the last 24 hours +prevPrice24h: string; // Price 24 hours ago +volume24h: string; // Volume for 24h +⋮---- +export interface SpreadRecentTradeV5 { + execId: string; // Execution ID + symbol: string; // Spread combination symbol name + price: string; // Trade price + size: string; // Trade size + side: 'Buy' | 'Sell'; // Side of taker + time: string; // Trade time (ms) + seq?: string; } ⋮---- -/** - * Response types - */ +execId: string; // Execution ID +symbol: string; // Spread combination symbol name +price: string; // Trade price +size: string; // Trade size +side: 'Buy' | 'Sell'; // Side of taker +time: string; // Trade time (ms) ⋮---- -export interface LeverageFilter { - min_leverage: numberInString; - max_leverage: numberInString; - leverage_step: numberInString; +export interface SpreadOpenOrderV5 { + symbol: string; + baseCoin: string; + orderType: 'Market' | 'Limit'; + orderLinkId: string; + side: 'Buy' | 'Sell'; + timeInForce: 'GTC' | 'FOK' | 'IOC' | 'PostOnly'; + orderId: string; + leavesQty: string; + orderStatus: 'New' | 'PartiallyFilled'; + cumExecQty: string; + price: string; + qty: string; + createdTime: string; + updatedTime: string; } -export interface PriceFilter { - min_price: numberInString; - max_price: numberInString; - tick_size: numberInString; +⋮---- +export interface SpreadOrderHistoryV5 { + symbol: string; + orderType: 'Market' | 'Limit'; + orderLinkId: string; + orderId: string; + contractType: 'FundingRateArb' | 'CarryTrade' | 'FutureSpread' | 'PerpBasis'; + orderStatus: 'Rejected' | 'Cancelled' | 'Filled'; + price: string; + orderQty: string; + timeInForce: 'GTC' | 'FOK' | 'IOC' | 'PostOnly'; + baseCoin: string; + createdAt: string; + updatedAt: string; + side: 'Buy' | 'Sell'; + leavesQty: string; + settleCoin: string; + cumExecQty: string; + qty: string; + leg1Symbol: string; + leg1ProdType: 'Futures' | 'Spot'; + leg1OrderId: string; + leg1Side: string; + leg2ProdType: 'Futures' | 'Spot'; + leg2OrderId: string; + leg2Symbol: string; + leg2Side: string; + cxlRejReason: string; + cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee } ⋮---- -export interface LotSizeFilter { - max_trading_qty: number; - min_trading_qty: number; - qty_step: number; +cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee +⋮---- +export interface SpreadTradeLegV5 { + symbol: string; + side: 'Buy' | 'Sell'; + execPrice: string; + execTime: string; + execValue: string; + execType: string; + category: 'linear' | 'spot'; + execQty: string; + execFee: string; + feeCurrency: string; // Trading fee currency + execId: string; } ⋮---- -export interface SymbolInfo { - name: string; - alias: string; - status: 'Trading' | string; - base_currency: string; - quote_currency: string; - price_scale: number; - taker_fee: numberInString; - maker_fee: numberInString; - leverage_filter: LeverageFilter; - price_filter: PriceFilter; - lot_size_filter: LotSizeFilter; +feeCurrency: string; // Trading fee currency +⋮---- +export interface SpreadTradeV5 { + symbol: string; + orderLinkId: string; + side: 'Buy' | 'Sell'; + orderId: string; + execPrice: string; + execTime: string; + execType: 'Trade'; + execQty: string; + execId: string; + legs: SpreadTradeLegV5[]; + extraFees: string; +} +⋮---- +/** GET /v5/spread/max-qty */ +export interface SpreadMaxQtyResultV5 { + /** Maximum order quantity (available balance for the spread order). */ + ab: string; } +⋮---- +/** Maximum order quantity (available balance for the spread order). */ ================ -File: src/websocket-api-client.ts +File: src/types/response/v5-strategy.ts ================ import { - AmendOrderParamsV5, - BatchAmendOrderParamsV5, - BatchAmendOrderResultV5, - BatchCancelOrderParamsV5, - BatchCancelOrderResultV5, - BatchCreateOrderResultV5, - BatchOrderParamsV5, - BatchOrdersRetExtInfoV5, - CancelOrderParamsV5, - OrderParamsV5, - OrderResultV5, -} from './types'; -import { WSAPIResponse } from './types/websockets/ws-api'; -import { WSClientConfigurableOptions } from './types/websockets/ws-general'; -import { DefaultLogger } from './util'; -import { WS_KEY_MAP } from './util/websockets/websocket-util'; -import { WebsocketClient } from './websocket-client'; + OrderSideV5, + PositionIdx, + PovModeV5, + StrategyCategoryV5, + StrategyPreferV5, + StrategyTypeV5, +} from '../shared-v5'; ⋮---- -/** - * 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 CreateStrategyOrderResultV5 { + strategyId: string; + /** null when creation succeeded */ + result: string | null; } ⋮---- -/** - * 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(....)`. - */ +/** null when creation succeeded */ ⋮---- -/** - * This is a minimal Websocket API wrapper around the WebsocketClient. - * - * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should - * be used to transmit that message. This is only useful if you wish to use an alternative wss - * domain that is supported by the SDK. - * - * Note: To use testnet, don't set the wsKey - use `testnet: true` in - * the constructor instead. - * - * 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/bybit-api/blob/master/examples/ws-api-raw-promises.ts - */ -export class WebsocketAPIClient +export interface StopStrategyResultV5 { + strategyId: string; +} ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +export interface StrategyListItemV5 { + strategyId: string; + category: StrategyCategoryV5; + symbol: string; + side: OrderSideV5; + size: string; + strategyType: StrategyTypeV5; + /** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ + status: 2 | 3 | 4 | 5 | 6; + executedSize: string; + executedAvgPrice: string; + executedStartTimeE3: string; + executedEndTimeE3: string; + createdTimeE3: string; + updatedTimeE3: string; + reduceOnly: boolean; + triggerPrice: string; + isTriggered: boolean; + leverageType: 0 | 1; + terminateType: number; + terminateRemark: string; + triggerCount: string; + tradingCount: string; + realizedPnl: string; + strategyName: string; + strategyPrefer: StrategyPreferV5 | string; + duration: number; + executedDuration: number; + isRandom: boolean; + interval: number; + limitPrice: string; + chasePercentE4: string; + chaseDistance: string; + maxChasePrice: string; + chaseOrderPrice: string; + chasePrice: string; + postOnly: number; + isRebalance: boolean; + orderType: string; + orderPriceOffset: string; + strategySl: string; + strategyTp: string; + arbitrageOrders: unknown[]; + positionValue: string; + filledPositionValue: string; + /** POV only */ + mode?: PovModeV5 | string; + participationRate?: string; + referenceWindow?: string; + depthReference?: string; +} ⋮---- -public getWSClient(): WebsocketClient +/** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ ⋮---- -public setTimeOffsetMs(newOffset: number): void +/** POV only */ ⋮---- -/* - * Bybit WebSocket API Methods - * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline - */ +export interface StrategyListResultV5 { + list: StrategyListItemV5[]; + nextCursor: string; + prevCursor: string; +} ⋮---- -/** - * Submit a new order - * - * @param params - * @returns - */ -submitNewOrder( - params: OrderParamsV5, -): Promise> +export interface StrategyOrderListItemV5 { + strategyId: string; + orderId: string; + symbol: string; + side: OrderSideV5; + size: string; + price: string; + /** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ + status: string; + executedSize: string; + dealTimeE3: string; + parentOrderId: string; + createdTimeE3: string; + updatedTimeE3: string; + code: number; + msg: string; + category: StrategyCategoryV5; + positionIdx: PositionIdx; + leverageType: 0 | 1; + tpPrice: string; + slPrice: string; + orderType: string; + orderPriceOffset: string; + positionValue: string; + filledPositionValue: string; +} ⋮---- -/** - * Amend an order - * - * @param params - * @returns - */ -amendOrder( - params: AmendOrderParamsV5, -): Promise> +/** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ ⋮---- -/** - * Cancel an order - * - * @param params - * @returns - */ -cancelOrder( - params: CancelOrderParamsV5, -): Promise> +export interface StrategyOrderListResultV5 { + list: StrategyOrderListItemV5[]; + nextCursor: string; + prevCursor: string; +} + +================ +File: src/types/shared.ts +================ +import { RestClientV5 } from '../rest-client-v5'; +import { SpotClientV3 } from '../spot-client-v3'; ⋮---- -/** - * Batch submit orders - * - * @param params - * @returns - */ -batchSubmitOrders( - category: 'option' | 'linear', - orders: BatchOrderParamsV5[], - ): Promise< - WSAPIResponse< - { - list: BatchCreateOrderResultV5[]; - }, - 'order.create-batch', - BatchOrdersRetExtInfoV5 - > - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.v5PrivateTrade, - 'order.create-batch', - { - category, - request: orders, - }, - ); +export type RESTClient = SpotClientV3 | RestClientV5; ⋮---- -/** - * Batch amend orders - * - * @param params - * @returns +export type numberInString = string; +⋮---- +export type OrderSide = 'Buy' | 'Sell'; +⋮---- +export type KlineInterval = + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '12h' + | '1d' + | '1w' + | '1M'; +⋮---- +export type KlineIntervalV3 = + | '1' + | '3' + | '5' + | '15' + | '30' + | '60' + | '120' + | '240' + | '360' + | '720' + | 'D' + | 'W' + | 'M'; +⋮---- +export interface APIRateLimit { + /** Remaining requests to this endpoint before the next reset */ + remainingRequests: number; + /** Max requests for this endpoint per rollowing window (before next reset) */ + maxRequests: number; + /** + * Timestamp when the rate limit resets if you have exceeded your current maxRequests. + * Otherwise, this is approximately your current timestamp. */ -batchAmendOrder( - category: 'option' | 'linear', - orders: BatchAmendOrderParamsV5[], - ): Promise< - WSAPIResponse< - { - list: BatchAmendOrderResultV5[]; - }, - 'order.amend-batch', - BatchOrdersRetExtInfoV5 - > - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.v5PrivateTrade, - 'order.amend-batch', - { - category, - request: orders, - }, - ); + resetAtTimestamp: number; +} +⋮---- +/** Remaining requests to this endpoint before the next reset */ +⋮---- +/** Max requests for this endpoint per rollowing window (before next reset) */ ⋮---- /** - * Batch cancel orders + * Timestamp when the rate limit resets if you have exceeded your current maxRequests. + * Otherwise, this is approximately your current timestamp. + */ +⋮---- +export interface APIResponseV3 { + retCode: number; + retMsg: 'OK' | string; + result: TResult; + retExtInfo: TExtInfo; + /** + * These are per-UID per-endpoint rate limits, automatically parsed from response headers if available. * - * @param params - * @returns + * Note: + * - this is primarily for V5 (or newer) APIs. + * - these rate limits are per-endpoint per-account, so will not appear for public API calls */ -batchCancelOrder( - category: 'option' | 'linear', - orders: BatchCancelOrderParamsV5[], - ): Promise< - WSAPIResponse< - { - list: BatchCancelOrderResultV5[]; - }, - 'order.cancel-batch', - BatchOrdersRetExtInfoV5 - > - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.v5PrivateTrade, - 'order.cancel-batch', - { - category, - request: orders, - }, - ); + rateLimitApi?: APIRateLimit; +} ⋮---- /** + * These are per-UID per-endpoint rate limits, automatically parsed from response headers if available. * - * - * - * - * - * - * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * - * + * Note: + * - this is primarily for V5 (or newer) APIs. + * - these rate limits are per-endpoint per-account, so will not appear for public API calls */ ⋮---- -private setupDefaultEventListeners() +export type APIResponseV3WithTime = APIResponseV3< + TResult, + TExtInfo +> & { time: number }; +⋮---- +export interface APIP2PResponse { + ret_code: number; + ret_msg: string; + result: { + result: TResult; + totalRows: string; + totalPages: string; + currentPage: string; + dayLimit: string; + showDayLimit: boolean; + }; + ext_code: string; + ext_info: TExtInfo; + time_now: string; +} ⋮---- /** - * General event handlers for monitoring the WebsocketClient - */ + * Request Parameter Types + */ +export interface SymbolParam { + symbol: string; +} ⋮---- -// Blind JSON.stringify can fail on circular references +export interface SymbolLimitParam { + symbol: string; + limit?: TLimit; +} ⋮---- -// JSON.stringify({ ...data, target: 'WebSocket' }), - -================ -File: webpack/webpack.config.js -================ -function generateConfig(name) +export interface SymbolPeriodLimitParam { + symbol: string; + period: string; + limit?: TLimit; +} ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +export interface SymbolFromLimitParam { + symbol: string; + from?: number; + limit?: number; +} ⋮---- -// 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 +export interface SymbolIntervalFromLimitParam { + symbol: string; + interval: string; + from: number; + limit?: number; +} ⋮---- -// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. +export interface CoinParam { + coin: string; +} ⋮---- -// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. - -================ -File: docs/BYBIT_SDK_QUICKSTART_GUIDE.md -================ -# Bybit API JavaScript Tutorial for Node.js and TypeScript - -> [!TIP] -> This guide can be read in tutorial format on the Siebly Website: [Bybit JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/bybit/javascript/tutorial) - -This tutorial walks through a practical Bybit REST API, WebSocket stream, and WebSocket API integration using [`bybit-api`](https://www.npmjs.com/package/bybit-api), the Bybit JavaScript and TypeScript SDK by Siebly.io. - -The SDK handles the repetitive parts: HMAC and RSA request signing, Bybit API endpoint routing, testnet and demo trading differences, WebSocket authentication, heartbeats, reconnects, resubscribe behavior, WebSocket API request/response matching, and TypeScript request and response definitions. The sections below move from installation and client choice to public calls, private auth, trading flows, WebSocket API commands, environments, and production checks. - -**Key links** - -- Bybit JavaScript SDK by Siebly: [`bybit-api`](https://www.npmjs.com/package/bybit-api) -- GitHub Repository: [`tiagosiebler/bybit-api`](https://github.com/tiagosiebler/bybit-api) -- SDK function-endpoint map: [Bybit JavaScript Endpoint Reference](./endpointFunctionList.md) -- REST API examples: [Bybit SDK REST API examples](../examples/Rest) -- WebSocket examples: [Bybit SDK WebSocket examples](../examples/Websocket) -- Bybit API docs: [Bybit API Documentation](https://bybit-exchange.github.io/docs/v5/intro) -- Position Management with Bybit APIs & WebSockets: [Siebly Position Management with Bybit APIs & WebSockets](https://siebly.io/ai/exchange-state/bybit) -- More SDKs: [Siebly.io](https://siebly.io) - ---- - -## Why use the SDK - -The Bybit API is unified, but a real integration still has several moving parts: - -- The API spans Spot, Linear contracts, Inverse contracts, Options, account, asset, user, broker, Earn, P2P, RFQ, spread trading, spot margin, and loan workflows. - - Within the Bybit JavaScript SDK by Siebly.io, all product groups are available in one unified REST API client. -- Many market and trade calls use a `category` parameter such as `spot`, `linear`, `inverse`, or `option`. -- Public WebSocket streams are split across category-specific endpoints. -- Private WebSocket streams use a separate private endpoint. -- WebSocket API commands use a separate endpoint represented by `v5PrivateTrade`. -- Private REST API and WebSocket API requests are timestamp-sensitive and must be signed. -- Bybit supports both HMAC keys and self-generated RSA keys. The SDK has automatic support for all key types. -- Live, testnet, demo trading, and regional Bybit domains are separate routing choices. - -The SDK gives you the main surfaces needed for those workflows: - -- `RestClientV5` for Bybit REST API calls. -- `WebsocketClient` for public and private streams. -- `WebsocketAPIClient` for promise-driven WebSocket API commands. -- `SpotClientV3` for the remaining legacy Spot V3 endpoint. New integrations should use the current Bybit API surface. The V3 client might be removed at any time. - -The method names stay close to Bybit's endpoint names, while the SDK handles base URLs, request signatures, request routing, headers, WebSocket lifecycle, authentication, topic tracking, reconnects, and typed request shapes. It also lets you use the WebSocket API in a request/response style: send a command and await the matching response, similar to a REST API. - ---- - -## Install and API keys - -If you do not have Node.js installed yet, install it first. The SDK is published to both [GitHub](https://github.com/tiagosiebler/bybit-api) and [npm](https://www.npmjs.com/package/bybit-api). +export interface WalletFundRecordsReq { + start_date?: string; + end_date?: string; + currency?: string; + coin?: string; + wallet_fund_type?: string; + page?: number; + limit?: number; +} +⋮---- +export interface WithdrawRecordsReq { + start_date?: string; + end_date?: string; + coin?: string; + status?: string; + page?: number; + limit?: number; +} +⋮---- +export interface AssetExchangeRecordsReq { + limit?: number; + from?: number; + direction?: string; +} +⋮---- +/** + * Response types + */ +⋮---- +export interface LeverageFilter { + min_leverage: numberInString; + max_leverage: numberInString; + leverage_step: numberInString; +} +export interface PriceFilter { + min_price: numberInString; + max_price: numberInString; + tick_size: numberInString; +} +⋮---- +export interface LotSizeFilter { + max_trading_qty: number; + min_trading_qty: number; + qty_step: number; +} +⋮---- +export interface SymbolInfo { + name: string; + alias: string; + status: 'Trading' | string; + base_currency: string; + quote_currency: string; + price_scale: number; + taker_fee: numberInString; + maker_fee: numberInString; + leverage_filter: LeverageFilter; + price_filter: PriceFilter; + lot_size_filter: LotSizeFilter; +} -Install the SDK with npm: +================ +File: .nvmrc +================ +v24.18.0 -```bash -npm install bybit-api -``` +================ +File: examples/Rest/rest-v5-proxies2.ts +================ +import { HttpsProxyAgent } from 'https-proxy-agent'; +⋮---- +import { RestClientV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +/** + * Some proxy services don't work with the proxy configuration that axios supports. + * + * For these, you can try using HttpsProxyAgent or SocksProxyAgent (depending on your proxy type, HTTP or SOCKS). + * + * The following example uses the HttpsProxyAgent (via the npm module https-proxy-agent). + */ +⋮---- +// Sometimes using a proxy introduces recv timestamp errors (due to the extra latency) +// If that happens, you can try increasing the recv window (which is 5000ms by default) +// recv_window: 10000, -Or use another npm-compatible package manager: +================ +File: examples/Websocket/Private/ws-private-v5.ts +================ +/* eslint-disable @typescript-eslint/no-empty-function */ +import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; +⋮---- +// Create & inject a custom logger to enable the trace logging level (empty function) +⋮---- +// trace: (...params) => console.log('trace', ...params), +⋮---- +/** + * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: + * - Connections are opened when you subscribe to topics + * - If key & secret are provided, authentication is handled automatically + * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), + * subscription events are automatically routed to the different ws endpoints on bybit's side + * - Heartbeats/ping/pong/reconnects are all handled automatically. + * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. + */ +⋮---- +// testnet: false, +// demoTrading: false, // set testnet to false, if you plan on using demo trading +⋮---- +// console.log('raw message received ', JSON.stringify(data, null, 2)); +⋮---- +// wsClient.on('exception', (data) => { +// console.error('ws exception: ', data); +// }); +⋮---- +/** + * For private V5 topics, us the subscribeV5() method on the ws client or use the original subscribe() method. + * + * Note: for private endpoints the "category" field is ignored since there is only one private endpoint + * (compared to one public one per category). + * The "category" is only needed for public topics since bybit has one endpoint for public events per category. + */ +⋮---- +// wsClient.subscribeV5('execution.fast', 'linear'); +// wsClient.subscribeV5('execution.fast.linear', 'linear'); +// wsClient.subscribeV5('execution.fast.spot', 'spot'); +// wsClient.subscribeV5('execution.fast.option', 'option'); +⋮---- +/** + * The following has the same effect as above, since there's only one private endpoint for V5 account topics: + */ +// wsClient.subscribe('position'); +// wsClient.subscribe('execution'); +// wsClient.subscribe(['order', 'wallet', 'greek']); +⋮---- +// To unsubscribe from topics (after a 5 second delay, in this example): +// setTimeout(() => { +// console.log('unsubscribing'); +// wsClient.unsubscribeV5('execution', 'linear'); +// }, 5 * 1000); +⋮---- +// Topics are tracked per websocket type +// Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) -```bash -pnpm install bybit-api -yarn add bybit-api -``` +================ +File: examples/Websocket/Public/ws-public-allLiquidations.ts +================ +import { + isWsAllLiquidationEvent, + RestClientV5, + WebsocketClient, +} from '../../../src'; +⋮---- +// or +// import { +// RestClientV5, +// WebsocketClient, +// isWsAllLiquidationEvent, +// } from 'bybit-api'; +⋮---- +function onAllLiquidationEvent(event: unknown) +⋮---- +/** + * + * If you want to receive data for all available symbols, this websocket topic + * requires you to subscribe to each symbol individually. + * + * This can be easily automated by fetching a list of symbols via the REST client, + * generating a list of topics (one per symbol), before simply passing an + * array of topics to the websocket client per product group (linear & inverse perps). + * + */ +async function start() +⋮---- +// Make an array of topics ready for submission +⋮---- +// subscribe to all linear symbols +⋮---- +// subscribe to all inverse symbols -Create API keys from the relevant Bybit page: +================ +File: examples/Websocket/Public/ws-public-v5.ts +================ +import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; +⋮---- +/** + * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: + * - Connections are opened when you subscribe to topics + * - If key & secret are provided, authentication is handled automatically + * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), + * subscription events are automatically routed to the different ws endpoints on bybit's side + * - Heartbeats/ping/pong/reconnects are all handled automatically. + * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. + */ +⋮---- +/** + * For public V5 topics, use the subscribeV5 method and include the API category this topic is for. + * Category is required, since each category has a different websocket endpoint. + */ +⋮---- +// Linear v5 +// -> Just one topic per call +// wsClient.subscribeV5('orderbook.50.BTCUSDT', 'linear'); +⋮---- +// -> Or multiple topics in one call +// wsClient.subscribeV5( +// ['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], +// 'linear' +// ); +⋮---- +// Inverse v5 +// wsClient.subscribeV5('orderbook.50.BTCUSD', 'inverse'); +⋮---- +// Spot v5 +// wsClient.subscribeV5('orderbook.50.BTCUSDT', 'spot'); +⋮---- +// Option v5 +// wsClient.subscribeV5('publicTrade.BTC', 'option'); +⋮---- +// Use the subscribeV5() call for most subscribe calls with v5 websockets +⋮---- +// Alternatively, you can also use objects in the wsClient.subscribe() call +// wsClient.subscribe({ +// topic: 'orderook.50.BTCUSDT', +// category: 'spot', +// }); +⋮---- +/** + * For private V5 topics, just call the same subscribeV5() method on the ws client or use the original subscribe() method. + * + * Note: for private endpoints the "category" field is ignored since there is only one private endpoint + * (compared to one public one per category) + */ +⋮---- +// wsClient.subscribeV5('position', 'linear'); +// wsClient.subscribeV5('execution', 'linear'); +// wsClient.subscribeV5(['order', 'wallet', 'greek'], 'linear'); +⋮---- +// To unsubscribe from topics (after a 5 second delay, in this example): +⋮---- +// Topics are tracked per websocket type +// Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) -- Bybit live API keys: [Bybit API Management](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1) -- Bybit testnet API keys: [Bybit Testnet API Management](https://testnet.bybit.com/app/user/api-management) -- Bybit demo trading notes: [Bybit Demo Trading Service](https://bybit-exchange.github.io/docs/v5/demo) - -> Always use the minimum permissions needed for your scenario. Trading does not require withdrawal permissions. Analytics does not require trading permissions. -> Always use strict IP whitelisting for API keys whenever your deployment environment allows it. - -The main auth and environment rules are: - -- Public market data does not usually require API keys. -- Private REST API calls require `key` and `secret`. -- Private WebSocket streams require `key` and `secret`. -- WebSocket API commands require `key` and `secret`. -- Live, testnet, and demo trading credentials are separate. -- API permissions must match the product and action your code is using. -- HMAC keys use a normal API key and API secret. -- RSA keys use a Bybit API key plus your PEM private key as `secret`. -- The SDK automatically detects RSA private keys when the secret contains a private-key PEM header. - -Typical environment variables: - -```bash -export BYBIT_API_KEY='your-api-key' -export BYBIT_API_SECRET='your-api-secret-or-rsa-private-key' -``` - -Create a private REST API client: - -```typescript -import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, -}); -``` - -If you are only testing public endpoints, you do not need keys: - -```typescript -import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5(); -``` - -For RSA setup details, see [examples/Auth/RSA-sign.md](../examples/Auth/RSA-sign.md). - ---- - -## Products and clients - -For new Bybit integrations, start with the current API. Older Bybit SDK surfaces were split into many product-specific clients; this SDK now centers the current API around one REST API client plus WebSocket clients. - -| Use case | SDK surface | Common usage | -| -------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -| REST API | `RestClientV5` | Public market data, account reads, order management, positions, wallet, asset transfers, user APIs, Earn, broker, P2P, RFQ, and other endpoint groups | -| Public and private streams | `WebsocketClient` | Live order books, trades, klines, tickers, liquidations, private orders, executions, positions, wallet, and greeks | -| WebSocket API commands | `WebsocketAPIClient` | Awaitable order create, amend, cancel, and batch order commands over Bybit's WebSocket API | -| Raw WebSocket API commands | `WebsocketClient.sendWSAPIRequest(...)` | Lower-level WebSocket API usage where you want to send an operation directly | - -The `category` parameter matters: - -| Category | Meaning | -| --------- | ----------------------------------------------- | -| `spot` | Spot market and Spot orders | -| `linear` | USDT and USDC linear contracts | -| `inverse` | Inverse perpetual and inverse futures contracts | -| `option` | Options | - -As a rule of thumb: - -- Use `RestClientV5` for current Bybit REST API endpoints. -- Use `WebsocketClient.subscribeV5(...)` when you want streaming data. -- Use `WebsocketAPIClient` when you want to send commands over WebSocket and await the response. -- Use `docs/endpointFunctionList.md` when you already know the Bybit endpoint path and need the matching SDK method. - -For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). - -### REST API, streams, and WebSocket API - -Bybit exposes several different integration flows. Keep them separate in your architecture: - -| Flow | SDK surface | Best for | What the SDK handles | -| ------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -| REST API | `RestClientV5` | Request/response calls, broad endpoint coverage, public reads, private account reads, order submission, reconciliation | Base URLs, timestamps, HMAC/RSA signing, headers, response parsing, optional rate-limit parsing | -| Public WebSocket streams | `WebsocketClient.subscribeV5(...)` | Real-time market data such as order books, trades, klines, tickers, and liquidations | Endpoint routing by category, subscribe requests, heartbeats, reconnects, resubscribe | -| Private WebSocket streams | `WebsocketClient.subscribeV5(...)` with keys | Account events such as orders, executions, wallet, positions, and greeks | Authentication, private endpoint routing, reconnects, resubscribe | -| WebSocket API commands | `WebsocketAPIClient` or `sendWSAPIRequest(...)` | Order create, amend, cancel, and batch order operations over a persistent WebSocket connection | Connection setup, authentication, request IDs, signing, promise resolution, response/error correlation | - -Use the REST API when you want maximum endpoint coverage or a simple one-off request. Use WebSocket streams when you need realtime lower-latency updates. Use the WebSocket API when you want a command path over an already-open WebSocket connection. - ---- - -## Start building: first calls - -If you only want the fastest path to a working integration, start here. - -### 1. First public REST API request - -```typescript -import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5(); - -async function main() { - const serverTime = await client.getServerTime(); - const instruments = await client.getInstrumentsInfo({ - category: 'linear', - symbol: 'BTCUSDT', - }); - const ticker = await client.getTickers({ - category: 'linear', - symbol: 'BTCUSDT', - }); - const orderBook = await client.getOrderbook({ - category: 'linear', - symbol: 'BTCUSDT', - limit: 50, - }); - const candles = await client.getKline({ - category: 'linear', - symbol: 'BTCUSDT', - interval: '1', - limit: 5, - }); - - console.log({ - serverTime, - instrument: instruments.result.list[0]?.symbol, - ticker: ticker.result.list[0], - orderBook, - candles, - }); +================ +File: src/types/request/v5-position.ts +================ +import { + CategoryV5, + ExecTypeV5, + OrderTriggerByV5, + OrderTypeV5, + PositionIdx, + TPSLModeV5, +} from '../shared-v5'; +⋮---- +export interface GetFuturesLeverageParamsV5 { + category: 'linear' | 'inverse'; + symbol?: string; } - -main().catch(console.error); -``` - -That confirms public REST API access is wired correctly. - -See also: [public REST API example](../examples/Rest/rest-v5-public.ts) - -### 2. First public WebSocket stream - -```typescript -import { WebsocketClient, isWsOrderbookEventV5 } from 'bybit-api'; - -const ws = new WebsocketClient(); - -ws.on('open', (data) => console.log('connected', data.wsKey, data.wsUrl)); -ws.on('response', (data) => console.log('response', JSON.stringify(data))); -ws.on('update', (data) => { - if (isWsOrderbookEventV5(data)) { - console.log('orderbook update', data.data.s, data.type); - return; - } - - console.log('stream update', JSON.stringify(data)); -}); -ws.on('reconnect', (data) => console.log('reconnecting', data.wsKey)); -ws.on('reconnected', (data) => console.log('reconnected', data.wsKey)); -ws.on('exception', console.error); - -ws.subscribeV5(['orderbook.50.BTCUSDT', 'tickers.BTCUSDT', 'publicTrade.BTCUSDT'], 'linear'); -``` - -For public streams, pass the category so the SDK can route the topic to the right public endpoint. - -See also: [public WebSocket example](../examples/Websocket/Public/ws-public-v5.ts) - -### 3. First private account WebSocket stream - -```typescript -import { WebsocketClient } from 'bybit-api'; - -const ws = new WebsocketClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, -}); - -ws.on('authenticated', (data) => { - console.log('authenticated', data.wsKey); -}); - -ws.on('update', (data) => { - console.log('account event', JSON.stringify(data)); -}); - -ws.on('reconnect', ({ wsKey }) => { - console.log('reconnecting', wsKey); -}); - -ws.on('reconnected', ({ wsKey }) => { - console.log('reconnected', wsKey); - // Fetch wallet, positions, open orders, or recent executions here if needed. -}); - -ws.on('exception', console.error); - -ws.subscribeV5(['order', 'execution', 'position', 'wallet'], 'linear'); -``` - -Private topics are routed to the private endpoint. The category argument is still required by `subscribeV5(...)`, but it is only used for public-topic routing. - -See also: [private WebSocket example](../examples/Websocket/Private/ws-private-v5.ts) - -### 4. First REST API order in demo trading - -Use demo trading before placing live orders. Demo trading uses a separate Bybit demo account and separate API keys. - -```typescript -import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - demoTrading: true, - throwExceptions: true, -}); - -async function placeDemoOrder() { - await client.requestDemoTradingFunds(); - - const orderRequest = { - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId: `demo-${Date.now()}`, - } as const; - - const result = await client.submitOrder(orderRequest); - console.log(result); +⋮---- +export interface PositionInfoParamsV5 { + category: CategoryV5; + symbol?: string; + baseCoin?: string; + settleCoin?: string; + limit?: number; + cursor?: string; } - -placeDemoOrder().catch(console.error); -``` - -This submits to Bybit demo trading because `demoTrading: true` is set. Do not remove that option or switch to live keys until you are ready to place real orders. - -For order workflows, prefer `throwExceptions: true` so non-zero Bybit API responses throw and can be handled in one structured catch path. If you intentionally set `throwExceptions: false`, a resolved REST promise can still be an exchange business rejection. Treat `retCode === 0` as acceptance and any non-zero `retCode` as a rejected or unknown submission state. - -See also: [Demo trading example](../examples/Rest/demo-trading.ts) - -### 5. First WebSocket API order command - -The WebSocket API lets you submit order commands over a persistent WebSocket connection and await responses. Bybit supports WebSocket API order commands in live and testnet environments, but not demo trading. - -```typescript -import { WebsocketAPIClient } from 'bybit-api'; - -const wsApi = new WebsocketAPIClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - // Use testnet API keys with this option. - testnet: true, -}); - -const wsClient = wsApi.getWSClient(); - -wsClient.on('open', (data) => console.log('ws api open', data.wsKey)); -wsClient.on('authenticated', (data) => { - console.log('ws api authenticated', data.wsKey); -}); -wsClient.on('exception', console.error); - -async function main() { - await wsClient.connectWSAPI(); - - if (process.env.BYBIT_PLACE_ORDER !== 'true') { - console.log('Set BYBIT_PLACE_ORDER=true when you are ready to submit.'); - return; - } - - const result = await wsApi.submitNewOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId: `wsapi-${Date.now()}`, - }); - - console.log(result); +⋮---- +export interface SetLeverageParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + buyLeverage: string; + sellLeverage: string; +} +⋮---- +export interface SwitchIsolatedMarginParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + tradeMode: 0 | 1; + buyLeverage: string; + sellLeverage: string; +} +⋮---- +export interface SetTPSLModeParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + tpSlMode: TPSLModeV5; +} +⋮---- +export interface SwitchPositionModeParamsV5 { + category: 'linear' | 'inverse'; + symbol?: string; + coin?: string; + mode: 0 | 3; +} +⋮---- +export interface SetRiskLimitParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + riskId: number; + positionIdx?: PositionIdx; +} +⋮---- +export interface SetTradingStopParamsV5 { + category: CategoryV5; + symbol: string; + takeProfit?: string; + stopLoss?: string; + trailingStop?: string; + tpTriggerBy?: OrderTriggerByV5; + slTriggerBy?: OrderTriggerByV5; + activePrice?: string; + tpslMode?: TPSLModeV5; + tpSize?: string; + slSize?: string; + tpLimitPrice?: string; + slLimitPrice?: string; + tpOrderType?: OrderTypeV5; + slOrderType?: OrderTypeV5; + positionIdx: PositionIdx; +} +⋮---- +export interface SetAutoAddMarginParamsV5 { + category: 'linear'; + symbol: string; + autoAddMargin: 0 | 1; + positionIdx?: PositionIdx; +} +⋮---- +export interface AddOrReduceMarginParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + margin: string; + positionIDex?: PositionIdx; +} +⋮---- +export interface GetExecutionListParamsV5 { + category: CategoryV5; + symbol?: string; + orderId?: string; + orderLinkId?: string; + baseCoin?: string; + settleCoin?: string; // Settle coin, uppercase only. For linear, inverse, option + startTime?: number; + endTime?: number; + execType?: ExecTypeV5; + limit?: number; + cursor?: string; +} +⋮---- +settleCoin?: string; // Settle coin, uppercase only. For linear, inverse, option +⋮---- +export interface GetClosedPnLParamsV5 { + category: CategoryV5; + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +export interface MovePositionParamsV5 { + fromUid: string; + toUid: string; + list: { + category: 'linear' | 'spot' | 'option' | 'inverse'; + symbol: string; + price: string; + side: 'Buy' | 'Sell'; + qty: string; + }[]; +} +⋮---- +export interface GetMovePositionHistoryParamsV5 { + category?: 'linear' | 'spot' | 'option'; + symbol?: string; + startTime?: number; + endTime?: number; + status?: 'Processing' | 'Filled' | 'Rejected'; + blockTradeId?: string; + limit?: string; + cursor?: string; +} +⋮---- +export interface ConfirmNewRiskLimitParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; +} +⋮---- +export interface GetClosedOptionsPositionsParamsV5 { + category: 'option'; + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } -main().catch(console.error); -``` - -The WebSocket API acknowledgement tells you the command was accepted. Track the final order state through the private `order` and `execution` streams, or reconcile with the REST API. - -See also: [WebSocket API client example](../examples/Websocket/WS-API/ws-api-client.ts) - ---- - -## REST API - -Most Bybit integrations start with `RestClientV5`. It covers the current REST API surface and uses Bybit's `category` parameter to distinguish product groups where the endpoint requires it. - -### Create a public `RestClientV5` - -```typescript -import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5(); -``` - -Public market calls do not require keys. - -### Create a private `RestClientV5` - -```typescript -import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - recv_window: 5000, - parseAPIRateLimits: true, -}); -``` - -Private REST API methods are signed automatically. You do not need to add timestamps, signatures, `X-BAPI-API-KEY` or `X-BAPI-SIGN` headers yourself. - -### Common public market data calls - -```typescript -const serverTime = await client.getServerTime(); - -const instruments = await client.getInstrumentsInfo({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -const orderBook = await client.getOrderbook({ - category: 'linear', - symbol: 'BTCUSDT', - limit: 50, -}); - -const ticker = await client.getTickers({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -const candles = await client.getKline({ - category: 'linear', - symbol: 'BTCUSDT', - interval: '5', - limit: 10, -}); - -const recentTrades = await client.getPublicTradingHistory({ - category: 'linear', - symbol: 'BTCUSDT', - limit: 10, -}); - -const funding = await client.getFundingRateHistory({ - category: 'linear', - symbol: 'BTCUSDT', - limit: 10, -}); - -const openInterest = await client.getOpenInterest({ - category: 'linear', - symbol: 'BTCUSDT', - intervalTime: '15min', -}); -``` - -For Spot market data, use `category: 'spot'`. For inverse contracts, use `category: 'inverse'`. For options, use `category: 'option'` where the endpoint supports it. - -### Common private account and order calls - -```typescript -const accountInfo = await client.getAccountInfo(); -const systemStatus = await client.getSystemStatus(); - -const wallet = await client.getWalletBalance({ - accountType: 'UNIFIED', -}); - -const positions = await client.getPositionInfo({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -const openOrders = await client.getActiveOrders({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -const orderHistory = await client.getHistoricOrders({ - category: 'linear', - symbol: 'BTCUSDT', - limit: 20, -}); - -const executions = await client.getExecutionList({ - category: 'linear', - symbol: 'BTCUSDT', - limit: 20, -}); +================ +File: src/types/request/v5-rfq.ts +================ +export interface RFQTransactionV5 { + category: 'spot' | 'linear' | 'inverse' | 'option'; // Product type + symbol: string; // Name of the trading contract + side: 'buy' | 'sell'; // Inquiry transaction direction + qty: string; // Transaction quantity + isLeverage?: boolean; // For spot lending, default false +} +⋮---- +category: 'spot' | 'linear' | 'inverse' | 'option'; // Product type +symbol: string; // Name of the trading contract +side: 'buy' | 'sell'; // Inquiry transaction direction +qty: string; // Transaction quantity +isLeverage?: boolean; // For spot lending, default false +⋮---- +export interface RFQHedgeLegV5 { + category: string; + symbol: string; + side: string; + qty: string; + price?: string; +} +⋮---- +export interface CreateRFQParamsV5 { + counterparties: string[]; // Array of deskCode + rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters + anonymous?: boolean; // Whether it is anonymous inquiry, default false + strategyType?: string; // Inquiry label, max 36 characters + list: RFQTransactionV5[]; // Transaction list, up to 10 sets + hedge?: RFQHedgeLegV5[]; +} +⋮---- +counterparties: string[]; // Array of deskCode +rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters +anonymous?: boolean; // Whether it is anonymous inquiry, default false +strategyType?: string; // Inquiry label, max 36 characters +list: RFQTransactionV5[]; // Transaction list, up to 10 sets +⋮---- +export interface CancelRFQParamsV5 { + rfqId?: string; // Inquiry ID + rfqLinkId?: string; // Inquiry Custom ID +} +⋮---- +rfqId?: string; // Inquiry ID +rfqLinkId?: string; // Inquiry Custom ID +⋮---- +export interface RFQQuoteV5 { + category: 'spot' | 'linear' | 'option'; // Product type + symbol: string; // Name of the trading contract + price: string; // Quote price + isLeverage?: boolean; // For spot lending, default false +} +⋮---- +category: 'spot' | 'linear' | 'option'; // Product type +symbol: string; // Name of the trading contract +price: string; // Quote price +isLeverage?: boolean; // For spot lending, default false +⋮---- +export interface CreateRFQQuoteParamsV5 { + rfqId: string; // Inquiry ID + quoteLinkId?: string; // Quotation custom ID, 1-32 characters + anonymous?: boolean; // Whether it is anonymous quotation, default false + expiresIn?: number; // Validity period in seconds, default 60 + quoteBuyList?: RFQQuoteV5[]; // Quotation buy direction + quoteSellList?: RFQQuoteV5[]; // Quotation sell direction +} +⋮---- +rfqId: string; // Inquiry ID +quoteLinkId?: string; // Quotation custom ID, 1-32 characters +anonymous?: boolean; // Whether it is anonymous quotation, default false +expiresIn?: number; // Validity period in seconds, default 60 +quoteBuyList?: RFQQuoteV5[]; // Quotation buy direction +quoteSellList?: RFQQuoteV5[]; // Quotation sell direction +⋮---- +export interface ExecuteRFQQuoteParamsV5 { + rfqId: string; // Inquiry ID + quoteId: string; // Quotation ID + quoteSide: 'buy' | 'sell'; // The direction of the quote + isHedge?: boolean; +} +⋮---- +rfqId: string; // Inquiry ID +quoteId: string; // Quotation ID +quoteSide: 'buy' | 'sell'; // The direction of the quote +⋮---- +export interface GetRFQDetailsParamsV5 { + rfqId?: string; + rfqLinkId?: string; + status?: + | 'Active' + | 'PendingFill' + | 'Canceled' + | 'Filled' + | 'Expired' + | 'Failed'; + traderType?: 'quote' | 'request'; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +export interface CancelRFQQuoteParamsV5 { + quoteId?: string; // Quotation ID + rfqId?: string; // Inquiry ID + quoteLinkId?: string; // Quotation Custom ID +} +⋮---- +quoteId?: string; // Quotation ID +rfqId?: string; // Inquiry ID +quoteLinkId?: string; // Quotation Custom ID +⋮---- +export interface GetRFQRealtimeParamsV5 { + rfqId?: string; // Inquiry ID + rfqLinkId?: string; // Inquiry Custom ID + traderType?: 'quote' | 'request'; // Trader type, default 'request' +} +⋮---- +rfqId?: string; // Inquiry ID +rfqLinkId?: string; // Inquiry Custom ID +traderType?: 'quote' | 'request'; // Trader type, default 'request' +⋮---- +export interface GetRFQListParamsV5 { + rfqId?: string; // Inquiry ID + rfqLinkId?: string; // Custom ID for inquiry form + traderType?: 'quoter' | 'request'; // Trader type, default 'request' + status?: + | 'Active' + | 'Canceled' + | 'PendingFill' + | 'Filled' + | 'Expired' + | 'Failed'; // Status of the inquiry form + limit?: number; // Return number of items, max 100, default 50 + cursor?: string; // Page turning mark +} +⋮---- +rfqId?: string; // Inquiry ID +rfqLinkId?: string; // Custom ID for inquiry form +traderType?: 'quoter' | 'request'; // Trader type, default 'request' +⋮---- +| 'Failed'; // Status of the inquiry form +limit?: number; // Return number of items, max 100, default 50 +cursor?: string; // Page turning mark +⋮---- +export interface GetRFQQuoteRealtimeParamsV5 { + rfqId?: string; // Inquiry ID + quoteId?: string; // Quotation ID + quoteLinkId?: string; // Quotation Custom ID + traderType?: 'quote' | 'request'; // Trader type, default 'quote' +} +⋮---- +rfqId?: string; // Inquiry ID +quoteId?: string; // Quotation ID +quoteLinkId?: string; // Quotation Custom ID +traderType?: 'quote' | 'request'; // Trader type, default 'quote' +⋮---- +export interface GetRFQHistoryParamsV5 { + rfqId?: string; // Inquiry ID + quoteId?: string; // Quotation ID + quoteLinkId?: string; // Quotation custom ID, can only check last 3 months + traderType?: 'quote' | 'request'; // Trader type, default 'quote' + status?: + | 'Active' + | 'Canceled' + | 'PendingFill' + | 'Filled' + | 'Expired' + | 'Failed'; // Status of quotation + limit?: number; // Return number of items, max 100, default 50 + cursor?: string; // Page turning mark +} +⋮---- +rfqId?: string; // Inquiry ID +quoteId?: string; // Quotation ID +quoteLinkId?: string; // Quotation custom ID, can only check last 3 months +traderType?: 'quote' | 'request'; // Trader type, default 'quote' +⋮---- +| 'Failed'; // Status of quotation +limit?: number; // Return number of items, max 100, default 50 +cursor?: string; // Page turning mark +⋮---- +export interface GetRFQTradeListParamsV5 { + rfqId?: string; // Inquiry ID + rfqLinkId?: string; // Custom ID for inquiry form, can only check last 3 months + quoteId?: string; // Quotation ID + quoteLinkId?: string; // Quotation custom ID, can only check last 3 months + status?: 'Filled' | 'Rejected'; // Status + limit?: number; // Return number of items, max 100, default 50 + cursor?: string; // Page turning mark +} +⋮---- +rfqId?: string; // Inquiry ID +rfqLinkId?: string; // Custom ID for inquiry form, can only check last 3 months +quoteId?: string; // Quotation ID +quoteLinkId?: string; // Quotation custom ID, can only check last 3 months +status?: 'Filled' | 'Rejected'; // Status +limit?: number; // Return number of items, max 100, default 50 +cursor?: string; // Page turning mark +⋮---- +export interface GetRFQPublicTradesParamsV5 { + startTime?: number; // Timestamp in milliseconds, time range is 7 days + endTime?: number; // Timestamp in milliseconds, time range is 7 days + limit?: number; // Return number of items, max 100, default 50 + cursor?: string; // Page turning mark +} +⋮---- +startTime?: number; // Timestamp in milliseconds, time range is 7 days +endTime?: number; // Timestamp in milliseconds, time range is 7 days +limit?: number; // Return number of items, max 100, default 50 +cursor?: string; // Page turning mark +⋮---- +export interface AcceptNonLPQuoteParamsV5 { + rfqId: string; // Inquiry ID +} +⋮---- +rfqId: string; // Inquiry ID -const feeRate = await client.getFeeRate({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -const transactions = await client.getTransactionLog({ - accountType: 'UNIFIED', -}); -``` - -See also: - -- [Private REST API example](../examples/Rest/rest-v5-private.ts) -- [Cursor pagination example](../examples/Rest/rest-v5-next-cursor.ts) -- [Endpoint function map](./endpointFunctionList.md) - -### Order examples - -Market order: - -```typescript -await client.submitOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Market', - qty: '0.001', - orderLinkId: `market-${Date.now()}`, -}); -``` - -Limit order: - -```typescript -await client.submitOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'GTC', - orderLinkId: `limit-${Date.now()}`, -}); -``` - -Post-only limit order: - -```typescript -await client.submitOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId: `postonly-${Date.now()}`, -}); -``` - -Amend an order: - -```typescript -await client.amendOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderId: 'existing-order-id', - price: '11000', - qty: '0.002', -}); -``` - -Cancel an order: - -```typescript -await client.cancelOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderId: 'existing-order-id', -}); -``` - -Cancel open orders for a category and symbol: - -```typescript -await client.cancelAllOrders({ - category: 'linear', - symbol: 'BTCUSDT', -}); -``` - -Batch submit orders: - -```typescript -await client.batchSubmitOrders('linear', [ - { - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId: `batch-a-${Date.now()}`, - }, - { - symbol: 'ETHUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.01', - price: '1000', - timeInForce: 'PostOnly', - orderLinkId: `batch-b-${Date.now()}`, - }, -]); -``` - -Pre-check an order where your account mode and product support it: - -```typescript -await client.preCheckOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', -}); -``` - -Bybit order acknowledgements are asynchronous. After submitting, use private WebSocket `order` and `execution` events, or REST API reads such as `getActiveOrders(...)`, `getHistoricOrders(...)`, and `getExecutionList(...)`, to track what actually happened. - -### Positions and risk - -```typescript -const positions = await client.getPositionInfo({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -await client.setLeverage({ - category: 'linear', - symbol: 'BTCUSDT', - buyLeverage: '3', - sellLeverage: '3', -}); - -await client.switchPositionMode({ - category: 'linear', - coin: 'USDT', - mode: 3, -}); - -await client.setTradingStop({ - category: 'linear', - symbol: 'BTCUSDT', - positionIdx: 0, - stopLoss: '25000', - slTriggerBy: 'LastPrice', -}); - -const closedPnl = await client.getClosedPnL({ - category: 'linear', - symbol: 'BTCUSDT', -}); -``` - -Position mode, margin mode, leverage, risk limit, and TP/SL behavior are account-sensitive. Read your current state first, then apply changes intentionally. - -### Wallet, assets, and transfers - -```typescript -const wallet = await client.getWalletBalance({ - accountType: 'UNIFIED', -}); - -const allCoins = await client.getAllCoinsBalance({ - accountType: 'UNIFIED', - coin: 'USDT,BTC', -}); - -const coinBalance = await client.getCoinBalance({ - accountType: 'UNIFIED', - coin: 'USDT', -}); - -const transferableCoins = await client.getTransferableCoinList('UNIFIED', 'FUND'); - -const deposits = await client.getDepositRecords({ - coin: 'USDT', -}); - -const withdrawals = await client.getWithdrawalRecords({ - coin: 'USDT', -}); -``` - -Withdrawal and transfer permissions are high risk. Keep those on separate keys where possible, and do not grant withdrawal permissions to trading services that do not need them. - -### Other endpoint groups - -`RestClientV5` also includes many specialized parts of the Bybit API. The most useful way to find the exact method is usually the [endpoint map](./endpointFunctionList.md), but the groups below show the shape of the surface: - -| Group | Example SDK methods | -| -------------------- | ------------------------------------------------------------------------------------------------- | -| Spread trading | `getSpreadInstrumentsInfo(...)`, `submitSpreadOrder(...)`, `cancelAllSpreadOrders(...)` | -| Spot margin | `toggleSpotMarginTrade(...)`, `setSpotMarginLeverageV2(...)`, `getSpotMarginLoanAccountInfo(...)` | -| Crypto loans | `borrowCryptoLoan(...)`, `repayCryptoLoan(...)`, `getUnpaidLoanOrders(...)` | -| Earn | `getEarnProduct(...)`, `submitStakeRedeem(...)`, `getEarnPosition(...)` | -| Broker and affiliate | `getBrokerRateLimitCap(...)`, `setBrokerRateLimit(...)`, `getAffiliateUserList(...)` | -| User and sub-account | `getSubUIDList(...)`, `createSubMember(...)`, `createSubUIDAPIKey(...)` | -| Convert | `requestConvertQuote(...)`, `confirmConvertQuote(...)`, `getConvertHistory(...)` | -| P2P | `getP2POrders(...)`, `sendP2POrderMessage(...)`, `uploadP2PChatFile(...)` | -| RFQ | `createRFQ(...)`, `createRFQQuote(...)`, `executeRFQQuote(...)` | - -If an endpoint exists in Bybit's API docs, search for the endpoint path or method group in [docs/endpointFunctionList.md](./endpointFunctionList.md). - ---- - -## WebSocket Streams - -Use `WebsocketClient` when you want event-driven updates instead of REST API polling. The same client handles public streams, private account streams, and raw WebSocket API commands. - -Typical setup is: create a client, attach event handlers, provide keys if private topics are needed, and subscribe to topics. The SDK opens the correct endpoint, authenticates when needed, sends subscribe requests, tracks topics, monitors heartbeats, reconnects dropped sockets, and resubscribes cached topics after reconnect. - -### Common `WebsocketClient` events - -| Event | Meaning | -| --------------- | ----------------------------------------------------------------- | -| `open` | Connection established | -| `update` | Streaming topic data received | -| `response` | Subscribe, unsubscribe, auth, or WebSocket API acknowledgement | -| `reconnect` | Connection dropped and the SDK is replacing it | -| `reconnected` | Replacement connection opened and cached subscriptions can resume | -| `close` | Socket closed | -| `authenticated` | Private authentication succeeded | -| `exception` | Errors and unexpected conditions | - -Use `exception`, not the deprecated `error` event. - -### Understanding `WS_KEY_MAP` - -[`WS_KEY_MAP`](/reference/glossary#ws-key) tells the SDK which Bybit WebSocket endpoint family a connection belongs to: - -| Key | Use | -| ----------------- | -------------------------- | -| `v5SpotPublic` | Spot public market data | -| `v5LinearPublic` | Linear public market data | -| `v5InversePublic` | Inverse public market data | -| `v5OptionPublic` | Options public market data | -| `v5Private` | Private account streams | -| `v5PrivateTrade` | WebSocket API commands | - -You normally do not need to pass these keys when subscribing to ordinary topics. `subscribeV5(...)` derives the correct connection from the topic and category. They are still useful for diagnostics, explicit connection calls, inspecting the internal topic store, and lower-level WebSocket API usage. - -### Public topics - -```typescript -import { WebsocketClient } from 'bybit-api'; - -const ws = new WebsocketClient(); - -ws.on('update', (data) => console.log('public update', JSON.stringify(data))); -ws.on('exception', console.error); - -ws.subscribeV5( - ['orderbook.50.BTCUSDT', 'publicTrade.BTCUSDT', 'tickers.BTCUSDT', 'kline.5.BTCUSDT'], - 'linear', -); -``` - -For Spot: - -```typescript -ws.subscribeV5(['orderbook.50.BTCUSDT', 'tickers.BTCUSDT'], 'spot'); -``` - -For inverse: - -```typescript -ws.subscribeV5(['orderbook.50.BTCUSD', 'tickers.BTCUSD'], 'inverse'); -``` - -For options: - -```typescript -ws.subscribeV5('publicTrade.BTC', 'option'); -``` - -See also: - -- [public WebSocket example](../examples/Websocket/Public/ws-public-v5.ts) -- [All liquidations WebSocket example](../examples/Websocket/Public/ws-public-allLiquidations.ts) - -### Private topics - -```typescript -import { WebsocketClient } from 'bybit-api'; - -const ws = new WebsocketClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, -}); - -ws.on('authenticated', (data) => console.log('authenticated', data.wsKey)); -ws.on('update', (data) => console.log('private update', JSON.stringify(data))); -ws.on('exception', console.error); - -ws.subscribeV5(['order', 'execution', 'position', 'wallet', 'greeks'], 'linear'); -``` - -Private topics currently share the private endpoint. The category parameter is ignored for private routing, but passing the category keeps your code consistent with `subscribeV5(...)`. - -### Unsubscribe and connection cleanup - -```typescript -ws.unsubscribeV5('kline.5.BTCUSDT', 'linear'); - -// Close all active WebSocket connections when shutting down a process. -ws.closeAll(); -``` - -`unsubscribeV5(...)` removes the topic from the SDK's subscription cache, so it will not be resubscribed after a reconnect. - -### Multiple connections for load isolation - -The SDK groups topics by Bybit endpoint. If you want to isolate heavy streams, create separate client instances and split topics yourself: - -```typescript -const marketDataA = new WebsocketClient(); -const marketDataB = new WebsocketClient(); - -marketDataA.subscribeV5(['orderbook.50.BTCUSDT'], 'linear'); -marketDataB.subscribeV5(['kline.1.BTCUSDT', 'publicTrade.BTCUSDT'], 'linear'); -``` - -Do not subscribe to the same topic in multiple clients unless you intentionally want duplicate events. - ---- - -## WebSocket API - -Bybit's WebSocket API is a request/response API over a persistent WebSocket connection. In this SDK, you can use it in two ways: - -- `WebsocketAPIClient` for promise-driven methods such as `submitNewOrder(...)`, `amendOrder(...)`, and `cancelOrder(...)`. -- `WebsocketClient.sendWSAPIRequest(...)` for lower-level operation calls such as `order.create`. - -The promise-driven client is the easiest place to start. - -```typescript -import { WebsocketAPIClient } from 'bybit-api'; - -const wsApi = new WebsocketAPIClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - // Use testnet API keys with this option. - testnet: true, -}); - -await wsApi.getWSClient().connectWSAPI(); - -const createResult = await wsApi.submitNewOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId: `wsapi-${Date.now()}`, -}); - -console.log(createResult); -``` - -Amend and cancel: - -```typescript -await wsApi.amendOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderId: createResult.data.orderId, - price: '11000', -}); - -await wsApi.cancelOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderId: createResult.data.orderId, -}); -``` - -Batch commands: - -```typescript -await wsApi.batchSubmitOrders('linear', [ - { - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId: `wsapi-batch-a-${Date.now()}`, - }, -]); -``` - -Raw command style: - -```typescript -import { WS_KEY_MAP, WebsocketClient } from 'bybit-api'; - -const ws = new WebsocketClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - testnet: true, -}); - -const result = await ws.sendWSAPIRequest(WS_KEY_MAP.v5PrivateTrade, 'order.create', { - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', -}); - -console.log(result); -``` - -Bybit's WebSocket API response means the request was accepted for processing. Use private streams to confirm order status and executions. - -See also: - -- [WebSocket API client example](../examples/Websocket/WS-API/ws-api-client.ts) -- [Raw WebSocket API promises example](../examples/Websocket/WS-API/ws-api-raw-promises.ts) -- [Raw WebSocket API events example](../examples/Websocket/WS-API/ws-api-raw-events.ts) -- [Bybit WebSocket API guideline](https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline) - ---- - -## Environments and regions - -### Live - -Live is the default environment: - -```typescript -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, -}); -``` - -### Testnet - -Testnet uses separate credentials and separate API domains: - -```typescript -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - testnet: true, -}); - -const ws = new WebsocketClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - testnet: true, -}); -``` - -Use testnet for endpoint wiring, permissions, and safe integration checks. Do not treat testnet market behavior as representative of live market behavior. - -### Demo trading - -Demo trading uses a mainnet demo account with simulated trading and separate demo keys. - -```typescript -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - demoTrading: true, -}); -``` - -Private demo WebSocket streams are also supported: - -```typescript -const ws = new WebsocketClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - demoTrading: true, -}); - -ws.subscribeV5(['order', 'execution', 'position', 'wallet'], 'linear'); -``` - -Do not combine `testnet: true` with `demoTrading: true`. Bybit's demo trading docs also note that WebSocket API commands are not supported in demo trading, so use REST API demo trading or private demo streams for demo workflows, and use testnet for WebSocket API command testing. - -### Regional REST API domains - -By default, REST API calls use the global Bybit domain. If your account belongs to a regional Bybit domain, set `apiRegion`: - -```typescript -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - apiRegion: 'EU', -}); -``` - -Supported API region values in this SDK: - -- `default` -- `bytick` -- `NL` -- `TK` -- `KZ` -- `HK` -- `GE` -- `UAE` -- `EU` - -New API regions will be supported as they become available. If you're looking for a region not yet supported, please get in touch. - -You can also pass `baseUrl` for a custom REST API domain, or `wsUrl` for a custom WebSocket URL when needed. - -See also: [custom REST API URL example](../examples/Rest/rest-v5-custom-url.ts) - ---- - -## Production notes - -Before a Bybit integration trades unattended, make these decisions explicit. - -### 1. Roll out in layers - -Move from read-only behavior to order placement one layer at a time: - -1. Public REST API calls -2. Public WebSocket streams -3. Private REST API account reads -4. Private WebSocket account streams -5. Demo or testnet order placement -6. Tiny live trading tests - -Keep each layer observable before adding the next one. - -### 2. Reconnect, then backfill - -Listen for `reconnect` and `reconnected`. A dropped WebSocket connection is a normal production condition, especially during volatility or scheduled exchange-side disconnects. - -When the SDK emits `reconnect`, pause risky actions if your strategy depends on stream state. When it emits `reconnected`, query the REST API for the account state you may have missed: - -```typescript -ws.on('reconnected', async ({ wsKey }) => { - console.log('reconnected', wsKey); - - const [wallet, positions, regularOpenOrders, stopOpenOrders] = await Promise.all([ - client.getWalletBalance({ accountType: 'UNIFIED' }), - client.getPositionInfo({ category: 'linear', settleCoin: 'USDT' }), - client.getActiveOrders({ - category: 'linear', - settleCoin: 'USDT', - openOnly: 0, - orderFilter: 'Order', - }), - client.getActiveOrders({ - category: 'linear', - settleCoin: 'USDT', - openOnly: 0, - orderFilter: 'StopOrder', - }), - ]); - - const openOrders = [ - ...(regularOpenOrders.result?.list ?? []), - ...(stopOpenOrders.result?.list ?? []), - ]; - - // Reconcile these with your local state before resuming risky actions. - console.log({ wallet, positions, openOrders }); -}); -``` - -For linear position managers that depend on conditional stop orders, do not assume the no-`orderFilter` active-order response covers both regular orders and `StopOrder` rows unless you have captured and verified that response shape for the account mode. - -### 3. Check Bybit business acceptance - -TypeScript validates the request fields you pass to the SDK. It does not prove that Bybit accepted a live request, private stream payload, or hydrated order state. For order-management services, prefer `throwExceptions: true` on `RestClientV5` so non-zero Bybit `retCode` responses throw and flow through your normal SDK/API error classifier. Preserve `retCode`, `retMsg`, `result`, request context, and product/symbol scope from the thrown error where available. - -If you intentionally use `throwExceptions: false`, business rejections resolve as response objects and must be classified manually: - -```typescript -type BybitResponse = { - retCode: number; - retMsg: string; - result: T; -}; - -function classifyBybitResponse(response: BybitResponse) { - if (response.retCode === 0) return { ok: true as const, response }; - - return { - ok: false as const, - code: response.retCode, - message: response.retMsg, - response, - }; -} -``` - -For order-management services, stop later non-sent intents on any Bybit business rejection, log the sanitized error or response, block or surface deterministic request failures, and reconcile before submitting later exposure. - -### 4. Include `triggerDirection` for conditional stops - -For Bybit V5 triggered stop-loss orders, verify the current request type and include `triggerDirection`. For a long position, the stop-loss exit usually sells when price falls to the trigger, so `triggerDirection` is `2`. For a short position, the stop-loss exit usually buys when price rises to the trigger, so `triggerDirection` is `1`. - -```typescript -await client.submitOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Sell', - orderType: 'Market', - qty: '0.001', - triggerPrice: '60000', - triggerDirection: 2, - triggerBy: 'MarkPrice', - orderFilter: 'StopOrder', - positionIdx: 0, - reduceOnly: true, - closeOnTrigger: true, - orderLinkId: `long-sl-${Date.now()}`, -}); -``` - -Hydrated active orders may include explicit defaults such as `closeOnTrigger: false`, `reduceOnly: false`, empty trigger fields, or stop-order defaults that were omitted from your original request. Compare desired and hydrated orders by order kind and normalize irrelevant defaults before deciding to cancel and replace an app-owned order. - -### 5. Watch clocks and receive windows - -Private requests are timestamp-sensitive. Keep your system clock synced first. If you still see receive-window errors, set the receive window intentionally. - -REST API calls use `recv_window`: - -```typescript -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - recv_window: 5000, -}); - -await client.fetchLatencySummary(); -``` - -WebSockets use `recvWindow`: - -```typescript -const ws = new WebsocketClient({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - recvWindow: 5000, -}); - -ws.setTimeOffsetMs(-500); -``` - -Use time offsets as a last resort. Fix host clock sync first. Refer to the timestamp guidance if you're having persistent issues with it: https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow - -### 6. Keep credentials scoped - -Live, testnet, and demo credentials are different. Keep them separate in your secrets manager and deployment configuration. - -Use separate keys for separate risk levels: - -- Read-only market and account monitoring. -- Trading without withdrawals. -- Transfers or withdrawals, only where absolutely required. - -Do not put private keys in frontend code. Use IP whitelisting. - -### 7. Monitor rate limits - -The SDK can parse Bybit REST API rate-limit headers into responses when `parseAPIRateLimits: true` is enabled: - -```typescript -const client = new RestClientV5({ - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - parseAPIRateLimits: true, -}); - -const response = await client.getPositionInfo({ - category: 'linear', - symbol: 'BTCUSDT', -}); - -console.log(response.rateLimitApi); -``` - -Bybit also returns rate-limit information in WebSocket API response headers. Use that data to reduce polling, back off safely, and prefer streaming updates where possible. - -### 8. Inject your own logger if needed - -If you want SDK logs in your own monitoring stack, pass a logger: - -```typescript -import { DefaultLogger, WebsocketClient } from 'bybit-api'; - -const customLogger: typeof DefaultLogger = { - ...DefaultLogger, - trace: () => {}, - info: (...params) => console.info(new Date(), ...params), - error: (...params) => console.error(new Date(), ...params), -}; - -const ws = new WebsocketClient( - { - key: process.env.BYBIT_API_KEY!, - secret: process.env.BYBIT_API_SECRET!, - }, - customLogger, -); -``` - -For raw HTTP request/response tracing during local debugging, the repo also supports the `BYBITTRACE` environment variable. Do not enable verbose tracing in production logs if it could expose sensitive request data. - ---- - -## FAQ - -**Do I need API keys for public market data?** - -No. Public REST API market data and public WebSocket market data do not usually require API keys. - -**Which REST API client should I use?** - -Use `RestClientV5` for new Bybit API work. `SpotClientV3` remains in the package for legacy compatibility, but new integrations should use the current API surface. - -**Why does every example use `category`?** - -The Bybit API uses `category` to distinguish Spot, Linear, Inverse, and Options behavior. The same SDK method can often cover several product groups, so the category tells Bybit which product family the request belongs to. Refer to Bybit's API documentation for exact guidance on expected request parameters. - -**Why both `WebsocketClient` and `WebsocketAPIClient`?** - -- `WebsocketClient` is for subscriptions and streaming topics. -- `WebsocketAPIClient` is for commands over Bybit's WebSocket API. Think request/response methods over a persistent WebSocket connection. - -**Can I use one key for everything?** - -Only if the key belongs to the correct environment and has the required permissions. For production systems, keep keys scoped by environment and permission level. Avoid withdrawal permissions unless your service truly needs them. - -**Does the SDK support RSA authentication?** - -Yes. Pass your Bybit API key as `key` and your PEM private key as `secret`. The SDK detects RSA private keys automatically. - -**Should I use demo trading or testnet?** - -Use demo trading for simulated trading with live-like market context where Bybit supports the endpoint. Use testnet for API wiring and WebSocket API command testing. Do not use testnet market behavior as evidence that a strategy will behave well live. Read more about CEX testnets here: https://github.com/sieblyio/awesome-crypto-examples/wiki/CEX-Testnets - -**What happens if a WebSocket connection drops?** - -The SDK detects dead connections, opens a replacement connection, authenticates where needed, and resubscribes cached topics. Listen for `reconnect` and `reconnected`, then reconcile state with the REST API before resuming risky trading actions. - -**Does this guide cover every SDK method?** - -No. This guide covers the common first steps and production concerns. For full method coverage, see: - -- [Bybit JavaScript endpoint reference](./endpointFunctionList.md) -- [Bybit SDK examples](../examples) -- [TSDoc documentation](https://tsdocs.dev/docs/bybit-api) - ---- - -## Next steps - -If you want to learn more about integrating with the Bybit API and WebSockets: - -- Explore the [Bybit JavaScript examples on GitHub](../examples) -- Review the full endpoint list: [Bybit JavaScript endpoint reference](./endpointFunctionList.md) -- Check the Bybit JavaScript SDK on npm: [`bybit-api`](https://www.npmjs.com/package/bybit-api) -- Browse the source code of the Bybit JavaScript SDK on GitHub: [`tiagosiebler/bybit-api`](https://github.com/tiagosiebler/bybit-api) -- Review RSA auth: [Bybit RSA authentication example](../examples/Auth/RSA-sign.md) -- Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) - -================ -File: examples/Rest/rest-v5-proxies2.ts -================ -import { HttpsProxyAgent } from 'https-proxy-agent'; -⋮---- -import { RestClientV5 } from '../../src/index'; -⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; -⋮---- -/** - * Some proxy services don't work with the proxy configuration that axios supports. - * - * For these, you can try using HttpsProxyAgent or SocksProxyAgent (depending on your proxy type, HTTP or SOCKS). - * - * The following example uses the HttpsProxyAgent (via the npm module https-proxy-agent). - */ -⋮---- -// Sometimes using a proxy introduces recv timestamp errors (due to the extra latency) -// If that happens, you can try increasing the recv window (which is 5000ms by default) -// recv_window: 10000, - -================ -File: examples/Websocket/Private/ws-private-v5.ts -================ -/* eslint-disable @typescript-eslint/no-empty-function */ -import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; -⋮---- -// Create & inject a custom logger to enable the trace logging level (empty function) -⋮---- -// trace: (...params) => console.log('trace', ...params), -⋮---- -/** - * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: - * - Connections are opened when you subscribe to topics - * - If key & secret are provided, authentication is handled automatically - * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), - * subscription events are automatically routed to the different ws endpoints on bybit's side - * - Heartbeats/ping/pong/reconnects are all handled automatically. - * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. - */ -⋮---- -// testnet: false, -// demoTrading: false, // set testnet to false, if you plan on using demo trading -⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); -⋮---- -// wsClient.on('exception', (data) => { -// console.error('ws exception: ', data); -// }); -⋮---- -/** - * For private V5 topics, us the subscribeV5() method on the ws client or use the original subscribe() method. - * - * Note: for private endpoints the "category" field is ignored since there is only one private endpoint - * (compared to one public one per category). - * The "category" is only needed for public topics since bybit has one endpoint for public events per category. - */ -⋮---- -// wsClient.subscribeV5('execution.fast', 'linear'); -// wsClient.subscribeV5('execution.fast.linear', 'linear'); -// wsClient.subscribeV5('execution.fast.spot', 'spot'); -// wsClient.subscribeV5('execution.fast.option', 'option'); -⋮---- -/** - * The following has the same effect as above, since there's only one private endpoint for V5 account topics: - */ -// wsClient.subscribe('position'); -// wsClient.subscribe('execution'); -// wsClient.subscribe(['order', 'wallet', 'greek']); -⋮---- -// To unsubscribe from topics (after a 5 second delay, in this example): -// setTimeout(() => { -// console.log('unsubscribing'); -// wsClient.unsubscribeV5('execution', 'linear'); -// }, 5 * 1000); -⋮---- -// Topics are tracked per websocket type -// Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) - -================ -File: examples/Websocket/Public/ws-public-allLiquidations.ts -================ -import { - isWsAllLiquidationEvent, - RestClientV5, - WebsocketClient, -} from '../../../src'; -⋮---- -// or -// import { -// RestClientV5, -// WebsocketClient, -// isWsAllLiquidationEvent, -// } from 'bybit-api'; -⋮---- -function onAllLiquidationEvent(event: unknown) -⋮---- -/** - * - * If you want to receive data for all available symbols, this websocket topic - * requires you to subscribe to each symbol individually. - * - * This can be easily automated by fetching a list of symbols via the REST client, - * generating a list of topics (one per symbol), before simply passing an - * array of topics to the websocket client per product group (linear & inverse perps). - * - */ -async function start() -⋮---- -// Make an array of topics ready for submission -⋮---- -// subscribe to all linear symbols -⋮---- -// subscribe to all inverse symbols - -================ -File: examples/Websocket/Public/ws-public-v5.ts -================ -import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; -⋮---- -/** - * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: - * - Connections are opened when you subscribe to topics - * - If key & secret are provided, authentication is handled automatically - * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), - * subscription events are automatically routed to the different ws endpoints on bybit's side - * - Heartbeats/ping/pong/reconnects are all handled automatically. - * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. - */ -⋮---- -/** - * For public V5 topics, use the subscribeV5 method and include the API category this topic is for. - * Category is required, since each category has a different websocket endpoint. - */ -⋮---- -// Linear v5 -// -> Just one topic per call -// wsClient.subscribeV5('orderbook.50.BTCUSDT', 'linear'); -⋮---- -// -> Or multiple topics in one call -// wsClient.subscribeV5( -// ['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], -// 'linear' -// ); -⋮---- -// Inverse v5 -// wsClient.subscribeV5('orderbook.50.BTCUSD', 'inverse'); -⋮---- -// Spot v5 -// wsClient.subscribeV5('orderbook.50.BTCUSDT', 'spot'); -⋮---- -// Option v5 -// wsClient.subscribeV5('publicTrade.BTC', 'option'); -⋮---- -// Use the subscribeV5() call for most subscribe calls with v5 websockets -⋮---- -// Alternatively, you can also use objects in the wsClient.subscribe() call -// wsClient.subscribe({ -// topic: 'orderook.50.BTCUSDT', -// category: 'spot', -// }); -⋮---- -/** - * For private V5 topics, just call the same subscribeV5() method on the ws client or use the original subscribe() method. - * - * Note: for private endpoints the "category" field is ignored since there is only one private endpoint - * (compared to one public one per category) - */ -⋮---- -// wsClient.subscribeV5('position', 'linear'); -// wsClient.subscribeV5('execution', 'linear'); -// wsClient.subscribeV5(['order', 'wallet', 'greek'], 'linear'); -⋮---- -// To unsubscribe from topics (after a 5 second delay, in this example): -⋮---- -// Topics are tracked per websocket type -// Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) - -================ -File: src/types/request/index.ts -================ - - -================ -File: src/types/response/index.ts -================ - - -================ -File: src/types/response/v5-account.ts -================ -import { - AccountMarginModeV5, - AccountTypeV5, - CategoryV5, - TransactionTypeV5, - UnifiedUpdateStatusV5, -} from '../shared-v5'; -⋮---- -export interface WalletBalanceV5Coin { - coin: string; - equity: string; - usdValue: string; - walletBalance: string; - free: string; // spot only - locked: string; // spot only - borrowAmount: string; - availableToBorrow: string; // deprecated field - availableToWithdraw: string; - accruedInterest: string; - totalOrderIM: string; - totalPositionIM: string; - totalPositionMM: string; - unrealisedPnl: string; - cumRealisedPnl: string; - bonus: string; - marginCollateral: boolean; - collateralSwitch: boolean; - spotBorrow: string; - colRes?: string; -} -⋮---- -free: string; // spot only -locked: string; // spot only -⋮---- -availableToBorrow: string; // deprecated field -⋮---- -export interface WalletBalanceV5 { - accountType: AccountTypeV5; - accountLTV: string; - accountIMRate: string; - accountMMRate: string; - accountIMRateByMp: string; - accountMMRateByMp: string; - totalInitialMarginByMp: string; - totalMaintenanceMarginByMp: string; - totalEquity: string; - totalWalletBalance: string; - totalMarginBalance: string; - totalAvailableBalance: string; - totalPerpUPL: string; - totalInitialMargin: string; - totalMaintenanceMargin: string; - coin: WalletBalanceV5Coin[]; -} -⋮---- -export interface UnifiedAccountUpgradeResultV5 { - unifiedUpdateStatus: UnifiedUpdateStatusV5; - unifiedUpdateMsg: { - msg: string[] | null; - }; -} -⋮---- -export interface BorrowHistoryRecordV5 { - currency: string; - createdTime: number; - borrowCost: string; - hourlyBorrowRate: string; - InterestBearingBorrowSize: string; - costExemption: string; - borrowAmount: string; - unrealisedLoss: string; - freeBorrowedAmount: string; -} -⋮---- -export interface CollateralInfoV5 { - currency: string; - hourlyBorrowRate: string; - maxBorrowingAmount: string; - freeBorrowAmount: string; - freeBorrowingLimit: string; - borrowAmount: string; - availableToBorrow: string; - borrowable: boolean; - borrowUsageRate: string; - marginCollateral: boolean; - collateralSwitch: boolean; - collateralRatio: string; -} -⋮---- -export interface CoinGreeksV5 { - baseCoin: string; - totalDelta: string; - totalGamma: string; - totalVega: string; - totalTheta: string; -} -⋮---- -export interface FeeRateV5 { - symbol: string; - baseCoin: string; - takerFeeRate: string; - makerFeeRate: string; -} -⋮---- -export interface AccountInfoV5 { - unifiedMarginStatus: number; - marginMode: AccountMarginModeV5; - isMasterTrader: boolean; - spotHedgingStatus: string; - updatedTime: string; -} -⋮---- -/** - * Get Trade Behaviour Config / `getLimitPriceAction()` — `/v5/account/user-setting-config` - */ -export interface UserSettingConfigV5 { - lpaSpot: boolean; - lpaPerp: boolean; - /** Spot MNT fee deduction enabled. */ - smsef?: boolean; - /** Futures MNT fee deduction enabled. */ - fmsef?: boolean; - /** Delta Neutral mode; may be absent on older API responses. */ - deltaEnable?: boolean; -} -⋮---- -/** Spot MNT fee deduction enabled. */ -⋮---- -/** Futures MNT fee deduction enabled. */ -⋮---- -/** Delta Neutral mode; may be absent on older API responses. */ -⋮---- -export interface TransactionLogV5 { - symbol: string; - category: CategoryV5; - side: string; - transactionTime: string; - type: TransactionTypeV5; - qty: string; - size: string; - currency: string; - tradePrice: string; - funding: string; - fee: string; - cashFlow: string; - change: string; - cashBalance: string; - feeRate: string; - bonusChange: string; - tradeId: string; - orderId: string; - orderLinkId: string; - extraFees: string; - transSubType: string; -} -⋮---- -export interface MMPStateV5 { - baseCoin: string; - mmpEnabled: boolean; - window: string; - frozenPeriod: string; - qtyLimit: string; - deltaLimit: string; - vegaLimit?: string; - mmpFrozenUntil: string; - mmpFrozen: boolean; -} -⋮---- -export interface RepayLiabilityResultV5 { - coin: string; - repaymentQty: string; -} -⋮---- -export interface DCPInfoV5 { - product: 'SPOT' | 'DERIVATIVES' | 'OPTIONS'; - dcpStatus: 'ON'; - timeWindow: string; -} -⋮---- -export interface ManualRepayResultV5 { - resultStatus: 'P' | 'SU' | 'FA'; -} -⋮---- -/** GET /v5/account/option-asset-info — response `result` wraps a nested `result` array. */ -export interface OptionAssetInfoRowV5 { - coin: string; - totalDelta: string; - totalRPL: string; - totalUPL: string; - assetIM: string; - assetMM: string; - sendTime: number; -} -⋮---- -export interface OptionAssetInfoNestedResultV5 { - result: OptionAssetInfoRowV5[]; -} -⋮---- -/** GET /v5/account/pay-info */ -export interface PayInfoCollateralItemV5 { - coin: string; - availableSize: string; - availableValue: string; - coinScale: number; - borrowSize: string; - spotHedgeAmount: string; - assetFrozen: string; -} -⋮---- -export interface PayInfoBorrowBlockV5 { - coin?: string; - borrowSize: string; - borrowValue?: string; - assetFrozen: string; - availableBalance: string; -} -⋮---- -export interface PayInfoResultV5 { - collateralInfo: { - collateralList: PayInfoCollateralItemV5[]; - }; - borrowInfo: PayInfoBorrowBlockV5; -} -⋮---- -/** GET /v5/account/trade-info-for-analysis */ -export interface TradeInfoAnalysisDailyV5 { - day: string; - sumBuyExecValue: string; - sumSellExecValue: string; - sumExecValue: string; -} -⋮---- -export interface TradeInfoForAnalysisResultV5 { - symbolRnl: string; - netExecQty: string; - sumExecValue: string; - sumExecQty: string; - avgBuyExecPrice: string; - sumBuyExecValue: string; - sumBuyExecQty: string; - sumBuyExecFee: string; - sumBuyOrderQty: string; - avgSellExecPrice: string; - sumSellExecValue: string; - sumSellExecQty: string; - sumSellExecFee: string; - sumSellOrderQty: string; - maxMarginVersion: number; - baseCoin: string; - settleCoin: string; - sumPriceList?: TradeInfoAnalysisDailyV5[]; -} - -================ -File: src/types/response/v5-trade.ts -================ -import { - CategoryV5, - OrderCancelTypeV5, - OrderCreateTypeV5, - OrderRejectReasonV5, - OrderSideV5, - OrderStatusV5, - OrderTimeInForceV5, - OrderTriggerByV5, - OrderTypeV5, - PositionIdx, - StopOrderTypeV5, -} from '../shared-v5'; -⋮---- -export interface OrderResultV5 { - orderId: string; - orderLinkId: string; -} -⋮---- -export interface AccountOrderV5 { - orderId: string; - orderLinkId: string; - parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) - blockTradeId: string; - symbol: string; - price: string; - qty: string; - side: OrderSideV5; - isLeverage: '0' | '1'; - positionIdx: PositionIdx; - orderStatus: OrderStatusV5; - createType: OrderCreateTypeV5; - cancelType: OrderCancelTypeV5; - rejectReason: OrderRejectReasonV5; - avgPrice: string; - leavesQty: string; - leavesValue: string; - cumExecQty: string; - cumExecValue: string; - cumExecFee: string; - timeInForce: OrderTimeInForceV5; - orderType: OrderTypeV5; - stopOrderType: StopOrderTypeV5; - orderIv: string; - marketUnit: 'baseCoin' | 'quoteCoin'; - slippageToleranceType: string; - slippageTolerance: string; - triggerPrice: string; - takeProfit: string; - stopLoss: string; - tpslMode: 'Full' | 'Partial' | ''; - ocoTriggerType: - | 'OcoTriggerByUnknown' - | 'OcoTriggerTp' - | 'OcoTriggerBySl' - | ''; - tpLimitPrice: string; - slLimitPrice: string; - tpTriggerBy: OrderTriggerByV5; - slTriggerBy: OrderTriggerByV5; - triggerDirection: 1 | 2; - triggerBy: OrderTriggerByV5; - lastPriceOnCreated: string; - basePrice: string; - reduceOnly: boolean; - closeOnTrigger: boolean; - placeType: 'iv' | 'price' | ''; - smpType: string; - smpGroup: number; - smpOrderId: string; - createdTime: string; - updatedTime: string; - extraFees: string; - cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee - rpiTakerAccess?: boolean; - rpiMatchedQty?: string; - fromAccount?: string; - toAccount?: string; - externalEventType?: string; -} -⋮---- -parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) -⋮---- -cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee -⋮---- -export interface BatchCreateOrderResultV5 { - category: CategoryV5; - symbol: string; - orderId: string; - orderLinkId: string; - createAt?: string; -} -⋮---- -export interface BatchOrdersRetExtInfoV5 { - list: { - code: number; - msg: string; - }[]; -} -⋮---- -export interface BatchAmendOrderResultV5 { - category: CategoryV5; - symbol: string; - orderId: string; - orderLinkId: string; -} -⋮---- -export interface BatchCancelOrderResultV5 { - category: CategoryV5; - symbol: string; - orderId: string; - orderLinkId: string; -} -⋮---- -export interface SpotBorrowCheckResultV5 { - symbol: string; - side: OrderSideV5; - maxTradeQty: string; - maxTradeAmount: string; - spotMaxTradeQty: string; - spotMaxTradeAmount: string; - borrowCoin: string; -} -⋮---- -export interface PreCheckOrderResultV5 { - orderId: string; - orderLinkId: string; - preImrE4: number; // Initial margin rate before checking (in basis points) - preMmrE4: number; // Maintenance margin rate before checking (in basis points) - postImrE4: number; // Initial margin rate after checking (in basis points) - postMmrE4: number; // Maintenance margin rate after checking (in basis points) -} -⋮---- -preImrE4: number; // Initial margin rate before checking (in basis points) -preMmrE4: number; // Maintenance margin rate before checking (in basis points) -postImrE4: number; // Initial margin rate after checking (in basis points) -postMmrE4: number; // Maintenance margin rate after checking (in basis points) - -================ -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 -dist -doc -bundleReport.html -.history/ -rawReq.ts -localtest.sh -localtest.ts -privaterepotracker -restClientRegex.ts -repomix.sh - -examples/ignored -examples/ts-testnet-private.ts -examples/ts-testnet-trade.ts -examples/ts-testnet.ts -*.pem - -================ -File: src/types/request/v5-account.ts -================ -import { - AccountTypeV5, - CategoryV5, - InstrumentSymbolTypeV5, - TransactionTypeV5, -} from '../shared-v5'; -⋮---- -export interface GetWalletBalanceParamsV5 { - accountType: AccountTypeV5; - coin?: string; -} -⋮---- -export interface GetBorrowHistoryParamsV5 { - currency?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetFeeRateParamsV5 { - category: CategoryV5; - symbol?: string; - baseCoin?: string; -} -⋮---- -export interface GetTransactionLogParamsV5 { - accountType?: AccountTypeV5; - category?: CategoryV5; - currency?: string; - baseCoin?: string; - type?: TransactionTypeV5; - /** - * Transaction sub type, "movePosition", used to filter trans logs of Move Position only - */ - transSubType?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -/** - * Transaction sub type, "movePosition", used to filter trans logs of Move Position only - */ -⋮---- -export interface MMPModifyParamsV5 { - baseCoin: string; - window: string; - frozenPeriod: string; - qtyLimit: string; - deltaLimit: string; - vegaLimit?: string; -} -⋮---- -export interface RepayLiabilityParamsV5 { - coin?: string; -} -⋮---- -export interface SetCollateralCoinParamsV5 { - coin: string; - collateralSwitch: 'ON' | 'OFF'; -} -⋮---- -export interface GetClassicTransactionLogsParamsV5 { - currency?: string; - baseCoin?: string; - type?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface SetLimitPriceActionParamsV5 { - category: CategoryV5; - modifyEnable: boolean; -} -⋮---- -/** - * Set Delta Neutral Mode. POST /v5/account/set-delta-mode - * 1: enable, 0: disable. - */ -export interface SetDeltaNeutralModeParamsV5 { - deltaEnable: '1' | '0'; -} -⋮---- -export interface GetAccountInstrumentsInfoParamsV5 { - category: 'spot' | 'linear' | 'inverse'; - symbol?: string; - /** Filter by `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ - symbolType?: InstrumentSymbolTypeV5; - limit?: number; - cursor?: string; -} -⋮---- -/** Filter by `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ -⋮---- -/** GET /v5/account/pay-info */ -export interface GetPayInfoParamsV5 { - coin?: string; -} -⋮---- -/** GET /v5/account/trade-info-for-analysis */ -export interface GetTradeInfoForAnalysisParamsV5 { - symbol: string; - startTime?: number; - endTime?: number; -} -⋮---- -export interface ManualRepayParamsV5 { - coin?: string; - amount?: string; - /** - * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. - * If neither `coin` nor `amount` is set, this must be ALL (repay all liabilities) or the request is rejected. - */ - repaymentType?: 'ALL' | 'FIXED' | 'FLEXIBLE'; -} -⋮---- -/** - * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. - * If neither `coin` nor `amount` is set, this must be ALL (repay all liabilities) or the request is rejected. - */ - -================ -File: src/types/request/v5-crypto-loan.ts -================ -export interface BorrowCryptoLoanParamsV5 { - loanCurrency: string; - loanAmount?: string; - loanTerm?: string; - collateralCurrency: string; - collateralAmount?: string; -} -⋮---- -export interface GetUnpaidLoanOrdersParamsV5 { - orderId?: string; - loanCurrency?: string; - collateralCurrency?: string; - loanTermType?: string; - loanTerm?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetRepaymentHistoryParamsV5 { - orderId?: string; - repayId?: string; - loanCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetCompletedLoanOrderHistoryParamsV5 { - orderId?: string; - loanCurrency?: string; - collateralCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetLoanLTVAdjustmentHistoryParamsV5 { - orderId?: string; - adjustId?: string; - collateralCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -// New Crypto Loan Request Types -⋮---- -export interface GetBorrowableCoinsParamsV5 { - vipLevel?: string; - currency?: string; -} -⋮---- -export interface GetCollateralCoinsParamsV5 { - currency?: string; -} -⋮---- -export interface GetMaxCollateralAmountParamsV5 { - currency: string; -} -⋮---- -export interface AdjustCollateralAmountParamsV5 { - currency: string; - amount: string; - direction: '0' | '1'; -} -⋮---- -export interface GetCollateralAdjustmentHistoryParamsV5 { - adjustId?: string; - collateralCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -// Flexible Loan Request Types -⋮---- -export interface BorrowFlexibleParamsV5 { - loanCurrency: string; - loanAmount: string; - collateralList?: { - currency: string; - amount: string; - }[]; -} -⋮---- -export interface RepayFlexibleParamsV5 { - loanCurrency: string; - amount: string; -} -⋮---- -export interface RepayCollateralFlexibleParamsV5 { - loanCurrency: string; - collateralCoin: string; - amount: string; -} -⋮---- -export interface GetOngoingFlexibleLoansParamsV5 { - loanCurrency?: string; -} -⋮---- -export interface GetBorrowHistoryFlexibleParamsV5 { - orderId?: string; - loanCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetRepaymentHistoryFlexibleParamsV5 { - repayId?: string; - loanCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -// Fixed Loan Request Types -⋮---- -export interface GetSupplyOrderQuoteFixedParamsV5 { - orderCurrency: string; - term?: string; - orderBy: 'apy' | 'term' | 'quantity'; - sort?: number; - limit?: number; -} -⋮---- -export interface GetBorrowOrderQuoteFixedParamsV5 { - orderCurrency: string; - term?: string; - orderBy: 'apy' | 'term' | 'quantity'; - sort?: number; - limit?: number; -} -⋮---- -export interface CreateBorrowOrderFixedParamsV5 { - orderCurrency: string; - orderAmount: string; - annualRate: string; - term: string; - autoRepay?: string; // Deprecated - repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan - collateralList?: { - currency: string; - amount: string; - }[]; -} -⋮---- -autoRepay?: string; // Deprecated -repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan -⋮---- -export interface CreateSupplyOrderFixedParamsV5 { - orderCurrency: string; - orderAmount: string; - annualRate: string; - term: string; - /** - * Source account for supply. 0: Funding Account; 1: Earn Flexible Account; 2: ALL. Default: 0 - */ - availableSource?: '0' | '1' | '2'; -} -⋮---- -/** - * Source account for supply. 0: Funding Account; 1: Earn Flexible Account; 2: ALL. Default: 0 - */ -⋮---- -export interface CancelBorrowOrderFixedParamsV5 { - orderId: string; -} -⋮---- -export interface CancelSupplyOrderFixedParamsV5 { - orderId: string; - /** - * Account to receive the refund. 0: Funding Account; 1: EasyEarn. Default: 0 - */ - refundedAccount?: '0' | '1'; -} -⋮---- -/** - * Account to receive the refund. 0: Funding Account; 1: EasyEarn. Default: 0 - */ -⋮---- -export interface GetBorrowContractInfoFixedParamsV5 { - orderId?: string; - loanId?: string; - orderCurrency?: string; - term?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetSupplyContractInfoFixedParamsV5 { - orderId?: string; - supplyId?: string; - supplyCurrency?: string; - term?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetBorrowOrderInfoFixedParamsV5 { - orderId?: string; - orderCurrency?: string; - state?: string; - term?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetSupplyOrderInfoFixedParamsV5 { - orderId?: string; - orderCurrency?: string; - state?: string; - term?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface RepayFixedParamsV5 { - loanId?: string; - loanCurrency?: string; -} -⋮---- -export interface RepayCollateralFixedParamsV5 { - loanCurrency: string; - collateralCoin: string; - amount: string; -} -⋮---- -export interface GetRepaymentHistoryFixedParamsV5 { - repayId?: string; - loanCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface RenewBorrowOrderFixedParamsV5 { - loanId: string; - collateralList?: { - currency?: string; - amount?: string; - }[]; -} -⋮---- -export interface GetRenewOrderInfoFixedParamsV5 { - orderId?: string; - orderCurrency?: string; - limit?: string; - cursor?: string; -} -⋮---- -// Max Loan Amount Request Types -⋮---- -export interface GetMaxLoanAmountParamsV5 { - currency: string; // Coin to borrow - collateralList?: { - ccy: string; // Collateral coin - amount: string; // Collateral amount - }[]; -} -⋮---- -currency: string; // Coin to borrow -⋮---- -ccy: string; // Collateral coin -amount: string; // Collateral amount -⋮---- -// Institutional Loan Request Types -⋮---- -export interface GetCoinDeltaAmountParamsV5 { - coin?: string; -} -⋮---- -export interface RepayInstitutionalLoanParamsV5 { - token: string; // Coin name - quantity: string; // The qty to be repaid -} -⋮---- -token: string; // Coin name -quantity: string; // The qty to be repaid - -================ -File: src/types/request/v5-earn.ts -================ -export interface GetEarnCouponListParamsV5 { - category: 'FlexibleSaving' | 'DualAssets'; -} -⋮---- -export interface SubmitStakeRedeemParamsV5 { - category: string; - orderType: 'Stake' | 'Redeem'; - accountType: 'FUND' | 'UNIFIED'; - amount: string; - coin: string; - productId: string; - orderLinkId: string; - toAccountType?: 'FUND' | 'UNIFIED'; -} -⋮---- -export interface GetEarnOrderHistoryParamsV5 { - category: string; - orderId?: string; - orderLinkId?: string; - productId?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetEarnPositionParamsV5 { - category: string; - productId?: string; - coin?: string; -} -⋮---- -export interface GetEarnYieldHistoryParamsV5 { - category: string; - productId?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetEarnHourlyYieldHistoryParamsV5 { - category: string; - productId?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface ModifyEarnPositionParamsV5 { - category: 'OnChain'; - productId: number; - positionId: number; - autoReinvest: 0 | 1; -} -⋮---- -export interface GetEarnAprHistoryParamsV5 { - category: 'FlexibleSaving' | 'OnChain'; - productId: string; - startTime?: number; - endTime?: number; -} -⋮---- -/** - * GET /v5/earn/advance/product — Advanced Earn: Dual Asset, Double Win, Smart Leverage, etc. - * Public, no auth. Rate limit: 50 req/s per IP. - */ -export interface GetAdvanceEarnProductParamsV5 { - category: 'DualAssets' | 'DoubleWin' | 'SmartLeverage' | 'DiscountBuy'; - coin?: string; - /** - * Product duration, e.g. 8h, 1d, 2d, 3d, 6d, 7d, 12d (depends on product). - */ - duration?: string; -} -⋮---- -/** - * Product duration, e.g. 8h, 1d, 2d, 3d, 6d, 7d, 12d (depends on product). - */ -⋮---- -/** GET /v5/earn/hold-to-earn/yield-history — Hold to Earn airdrop daily PnL (Earn permission) */ -export interface GetHoldToEarnAirdropYieldHistoryParamsV5 { - /** Unix seconds. Cannot be earlier than now minus 3 months */ - timeStart?: number; - /** Unix seconds. Requires timeStart ≤ timeEnd */ - timeEnd?: number; - /** Page size [1, 49] */ - limit: number; - /** Pagination cursor from previous `nextCursor` */ - cursor?: string; -} -⋮---- -/** Unix seconds. Cannot be earlier than now minus 3 months */ -⋮---- -/** Unix seconds. Requires timeStart ≤ timeEnd */ -⋮---- -/** Page size [1, 49] */ -⋮---- -/** Pagination cursor from previous `nextCursor` */ - -================ -File: src/types/request/v5-market.ts -================ -import { KlineIntervalV3 } from '../shared'; -import { - CategoryV5, - InstrumentStatusV5, - InstrumentSymbolTypeV5, - OptionTypeV5, -} from '../shared-v5'; -⋮---- -export interface GetKlineParamsV5 { - category: 'spot' | 'linear' | 'inverse'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - limit?: number; -} -⋮---- -export interface GetMarkPriceKlineParamsV5 { - /** - * linear (default if omitted), inverse, or option. - */ - category?: 'linear' | 'inverse' | 'option'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - /** - * Futures: [1, 1000], default 200. Options: [1, 500], default 200. - */ - limit?: number; -} -⋮---- -/** - * linear (default if omitted), inverse, or option. - */ -⋮---- -/** - * Futures: [1, 1000], default 200. Options: [1, 500], default 200. - */ -⋮---- -export interface GetIndexPriceKlineParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - limit?: number; -} -⋮---- -export interface GetPremiumIndexPriceKlineParamsV5 { - category: 'linear'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - limit?: number; -} -⋮---- -export interface GetInstrumentsInfoParamsV5 { - category: CategoryV5; - symbol?: string; - /** Filter by instrument `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ - symbolType?: InstrumentSymbolTypeV5; - status?: InstrumentStatusV5; - baseCoin?: string; - limit?: number; - cursor?: string; -} -⋮---- -/** Filter by instrument `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ -⋮---- -export interface GetOrderbookParamsV5 { - category: CategoryV5; - symbol: string; - limit?: number; -} -⋮---- -export interface GetRPIOrderbookParamsV5 { - category?: 'spot' | 'linear' | 'inverse'; - symbol: string; - limit: number; // Required for RPI orderbook, [1, 50] -} -⋮---- -limit: number; // Required for RPI orderbook, [1, 50] -⋮---- -export interface GetIndexPriceComponentsParamsV5 { - indexName: string; // Index name, like BTCUSDT -} -⋮---- -indexName: string; // Index name, like BTCUSDT -⋮---- -export interface GetADLAlertParamsV5 { - symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only -} -⋮---- -symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only -⋮---- -export interface GetFeeGroupStructureParamsV5 { - productType: string; // Product type. contract only for now - groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 -} -⋮---- -productType: string; // Product type. contract only for now -groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 -⋮---- -export interface GetTickersParamsV5 { - category: TCategory; - symbol?: string; - baseCoin?: string; - expDate?: string; -} -⋮---- -export interface GetFundingRateHistoryParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetPublicTradingHistoryParamsV5 { - category: CategoryV5; - symbol: string; - baseCoin?: string; - optionType?: OptionTypeV5; - limit?: number; -} -⋮---- -export type OpenInterestIntervalV5 = - | '5min' - | '15min' - | '30min' - | '1h' - | '4h' - | '1d'; -⋮---- -export interface GetOpenInterestParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - intervalTime: OpenInterestIntervalV5; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetHistoricalVolatilityParamsV5 { - category: 'option'; - baseCoin?: string; - period?: 7 | 14 | 21 | 30 | 60 | 90 | 180 | 270; - startTime?: number; - endTime?: number; -} -⋮---- -export interface GetInsuranceParamsV5 { - coin?: string; -} -⋮---- -export interface GetRiskLimitParamsV5 { - category?: 'linear' | 'inverse'; - symbol?: string; - cursor?: string; -} -⋮---- -export interface GetOptionDeliveryPriceParamsV5 { - category: 'option'; - symbol?: string; - baseCoin?: string; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetDeliveryPriceParamsV5 { - category: 'linear' | 'inverse' | 'option'; - symbol?: string; - baseCoin?: string; - settleCoin?: string; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetLongShortRatioParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - period: OpenInterestIntervalV5; - startTime?: string; - endTime?: string; - limit?: number; - cursor?: string; -} - -================ -File: src/types/request/v5-spot-leverage-token.ts -================ -import { LTOrderTypeV5 } from '../shared-v5'; -⋮---- -export interface PurchaseSpotLeveragedTokenParamsV5 { - ltCoin: string; - amount: string; - serialNo?: string; -} -⋮---- -export interface RedeemSpotLeveragedTokenParamsV5 { - ltCoin: string; - quantity: string; - serialNo?: string; -} -⋮---- -export interface GetSpotLeveragedTokenOrderHistoryParamsV5 { - ltCoin?: string; - orderId?: string; - startTime?: number; - endTime?: number; - limit?: number; - ltOrderType?: LTOrderTypeV5; - serialNo?: string; -} -⋮---- -export interface GetVIPMarginDataParamsV5 { - vipLevel?: string; - currency?: string; -} -⋮---- -export interface GetSpotMarginCurrencyDataParamsV5 { - currency?: string; -} -⋮---- -// Spot Margin Trade (UTA) endpoints -export interface ManualBorrowParamsV5 { - coin: string; - amount: string; -} -⋮---- -export interface GetMaxBorrowableAmountParamsV5 { - currency: string; -} -⋮---- -export interface GetPositionTiersParamsV5 { - currency?: string; -} -⋮---- -export interface GetCoinStateParamsV5 { - currency?: string; -} -⋮---- -export interface GetAvailableAmountToRepayParamsV5 { - currency: string; -} -⋮---- -export interface SetSpotMarginLeverageParamsV5 { - leverage: string; - currency?: string; -} -⋮---- -export interface ManualRepayWithoutConversionParamsV5 { - coin: string; - amount?: string; - /** - * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. - */ - repaymentType?: 'ALL' | 'FIXED' | 'FLEXIBLE'; -} -⋮---- -/** - * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. - */ -⋮---- -export interface GetAutoRepayModeParamsV5 { - currency?: string; // Coin name, uppercase only. If not passed, returns all currencies -} -⋮---- -currency?: string; // Coin name, uppercase only. If not passed, returns all currencies -⋮---- -export interface SetAutoRepayModeParamsV5 { - currency?: string; // Coin name, uppercase only. If not passed, enables for all currencies - autoRepayMode: '0' | '1'; // 0: Off, 1: On -} -⋮---- -currency?: string; // Coin name, uppercase only. If not passed, enables for all currencies -autoRepayMode: '0' | '1'; // 0: Off, 1: On -⋮---- -export interface GetSpotMarginLiabilityInfoParamsV5 { - currency: string; -} -⋮---- -export interface FixedRateBorrowParamsV5 { - orderCurrency: string; - orderAmount: string; - /** e.g. 0.02 = 2% p.a. */ - annualRate: string; - /** 7, 14, 30, 90, 180 (days) */ - term: string; - /** 1: auto repayment; 2: transfer to flexible loan */ - repayType?: '1' | '2'; -} -⋮---- -/** e.g. 0.02 = 2% p.a. */ -⋮---- -/** 7, 14, 30, 90, 180 (days) */ -⋮---- -/** 1: auto repayment; 2: transfer to flexible loan */ -⋮---- -export interface GetFixedRateBorrowOrderInfoParamsV5 { - orderId?: string; - orderCurrency?: string; - state?: string; - term?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetFixedRateBorrowContractInfoParamsV5 { - orderId?: string; - orderCurrency?: string; - term?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetFixedRateBorrowOrderQuoteParamsV5 { - orderCurrency: string; - term?: string; - orderBy?: 'apy' | 'term' | 'quantity'; - sort?: 0 | 1; - limit?: number; -} -⋮---- -export interface RenewFixedRateBorrowParamsV5 { - loanId: string; - qty?: string; -} - -================ -File: src/types/response/v5-crypto-loan.ts -================ -export interface CollateralCoinV5 { - collateralAccuracy: number; - initialLTV: string; - liquidationLTV: string; - marginCallLTV: string; - maxLimit: string; -} -⋮---- -export interface VipCollateralCoinsV5 { - list: CollateralCoinV5[]; - vipLevel: string; -} -⋮---- -export interface BorrowableCoinV5 { - borrowingAccuracy: number; - currency: string; - flexibleHourlyInterestRate: string; - hourlyInterestRate7D: string; - hourlyInterestRate14D: string; - hourlyInterestRate30D: string; - hourlyInterestRate90D: string; - hourlyInterestRate180D: string; - maxBorrowingAmount: string; - minBorrowingAmount: string; -} -⋮---- -export interface VipBorrowableCoinsV5 { - list: BorrowableCoinV5[]; - vipLevel: string; -} -⋮---- -export interface AccountBorrowCollateralLimitV5 { - collateralCurrency: string; - loanCurrency: string; - maxCollateralAmount: string; - maxLoanAmount: string; - minCollateralAmount: string; - minLoanAmount: string; -} -⋮---- -export interface UnpaidLoanOrderV5 { - collateralAmount: string; - collateralCurrency: string; - currentLTV: string; - expirationTime: string; - hourlyInterestRate: string; - loanCurrency: string; - loanTerm: string; - orderId: string; - residualInterest: string; - residualPenaltyInterest: string; - totalDebt: string; -} -⋮---- -export interface RepaymentHistoryV5 { - collateralCurrency: string; - collateralReturn: string; - loanCurrency: string; - loanTerm: string; - orderId: string; - repayAmount: string; - repayId: string; - repayStatus: number; - repayTime: string; - repayType: string; -} -⋮---- -export interface CompletedLoanOrderV5 { - borrowTime: string; - collateralCurrency: string; - expirationTime: string; - hourlyInterestRate: string; - initialCollateralAmount: string; - initialLoanAmount: string; - loanCurrency: string; - loanTerm: string; - orderId: string; - repaidInterest: string; - repaidPenaltyInterest: string; - status: number; -} -export interface LoanLTVAdjustmentHistoryV5 { - collateralCurrency: string; - orderId: string; - adjustId: string; - adjustTime: string; - preLTV: string; - afterLTV: string; - direction: number; - amount: string; +================ +File: src/types/response/v5-rfq.ts +================ +export interface RFQConfigV5 { + deskCode: string; // Own deskCode, unique identification code + maxLegs: number; // Maximum number of legs + maxLP: number; // Maximum number of LPs selected in inquiry form + maxActiveRfq: number; // Maximum number of unfinished inquiry orders allowed + minLimitQtySpotOrder: number; // Spot minimum order quantity multiplier + minLimitQtyContractOrder: number; // Contract minimum order quantity multiplier + minLimitQtyOptionOrder: number; // Option minimum order multiplier + strategyTypes: { + strategyName: string; // Policy name + }[]; + counterparties: { + strategyName: string; // Policy name + }[]; } ⋮---- -// New Crypto Loan Types +deskCode: string; // Own deskCode, unique identification code +maxLegs: number; // Maximum number of legs +maxLP: number; // Maximum number of LPs selected in inquiry form +maxActiveRfq: number; // Maximum number of unfinished inquiry orders allowed +minLimitQtySpotOrder: number; // Spot minimum order quantity multiplier +minLimitQtyContractOrder: number; // Contract minimum order quantity multiplier +minLimitQtyOptionOrder: number; // Option minimum order multiplier ⋮---- -export interface BorrowCoinV5 { - currency: string; - fixedBorrowable: boolean; - fixedBorrowingAccuracy: number; - flexibleBorrowable: boolean; - flexibleBorrowingAccuracy: number; - maxBorrowingAmount: string; - minFixedBorrowingAmount: string; - minFlexibleBorrowingAmount: string; - vipLevel: string; - flexibleAnnualizedInterestRate: string; - annualizedInterestRate7D: string; - annualizedInterestRate14D: string; - annualizedInterestRate30D: string; - annualizedInterestRate60D: string; - annualizedInterestRate90D: string; - annualizedInterestRate180D: string; -} +strategyName: string; // Policy name ⋮---- -export interface CollateralRatioV5 { - collateralRatio: string; - maxValue: string; - minValue: string; -} +strategyName: string; // Policy name ⋮---- -export interface CollateralRatioConfigV5 { - collateralRatioList: CollateralRatioV5[]; - currencies: string; +export interface RFQCounterpartyV5 { + traderName: string; // Name of the bidder + deskCode: string; // Unique identification code of the quotation party + type: string | null; // Quoter type. LP is automated market maker, null means normal quote party } ⋮---- -export interface CurrencyLiquidationV5 { - currency: string; - liquidationOrder: number; -} +traderName: string; // Name of the bidder +deskCode: string; // Unique identification code of the quotation party +type: string | null; // Quoter type. LP is automated market maker, null means normal quote party ⋮---- -export interface CollateralDataV5 { - collateralRatioConfigList: CollateralRatioConfigV5[]; - currencyLiquidationList: CurrencyLiquidationV5[]; +export interface CreateRFQResultV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Inquiry Custom ID + status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form + expiresAt: string; // Expiration time in milliseconds Unix timestamp + deskCode: string; // Inquiry party unique identification code } ⋮---- -// Additional New Crypto Loan Types -⋮---- -export interface AdjustCollateralAmountV5 { - adjustId: number; -} +rfqId: string; // Inquiry ID +rfqLinkId: string; // Inquiry Custom ID +status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form +expiresAt: string; // Expiration time in milliseconds Unix timestamp +deskCode: string; // Inquiry party unique identification code ⋮---- -export interface CollateralAdjustmentHistoryV5 { - adjustId: number; - adjustTime: number; - afterLTV: string; - amount: string; - collateralCurrency: string; - direction: number; - preLTV: string; - status: number; +export interface CancelRFQResultV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Inquiry Custom ID } ⋮---- -export interface BorrowListV5 { - fixedTotalDebt: string; - fixedTotalDebtUSD: string; - flexibleHourlyInterestRate: string; - flexibleTotalDebt: string; - flexibleTotalDebtUSD: string; - loanCurrency: string; -} +rfqId: string; // Inquiry ID +rfqLinkId: string; // Inquiry Custom ID ⋮---- -export interface CollateralListV5 { - amount: string; - amountUSD: string; - currency: string; - ltv: string; +export interface CancelRFQItemV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Inquiry Custom ID + code: number; // Cancel success or failure, 0 means success + msg: string; // Cancellation failure reason } ⋮---- -export interface SupplyListV5 { - amount: string; - amountUSD: string; - currency: string; -} +rfqId: string; // Inquiry ID +rfqLinkId: string; // Inquiry Custom ID +code: number; // Cancel success or failure, 0 means success +msg: string; // Cancellation failure reason ⋮---- -export interface CryptoLoanPositionV5 { - borrowList: BorrowListV5[]; - collateralList: CollateralListV5[]; - supplyList: SupplyListV5[]; - totalCollateral: string; - totalDebt: string; - totalSupply: string; - colRes?: string; +export interface CancelAllRFQResultV5 { + data: CancelRFQItemV5[]; // Array of cancellation results } ⋮---- -// Flexible Loan Types +data: CancelRFQItemV5[]; // Array of cancellation results ⋮---- -export interface BorrowFlexibleV5 { - orderId: string; +export interface CreateRFQQuoteResultV5 { + rfqId: string; // Inquiry ID + quoteId: string; // Quotation ID + quoteLinkId: string; // Quotation Custom ID + expiresAt: string; // Expiration time in milliseconds Unix timestamp + deskCode: string; // Quoter's unique identification code + status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation } ⋮---- -export interface RepayFlexibleV5 { - repayId: string; -} +rfqId: string; // Inquiry ID +quoteId: string; // Quotation ID +quoteLinkId: string; // Quotation Custom ID +expiresAt: string; // Expiration time in milliseconds Unix timestamp +deskCode: string; // Quoter's unique identification code +status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation ⋮---- -export interface OngoingFlexibleLoanV5 { - hourlyInterestRate: string; - loanCurrency: string; - totalDebt: string; - unpaidAmount: string; - unpaidInterest: string; +export interface ExecuteRFQQuoteResultV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Inquiry Custom ID + quoteId: string; // Quotation ID + status: 'Processing' | 'Rejected'; // Order status + rejectParty: string; // Empty means passed, "Taker", "Maker", "Bybit" when rejected } ⋮---- -export interface BorrowHistoryFlexibleV5 { - borrowTime: number; - initialLoanAmount: string; - loanCurrency: string; - orderId: string; - status: number; -} +rfqId: string; // Inquiry ID +rfqLinkId: string; // Inquiry Custom ID +quoteId: string; // Quotation ID +status: 'Processing' | 'Rejected'; // Order status +rejectParty: string; // Empty means passed, "Taker", "Maker", "Bybit" when rejected ⋮---- -export interface RepaymentHistoryFlexibleV5 { - loanCurrency: string; - repayAmount: string; - repayId: string; - repayStatus: number; - repayTime: number; - repayType: number; +export interface CancelRFQQuoteResultV5 { + rfqId: string; // Inquiry ID + quoteId: string; // Quotation ID + quoteLinkId: string; // Quotation Custom ID } ⋮---- -// Fixed Loan Types +rfqId: string; // Inquiry ID +quoteId: string; // Quotation ID +quoteLinkId: string; // Quotation Custom ID ⋮---- -export interface SupplyOrderQuoteFixedV5 { - orderCurrency: string; - term: number; - annualRate: string; - qty: string; +export interface CancelRFQQuoteItemV5 { + rfqId: string; // Inquiry ID + quoteId: string; // Quotation ID + quoteLinkId: string; // Quotation Custom ID + code: number; // Cancel success or failure, 0 means success + msg: string; // Cancellation failure reason } ⋮---- -export interface BorrowOrderQuoteFixedV5 { - orderCurrency: string; - term: number; - annualRate: string; - qty: string; -} +rfqId: string; // Inquiry ID +quoteId: string; // Quotation ID +quoteLinkId: string; // Quotation Custom ID +code: number; // Cancel success or failure, 0 means success +msg: string; // Cancellation failure reason ⋮---- -export interface CreateBorrowOrderFixedV5 { - orderId: string; +export interface RFQLegV5 { + category: 'linear' | 'option' | 'spot'; // Product category + symbol: string; // The unique instrument ID + side: 'buy' | 'sell'; // Inquiry direction + qty: string; // Order quantity of the instrument + isLeverage?: boolean; // For spot lending } ⋮---- -export interface CreateSupplyOrderFixedV5 { - orderId: string; +category: 'linear' | 'option' | 'spot'; // Product category +symbol: string; // The unique instrument ID +side: 'buy' | 'sell'; // Inquiry direction +qty: string; // Order quantity of the instrument +isLeverage?: boolean; // For spot lending +⋮---- +export interface RFQHedgeLegItemV5 { + category: string; + symbol: string; + side: string; + qty: string; + price?: string; } ⋮---- -export interface BorrowContractInfoFixedV5 { - annualRate: string; - autoRepay: string; // Deprecated - borrowCurrency: string; - borrowTime: string; - interestPaid: string; - loanId: string; - orderId: string; - repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment - repaymentTime: string; - residualPenaltyInterest: string; - residualPrincipal: string; - status: number; - term: string; +export interface RFQItemV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Custom ID for inquiry form + counterparties: string[]; // List of bidders + expiresAt: string; // Expiration time in milliseconds Unix timestamp + strategyType: string; // Inquiry label + status: + | 'Active' + | 'Canceled' + | 'PendingFill' + | 'Filled' + | 'Expired' + | 'Failed'; // Status + acceptOtherQuoteStatus?: string; // Whether to accept non-LP quotes. "false": do not accept, "true": accept + deskCode: string; // Unique identification code of the inquiry party + anonymous?: boolean; + createdAt: number; // Time when the trade is created in epoch + updatedAt: number; // Time when the trade is updated in epoch + legs: RFQLegV5[]; // Combination transaction + hedge?: RFQHedgeLegItemV5[]; } ⋮---- -autoRepay: string; // Deprecated +rfqId: string; // Inquiry ID +rfqLinkId: string; // Custom ID for inquiry form +counterparties: string[]; // List of bidders +expiresAt: string; // Expiration time in milliseconds Unix timestamp +strategyType: string; // Inquiry label ⋮---- -repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +| 'Failed'; // Status +acceptOtherQuoteStatus?: string; // Whether to accept non-LP quotes. "false": do not accept, "true": accept +deskCode: string; // Unique identification code of the inquiry party ⋮---- -export interface SupplyContractInfoFixedV5 { - annualRate: string; - supplyCurrency: string; - supplyTime: string; - supplyAmount: string; - interestPaid: string; - supplyId: string; - orderId: string; - redemptionTime: string; - penaltyInterest: string; - actualRedemptionTime: string; - status: number; - term: string; -} +createdAt: number; // Time when the trade is created in epoch +updatedAt: number; // Time when the trade is updated in epoch +legs: RFQLegV5[]; // Combination transaction ⋮---- -export interface BorrowOrderInfoFixedV5 { - annualRate: string; - orderId: number; - orderTime: string; - filledQty: string; - orderQty: string; - orderCurrency: string; - state: number; - term: number; - repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +export interface GetRFQRealtimeResultV5 { + list: RFQItemV5[]; // Array of RFQ items } ⋮---- -repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +list: RFQItemV5[]; // Array of RFQ items ⋮---- -export interface SupplyOrderInfoFixedV5 { - annualRate: string; - orderId: number; - orderTime: string; - filledQty: string; - orderQty: string; - orderCurrency: string; - state: number; - term: number; +export interface RFQHistory { + cursor: string; // Page turning mark + list: RFQItemV5[]; // Array of RFQ items } ⋮---- -export interface RepayFixedV5 { - repayId: string; -} +cursor: string; // Page turning mark +list: RFQItemV5[]; // Array of RFQ items ⋮---- -export interface RepaymentHistoryFixedV5 { - details: { - loanCurrency: string; - loanId: string; - repayAmount: string; - }[]; - loanCurrency: string; - repayAmount: string; - repayId: string; - repayStatus: number; - repayTime: number; - repayType: number; +export interface QuoteLegV5 { + category: 'spot' | 'linear' | 'option'; // Product type + symbol: string; // The unique instrument ID or name of trading contract + price: string; // Order price or quote price + qty?: string; // Order quantity + isLeverage?: boolean; // For spot lending + isHedge?: boolean; } ⋮---- -export interface RenewBorrowOrderFixedV5 { - orderId: string; +category: 'spot' | 'linear' | 'option'; // Product type +symbol: string; // The unique instrument ID or name of trading contract +price: string; // Order price or quote price +qty?: string; // Order quantity +isLeverage?: boolean; // For spot lending +⋮---- +export interface RFQQuoteItemV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Custom ID for inquiry form + quoteId: string; // Quotation ID + quoteLinkId: string; // Quotation custom ID + expiresAt: string; // Expiration time in milliseconds Unix timestamp + deskCode: string; // Unique identification code of quotation party + anonymous?: boolean; + status: + | 'Active' + | 'Canceled' + | 'PendingFill' + | 'Filled' + | 'Expired' + | 'Failed'; // Status + execQuoteSide: string; // Execute quote direction, buy or sell + createdAt: number; // Time when the trade is created in epoch + updatedAt: number; // Time when the trade is updated in epoch + quoteBuyList: QuoteLegV5[]; // Quotation buy direction + quoteSellList: QuoteLegV5[]; // Quotation sell direction } ⋮---- -export interface RenewOrderInfoFixedV5 { - amount: string; - autoRepay: number; - borrowCurrency: string; - contractNo: string; - dueTime: string; - loanId: string; - orderId: number; - renewLoanNo: string; - time: string; +rfqId: string; // Inquiry ID +rfqLinkId: string; // Custom ID for inquiry form +quoteId: string; // Quotation ID +quoteLinkId: string; // Quotation custom ID +expiresAt: string; // Expiration time in milliseconds Unix timestamp +deskCode: string; // Unique identification code of quotation party +⋮---- +| 'Failed'; // Status +execQuoteSide: string; // Execute quote direction, buy or sell +createdAt: number; // Time when the trade is created in epoch +updatedAt: number; // Time when the trade is updated in epoch +quoteBuyList: QuoteLegV5[]; // Quotation buy direction +quoteSellList: QuoteLegV5[]; // Quotation sell direction +⋮---- +export interface RFQTradeLegV5 { + category: 'linear' | 'option' | 'spot'; // Product category + orderId: string; // Bybit order ID + symbol: string; // The unique instrument ID + side: 'buy' | 'sell'; // Direction + price: string; // Execution price + qty: string; // Number of executions + isLeverage?: boolean; // For spot lending + markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot + execFee: string; // Fee for taker or maker in base currency + execId: string; // Unique exec(trade) ID from exchange + resultCode: number; // Status code, 0 means success + resultMessage: string; // Error message about resultCode + rejectParty: string; // Empty if Filled, "Taker"/"Maker"/"bybit" if Rejected } ⋮---- -// Institutional Loan Types +category: 'linear' | 'option' | 'spot'; // Product category +orderId: string; // Bybit order ID +symbol: string; // The unique instrument ID +side: 'buy' | 'sell'; // Direction +price: string; // Execution price +qty: string; // Number of executions +isLeverage?: boolean; // For spot lending +markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot +execFee: string; // Fee for taker or maker in base currency +execId: string; // Unique exec(trade) ID from exchange +resultCode: number; // Status code, 0 means success +resultMessage: string; // Error message about resultCode +rejectParty: string; // Empty if Filled, "Taker"/"Maker"/"bybit" if Rejected ⋮---- -export interface InstitutionalLendingProductInfoV5 { - productId: string; - leverage: string; - supportSpot: number; - supportContract: number; - supportMarginTrading: number; - withdrawLine: string; - transferLine: string; - spotBuyLine: string; - spotSellLine: string; - contractOpenLine: string; - liquidationLine: string; - stopLiquidationLine: string; - contractLeverage: string; - transferRatio: string; - spotSymbols: unknown[]; - contractSymbols: unknown[]; - supportUSDCContract: number; - supportUSDCOptions: number; - USDTPerpetualOpenLine?: string; - USDCContractOpenLine?: string; - USDCOptionsOpenLine?: string; - USDTPerpetualCloseLine?: string; - USDCContractCloseLine?: string; - USDCOptionsCloseLine?: string; - USDTPerpetualLeverage?: { symbol: string; leverage: string }[]; - USDCContractLeverage?: { symbol: string; leverage: string }[]; - deferredLiquidationLine?: string; - deferredLiquidationTime?: string; - marginLeverage?: string; - /** `0`: Default, `1`: CTA, `2`: Hedge */ - productType?: '0' | '1' | '2' | string; +export interface RFQTradeV5 { + rfqId: string; // Inquiry ID + quoteId: string; // Completed inquiry form and executed quotation ID + quoteSide: 'buy' | 'sell'; // Executed quotation direction + strategyType: string; // Inquiry label + status: 'Filled' | 'Rejected'; // Status + rfqDeskCode: string; // Unique identification code of inquiry party + quoteDestCode: string; // Unique identification code of quotation party + createdAt: number; // Time when trade is created in epoch + updatedAt: number; // Time when trade is updated in epoch + legs: RFQTradeLegV5[]; // Combination transaction } ⋮---- -/** `0`: Default, `1`: CTA, `2`: Hedge */ +rfqId: string; // Inquiry ID +quoteId: string; // Completed inquiry form and executed quotation ID +quoteSide: 'buy' | 'sell'; // Executed quotation direction +strategyType: string; // Inquiry label +status: 'Filled' | 'Rejected'; // Status +rfqDeskCode: string; // Unique identification code of inquiry party +quoteDestCode: string; // Unique identification code of quotation party +createdAt: number; // Time when trade is created in epoch +updatedAt: number; // Time when trade is updated in epoch +legs: RFQTradeLegV5[]; // Combination transaction ⋮---- -export interface InstitutionalLendingCoinDeltaItemV5 { - coin: string; - coinDeltaSize: string; - coinDeltaAvailableAmount: string; - coinDeltaAmount: string; +export interface RFQPublicTradeLegV5 { + category: 'linear' | 'option' | 'spot'; // Product category + symbol: string; // The unique instrument ID + side: 'buy' | 'sell'; // Inquiry direction + price: string; // Execution price + qty: string; // Number of executions + markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot } ⋮---- -export interface InstitutionalLendingCoinDeltaAmountV5 { - riskUnitDeltaAmount: string; - riskUnitDeltaAvailableAmount: string; - list: InstitutionalLendingCoinDeltaItemV5[]; -} +category: 'linear' | 'option' | 'spot'; // Product category +symbol: string; // The unique instrument ID +side: 'buy' | 'sell'; // Inquiry direction +price: string; // Execution price +qty: string; // Number of executions +markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot ⋮---- -export interface UnpaidInfoV5 { - token: string; // Coin - unpaidQty: string; // Unpaid principle - unpaidInterest: string; // Unpaid interest +export interface RFQPublicTradeV5 { + rfqId: string; // Inquiry ID + strategyType: string; // Inquiry label + createdAt: number; // Time when trade is created in epoch + updatedAt: number; // Time when trade is updated in epoch + legs: RFQPublicTradeLegV5[]; // Combination transaction } ⋮---- -token: string; // Coin -unpaidQty: string; // Unpaid principle -unpaidInterest: string; // Unpaid interest +rfqId: string; // Inquiry ID +strategyType: string; // Inquiry label +createdAt: number; // Time when trade is created in epoch +updatedAt: number; // Time when trade is updated in epoch +legs: RFQPublicTradeLegV5[]; // Combination transaction ⋮---- -export interface BalanceInfoV5 { - token: string; // Margin coin - price: string; // Margin coin price - qty: string; // Margin coin quantity - convertedAmount: string; // Margin conversion amount +export interface AcceptNonLPQuoteResultV5 { + rfqId: string; // Inquiry ID } ⋮---- -token: string; // Margin coin -price: string; // Margin coin price -qty: string; // Margin coin quantity -convertedAmount: string; // Margin conversion amount +rfqId: string; // Inquiry ID ⋮---- -export interface LTVInfoV5 { - ltv: string; // Risk rate (when liqStatus != 0, returns empty string) - rst: string; // Remaining liquidation time in UTC seconds (when liqStatus != 0, returns empty string) - parentUid: string; // The designated Risk Unit ID - subAccountUids: string[]; // Bound user IDs - unpaidAmount: string; // Total debt in USDT (when liqStatus != 0, returns empty string) - unpaidInfo: UnpaidInfoV5[]; // Debt details (when liqStatus != 0, returns empty array) - balance: string; // Total asset in USDT (when liqStatus != 0, returns empty string) - balanceInfo: BalanceInfoV5[]; // Asset details (when liqStatus != 0, returns empty array) - liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress +export interface RFQDetailQuoteLegV5 { + category: string; + symbol: string; + price: string; + qty: string; + isHedge?: boolean; } ⋮---- -ltv: string; // Risk rate (when liqStatus != 0, returns empty string) -rst: string; // Remaining liquidation time in UTC seconds (when liqStatus != 0, returns empty string) -parentUid: string; // The designated Risk Unit ID -subAccountUids: string[]; // Bound user IDs -unpaidAmount: string; // Total debt in USDT (when liqStatus != 0, returns empty string) -unpaidInfo: UnpaidInfoV5[]; // Debt details (when liqStatus != 0, returns empty array) -balance: string; // Total asset in USDT (when liqStatus != 0, returns empty string) -balanceInfo: BalanceInfoV5[]; // Asset details (when liqStatus != 0, returns empty array) -liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress -⋮---- -export interface InstitutionalLoanLTVV5 { - ltvInfo: LTVInfoV5[]; // LTV info array - liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress +export interface RFQDetailQuoteV5 { + quoteId: string; + deskCode: string; + anonymous?: boolean; + status: string; + createdAt: string; + updatedAt: string; + expiresAt: string; + quoteBuyList?: RFQDetailQuoteLegV5[]; + quoteSellList?: RFQDetailQuoteLegV5[]; } ⋮---- -ltvInfo: LTVInfoV5[]; // LTV info array -liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress +export interface RFQDetailTradeLegV5 { + category: string; + orderId: string; + symbol: string; + side: string; + price: string; + qty: string; + markPrice: string; + execFee: string; + extraFees: string; + execId: string; + resultCode: number; + resultMessage: string; + rejectParty: string; +} ⋮---- -export interface RepayInstitutionalLoanResultV5 { - repayOrderStatus: string; // P: processing +export interface RFQDetailItemV5 { + rfqId: string; + rfqLinkId: string; + counterparties: string[]; + expiresAt: string; + strategyType: string; + status: string; + acceptOtherQuoteStatus?: boolean; + execQuoteId?: string; + execQuoteSide?: string; + deskCode: string; + anonymous?: boolean; + createdAt: string; + updatedAt: string; + legs: RFQLegV5[]; + hedge?: RFQHedgeLegItemV5[]; + quoteList?: RFQDetailQuoteV5[]; + tradeLegs?: RFQDetailTradeLegV5[]; } + +================ +File: webpack/webpack.config.js +================ +function generateConfig(name) ⋮---- -repayOrderStatus: string; // P: processing +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -// Max Loan Amount Response Types +// 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 ⋮---- -export interface MaxLoanAmountV5 { - currency: string; // Coin to borrow - maxLoan: string; // Maximum borrowable amount based on current collateral - notionalUsd: string; // Notional USD value - remainingQuota: string; // Remaining individual platform borrowing limit (shared between main and sub accounts) -} +// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. ⋮---- -currency: string; // Coin to borrow -maxLoan: string; // Maximum borrowable amount based on current collateral -notionalUsd: string; // Notional USD value -remainingQuota: string; // Remaining individual platform borrowing limit (shared between main and sub accounts) +// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. ================ -File: src/types/response/v5-earn.ts +File: src/types/request/v5-account.ts ================ -export interface EarnInterestCardV5 { - awardId: number; - specCode: string; - coin: string; - apy: string; - duration: number; - claimedAt: number; - expireAt: number; - usedAt: number; - status: 'InUse' | 'NotUse' | 'Expired' | 'AlreadyUsed' | string; - currentPnl: string; - limitPnl: string; - positionEffectiveAmount: string; - productId: number; - category: 'FlexibleSaving' | 'DualAssets' | string; +import { + AccountTypeV5, + CategoryV5, + InstrumentSymbolTypeV5, + TransactionTypeV5, +} from '../shared-v5'; +⋮---- +export interface GetWalletBalanceParamsV5 { + accountType: AccountTypeV5; + coin?: string; } ⋮---- -export interface EarnAwardCardV5 { - awardId: number; - specCode: string; - claimedAt: number; - usedAt: number; - expireAt: number; - status: 'InUse' | 'NotUse' | 'Expired' | 'AlreadyUsed' | string; - amount: string; - limitPnlPercentage: string; +export interface GetBorrowHistoryParamsV5 { + currency?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetFeeRateParamsV5 { + category: CategoryV5; + symbol?: string; + baseCoin?: string; +} +⋮---- +export interface GetTransactionLogParamsV5 { + accountType?: AccountTypeV5; + category?: CategoryV5; + currency?: string; + baseCoin?: string; + type?: TransactionTypeV5; + /** + * Transaction sub type, "movePosition", used to filter trans logs of Move Position only + */ + transSubType?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +/** + * Transaction sub type, "movePosition", used to filter trans logs of Move Position only + */ +⋮---- +export interface MMPModifyParamsV5 { baseCoin: string; - quoteCoin: string; - direction: 1 | 2; - category: 'FlexibleSaving' | 'DualAssets' | string; + window: string; + frozenPeriod: string; + qtyLimit: string; + deltaLimit: string; + vegaLimit?: string; } ⋮---- -export interface EarnCouponListResultV5 { - interestCards: EarnInterestCardV5[]; - awardCards: EarnAwardCardV5[]; +export interface RepayLiabilityParamsV5 { + coin?: string; } ⋮---- -export interface EarnProductV5 { - category: string; - estimateApr: string; +export interface SetCollateralCoinParamsV5 { coin: string; - minStakeAmount: string; - maxStakeAmount: string; - precision: string; - productId: string; - status: 'Available' | 'NotAvailable'; + collateralSwitch: 'ON' | 'OFF'; } ⋮---- -export interface EarnOrderHistoryV5 { - coin: string; - orderValue: string; - orderType: 'Redeem' | 'Stake'; - orderId: string; - orderLinkId: string; - status: 'Success' | 'Fail' | 'Pending'; - createdAt: string; - productId: string; - updatedAt: string; - swapOrderValue: string; - estimateRedeemTime: string; - estimateStakeTime: string; +export interface GetClassicTransactionLogsParamsV5 { + currency?: string; + baseCoin?: string; + type?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -export interface EarnPositionFreezeDetailV5 { - amount: string; - description: string; +export interface SetLimitPriceActionParamsV5 { + category: CategoryV5; + modifyEnable: boolean; } ⋮---- -export interface EarnPositionV5 { - coin: string; - productId: string; - amount: string; - totalPnl: string; - claimableYield: string; - id?: string; - status?: string; - orderId?: string; - estimateRedeemTime?: string; - estimateStakeTime?: string; - estimateInterestCalculationTime?: string; - settlementTime?: string; - autoReinvest?: string; - /** Redeemable amount */ - availableAmount: string; - freezeDetails: EarnPositionFreezeDetailV5[]; +/** + * Set Delta Neutral Mode. POST /v5/account/set-delta-mode + * 1: enable, 0: disable. + */ +export interface SetDeltaNeutralModeParamsV5 { + deltaEnable: '1' | '0'; } ⋮---- -/** Redeemable amount */ +export interface GetAccountInstrumentsInfoParamsV5 { + category: 'spot' | 'linear' | 'inverse'; + symbol?: string; + /** Filter by `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ + symbolType?: InstrumentSymbolTypeV5; + limit?: number; + cursor?: string; +} ⋮---- -export interface EarnYieldHistoryV5 { - productId: string; - coin: string; - id: string; - amount: string; - yieldType: string; - distributionMode: string; - effectiveStakingAmount: string; - orderId: string; - status: 'Pending' | 'Success' | 'Fail'; - createdAt: string; +/** Filter by `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ +⋮---- +/** GET /v5/account/pay-info */ +export interface GetPayInfoParamsV5 { + coin?: string; } ⋮---- -export interface EarnHourlyYieldHistoryV5 { - productId: string; - coin: string; - id: string; - amount: string; - effectiveStakingAmount: string; - status: 'Pending' | 'Success' | 'Fail'; - hourlyDate: string; - createdAt: string; +/** GET /v5/account/trade-info-for-analysis */ +export interface GetTradeInfoForAnalysisParamsV5 { + symbol: string; + startTime?: number; + endTime?: number; } ⋮---- -export interface EarnAprHistoryPointV5 { - timestamp: string; - apr: string; +export interface ManualRepayParamsV5 { + coin?: string; + amount?: string; + /** + * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. + * If neither `coin` nor `amount` is set, this must be ALL (repay all liabilities) or the request is rejected. + */ + repaymentType?: 'ALL' | 'FIXED' | 'FLEXIBLE'; } ⋮---- /** - * Advanced Earn — Dual Asset product (GET /v5/earn/advance/product). - */ -export interface AdvanceEarnDualAssetProductV5 { + * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. + * If neither `coin` nor `amount` is set, this must be ALL (repay all liabilities) or the request is rejected. + */ + +================ +File: src/types/request/v5-earn.ts +================ +export interface GetEarnCouponListParamsV5 { + category: 'FlexibleSaving' | 'DualAssets'; +} +⋮---- +export interface SubmitStakeRedeemParamsV5 { category: string; + orderType: 'Stake' | 'Redeem'; + accountType: 'FUND' | 'UNIFIED'; + amount: string; + coin: string; productId: string; - baseCoin: string; - quoteCoin: string; - expectReceiveAt: string; - duration: string; - status: 'Available' | 'NotAvailable'; - isVipProduct: boolean; - subscribeStartAt: string; - subscribeEndAt: string; - applyStartAt: string; - settlementTime: string; - minPurchaseQuoteAmount: string; - minPurchaseBaseAmount: string; - remainingAmountQuote: string; - remainingAmountBase: string; - orderPrecisionDigitalQuote: number; - orderPrecisionDigitalBase: number; + orderLinkId: string; + toAccountType?: 'FUND' | 'UNIFIED'; } ⋮---- -export interface AdvanceEarnDualAssetProductInfoV5 { +export interface GetEarnOrderHistoryParamsV5 { category: string; - list: AdvanceEarnDualAssetProductV5[]; + orderId?: string; + orderLinkId?: string; + productId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -/** - * Advanced Earn — Double Win (GET /v5/earn/advance/product?category=DoubleWin). - */ -export interface AdvanceEarnDoubleWinProductV5 { +export interface GetEarnPositionParamsV5 { category: string; - productId: string; - investCoin: string; - underlyingAsset: string; - duration: string; - subscribeStartAt: string; - subscribeEndAt: string; - settlementTime: string; - expectReceiveAt: string; - minPurchaseAmount: string; - orderPrecisionDigital: number; - isRfqProduct: boolean; - lowerPriceBuffer: string; - upperPriceBuffer: string; - minDeviationRatio: string; - maxDeviationRatio: string; - priceTickSize: string; + productId?: string; + coin?: string; } ⋮---- -/** - * Advanced Earn — Smart Leverage (GET /v5/earn/advance/product?category=SmartLeverage). - */ -export interface AdvanceEarnSmartLeverageProductV5 { +export interface GetEarnYieldHistoryParamsV5 { category: string; - productId: string; - investCoin: string; - underlyingAsset: string; - direction: 'Long' | 'Short'; - leverage: string; - duration: string; - subscribeStartAt: string; - subscribeEndAt: string; - settlementTime: string; - expectReceiveAt: string; - minPurchaseAmount: string; - remainingAmount: string; - orderPrecisionDigital: number; + productId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -/** - * Advanced Earn — Discount Buy (GET /v5/earn/advance/product?category=DiscountBuy). - */ -export interface AdvanceEarnDiscountBuyProductV5 { +export interface GetEarnHourlyYieldHistoryParamsV5 { category: string; - productId: string; - coin: string; - underlyingAsset: string; - settlementTime: string; - duration: string; - isVipProduct: boolean; - subscribeStartAt: string; - subscribeEndAt: string; - minPurchaseAmount: string; - remainingAmount: string; - orderPrecisionDigital: number; - expectReceiveAt: string; + productId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -export type AdvanceEarnAdvanceProductListItemV5 = - | AdvanceEarnDualAssetProductV5 - | AdvanceEarnDoubleWinProductV5 - | AdvanceEarnSmartLeverageProductV5 - | AdvanceEarnDiscountBuyProductV5; -⋮---- -export interface AdvanceEarnAdvanceProductInfoV5 { - category: string; - list: AdvanceEarnAdvanceProductListItemV5[]; +export interface ModifyEarnPositionParamsV5 { + category: 'OnChain'; + productId: number; + positionId: number; + autoReinvest: 0 | 1; } ⋮---- -/** GET /v5/earn/hold-to-earn/product — Hold to Earn airdrop products */ -export type HoldToEarnAirdropProductStatusV5 = - | 'NotStarted' - | 'Online' - | 'Ended'; +export interface GetEarnAprHistoryParamsV5 { + category: 'FlexibleSaving' | 'OnChain'; + productId: string; + startTime?: number; + endTime?: number; +} ⋮---- -export interface HoldToEarnAirdropProductYieldV5 { - coinName: string; - /** Yesterday's APR for display, e.g. "10%", "0%" */ - apy: string; +/** + * GET /v5/earn/advance/product — Advanced Earn: Dual Asset, Double Win, Smart Leverage, etc. + * Public, no auth. Rate limit: 50 req/s per IP. + */ +export interface GetAdvanceEarnProductParamsV5 { + category: 'DualAssets' | 'DoubleWin' | 'SmartLeverage' | 'DiscountBuy'; + coin?: string; + /** + * Product duration, e.g. 8h, 1d, 2d, 3d, 6d, 7d, 12d (depends on product). + */ + duration?: string; } ⋮---- -/** Yesterday's APR for display, e.g. "10%", "0%" */ +/** + * Product duration, e.g. 8h, 1d, 2d, 3d, 6d, 7d, 12d (depends on product). + */ ⋮---- -export interface HoldToEarnAirdropProductV5 { - coinName: string; - yields: HoldToEarnAirdropProductYieldV5[]; - status: HoldToEarnAirdropProductStatusV5; - announcementUrl: string; - /** Yesterday's avg APR across yield coins */ - apy: string; +/** GET /v5/earn/hold-to-earn/yield-history — Hold to Earn airdrop daily PnL (Earn permission) */ +export interface GetHoldToEarnAirdropYieldHistoryParamsV5 { + /** Unix seconds. Cannot be earlier than now minus 3 months */ + timeStart?: number; + /** Unix seconds. Requires timeStart ≤ timeEnd */ + timeEnd?: number; + /** Page size [1, 49] */ + limit: number; + /** Pagination cursor from previous `nextCursor` */ + cursor?: string; } ⋮---- -/** Yesterday's avg APR across yield coins */ +/** Unix seconds. Cannot be earlier than now minus 3 months */ ⋮---- -export interface HoldToEarnAirdropProductsResultV5 { - products: HoldToEarnAirdropProductV5[]; -} +/** Unix seconds. Requires timeStart ≤ timeEnd */ ⋮---- -/** GET /v5/earn/hold-to-earn/yield-history */ -export interface HoldToEarnAirdropDailyPnlV5 { - coinName: string; - yieldCoinName: string; - effectiveAmount: string; - pnl: string; - apy: string; - createdAt: number; -} +/** Page size [1, 49] */ ⋮---- -export interface HoldToEarnAirdropYieldHistoryResultV5 { - nextCursor: string; - airdropDailyPnls: HoldToEarnAirdropDailyPnlV5[]; -} +/** Pagination cursor from previous `nextCursor` */ ================ -File: src/types/response/v5-position.ts +File: src/types/request/v5-market.ts ================ +import { KlineIntervalV3 } from '../shared'; import { CategoryV5, - ExecTypeV5, - OrderSideV5, - OrderTypeV5, - PositionIdx, - PositionSideV5, - PositionStatusV5, - StopOrderTypeV5, - TPSLModeV5, - TradeModeV5, + InstrumentStatusV5, + InstrumentSymbolTypeV5, + OptionTypeV5, } from '../shared-v5'; ⋮---- -export interface FuturesLeverageItemV5 { +export interface GetKlineParamsV5 { + category: 'spot' | 'linear' | 'inverse'; symbol: string; - leverage: string; - side: OrderSideV5 | ''; - positionIdx: PositionIdx; + interval: KlineIntervalV3; + start?: number; + end?: number; + limit?: number; } ⋮---- -export interface FuturesLeverageResultV5 { +export interface GetMarkPriceKlineParamsV5 { + /** + * linear (default if omitted), inverse, or option. + */ + category?: 'linear' | 'inverse' | 'option'; + symbol: string; + interval: KlineIntervalV3; + start?: number; + end?: number; + /** + * Futures: [1, 1000], default 200. Options: [1, 500], default 200. + */ + limit?: number; +} +⋮---- +/** + * linear (default if omitted), inverse, or option. + */ +⋮---- +/** + * Futures: [1, 1000], default 200. Options: [1, 500], default 200. + */ +⋮---- +export interface GetIndexPriceKlineParamsV5 { category: 'linear' | 'inverse'; - list: FuturesLeverageItemV5[]; + symbol: string; + interval: KlineIntervalV3; + start?: number; + end?: number; + limit?: number; } ⋮---- -export interface PositionV5 { - positionIdx: PositionIdx; - riskId: number; - riskLimitValue: string; +export interface GetPremiumIndexPriceKlineParamsV5 { + category: 'linear'; symbol: string; - side: PositionSideV5; - size: string; - avgPrice: string; - positionValue: string; - tradeMode: TradeModeV5; - autoAddMargin?: number; - positionStatus: PositionStatusV5; - leverage?: string; - breakEvenPrice?: string; // Break even price, only for linear & inverse - markPrice: string; - liqPrice: string | ''; - bustPrice?: string; - positionIM?: string; - positionMM?: string; - positionBalance?: string; - tpslMode?: TPSLModeV5; - takeProfit?: string; - stopLoss?: string; - trailingStop?: string; - sessionAvgPrice: string | ''; - delta?: string; - gamma?: string; - vega?: string; - theta?: string; - unrealisedPnl: string; - curRealisedPnl: string; - cumRealisedPnl: string; - adlRankIndicator: number; - isReduceOnly: boolean; - mmrSysUpdatedTime: string | ''; - leverageSysUpdatedTime: string | ''; - createdTime: string; - updatedTime: string; - /** Position open timestamp (ms). Default `0` when not set. */ - openTime: number; - positionIMByMp: string; - positionMMByMp: string; - seq: number; + interval: KlineIntervalV3; + start?: number; + end?: number; + limit?: number; } ⋮---- -breakEvenPrice?: string; // Break even price, only for linear & inverse +export interface GetInstrumentsInfoParamsV5 { + category: CategoryV5; + symbol?: string; + /** Filter by instrument `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ + symbolType?: InstrumentSymbolTypeV5; + status?: InstrumentStatusV5; + baseCoin?: string; + limit?: number; + cursor?: string; +} ⋮---- -/** Position open timestamp (ms). Default `0` when not set. */ +/** Filter by instrument `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ ⋮---- -export interface SetRiskLimitResultV5 { +export interface GetOrderbookParamsV5 { category: CategoryV5; - riskId: number; - riskLimitValue: string; + symbol: string; + limit?: number; } ⋮---- -export interface AddOrReduceMarginResultV5 { +export interface GetRPIOrderbookParamsV5 { + category?: 'spot' | 'linear' | 'inverse'; + symbol: string; + limit: number; // Required for RPI orderbook, [1, 50] +} +⋮---- +limit: number; // Required for RPI orderbook, [1, 50] +⋮---- +export interface GetIndexPriceComponentsParamsV5 { + indexName: string; // Index name, like BTCUSDT +} +⋮---- +indexName: string; // Index name, like BTCUSDT +⋮---- +export interface GetADLAlertParamsV5 { + symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only +} +⋮---- +symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only +⋮---- +export interface GetFeeGroupStructureParamsV5 { + productType: string; // Product type. contract only for now + groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 +} +⋮---- +productType: string; // Product type. contract only for now +groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 +⋮---- +export interface GetTickersParamsV5 { + category: TCategory; + symbol?: string; + baseCoin?: string; + expDate?: string; +} +⋮---- +export interface GetFundingRateHistoryParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetPublicTradingHistoryParamsV5 { category: CategoryV5; symbol: string; - positionIdx: PositionIdx; - riskId: number; - riskLimitValue: string; - size: string; - avgPrice: string; - liqPrice: string; - bustPrice: string; - markPrice: string; - positionValue: string; - leverage: string; - autoAddMargin: 0 | 1; - positionStatus: PositionStatusV5; - positionIM: string; - positionMM: string; - takeProfit: string; - stopLoss: string; - trailingStop: string; - unrealisedPnl: string; - cumRealisedPnl: string; - createdTime: string; - updatedTime: string; + baseCoin?: string; + optionType?: OptionTypeV5; + limit?: number; } ⋮---- -export interface ExecutionV5 { +export type OpenInterestIntervalV5 = + | '5min' + | '15min' + | '30min' + | '1h' + | '4h' + | '1d'; +⋮---- +export interface GetOpenInterestParamsV5 { + category: 'linear' | 'inverse'; symbol: string; - orderId: string; - orderLinkId: string; - side: OrderSideV5; - orderPrice: string; - orderQty: string; - leavesQty: string; - orderType: OrderTypeV5; - stopOrderType?: StopOrderTypeV5; - execFee: string; - execFeeV2: string; - feeCurrency: string; // Trading fee currency - execId: string; - execPrice: string; - execQty: string; - execType: ExecTypeV5; - execValue: string; - execTime: string; - isMaker: boolean; - feeRate: string; - tradeIv?: string; - markIv?: string; - markPrice: string; - indexPrice: string; - underlyingPrice?: string; - blockTradeId?: string; - closedSize?: string; - seq: number; - extraFees: string; + intervalTime: OpenInterestIntervalV5; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -feeCurrency: string; // Trading fee currency +export interface GetHistoricalVolatilityParamsV5 { + category: 'option'; + baseCoin?: string; + period?: 7 | 14 | 21 | 30 | 60 | 90 | 180 | 270; + startTime?: number; + endTime?: number; +} ⋮---- -export interface ClosedPnLV5 { - symbol: string; - orderId: string; - side: string; - qty: string; - orderPrice: string; - orderType: OrderTypeV5; - execType: ExecTypeV5; - closedSize: string; - openFee: string; - closeFee: string; - cumEntryValue: string; - avgEntryPrice: string; - cumExitValue: string; - avgExitPrice: string; - closedPnl: string; - fillCount: string; - leverage: string; - createdTime: string; - updatedTime: string; +export interface GetInsuranceParamsV5 { + coin?: string; } ⋮---- -export interface MovePositionResultV5 { - blockTradeId: string; - status: 'Processing' | 'Rejected'; - rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; +export interface GetRiskLimitParamsV5 { + category?: 'linear' | 'inverse'; + symbol?: string; + cursor?: string; } ⋮---- -export interface MovePositionHistoryV5 { - blockTradeId: string; - category: 'linear' | 'spot' | 'option'; - orderId: string; - userId: number; +export interface GetOptionDeliveryPriceParamsV5 { + category: 'option'; + symbol?: string; + baseCoin?: string; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetDeliveryPriceParamsV5 { + category: 'linear' | 'inverse' | 'option'; + symbol?: string; + baseCoin?: string; + settleCoin?: string; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetLongShortRatioParamsV5 { + category: 'linear' | 'inverse'; symbol: string; - side: 'Buy' | 'Sell'; - price: string; - qty: string; - execFee: string; - status: 'Processing' | 'Filled' | 'Rejected'; - execId: string; - resultCode: number; - resultMessage: string; - createdAt: number; - updatedAt: number; - rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; + period: OpenInterestIntervalV5; + startTime?: string; + endTime?: string; + limit?: number; + cursor?: string; } ⋮---- -export interface ClosedOptionsPositionV5 { +export interface GetFullDepthOrderbookParamsV5 { + category: 'spot' | 'linear' | 'inverse'; symbol: string; - side: 'Buy' | 'Sell'; - totalOpenFee: string; - deliveryFee: string; - totalCloseFee: string; - qty: string; - closeTime: number; - avgExitPrice: string; - deliveryPrice: string; - openTime: number; - avgEntryPrice: string; - totalPnl: string; } ================ -File: src/types/response/v5-spot-leverage-token.ts +File: src/types/request/v5-spot-leverage-token.ts ================ -import { - LeverageTokenStatusV5, - LTOrderStatusV5, - LTOrderTypeV5, -} from '../shared-v5'; -⋮---- -export interface LeverageTokenInfoV5 { - ltCoin: string; - ltName: string; - maxPurchase: string; - minPurchase: string; - maxPurchaseDaily: string; - maxRedeem: string; - minRedeem: string; - maxRedeemDaily: string; - purchaseFeeRate: string; - redeemFeeRate: string; - ltStatus: LeverageTokenStatusV5; - fundFee: string; - fundFeeTime: string; - manageFeeRate: string; - manageFeeTime: string; - value: string; - netValue: string; - total: string; -} -⋮---- -export interface LeveragedTokenMarketResultV5 { - ltCoin: string; - nav: string; - navTime: string; - circulation: string; - basket: string; - leverage: string; -} +import { LTOrderTypeV5 } from '../shared-v5'; ⋮---- -export interface PurchaseSpotLeveragedTokenResultV5 { +export interface PurchaseSpotLeveragedTokenParamsV5 { ltCoin: string; - ltOrderStatus: LTOrderStatusV5; - execQty: string; - execAmt: string; amount: string; - purchaseId: string; - serialNo: string; - valueCoin: string; -} -export interface RedeemSpotLeveragedTokenResultV5 { - ltCoin: string; - ltOrderStatus: LTOrderStatusV5; - quantity: string; - execQty: string; - execAmt: string; - redeemId: string; - serialNo: string; - valueCoin: string; + serialNo?: string; } ⋮---- -export interface SpotLeveragedTokenOrderHistoryV5 { +export interface RedeemSpotLeveragedTokenParamsV5 { ltCoin: string; - orderId: string; - ltOrderType: LTOrderTypeV5; - orderTime: number; - updateTime: number; - ltOrderStatus: LTOrderStatusV5; - fee: string; - amount: string; - value: string; - valueCoin: string; - serialNo: string; + quantity: string; + serialNo?: string; } ⋮---- -export interface VIPMarginDataV5 { - vipCoinList: { - list: { - borrowable: boolean; - collateralRatio: string; - currency: string; - hourlyBorrowRate: string; - liquidationOrder: string; - marginCollateral: boolean; - maxBorrowingAmount: string; - }[]; - vipLevel: string; - }[]; +export interface GetSpotLeveragedTokenOrderHistoryParamsV5 { + ltCoin?: string; + orderId?: string; + startTime?: number; + endTime?: number; + limit?: number; + ltOrderType?: LTOrderTypeV5; + serialNo?: string; } ⋮---- -export interface SpotMarginCurrencyDataV5 { - currency: string; - flexibleManualBorrowable: boolean; - minFlexibleManualBorrowQty: string; - flexibleManualBorrowAccuracy: string; - fixedManualBorrowable: boolean; - minFixedManualBorrowQty: string; - fixedManualBorrowAccuracy: string; - fixedInterestRateAccuracy: string; - minFixedInterestRate: string; - maxFixedInterestRate: string; +export interface GetVIPMarginDataParamsV5 { + vipLevel?: string; + currency?: string; } ⋮---- -export interface SpotMarginStateV5 { - spotLeverage: string; - spotMarginMode: '1' | '0'; - effectiveLeverage: string; +export interface GetSpotMarginCurrencyDataParamsV5 { + currency?: string; } ⋮---- -// Spot Margin Trade (UTA) response types -export interface ManualBorrowResultV5 { +// Spot Margin Trade (UTA) endpoints +export interface ManualBorrowParamsV5 { coin: string; amount: string; } ⋮---- -export interface MaxBorrowableAmountV5 { +export interface GetMaxBorrowableAmountParamsV5 { currency: string; - maxLoan: string; } ⋮---- -export interface PositionTierV5 { - tier: string; - borrowLimit: string; - positionMMR: string; - positionIMR: string; - maxLeverage: string; +export interface GetPositionTiersParamsV5 { + currency?: string; } ⋮---- -export interface CurrencyPositionTiersV5 { - currency: string; - positionTiersRatioList: PositionTierV5[]; +export interface GetCoinStateParamsV5 { + currency?: string; } ⋮---- -export interface CoinStateV5 { +export interface GetAvailableAmountToRepayParamsV5 { currency: string; - spotLeverage: string; } ⋮---- -export interface AvailableAmountToRepayV5 { - currency: string; - lossLessRepaymentAmount: string; +export interface SetSpotMarginLeverageParamsV5 { + leverage: string; + currency?: string; } ⋮---- -export interface ManualRepayWithoutConversionResultV5 { +export interface ManualRepayWithoutConversionParamsV5 { + coin: string; + amount?: string; /** - * Result status: - * - P: Processing - * - SU: Success - * - FA: Failed + * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. */ - resultStatus: 'P' | 'SU' | 'FA'; + repaymentType?: 'ALL' | 'FIXED' | 'FLEXIBLE'; } ⋮---- /** - * Result status: - * - P: Processing - * - SU: Success - * - FA: Failed + * ALL: fixed + floating (floating first); FIXED: fixed only; FLEXIBLE: floating only. Default: FLEXIBLE. */ ⋮---- -export interface AutoRepayModeItemV5 { - currency: string; // Coin name, uppercase only +export interface GetAutoRepayModeParamsV5 { + currency?: string; // Coin name, uppercase only. If not passed, returns all currencies +} +⋮---- +currency?: string; // Coin name, uppercase only. If not passed, returns all currencies +⋮---- +export interface SetAutoRepayModeParamsV5 { + currency?: string; // Coin name, uppercase only. If not passed, enables for all currencies autoRepayMode: '0' | '1'; // 0: Off, 1: On } ⋮---- -currency: string; // Coin name, uppercase only +currency?: string; // Coin name, uppercase only. If not passed, enables for all currencies autoRepayMode: '0' | '1'; // 0: Off, 1: On ⋮---- -export interface AutoRepayModeResultV5 { - data: AutoRepayModeItemV5[]; +export interface GetSpotMarginLiabilityInfoParamsV5 { + currency: string; } ⋮---- -export interface SpotMarginLiabilityInfoV5 { - currency: string; - totalBorrowAmount: string; - fixedBorrowAmount: string; - flexibleBorrowAmount: string; - spotTotalBorrow: string; - derivativesBorrow: string; +export interface FixedRateBorrowParamsV5 { + orderCurrency: string; + orderAmount: string; + /** e.g. 0.02 = 2% p.a. */ + annualRate: string; + /** 7, 14, 30, 90, 180 (days) */ + term: string; + /** 1: auto repayment; 2: transfer to flexible loan */ + repayType?: '1' | '2'; } ⋮---- -export interface FixedRateBorrowResultV5 { - orderId: string; +/** e.g. 0.02 = 2% p.a. */ +⋮---- +/** 7, 14, 30, 90, 180 (days) */ +⋮---- +/** 1: auto repayment; 2: transfer to flexible loan */ +⋮---- +export interface GetFixedRateBorrowOrderInfoParamsV5 { + orderId?: string; + orderCurrency?: string; + state?: string; + term?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface FixedRateBorrowOrderInfoV5 { - annualRate: string; - orderId: string; - orderTime: string; - filledQty: string; - orderQty: string; +export interface GetFixedRateBorrowContractInfoParamsV5 { + orderId?: string; + orderCurrency?: string; + term?: string; + limit?: string; + cursor?: string; +} +⋮---- +export interface GetFixedRateBorrowOrderQuoteParamsV5 { orderCurrency: string; - state: number; - term: number; - repayType: string; - strategyType: 'PARTIAL' | 'FULL'; + term?: string; + orderBy?: 'apy' | 'term' | 'quantity'; + sort?: 0 | 1; + limit?: number; } ⋮---- -export interface FixedRateBorrowContractInfoV5 { - annualRate: string; - borrowCurrency: string; - borrowTime: string; - interestPaid: string; +export interface RenewFixedRateBorrowParamsV5 { loanId: string; - orderId: string; - repaymentTime: string; - residualPenaltyInterest: string; - residualPrincipal: string; - status: number; - term: string; - repayType: string; - strategyType: 'PARTIAL' | 'FULL'; + qty?: string; } ⋮---- -export interface FixedRateBorrowQuoteV5 { - orderCurrency: string; - term: number; +export interface GetFlexibleAvailableInventoryParamsV5 { + currency: string; +} +⋮---- +export interface GetFixedRateAvailableInventoryParamsV5 { + currency: string; + term: string; annualRate: string; - qty: string; } ================ -File: src/types/shared-v5.ts +File: src/types/request/v5-user.ts ================ -export type CategoryV5 = 'spot' | 'linear' | 'inverse' | 'option'; -export type ContractTypeV5 = - | 'InversePerpetual' - | 'LinearPerpetual' - | 'InverseFutures'; -export type CopyTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalOnly'; +import { PermissionsV5 } from '../shared-v5'; ⋮---- -export type InstrumentStatusV5 = - | 'PreLaunch' - | 'Trading' - | 'Settling' - | 'Delivering' - | 'Closed'; +export interface CreateSubMemberParamsV5 { + username: string; + password?: string; + /** + * 1: normal, 6: custodial + */ + memberType: 1 | 6; + /** + * 0: quick login disabled (default), 1: quick login enabled + */ + switch?: 0 | 1; + isUta?: boolean; + note?: string; +} ⋮---- /** - * Region / product class returned as `symbolType` on instruments-info (and account instruments-info). - * For `category=linear`, includes e.g. `stock`, `forex`, `commodity`, `xstocks`. Spot may return `''`. - */ -export type InstrumentSymbolTypeV5 = - | '' - | 'stock' - | 'forex' - | 'commodity' - | 'xstocks'; -⋮---- -export type MarginTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalSpotOnly'; -⋮---- -/** Product type for strategy APIs (create / list). */ -export type StrategyCategoryV5 = - | 'UTA_USDT' - | 'UTA_USDC' - | 'UTA_USDC_FUTURE' - | 'UTA_SPOT' - | 'UTA_INVERSE' - | 'UTA_INVERSE_FUTURE' - | 'UTA_USDT_FUTURE'; -⋮---- -export type StrategyTypeV5 = 'twap' | 'chaseOrder' | 'iceberg' | 'pov'; -⋮---- -export type StrategyPreferV5 = - | 'limit' - | 'priceSpeedBalance' - | 'fastestExecution' - | 'quickExecution'; -⋮---- -/** POV strategy execution mode */ -export type PovModeV5 = - | 'TradedVolume' - | 'OppositeSideLiquidity' - | 'SameSideLiquidity'; -⋮---- -export type OrderFilterV5 = 'Order' | 'tpslOrder' | 'StopOrder'; -export type OrderSideV5 = 'Buy' | 'Sell'; -export type OrderTypeV5 = 'Market' | 'Limit'; -export type OrderTimeInForceV5 = 'GTC' | 'IOC' | 'FOK' | 'PostOnly' | 'RPI'; -export type OrderTriggerByV5 = 'LastPrice' | 'IndexPrice' | 'MarkPrice'; -export type OCOTriggerTypeV5 = - | 'OcoTriggerByUnknown' - | 'OcoTriggerTp' - | 'OcoTriggerBySl'; -⋮---- -export type OrderSMPTypeV5 = - | 'None' - | 'CancelMaker' - | 'CancelTaker' - | 'CancelBoth'; -⋮---- -export type OrderStatusV5 = - | 'Created' - | 'New' - | 'Rejected' - | 'PartiallyFilled' - | 'PartiallyFilledCanceled' - | 'Filled' - | 'Cancelled' - | 'Untriggered' - | 'Triggered' - | 'Deactivated' - | 'Active'; + * 1: normal, 6: custodial + */ ⋮---- /** - * Defines the types of order creation mechanisms. - */ -export type OrderCreateTypeV5 = - /** Represents an order created by a user. */ - | 'CreateByUser' - /** Represents an order created by an admin closing. */ - | 'CreateByAdminClosing' - /** Futures conditional order. */ - | 'CreateByStopOrder' - /** Futures take profit order. */ - | 'CreateByTakeProfit' - /** Futures partial take profit order. */ - | 'CreateByPartialTakeProfit' - /** Futures stop loss order. */ - | 'CreateByStopLoss' - /** Futures partial stop loss order. */ - | 'CreateByPartialStopLoss' - /** Futures trailing stop order. */ - | 'CreateByTrailingStop' - /** Laddered liquidation to reduce the required maintenance margin. */ - | 'CreateByLiq' - /** - * If the position is still subject to liquidation (i.e., does not meet the required maintenance margin level), - * the position shall be taken over by the liquidation engine and closed at the bankruptcy price. + * 0: quick login disabled (default), 1: quick login enabled */ - | 'CreateByTakeOver_PassThrough' - /** Auto-Deleveraging(ADL) */ - | 'CreateByAdl_PassThrough' - /** Order placed via Paradigm. */ - | 'CreateByBlock_PassThrough' - /** Order created by move position. */ - | 'CreateByBlockTradeMovePosition_PassThrough' - /** The close order placed via web or app position area - web/app. */ - | 'CreateByClosing' - /** Order created via grid bot - web/app. */ - | 'CreateByFGridBot' - /** Order closed via grid bot - web/app. */ - | 'CloseByFGridBot' - /** Order created by TWAP - web/app. */ - | 'CreateByTWAP' - /** Order created by TV webhook - web/app. */ - | 'CreateByTVSignal' - /** Order created by Mm rate close function - web/app. */ - | 'CreateByMmRateClose' - /** Order created by Martingale bot - web/app. */ - | 'CreateByMartingaleBot' - /** Order closed by Martingale bot - web/app. */ - | 'CloseByMartingaleBot' - /** Order created by Ice berg strategy - web/app. */ - | 'CreateByIceBerg' - /** Order created by arbitrage - web/app. */ - | 'CreateByArbitrage' - /** Option dynamic delta hedge order - web/app */ - | 'CreateByDdh' - /** BBO Order - Best Bid/Offer order */ - | 'CreateByBboOrder'; -⋮---- -/** Represents an order created by a user. */ -⋮---- -/** Represents an order created by an admin closing. */ -⋮---- -/** Futures conditional order. */ ⋮---- -/** Futures take profit order. */ -⋮---- -/** Futures partial take profit order. */ +export interface CreateSubApiKeyParamsV5 { + subuid: number; + note?: string; + readOnly: 0 | 1; + ips?: string; + permissions: PermissionsV5; +} ⋮---- -/** Futures stop loss order. */ +export interface UpdateApiKeyParamsV5 { + apikey?: string; + readOnly?: 0 | 1; + permissions: PermissionsV5; +} ⋮---- -/** Futures partial stop loss order. */ +export interface UpdateSubApiKeyUpdateParamsV5 { + readOnly?: number; + ips?: string[]; + permissions: PermissionsV5; +} ⋮---- -/** Futures trailing stop order. */ +export interface DeleteSubMemberParamsV5 { + subMemberId: string; +} ⋮---- -/** Laddered liquidation to reduce the required maintenance margin. */ +export interface GetSubAccountAllApiKeysParamsV5 { + subMemberId: string; + limit?: number; + cursor?: string; +} ⋮---- -/** - * If the position is still subject to liquidation (i.e., does not meet the required maintenance margin level), - * the position shall be taken over by the liquidation engine and closed at the bankruptcy price. - */ +export interface GetAffiliateUserListParamsV5 { + size?: number; + cursor?: string; + needDeposit?: boolean; + need30?: boolean; + need365?: boolean; + startDate?: string; + endDate?: string; +} ⋮---- -/** Auto-Deleveraging(ADL) */ +/** GET /v5/affiliate/affiliate-sub-list */ +export interface GetAffiliateSubAffiliateListParamsV5 { + cursor?: string; + /** [0, 100]. Default: 0 */ + size?: number; + /** YYYY-MM-DD. Range with endDate max 3 months */ + startDate?: string; + /** YYYY-MM-DD. Must be provided with startDate or both omitted (T-1 default) */ + endDate?: string; + /** Exact sub-affiliate ID. 0 or omit for all */ + subAffId?: number; +} ⋮---- -/** Order placed via Paradigm. */ +/** [0, 100]. Default: 0 */ ⋮---- -/** Order created by move position. */ +/** YYYY-MM-DD. Range with endDate max 3 months */ ⋮---- -/** The close order placed via web or app position area - web/app. */ +/** YYYY-MM-DD. Must be provided with startDate or both omitted (T-1 default) */ ⋮---- -/** Order created via grid bot - web/app. */ +/** Exact sub-affiliate ID. 0 or omit for all */ ⋮---- -/** Order closed via grid bot - web/app. */ +export interface GetAffiliateUserInfoParamsV5 { + /** The master account UID of affiliate's client */ + uid: string; + /** Coin type for filtering, e.g. USDT */ + coin?: string; + /** + * Business line filter. 1: Derivatives, 2: Spot, 3: ByFi, 4: USDC, 5: Options + */ + business?: '1' | '2' | '3' | '4' | '5'; +} ⋮---- -/** Order created by TWAP - web/app. */ +/** The master account UID of affiliate's client */ ⋮---- -/** Order created by TV webhook - web/app. */ +/** Coin type for filtering, e.g. USDT */ ⋮---- -/** Order created by Mm rate close function - web/app. */ +/** + * Business line filter. 1: Derivatives, 2: Spot, 3: ByFi, 4: USDC, 5: Options + */ ⋮---- -/** Order created by Martingale bot - web/app. */ +/** Get Friend Referrals - invitation relationship status. 0: alive; 1: invalid */ +export interface GetFriendReferralsParamsV5 { + status?: string; + size?: string; + cursor?: string; +} ⋮---- -/** Order closed by Martingale bot - web/app. */ +/** Sign Agreement. Only master account. + * - `category` (legacy): 2 = metals (XAU/XAG perps; stock perps share this); 3 = crude oil. New enum values are not added here; prefer `categoryV2`. + * - `categoryV2` (recommended): 1 = metals; 2 = crude oil. Additional values may be added by the API; use a numeric literal or variable. + * - Either `category` or `categoryV2` must be sent. */ +export interface SignAgreementParamsV5 { + agree: boolean; + category?: 2 | 3; + categoryV2?: number; +} + +================ +File: src/types/response/v5-account.ts +================ +import { + AccountMarginModeV5, + AccountTypeV5, + CategoryV5, + TransactionTypeV5, + UnifiedUpdateStatusV5, +} from '../shared-v5'; ⋮---- -/** Order created by Ice berg strategy - web/app. */ +export interface WalletBalanceV5Coin { + coin: string; + equity: string; + usdValue: string; + walletBalance: string; + free: string; // spot only + locked: string; // spot only + borrowAmount: string; + availableToBorrow: string; // deprecated field + availableToWithdraw: string; + accruedInterest: string; + totalOrderIM: string; + totalPositionIM: string; + totalPositionMM: string; + unrealisedPnl: string; + cumRealisedPnl: string; + bonus: string; + marginCollateral: boolean; + collateralSwitch: boolean; + spotBorrow: string; + colRes?: string; +} ⋮---- -/** Order created by arbitrage - web/app. */ +free: string; // spot only +locked: string; // spot only ⋮---- -/** Option dynamic delta hedge order - web/app */ +availableToBorrow: string; // deprecated field ⋮---- -/** BBO Order - Best Bid/Offer order */ +export interface WalletBalanceV5 { + accountType: AccountTypeV5; + accountLTV: string; + accountIMRate: string; + accountMMRate: string; + accountIMRateByMp: string; + accountMMRateByMp: string; + totalInitialMarginByMp: string; + totalMaintenanceMarginByMp: string; + totalEquity: string; + totalWalletBalance: string; + totalMarginBalance: string; + totalAvailableBalance: string; + totalPerpUPL: string; + totalInitialMargin: string; + totalMaintenanceMargin: string; + coin: WalletBalanceV5Coin[]; +} ⋮---- -export type OrderCancelTypeV5 = - | 'CancelByUser' - | 'CancelByReduceOnly' - | 'CancelByPrepareLiq' - | 'CancelAllBeforeLiq' - | 'CancelByPrepareAdl' - | 'CancelAllBeforeAdl' - | 'CancelByAdmin' - | 'CancelByTpSlTsClear' - | 'CancelByPzSideCh' - | 'UNKNOWN'; +export interface UnifiedAccountUpgradeResultV5 { + unifiedUpdateStatus: UnifiedUpdateStatusV5; + unifiedUpdateMsg: { + msg: string[] | null; + }; +} ⋮---- -export type OrderRejectReasonV5 = - | 'EC_NoError' - | 'EC_Others' - | 'EC_UnknownMessageType' - | 'EC_MissingClOrdID' - | 'EC_MissingOrigClOrdID' - | 'EC_ClOrdIDOrigClOrdIDAreTheSame' - | 'EC_DuplicatedClOrdID' - | 'EC_OrigClOrdIDDoesNotExist' - | 'EC_TooLateToCancel' - | 'EC_UnknownOrderType' - | 'EC_UnknownSide' - | 'EC_UnknownTimeInForce' - | 'EC_WronglyRouted' - | 'EC_MarketOrderPriceIsNotZero' - | 'EC_LimitOrderInvalidPrice' - | 'EC_NoEnoughQtyToFill' - | 'EC_NoImmediateQtyToFill' - | 'EC_PerCancelRequest' - | 'EC_MarketOrderCannotBePostOnly' - | 'EC_PostOnlyWillTakeLiquidity' - | 'EC_CancelReplaceOrder' - | 'EC_InvalidSymbolStatus'; +export interface BorrowHistoryRecordV5 { + currency: string; + createdTime: number; + borrowCost: string; + hourlyBorrowRate: string; + InterestBearingBorrowSize: string; + costExemption: string; + borrowAmount: string; + unrealisedLoss: string; + freeBorrowedAmount: string; +} ⋮---- -export type StopOrderTypeV5 = - | 'TakeProfit' - | 'StopLoss' - | 'TrailingStop' - | 'Stop' - | 'PartialTakeProfit' - | 'PartialStopLoss' - | 'tpslOrder' - | 'OcoOrder' - | 'MmRateClose' - | 'BidirectionalTpslOrder'; +export interface CollateralInfoV5 { + currency: string; + hourlyBorrowRate: string; + maxBorrowingAmount: string; + freeBorrowAmount: string; + freeBorrowingLimit: string; + borrowAmount: string; + availableToBorrow: string; + borrowable: boolean; + borrowUsageRate: string; + marginCollateral: boolean; + collateralSwitch: boolean; + collateralRatio: string; +} ⋮---- -/** - * Position index. Used to identify positions in different position modes. - * - * - 0 one-way mode position - * - 1 Buy side of hedge-mode position - * - 2 Sell side of hedge-mode position - */ -export type PositionIdx = 0 | 1 | 2; +export interface CoinGreeksV5 { + baseCoin: string; + totalDelta: string; + totalGamma: string; + totalVega: string; + totalTheta: string; +} ⋮---- -/** - * Position status. - * - * - 'Normal' - * - 'Liq' in the liquidation progress - * - 'Adl' in the auto-deleverage progress - */ -export type PositionStatusV5 = 'Normal' | 'Liq' | 'Adl'; -export type PositionSideV5 = 'Buy' | 'Sell' | 'None' | ''; +export interface FeeRateV5 { + symbol: string; + baseCoin: string; + takerFeeRate: string; + makerFeeRate: string; +} ⋮---- -export type OptionTypeV5 = 'Call' | 'Put'; +export interface AccountInfoV5 { + unifiedMarginStatus: number; + marginMode: AccountMarginModeV5; + isMasterTrader: boolean; + spotHedgingStatus: string; + updatedTime: string; +} ⋮---- /** - * Trade mode. - * - * - 0 cross-margin, - * - 1 isolated margin + * Get Trade Behaviour Config / `getLimitPriceAction()` — `/v5/account/user-setting-config` */ -export type TradeModeV5 = 0 | 1; -⋮---- -export type TPSLModeV5 = 'Full' | 'Partial'; -export type AccountMarginModeV5 = - | 'ISOLATED_MARGIN' - | 'REGULAR_MARGIN' - | 'PORTFOLIO_MARGIN'; -export type UnifiedUpdateStatusV5 = 'FAIL' | 'PROCESS' | 'SUCCESS'; +export interface UserSettingConfigV5 { + lpaSpot: boolean; + lpaPerp: boolean; + /** Spot MNT fee deduction enabled. */ + smsef?: boolean; + /** Futures MNT fee deduction enabled. */ + fmsef?: boolean; + /** Delta Neutral mode; may be absent on older API responses. */ + deltaEnable?: boolean; + smpType?: '0' | '1' | '2' | '3' | string; +} ⋮---- -export type AccountTypeV5 = - | 'CONTRACT' - | 'SPOT' - | 'INVESTMENT' - | 'OPTION' - | 'UNIFIED' - | 'FUND' - | 'EARN'; +/** Spot MNT fee deduction enabled. */ ⋮---- -export type TransactionTypeV5 = - | 'TRANSFER_IN' - | 'TRANSFER_OUT' - | 'TRADE' - | 'SETTLEMENT' - | 'DELIVERY' - | 'LIQUIDATION' - | 'ADL' - | 'AIRDROP' - | 'BONUS_RECOLLECT' - | 'BONUS_RECOLLECT' - | 'FEE_REFUND' - | 'INTEREST' - | 'CURRENCY_BUY' - | 'CURRENCY_SELL' - | 'BORROWED_AMOUNT_INS_LOAN' - | 'PRINCIPLE_REPAYMENT_INS_LOAN' - | 'INTEREST_REPAYMENT_INS_LOAN' - | 'AUTO_SOLD_COLLATERAL_INS_LOAN' - | 'AUTO_BUY_LIABILITY_INS_LOAN' - | 'AUTO_PRINCIPLE_REPAYMENT_INS_LOAN' - | 'AUTO_INTEREST_REPAYMENT_INS_LOAN' - | 'TRANSFER_IN_INS_LOAN' - | 'TRANSFER_OUT_INS_LOAN' - | 'SPOT_REPAYMENT_SELL' - | 'SPOT_REPAYMENT_BUY' - | 'TOKENS_SUBSCRIPTION' - | 'TOKENS_REDEMPTION' - | 'AUTO_DEDUCTION' - | 'FLEXIBLE_STAKING_SUBSCRIPTION' - | 'FLEXIBLE_STAKING_REDEMPTION' - | 'FIXED_STAKING_SUBSCRIPTION' - | 'BORROWED_AMOUNT_INS_LOAN' - | 'PRINCIPLE_REPAYMENT_INS_LOAN' - | 'INTEREST_REPAYMENT_INS_LOAN' - | 'AUTO_SOLD_COLLATERAL_INS_LOAN' - | 'AUTO_BUY_LIABILITY_INS_LOAN' - | 'AUTO_PRINCIPLE_REPAYMENT_INS_LOAN' - | 'AUTO_INTEREST_REPAYMENT_INS_LOAN' - | 'TRANSFER_IN_INS_LOAN' - | 'TRANSFER_OUT_INS_LOAN' - | 'SPOT_REPAYMENT_SELL' - | 'SPOT_REPAYMENT_BUY' - | 'TOKENS_SUBSCRIPTION' - | 'TOKENS_REDEMPTION' - | 'AUTO_DEDUCTION' - | 'FLEXIBLE_STAKING_SUBSCRIPTION' - | 'FLEXIBLE_STAKING_REDEMPTION' - | 'FIXED_STAKING_SUBSCRIPTION' - | 'FLEXIBLE_STAKING_REFUND' - | 'FIXED_STAKING_REFUND' - | 'PREMARKET_TRANSFER_OUT' - | 'PREMARKET_DELIVERY_SELL_NEW_COIN' - | 'PREMARKET_DELIVERY_BUY_NEW_COIN' - | 'PREMARKET_DELIVERY_PLEDGE_PAY_SELLER' - | 'PREMARKET_DELIVERY_PLEDGE_BACK' - | 'PREMARKET_ROLLBACK_PLEDGE_BACK' - | 'PREMARKET_ROLLBACK_PLEDGE_PENALTY_TO_BUYER' - | 'CUSTODY_NETWORK_FEE' - | 'CUSTODY_SETTLE_FEE' - | 'CUSTODY_LOCK' - | 'CUSTODY_UNLOCK' - | 'CUSTODY_UNLOCK_REFUND' - | 'LOANS_BORROW_FUNDS' - | 'LOANS_PLEDGE_ASSET' - | 'BONUS_TRANSFER_IN' - | 'BONUS_TRANSFER_OUT' - | 'PEF_TRANSFER_IN' - | 'PEF_TRANSFER_OUT' - | 'PEF_PROFIT_SHARE' - | 'ONCHAINEARN_SUBSCRIPTION' - | 'ONCHAINEARN_REDEMPTION' - | 'ONCHAINEARN_REFUND' - | 'STRUCTURE_PRODUCT_SUBSCRIPTION' - | 'STRUCTURE_PRODUCT_REFUND' - | 'CLASSIC_WEALTH_MANAGEMENT_SUBSCRIPTION' - | 'PREMIMUM_WEALTH_MANAGEMENT_SUBSCRIPTION' - | 'PREMIMUM_WEALTH_MANAGEMENT_REFUND' - | 'LIQUIDITY_MINING_SUBSCRIPTION' - | 'LIQUIDITY_MINING_REFUND' - | 'PWM_SUBSCRIPTION' - | 'PWM_REFUND' - | 'DEFI_INVESTMENT_SUBSCRIPTION' - | 'DEFI_INVESTMENT_REFUND' - | 'DEFI_INVESTMENT_REDEMPTION' - | 'INSTITUTION_LOAN_IN' - | 'INSTITUTION_PAYBACK_PRINCIPAL_OUT' - | 'INSTITUTION_PAYBACK_INTEREST_OUT' - | 'INSTITUTION_EXCHANGE_SELL' - | 'INSTITUTION_EXCHANGE_BUY' - | 'INSTITUTION_LIQ_PRINCIPAL_OUT' - | 'INSTITUTION_LIQ_INTEREST_OUT' - | 'INSTITUTION_LOAN_TRANSFER_IN' - | 'INSTITUTION_LOAN_TRANSFER_OUT' - | 'INSTITUTION_LOAN_WITHOUT_WITHDRAW' - | 'INSTITUTION_LOAN_RESERVE_IN' - | 'INSTITUTION_LOAN_RESERVE_OUT' - | 'PLATFORM_TOKEN_MNT_LIQRECALLEDMMNT' - | 'PLATFORM_TOKEN_MNT_LIQRETURNEDMNT'; +/** Futures MNT fee deduction enabled. */ ⋮---- -export type PermissionTypeV5 = - | 'ContractTrade' - | 'Spot' - | 'Wallet' - | 'Options' - | 'Derivatives' - | 'Exchange' - | 'NFT'; +/** Delta Neutral mode; may be absent on older API responses. */ ⋮---- -/** - * Leveraged token status: - * - * - '1' LT can be purchased and redeemed - * - '2' LT can be purchased, but not redeemed - * - '3' LT can be redeemed, but not purchased - * - '4' LT cannot be purchased nor redeemed - * - '5' Adjusting position - */ -export type LeverageTokenStatusV5 = '1' | '2' | '3' | '4' | '5'; +export interface TransactionLogV5 { + symbol: string; + category: CategoryV5; + side: string; + transactionTime: string; + type: TransactionTypeV5; + qty: string; + size: string; + currency: string; + tradePrice: string; + funding: string; + fee: string; + cashFlow: string; + change: string; + cashBalance: string; + feeRate: string; + bonusChange: string; + tradeId: string; + orderId: string; + orderLinkId: string; + extraFees: string; + transSubType: string; + displayType?: string; +} ⋮---- -/** - * Leveraged token order type: '1': purchase, '2': redeem - */ -export type LTOrderTypeV5 = '1' | '2'; +export interface MMPStateV5 { + baseCoin: string; + mmpEnabled: boolean; + window: string; + frozenPeriod: string; + qtyLimit: string; + deltaLimit: string; + vegaLimit?: string; + mmpFrozenUntil: string; + mmpFrozen: boolean; +} ⋮---- -/** - * Leveraged token order status: '1': completed, '2': in progress, '3': failed - */ -export type LTOrderStatusV5 = '1' | '2' | '3'; +export interface RepayLiabilityResultV5 { + coin: string; + repaymentQty: string; +} ⋮---- -export type ExecTypeV5 = - | 'Trade' - | 'AdlTrade' - | 'Funding' - | 'BustTrade' - | 'Settle' - | 'BlockTrade' - | 'MovePosition' - | 'UNKNOWN'; +export interface DCPInfoV5 { + product: 'SPOT' | 'DERIVATIVES' | 'OPTIONS'; + dcpStatus: 'ON'; + timeWindow: string; +} ⋮---- -/** - * Withdraw type. 0(default): on chain. 1: off chain. 2: all. - */ -export type WithdrawalTypeV5 = '0' | '1' | '2'; +export interface ManualRepayResultV5 { + resultStatus: 'P' | 'SU' | 'FA'; +} ⋮---- -export interface PermissionsV5 { - ContractTrade?: string[]; - Spot?: string[]; - Wallet?: string[]; - Options?: string[]; - Derivatives?: string[]; - CopyTrading?: string[]; - BlockTrade?: string[]; - Exchange?: string[]; - /** @deprecated , always returns []*/ - NFT?: string[]; - Earn?: string[]; - Affiliate?: string[]; - FiatP2P?: string[]; - /** Bybit Pay (FaitPayOrder) */ - FiatBitPay?: string[]; - FiatConvertBroker?: string[]; - BitCard?: string[]; - ByXPost?: string[]; +/** GET /v5/account/option-asset-info — response `result` wraps a nested `result` array. */ +export interface OptionAssetInfoRowV5 { + coin: string; + totalDelta: string; + totalRPL: string; + totalUPL: string; + assetIM: string; + assetMM: string; + sendTime: number; +} +⋮---- +export interface OptionAssetInfoNestedResultV5 { + result: OptionAssetInfoRowV5[]; } ⋮---- -/** @deprecated , always returns []*/ +/** GET /v5/account/pay-info */ +export interface PayInfoCollateralItemV5 { + coin: string; + availableSize: string; + availableValue: string; + coinScale: number; + borrowSize: string; + spotHedgeAmount: string; + assetFrozen: string; +} ⋮---- -/** Bybit Pay (FaitPayOrder) */ +export interface PayInfoBorrowBlockV5 { + coin?: string; + borrowSize: string; + borrowValue?: string; + assetFrozen: string; + availableBalance: string; +} ⋮---- -export interface CategoryCursorListV5< - T extends unknown[], - TCategory extends CategoryV5 = CategoryV5, -> { - category: TCategory; - list: T; - nextPageCursor?: string; +export interface PayInfoResultV5 { + collateralInfo: { + collateralList: PayInfoCollateralItemV5[]; + }; + borrowInfo: PayInfoBorrowBlockV5; } ⋮---- -/** - * Next page cursor does not exist for spot! - */ -export interface CursorListV5 { - nextPageCursor: string; - list: T; +/** GET /v5/account/trade-info-for-analysis */ +export interface TradeInfoAnalysisDailyV5 { + day: string; + sumBuyExecValue: string; + sumSellExecValue: string; + sumExecValue: string; } ⋮---- -/** - * A wrapper type for any responses that have a "nextPageCursor" property, and a "rows" property with an array of elements - * - * ```{ nextPageCursor: "something", rows: someData[] }``` - */ -export interface CursorRowsV5 { - nextPageCursor: string; - rows: T; +export interface TradeInfoForAnalysisResultV5 { + symbolRnl: string; + netExecQty: string; + sumExecValue: string; + sumExecQty: string; + avgBuyExecPrice: string; + sumBuyExecValue: string; + sumBuyExecQty: string; + sumBuyExecFee: string; + sumBuyOrderQty: string; + avgSellExecPrice: string; + sumSellExecValue: string; + sumSellExecQty: string; + sumSellExecFee: string; + sumSellOrderQty: string; + maxMarginVersion: number; + baseCoin: string; + settleCoin: string; + sumPriceList?: TradeInfoAnalysisDailyV5[]; +} + +================ +File: src/types/response/v5-crypto-loan.ts +================ +export interface CollateralCoinV5 { + collateralAccuracy: number; + initialLTV: string; + liquidationLTV: string; + marginCallLTV: string; + maxLimit: string; } ⋮---- -export interface CategoryListV5< - T extends unknown[], - TCategory extends CategoryV5, -> { - category: TCategory; - list: T; +export interface VipCollateralCoinsV5 { + list: CollateralCoinV5[]; + vipLevel: string; } ⋮---- -export interface CategorySymbolListV5< - T extends unknown[], - TCategory extends CategoryV5, -> { - category: TCategory; - symbol: string; - list: T; +export interface BorrowableCoinV5 { + borrowingAccuracy: number; + currency: string; + flexibleHourlyInterestRate: string; + hourlyInterestRate7D: string; + hourlyInterestRate14D: string; + hourlyInterestRate30D: string; + hourlyInterestRate90D: string; + hourlyInterestRate180D: string; + maxBorrowingAmount: string; + minBorrowingAmount: string; } ⋮---- -export interface GetSystemStatusParamsV5 { - id?: string; - state?: string; +export interface VipBorrowableCoinsV5 { + list: BorrowableCoinV5[]; + vipLevel: string; } ⋮---- -export interface SystemStatusItemV5 { - id: string; - title: string; - state: string; - begin: string; - end: string; - href: string; - serviceTypes: number[]; - product: number[]; - uidSuffix: number[]; - maintainType: string; - env: string; +export interface AccountBorrowCollateralLimitV5 { + collateralCurrency: string; + loanCurrency: string; + maxCollateralAmount: string; + maxLoanAmount: string; + minCollateralAmount: string; + minLoanAmount: string; } - -================ -File: src/types/request/v5-asset.ts -================ -import { AccountTypeV5, CategoryV5 } from '../shared-v5'; ⋮---- -export interface GetCoinExchangeRecordParamsV5 { - fromCoin?: string; - toCoin?: string; - limit?: number; - cursor?: string; +export interface UnpaidLoanOrderV5 { + collateralAmount: string; + collateralCurrency: string; + currentLTV: string; + expirationTime: string; + hourlyInterestRate: string; + loanCurrency: string; + loanTerm: string; + orderId: string; + residualInterest: string; + residualPenaltyInterest: string; + totalDebt: string; } ⋮---- -export interface GetDeliveryRecordParamsV5 { - category: CategoryV5; - symbol?: string; - startTime?: number; - endTime?: number; - expDate?: string; - limit?: number; - cursor?: string; +export interface RepaymentHistoryV5 { + collateralCurrency: string; + collateralReturn: string; + loanCurrency: string; + loanTerm: string; + orderId: string; + repayAmount: string; + repayId: string; + repayStatus: number; + repayTime: string; + repayType: string; } ⋮---- -export interface GetSettlementRecordParamsV5 { - category: CategoryV5; - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface CompletedLoanOrderV5 { + borrowTime: string; + collateralCurrency: string; + expirationTime: string; + hourlyInterestRate: string; + initialCollateralAmount: string; + initialLoanAmount: string; + loanCurrency: string; + loanTerm: string; + orderId: string; + repaidInterest: string; + repaidPenaltyInterest: string; + status: number; +} +export interface LoanLTVAdjustmentHistoryV5 { + collateralCurrency: string; + orderId: string; + adjustId: string; + adjustTime: string; + preLTV: string; + afterLTV: string; + direction: number; + amount: string; } ⋮---- -export interface GetAssetInfoParamsV5 { - accountType: AccountTypeV5; - coin?: string; +// New Crypto Loan Types +⋮---- +export interface BorrowCoinV5 { + currency: string; + fixedBorrowable: boolean; + fixedBorrowingAccuracy: number; + flexibleBorrowable: boolean; + flexibleBorrowingAccuracy: number; + maxBorrowingAmount: string; + minFixedBorrowingAmount: string; + minFlexibleBorrowingAmount: string; + vipLevel: string; + flexibleAnnualizedInterestRate: string; + annualizedInterestRate7D: string; + annualizedInterestRate14D: string; + annualizedInterestRate30D: string; + annualizedInterestRate60D: string; + annualizedInterestRate90D: string; + annualizedInterestRate180D: string; } ⋮---- -export interface GetAllCoinsBalanceParamsV5 { - memberId?: string; - accountType: AccountTypeV5; - coin?: string; - withBonus?: number; +export interface CollateralRatioV5 { + collateralRatio: string; + maxValue: string; + minValue: string; } ⋮---- -export interface GetAccountCoinBalanceParamsV5 { - memberId?: string; - toMemberId?: string; - accountType: AccountTypeV5; - coin: string; - toAccountType?: AccountTypeV5; - withBonus?: number; - withTransferSafeAmount?: 0 | 1; - withLtvTransferSafeAmount?: 0 | 1; +export interface CollateralRatioConfigV5 { + collateralRatioList: CollateralRatioV5[]; + currencies: string; +} +⋮---- +export interface CurrencyLiquidationV5 { + currency: string; + liquidationOrder: number; +} +⋮---- +export interface CollateralDataV5 { + collateralRatioConfigList: CollateralRatioConfigV5[]; + currencyLiquidationList: CurrencyLiquidationV5[]; } ⋮---- -export interface GetInternalTransferParamsV5 { - transferId?: string; - coin?: string; - status?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +// Additional New Crypto Loan Types +⋮---- +export interface AdjustCollateralAmountV5 { + adjustId: number; } ⋮---- -export interface UniversalTransferParamsV5 { - transferId: string; - coin: string; +export interface CollateralAdjustmentHistoryV5 { + adjustId: number; + adjustTime: number; + afterLTV: string; amount: string; - fromMemberId: number; - toMemberId: number; - fromAccountType: AccountTypeV5; - toAccountType: AccountTypeV5; + collateralCurrency: string; + direction: number; + preLTV: string; + status: number; } ⋮---- -export interface GetUniversalTransferRecordsParamsV5 { - transferId?: string; - coin?: string; - status?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface BorrowListV5 { + fixedTotalDebt: string; + fixedTotalDebtUSD: string; + flexibleHourlyInterestRate: string; + flexibleTotalDebt: string; + flexibleTotalDebtUSD: string; + loanCurrency: string; } ⋮---- -export interface GetAllowedDepositCoinInfoParamsV5 { - coin?: string; - chain?: string; - limit?: number; - cursor?: string; +export interface CollateralListV5 { + amount: string; + amountUSD: string; + currency: string; + ltv: string; } ⋮---- -export interface GetDepositRecordParamsV5 { - id?: string; - txID?: string; - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface SupplyListV5 { + amount: string; + amountUSD: string; + currency: string; } ⋮---- -export interface GetSubAccountDepositRecordParamsV5 { - id?: string; - txID?: string; - subMemberId: string; - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface CryptoLoanPositionV5 { + borrowList: BorrowListV5[]; + collateralList: CollateralListV5[]; + supplyList: SupplyListV5[]; + totalCollateral: string; + totalDebt: string; + totalSupply: string; + colRes?: string; } ⋮---- -export interface GetInternalDepositRecordParamsV5 { - txID?: string; - startTime?: number; - endTime?: number; - coin?: string; - cursor?: string; - limit?: number; -} +// Flexible Loan Types ⋮---- -export interface GetWithdrawalRecordsParamsV5 { - withdrawID?: string; - txID?: string; - coin?: string; - withdrawType?: number; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface BorrowFlexibleV5 { + orderId: string; } ⋮---- -export interface GetWithdrawalAddressListParamsV5 { - coin?: string; - chain?: string; - addressType?: 0 | 1 | 2; - limit?: number; - cursor?: string; +export interface RepayFlexibleV5 { + repayId: string; } ⋮---- -export interface SubmitDepositOriginatorInfoParamsV5 { - depositId: number; - subAccountId?: number; - /** Travel Rule questionnaire JSON string. See Questionnaire docs. */ - questionnaire: string; +export interface OngoingFlexibleLoanV5 { + hourlyInterestRate: string; + loanCurrency: string; + totalDebt: string; + unpaidAmount: string; + unpaidInterest: string; } ⋮---- -/** Travel Rule questionnaire JSON string. See Questionnaire docs. */ +export interface BorrowHistoryFlexibleV5 { + borrowTime: number; + initialLoanAmount: string; + loanCurrency: string; + orderId: string; + status: number; +} ⋮---- -export interface WithdrawParamsV5 { - coin: string; - /** - * When forceChain is 0 or 1, required. When forceChain is 2 (Bybit UID withdraw), may be null/omitted. - */ - chain?: string; - address: string; - tag?: string; - amount: string; - timestamp: number; - forceChain?: number; - /** - * FUND, UTA, or EARN; or comma combo e.g. FUND,UTA,EARN (funding first, then UTA and Earn for remainder). - * SPOT is legacy if still supported for older integrations. - */ - accountType: string; - feeType?: 0 | 1; - requestId?: string; - /** - * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. - */ - transactionPurpose?: string; - /** - * Travel Rule questionnaire JSON string (max 16384 bytes). Takes precedence over `beneficiary` / `transactionPurpose` when both are set. - */ - questionnaire?: string; - beneficiary?: { - vaspEntityId?: string; - beneficiaryName?: string; - beneficiaryLegalType?: string; - beneficiaryWalletType?: string; - beneficiaryUnhostedWalletType?: string; - beneficiaryPoiNumber?: string; - beneficiaryPoiType?: string; - beneficiaryPoiIssuingCountry?: string; - beneficiaryPoiExpiredDate?: string; - }; +export interface RepaymentHistoryFlexibleV5 { + loanCurrency: string; + repayAmount: string; + repayId: string; + repayStatus: number; + repayTime: number; + repayType: number; } ⋮---- -/** - * When forceChain is 0 or 1, required. When forceChain is 2 (Bybit UID withdraw), may be null/omitted. - */ +// Fixed Loan Types ⋮---- -/** - * FUND, UTA, or EARN; or comma combo e.g. FUND,UTA,EARN (funding first, then UTA and Earn for remainder). - * SPOT is legacy if still supported for older integrations. - */ +export interface SupplyOrderQuoteFixedV5 { + orderCurrency: string; + term: number; + annualRate: string; + qty: string; +} ⋮---- -/** - * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. - */ +export interface BorrowOrderQuoteFixedV5 { + orderCurrency: string; + term: number; + annualRate: string; + qty: string; +} ⋮---- -/** - * Travel Rule questionnaire JSON string (max 16384 bytes). Takes precedence over `beneficiary` / `transactionPurpose` when both are set. - */ +export interface CreateBorrowOrderFixedV5 { + orderId: string; +} ⋮---- -export interface ConvertCoinsParamsV5 { - coin?: string; - side?: number; - accountType: - | 'eb_convert_funding' - | 'eb_convert_uta' - | 'eb_convert_spot' - | 'eb_convert_contract' - | 'eb_convert_inverse'; +export interface CreateSupplyOrderFixedV5 { + orderId: string; } ⋮---- -export interface RequestConvertQuoteParamsV5 { - fromCoin: string; - toCoin: string; - fromCoinType?: string; - toCoinType?: string; - requestCoin: string; - requestAmount: string; - accountType: - | 'eb_convert_funding' - | 'eb_convert_uta' - | 'eb_convert_spot' - | 'eb_convert_contract' - | 'eb_convert_inverse'; - requestId?: string; +export interface BorrowContractInfoFixedV5 { + annualRate: string; + autoRepay: string; // Deprecated + borrowCurrency: string; + borrowTime: string; + interestPaid: string; + loanId: string; + orderId: string; + repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment + repaymentTime: string; + residualPenaltyInterest: string; + residualPrincipal: string; + status: number; + term: string; } ⋮---- -export interface GetConvertHistoryParamsV5 { - accountType?: string; - index?: number; - limit?: number; +autoRepay: string; // Deprecated +⋮---- +repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +⋮---- +export interface SupplyContractInfoFixedV5 { + annualRate: string; + supplyCurrency: string; + supplyTime: string; + supplyAmount: string; + interestPaid: string; + supplyId: string; + orderId: string; + redemptionTime: string; + penaltyInterest: string; + actualRedemptionTime: string; + status: number; + term: string; } ⋮---- -export interface GetSmallBalanceListParamsV5 { - accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet - fromCoin?: string; // Source currency +export interface BorrowOrderInfoFixedV5 { + annualRate: string; + orderId: number; + orderTime: string; + filledQty: string; + orderQty: string; + orderCurrency: string; + state: number; + term: number; + repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment + strategyType?: 'PARTIAL' | 'FULL' | string; } ⋮---- -accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet -fromCoin?: string; // Source currency +repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment ⋮---- -export interface GetFiatTradingPairListParamsV5 { - side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) +export interface FixedLoanAvailableInventoryV5 { + currency: string; + term: string; + annualRate: string; + availableInventory: string; + updateTime: string; } ⋮---- -side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) -⋮---- -/** Funding Account Transaction History. Interval createTimeFrom-createTimeTo max 7 days. */ -export interface GetFundingAccountTransactionHistoryParamsV5 { - createTimeFrom?: string; - createTimeTo?: string; - limit?: string; - cursor?: string; +export interface FlexibleLoanAvailableInventoryV5 { + currency: string; + availableInventory: string; + updateTime: string; } ⋮---- -/** Asset Overview. memberId required when querying sub account via master API key. */ -export interface GetAssetOverviewParamsV5 { - memberId?: string; - /** Fiat currency for valuation; defaults to USD if omitted. */ - valuationCurrency?: string; - /** Account type filter; returns all if omitted. */ - accountType?: string; +export interface SupplyOrderInfoFixedV5 { + annualRate: string; + orderId: number; + orderTime: string; + filledQty: string; + orderQty: string; + orderCurrency: string; + state: number; + term: number; } ⋮---- -/** Fiat currency for valuation; defaults to USD if omitted. */ -⋮---- -/** Account type filter; returns all if omitted. */ -⋮---- -/** GET /v5/asset/portfolio-margin */ -export interface GetPortfolioMarginInfoParamsV5 { - baseCoin?: string; +export interface RepayFixedV5 { + repayId: string; } ⋮---- -/** GET /v5/asset/total-members-assets */ -export interface GetTotalMembersAssetsParamsV5 { - /** If omitted, defaults to BTC. Total is quoted in this coin. */ - coin?: string; +export interface RepaymentHistoryFixedV5 { + details: { + loanCurrency: string; + loanId: string; + repayAmount: string; + }[]; + loanCurrency: string; + repayAmount: string; + repayId: string; + repayStatus: number; + repayTime: number; + repayType: number; } ⋮---- -/** If omitted, defaults to BTC. Total is quoted in this coin. */ - -================ -File: src/types/request/v5-user.ts -================ -import { PermissionsV5 } from '../shared-v5'; -⋮---- -export interface CreateSubMemberParamsV5 { - username: string; - password?: string; - /** - * 1: normal, 6: custodial - */ - memberType: 1 | 6; - /** - * 0: quick login disabled (default), 1: quick login enabled - */ - switch?: 0 | 1; - isUta?: boolean; - note?: string; +export interface RenewBorrowOrderFixedV5 { + orderId: string; } ⋮---- -/** - * 1: normal, 6: custodial - */ +export interface RenewOrderInfoFixedV5 { + amount: string; + autoRepay: number; + borrowCurrency: string; + contractNo: string; + dueTime: string; + loanId: string; + orderId: number; + renewLoanNo: string; + time: string; +} ⋮---- -/** - * 0: quick login disabled (default), 1: quick login enabled - */ +// Institutional Loan Types ⋮---- -export interface CreateSubApiKeyParamsV5 { - subuid: number; - note?: string; - readOnly: 0 | 1; - ips?: string; - permissions: PermissionsV5; +export interface InstitutionalLendingProductInfoV5 { + productId: string; + leverage: string; + supportSpot: number; + supportContract: number; + supportMarginTrading: number; + withdrawLine: string; + transferLine: string; + spotBuyLine: string; + spotSellLine: string; + contractOpenLine: string; + liquidationLine: string; + stopLiquidationLine: string; + contractLeverage: string; + transferRatio: string; + spotSymbols: unknown[]; + contractSymbols: unknown[]; + supportUSDCContract: number; + supportUSDCOptions: number; + USDTPerpetualOpenLine?: string; + USDCContractOpenLine?: string; + USDCOptionsOpenLine?: string; + USDTPerpetualCloseLine?: string; + USDCContractCloseLine?: string; + USDCOptionsCloseLine?: string; + USDTPerpetualLeverage?: { symbol: string; leverage: string }[]; + USDCContractLeverage?: { symbol: string; leverage: string }[]; + deferredLiquidationLine?: string; + deferredLiquidationTime?: string; + marginLeverage?: string; + /** `0`: Default, `1`: CTA, `2`: Hedge */ + productType?: '0' | '1' | '2' | string; } ⋮---- -export interface UpdateApiKeyParamsV5 { - apikey?: string; - readOnly?: 0 | 1; - permissions: PermissionsV5; -} +/** `0`: Default, `1`: CTA, `2`: Hedge */ ⋮---- -export interface UpdateSubApiKeyUpdateParamsV5 { - readOnly?: number; - ips?: string[]; - permissions: PermissionsV5; +export interface InstitutionalLendingCoinDeltaItemV5 { + coin: string; + coinDeltaSize: string; + coinDeltaAvailableAmount: string; + coinDeltaAmount: string; } ⋮---- -export interface DeleteSubMemberParamsV5 { - subMemberId: string; +export interface InstitutionalLendingCoinDeltaAmountV5 { + riskUnitDeltaAmount: string; + riskUnitDeltaAvailableAmount: string; + riskUnitDelta?: string; + list: InstitutionalLendingCoinDeltaItemV5[]; } ⋮---- -export interface GetSubAccountAllApiKeysParamsV5 { - subMemberId: string; - limit?: number; - cursor?: string; +export interface UnpaidInfoV5 { + token: string; // Coin + unpaidQty: string; // Unpaid principle + unpaidInterest: string; // Unpaid interest } ⋮---- -export interface GetAffiliateUserListParamsV5 { - size?: number; - cursor?: string; - needDeposit?: boolean; - need30?: boolean; - need365?: boolean; - startDate?: string; - endDate?: string; -} +token: string; // Coin +unpaidQty: string; // Unpaid principle +unpaidInterest: string; // Unpaid interest ⋮---- -/** GET /v5/affiliate/affiliate-sub-list */ -export interface GetAffiliateSubAffiliateListParamsV5 { - cursor?: string; - /** [0, 100]. Default: 0 */ - size?: number; - /** YYYY-MM-DD. Range with endDate max 3 months */ - startDate?: string; - /** YYYY-MM-DD. Must be provided with startDate or both omitted (T-1 default) */ - endDate?: string; - /** Exact sub-affiliate ID. 0 or omit for all */ - subAffId?: number; +export interface BalanceInfoV5 { + token: string; // Margin coin + price: string; // Margin coin price + qty: string; // Margin coin quantity + convertedAmount: string; // Margin conversion amount } ⋮---- -/** [0, 100]. Default: 0 */ -⋮---- -/** YYYY-MM-DD. Range with endDate max 3 months */ +token: string; // Margin coin +price: string; // Margin coin price +qty: string; // Margin coin quantity +convertedAmount: string; // Margin conversion amount ⋮---- -/** YYYY-MM-DD. Must be provided with startDate or both omitted (T-1 default) */ +export interface LTVInfoV5 { + ltv: string; // Risk rate (when liqStatus != 0, returns empty string) + rst: string; // Remaining liquidation time in UTC seconds (when liqStatus != 0, returns empty string) + parentUid: string; // The designated Risk Unit ID + subAccountUids: string[]; // Bound user IDs + unpaidAmount: string; // Total debt in USDT (when liqStatus != 0, returns empty string) + unpaidInfo: UnpaidInfoV5[]; // Debt details (when liqStatus != 0, returns empty array) + balance: string; // Total asset in USDT (when liqStatus != 0, returns empty string) + balanceInfo: BalanceInfoV5[]; // Asset details (when liqStatus != 0, returns empty array) + liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress +} ⋮---- -/** Exact sub-affiliate ID. 0 or omit for all */ +ltv: string; // Risk rate (when liqStatus != 0, returns empty string) +rst: string; // Remaining liquidation time in UTC seconds (when liqStatus != 0, returns empty string) +parentUid: string; // The designated Risk Unit ID +subAccountUids: string[]; // Bound user IDs +unpaidAmount: string; // Total debt in USDT (when liqStatus != 0, returns empty string) +unpaidInfo: UnpaidInfoV5[]; // Debt details (when liqStatus != 0, returns empty array) +balance: string; // Total asset in USDT (when liqStatus != 0, returns empty string) +balanceInfo: BalanceInfoV5[]; // Asset details (when liqStatus != 0, returns empty array) +liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress ⋮---- -export interface GetAffiliateUserInfoParamsV5 { - /** The master account UID of affiliate's client */ - uid: string; - /** Coin type for filtering, e.g. USDT */ - coin?: string; - /** - * Business line filter. 1: Derivatives, 2: Spot, 3: ByFi, 4: USDC, 5: Options - */ - business?: '1' | '2' | '3' | '4' | '5'; +export interface InstitutionalLoanLTVV5 { + ltvInfo: LTVInfoV5[]; // LTV info array + liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress } ⋮---- -/** The master account UID of affiliate's client */ +ltvInfo: LTVInfoV5[]; // LTV info array +liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress ⋮---- -/** Coin type for filtering, e.g. USDT */ +export interface RepayInstitutionalLoanResultV5 { + repayOrderStatus: string; // P: processing +} ⋮---- -/** - * Business line filter. 1: Derivatives, 2: Spot, 3: ByFi, 4: USDC, 5: Options - */ +repayOrderStatus: string; // P: processing ⋮---- -/** Get Friend Referrals - invitation relationship status. 0: alive; 1: invalid */ -export interface GetFriendReferralsParamsV5 { - status?: string; - size?: string; - cursor?: string; -} +// Max Loan Amount Response Types ⋮---- -/** Sign Agreement. Only master account. - * - `category` (legacy): 2 = metals (XAU/XAG perps; stock perps share this); 3 = crude oil. New enum values are not added here; prefer `categoryV2`. - * - `categoryV2` (recommended): 1 = metals; 2 = crude oil. Additional values may be added by the API; use a numeric literal or variable. - * - Either `category` or `categoryV2` must be sent. */ -export interface SignAgreementParamsV5 { - agree: boolean; - category?: 2 | 3; - categoryV2?: number; +export interface MaxLoanAmountV5 { + currency: string; // Coin to borrow + maxLoan: string; // Maximum borrowable amount based on current collateral + notionalUsd: string; // Notional USD value + remainingQuota: string; // Remaining individual platform borrowing limit (shared between main and sub accounts) } +⋮---- +currency: string; // Coin to borrow +maxLoan: string; // Maximum borrowable amount based on current collateral +notionalUsd: string; // Notional USD value +remainingQuota: string; // Remaining individual platform borrowing limit (shared between main and sub accounts) ================ File: src/types/response/v5-market.ts @@ -13748,2926 +10823,5926 @@ export interface OptionDeliveryPriceV5 { deliveryTime: string; } ⋮---- -export interface DeliveryPriceV5 { - symbol: string; - deliveryPrice: string; - deliveryTime: string; +export interface DeliveryPriceV5 { + symbol: string; + deliveryPrice: string; + deliveryTime: string; +} +⋮---- +export interface LongShortRatioV5 { + symbol: string; + buyRatio: string; + sellRatio: string; + timestamp: string; +} +⋮---- +export interface OrderPriceLimitV5 { + symbol: string; + buyLmt: string; + sellLmt: string; + ts: string; +} +⋮---- +export interface IndexPriceComponentV5 { + exchange: string; // Name of the exchange + spotPair: string; // Spot trading pair on the exchange (e.g., BTCUSDT) + equivalentPrice: string; // Equivalent price + multiplier: string; // Multiplier used for the component price + price: string; // Actual price + weight: string; // Weight in the index calculation +} +⋮---- +exchange: string; // Name of the exchange +spotPair: string; // Spot trading pair on the exchange (e.g., BTCUSDT) +equivalentPrice: string; // Equivalent price +multiplier: string; // Multiplier used for the component price +price: string; // Actual price +weight: string; // Weight in the index calculation +⋮---- +export interface IndexPriceComponentsResponseV5 { + indexName: string; // Name of the index (e.g., BTCUSDT) + lastPrice: string; // Last price of the index + updateTime: string; // Timestamp of the last update in milliseconds + components: IndexPriceComponentV5[]; // List of components contributing to the index price +} +⋮---- +indexName: string; // Name of the index (e.g., BTCUSDT) +lastPrice: string; // Last price of the index +updateTime: string; // Timestamp of the last update in milliseconds +components: IndexPriceComponentV5[]; // List of components contributing to the index price +⋮---- +export interface ADLAlertItemV5 { + coin: string; // Token of the insurance pool + symbol: string; // Trading pair name + balance: string; // Balance of the insurance fund. Used to determine if ADL is triggered + maxBalance: string; // Maximum balance of the insurance pool in the last 8 hours + insurancePnlRatio: string; // PnL ratio threshold for triggering contract PnL drawdown ADL + pnlRatio: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped + adlTriggerThreshold: string; // Trigger threshold for contract PnL drawdown ADL + adlStopRatio: string; // Stop ratio threshold for contract PnL drawdown ADL +} +⋮---- +coin: string; // Token of the insurance pool +symbol: string; // Trading pair name +balance: string; // Balance of the insurance fund. Used to determine if ADL is triggered +maxBalance: string; // Maximum balance of the insurance pool in the last 8 hours +insurancePnlRatio: string; // PnL ratio threshold for triggering contract PnL drawdown ADL +pnlRatio: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped +adlTriggerThreshold: string; // Trigger threshold for contract PnL drawdown ADL +adlStopRatio: string; // Stop ratio threshold for contract PnL drawdown ADL +⋮---- +export interface ADLAlertResponseV5 { + updateTime: string; // Latest data update timestamp (ms) + list: ADLAlertItemV5[]; // List of ADL alert items +} +⋮---- +updateTime: string; // Latest data update timestamp (ms) +list: ADLAlertItemV5[]; // List of ADL alert items +⋮---- +export interface FeeGroupLevelV5 { + level: string; // Pro level name or Market Maker level name + takerFeeRate: string; // Taker fee rate + makerFeeRate: string; // Maker fee rate + makerRebate: string; // Maker rebate fee rate +} +⋮---- +level: string; // Pro level name or Market Maker level name +takerFeeRate: string; // Taker fee rate +makerFeeRate: string; // Maker fee rate +makerRebate: string; // Maker rebate fee rate +⋮---- +export interface FeeGroupRatesV5 { + pro: FeeGroupLevelV5[]; // Pro-level fee structures + marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures +} +⋮---- +pro: FeeGroupLevelV5[]; // Pro-level fee structures +marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures +⋮---- +export interface FeeGroupItemV5 { + groupName: string; // Fee group name + weightingFactor: number; // Group weighting factor + symbolsNumbers: number; // Symbols number + symbols: string[]; // Symbol names + feeRates: FeeGroupRatesV5; // Fee rate details for different categories + updateTime: string; // Latest data update timestamp (ms) +} +⋮---- +groupName: string; // Fee group name +weightingFactor: number; // Group weighting factor +symbolsNumbers: number; // Symbols number +symbols: string[]; // Symbol names +feeRates: FeeGroupRatesV5; // Fee rate details for different categories +updateTime: string; // Latest data update timestamp (ms) +⋮---- +export interface FeeGroupStructureResponseV5 { + list: FeeGroupItemV5[]; // List of fee group objects +} +⋮---- +list: FeeGroupItemV5[]; // List of fee group objects + +================ +File: src/types/response/v5-spot-leverage-token.ts +================ +import { + LeverageTokenStatusV5, + LTOrderStatusV5, + LTOrderTypeV5, +} from '../shared-v5'; +⋮---- +export interface LeverageTokenInfoV5 { + ltCoin: string; + ltName: string; + maxPurchase: string; + minPurchase: string; + maxPurchaseDaily: string; + maxRedeem: string; + minRedeem: string; + maxRedeemDaily: string; + purchaseFeeRate: string; + redeemFeeRate: string; + ltStatus: LeverageTokenStatusV5; + fundFee: string; + fundFeeTime: string; + manageFeeRate: string; + manageFeeTime: string; + value: string; + netValue: string; + total: string; +} +⋮---- +export interface LeveragedTokenMarketResultV5 { + ltCoin: string; + nav: string; + navTime: string; + circulation: string; + basket: string; + leverage: string; +} +⋮---- +export interface PurchaseSpotLeveragedTokenResultV5 { + ltCoin: string; + ltOrderStatus: LTOrderStatusV5; + execQty: string; + execAmt: string; + amount: string; + purchaseId: string; + serialNo: string; + valueCoin: string; +} +export interface RedeemSpotLeveragedTokenResultV5 { + ltCoin: string; + ltOrderStatus: LTOrderStatusV5; + quantity: string; + execQty: string; + execAmt: string; + redeemId: string; + serialNo: string; + valueCoin: string; +} +⋮---- +export interface SpotLeveragedTokenOrderHistoryV5 { + ltCoin: string; + orderId: string; + ltOrderType: LTOrderTypeV5; + orderTime: number; + updateTime: number; + ltOrderStatus: LTOrderStatusV5; + fee: string; + amount: string; + value: string; + valueCoin: string; + serialNo: string; +} +⋮---- +export interface VIPMarginDataV5 { + vipCoinList: { + list: { + borrowable: boolean; + collateralRatio: string; + currency: string; + hourlyBorrowRate: string; + liquidationOrder: string; + marginCollateral: boolean; + maxBorrowingAmount: string; + }[]; + vipLevel: string; + }[]; +} +⋮---- +export interface SpotMarginCurrencyDataV5 { + currency: string; + flexibleManualBorrowable: boolean; + minFlexibleManualBorrowQty: string; + flexibleManualBorrowAccuracy: string; + fixedManualBorrowable: boolean; + minFixedManualBorrowQty: string; + fixedManualBorrowAccuracy: string; + fixedInterestRateAccuracy: string; + minFixedInterestRate: string; + maxFixedInterestRate: string; +} +⋮---- +export interface SpotMarginStateV5 { + spotLeverage: string; + spotMarginMode: '1' | '0'; + effectiveLeverage: string; } ⋮---- -export interface LongShortRatioV5 { - symbol: string; - buyRatio: string; - sellRatio: string; - timestamp: string; +// Spot Margin Trade (UTA) response types +export interface ManualBorrowResultV5 { + coin: string; + amount: string; } ⋮---- -export interface OrderPriceLimitV5 { - symbol: string; - buyLmt: string; - sellLmt: string; - ts: string; +export interface MaxBorrowableAmountV5 { + currency: string; + maxLoan: string; } ⋮---- -export interface IndexPriceComponentV5 { - exchange: string; // Name of the exchange - spotPair: string; // Spot trading pair on the exchange (e.g., BTCUSDT) - equivalentPrice: string; // Equivalent price - multiplier: string; // Multiplier used for the component price - price: string; // Actual price - weight: string; // Weight in the index calculation +export interface PositionTierV5 { + tier: string; + borrowLimit: string; + positionMMR: string; + positionIMR: string; + maxLeverage: string; } ⋮---- -exchange: string; // Name of the exchange -spotPair: string; // Spot trading pair on the exchange (e.g., BTCUSDT) -equivalentPrice: string; // Equivalent price -multiplier: string; // Multiplier used for the component price -price: string; // Actual price -weight: string; // Weight in the index calculation +export interface CurrencyPositionTiersV5 { + currency: string; + positionTiersRatioList: PositionTierV5[]; +} ⋮---- -export interface IndexPriceComponentsResponseV5 { - indexName: string; // Name of the index (e.g., BTCUSDT) - lastPrice: string; // Last price of the index - updateTime: string; // Timestamp of the last update in milliseconds - components: IndexPriceComponentV5[]; // List of components contributing to the index price +export interface CoinStateV5 { + currency: string; + spotLeverage: string; } ⋮---- -indexName: string; // Name of the index (e.g., BTCUSDT) -lastPrice: string; // Last price of the index -updateTime: string; // Timestamp of the last update in milliseconds -components: IndexPriceComponentV5[]; // List of components contributing to the index price +export interface AvailableAmountToRepayV5 { + currency: string; + lossLessRepaymentAmount: string; +} ⋮---- -export interface ADLAlertItemV5 { - coin: string; // Token of the insurance pool - symbol: string; // Trading pair name - balance: string; // Balance of the insurance fund. Used to determine if ADL is triggered - maxBalance: string; // Maximum balance of the insurance pool in the last 8 hours - insurancePnlRatio: string; // PnL ratio threshold for triggering contract PnL drawdown ADL - pnlRatio: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped - adlTriggerThreshold: string; // Trigger threshold for contract PnL drawdown ADL - adlStopRatio: string; // Stop ratio threshold for contract PnL drawdown ADL +export interface ManualRepayWithoutConversionResultV5 { + /** + * Result status: + * - P: Processing + * - SU: Success + * - FA: Failed + */ + resultStatus: 'P' | 'SU' | 'FA'; } ⋮---- -coin: string; // Token of the insurance pool -symbol: string; // Trading pair name -balance: string; // Balance of the insurance fund. Used to determine if ADL is triggered -maxBalance: string; // Maximum balance of the insurance pool in the last 8 hours -insurancePnlRatio: string; // PnL ratio threshold for triggering contract PnL drawdown ADL -pnlRatio: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped -adlTriggerThreshold: string; // Trigger threshold for contract PnL drawdown ADL -adlStopRatio: string; // Stop ratio threshold for contract PnL drawdown ADL +/** + * Result status: + * - P: Processing + * - SU: Success + * - FA: Failed + */ ⋮---- -export interface ADLAlertResponseV5 { - updateTime: string; // Latest data update timestamp (ms) - list: ADLAlertItemV5[]; // List of ADL alert items +export interface AutoRepayModeItemV5 { + currency: string; // Coin name, uppercase only + autoRepayMode: '0' | '1'; // 0: Off, 1: On } ⋮---- -updateTime: string; // Latest data update timestamp (ms) -list: ADLAlertItemV5[]; // List of ADL alert items +currency: string; // Coin name, uppercase only +autoRepayMode: '0' | '1'; // 0: Off, 1: On ⋮---- -export interface FeeGroupLevelV5 { - level: string; // Pro level name or Market Maker level name - takerFeeRate: string; // Taker fee rate - makerFeeRate: string; // Maker fee rate - makerRebate: string; // Maker rebate fee rate +export interface AutoRepayModeResultV5 { + data: AutoRepayModeItemV5[]; } ⋮---- -level: string; // Pro level name or Market Maker level name -takerFeeRate: string; // Taker fee rate -makerFeeRate: string; // Maker fee rate -makerRebate: string; // Maker rebate fee rate +export interface SpotMarginLiabilityInfoV5 { + currency: string; + totalBorrowAmount: string; + fixedBorrowAmount: string; + flexibleBorrowAmount: string; + spotTotalBorrow: string; + derivativesBorrow: string; +} ⋮---- -export interface FeeGroupRatesV5 { - pro: FeeGroupLevelV5[]; // Pro-level fee structures - marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures +export interface FixedRateBorrowResultV5 { + orderId: string; } ⋮---- -pro: FeeGroupLevelV5[]; // Pro-level fee structures -marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures +export interface FixedRateBorrowOrderInfoV5 { + annualRate: string; + orderId: string; + orderTime: string; + filledQty: string; + orderQty: string; + orderCurrency: string; + state: number; + term: number; + repayType: string; + strategyType: 'PARTIAL' | 'FULL'; +} ⋮---- -export interface FeeGroupItemV5 { - groupName: string; // Fee group name - weightingFactor: number; // Group weighting factor - symbolsNumbers: number; // Symbols number - symbols: string[]; // Symbol names - feeRates: FeeGroupRatesV5; // Fee rate details for different categories - updateTime: string; // Latest data update timestamp (ms) +export interface FixedRateBorrowContractInfoV5 { + annualRate: string; + borrowCurrency: string; + borrowTime: string; + interestPaid: string; + loanId: string; + orderId: string; + repaymentTime: string; + residualPenaltyInterest: string; + residualPrincipal: string; + status: number; + term: string; + repayType: string; + strategyType: 'PARTIAL' | 'FULL'; } ⋮---- -groupName: string; // Fee group name -weightingFactor: number; // Group weighting factor -symbolsNumbers: number; // Symbols number -symbols: string[]; // Symbol names -feeRates: FeeGroupRatesV5; // Fee rate details for different categories -updateTime: string; // Latest data update timestamp (ms) +export interface FixedRateBorrowQuoteV5 { + orderCurrency: string; + term: number; + annualRate: string; + qty: string; +} ⋮---- -export interface FeeGroupStructureResponseV5 { - list: FeeGroupItemV5[]; // List of fee group objects +export interface FlexibleAvailableInventoryV5 { + currency: string; + availableInventory: string; + updateTime: string; } ⋮---- -list: FeeGroupItemV5[]; // List of fee group objects +export interface FixedRateAvailableInventoryV5 { + currency: string; + term: string; + annualRate: string; + availableInventory: string; + updateTime: string; +} ================ -File: src/types/response/v5-user.ts +File: src/types/shared-v5.ts ================ -import { PermissionsV5 } from '../shared-v5'; +export type CategoryV5 = 'spot' | 'linear' | 'inverse' | 'option'; +export type ContractTypeV5 = + | 'InversePerpetual' + | 'LinearPerpetual' + | 'InverseFutures'; +export type CopyTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalOnly'; ⋮---- -export interface CreateSubMemberResultV5 { - uid: string; - username: string; - memberType: number; - status: number; - remark: string; -} +export type InstrumentStatusV5 = + | 'PreLaunch' + | 'Trading' + | 'Settling' + | 'Delivering' + | 'Closed'; +⋮---- +/** + * Region / product class returned as `symbolType` on instruments-info (and account instruments-info). + * For `category=linear`, includes e.g. `stock`, `forex`, `commodity`, `xstocks`. Spot may return `''`. + */ +export type InstrumentSymbolTypeV5 = + | '' + | 'stock' + | 'forex' + | 'commodity' + | 'xstocks'; +⋮---- +export type MarginTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalSpotOnly'; +⋮---- +/** Product type for strategy APIs (create / list). */ +export type StrategyCategoryV5 = + | 'UTA_USDT' + | 'UTA_USDC' + | 'UTA_USDC_FUTURE' + | 'UTA_SPOT' + | 'UTA_INVERSE' + | 'UTA_INVERSE_FUTURE' + | 'UTA_USDT_FUTURE'; +⋮---- +export type StrategyTypeV5 = 'twap' | 'chaseOrder' | 'iceberg' | 'pov'; +⋮---- +export type StrategyPreferV5 = + | 'limit' + | 'priceSpeedBalance' + | 'fastestExecution' + | 'quickExecution'; +⋮---- +/** POV strategy execution mode */ +export type PovModeV5 = + | 'TradedVolume' + | 'OppositeSideLiquidity' + | 'SameSideLiquidity'; +⋮---- +export type OrderFilterV5 = 'Order' | 'tpslOrder' | 'StopOrder'; +export type OrderSideV5 = 'Buy' | 'Sell'; +export type OrderTypeV5 = 'Market' | 'Limit'; +export type OrderTimeInForceV5 = 'GTC' | 'IOC' | 'FOK' | 'PostOnly' | 'RPI'; +export type OrderTriggerByV5 = 'LastPrice' | 'IndexPrice' | 'MarkPrice'; +export type OCOTriggerTypeV5 = + | 'OcoTriggerByUnknown' + | 'OcoTriggerTp' + | 'OcoTriggerBySl'; ⋮---- -export interface CreateSubApiKeyResultV5 { - id: string; - note: string; - apiKey: string; - readOnly: number; - secret: string; - permissions: PermissionsV5; -} +export type OrderSMPTypeV5 = + | 'None' + | 'CancelMaker' + | 'CancelTaker' + | 'CancelBoth'; ⋮---- -export interface SubMemberV5 { - uid: string; - username: string; - memberType: number; - status: number; - accountMode: number; - remark: string; -} -export type ApiKeyType = 1 | 2; +export type OrderStatusV5 = + | 'Created' + | 'New' + | 'Rejected' + | 'PartiallyFilled' + | 'PartiallyFilledCanceled' + | 'Filled' + | 'Cancelled' + | 'Untriggered' + | 'Triggered' + | 'Deactivated' + | 'Active'; ⋮---- -export interface ApiKeyPermissionsV5 { - ContractTrade: string[]; - Spot: string[]; - Wallet: string[]; - Options: string[]; - Derivatives: string[]; - CopyTrading: string[]; - BlockTrade: string[]; - Exchange: string[]; - NFT: string[]; - Affiliate: string[]; - Earn?: string[]; - FiatP2P?: string[]; - FiatBitPay?: string[]; - FiatConvertBroker?: string[]; - /** @deprecated */ - FiatGlobalPay?: string[]; - BitCard?: string[]; - ByXPost?: string[]; -} +/** + * Defines the types of order creation mechanisms. + */ +export type OrderCreateTypeV5 = + /** Represents an order created by a user. */ + | 'CreateByUser' + /** Represents an order created by an admin closing. */ + | 'CreateByAdminClosing' + /** Futures conditional order. */ + | 'CreateByStopOrder' + /** Futures take profit order. */ + | 'CreateByTakeProfit' + /** Futures partial take profit order. */ + | 'CreateByPartialTakeProfit' + /** Futures stop loss order. */ + | 'CreateByStopLoss' + /** Futures partial stop loss order. */ + | 'CreateByPartialStopLoss' + /** Futures trailing stop order. */ + | 'CreateByTrailingStop' + /** Laddered liquidation to reduce the required maintenance margin. */ + | 'CreateByLiq' + /** + * If the position is still subject to liquidation (i.e., does not meet the required maintenance margin level), + * the position shall be taken over by the liquidation engine and closed at the bankruptcy price. + */ + | 'CreateByTakeOver_PassThrough' + /** Auto-Deleveraging(ADL) */ + | 'CreateByAdl_PassThrough' + /** Order placed via Paradigm. */ + | 'CreateByBlock_PassThrough' + /** Order created by move position. */ + | 'CreateByBlockTradeMovePosition_PassThrough' + /** The close order placed via web or app position area - web/app. */ + | 'CreateByClosing' + /** Order created via grid bot - web/app. */ + | 'CreateByFGridBot' + /** Order closed via grid bot - web/app. */ + | 'CloseByFGridBot' + /** Order created by TWAP - web/app. */ + | 'CreateByTWAP' + /** Order created by TV webhook - web/app. */ + | 'CreateByTVSignal' + /** Order created by Mm rate close function - web/app. */ + | 'CreateByMmRateClose' + /** Order created by Martingale bot - web/app. */ + | 'CreateByMartingaleBot' + /** Order closed by Martingale bot - web/app. */ + | 'CloseByMartingaleBot' + /** Order created by Ice berg strategy - web/app. */ + | 'CreateByIceBerg' + /** Order created by arbitrage - web/app. */ + | 'CreateByArbitrage' + /** Option dynamic delta hedge order - web/app */ + | 'CreateByDdh' + /** BBO Order - Best Bid/Offer order */ + | 'CreateByBboOrder'; ⋮---- -/** @deprecated */ +/** Represents an order created by a user. */ ⋮---- -export interface ApiKeyInfoV5 { - id: string; - note: string; - apiKey: string; - readOnly: 0 | 1; - secret: string; - permissions: ApiKeyPermissionsV5; - ips: string[]; - type: 1 | 2; // 1: personal, 2: connected to third-party app - deadlineDay: number; - expiredAt: string; - createdAt: string; - /** @deprecated */ - unified: number; - uta: 0 | 1; // 0: regular account, 1: unified trade account - userID: number; - inviterID: number; - vipLevel: string; - mktMakerLevel: string; - affiliateID: number; - rsaPublicKey: string; - isMaster: boolean; - parentUid: string; - kycLevel: 'LEVEL_DEFAULT' | 'LEVEL_1' | 'LEVEL_2'; - kycRegion: string; -} +/** Represents an order created by an admin closing. */ ⋮---- -type: 1 | 2; // 1: personal, 2: connected to third-party app +/** Futures conditional order. */ ⋮---- -/** @deprecated */ +/** Futures take profit order. */ ⋮---- -uta: 0 | 1; // 0: regular account, 1: unified trade account +/** Futures partial take profit order. */ ⋮---- -export interface UpdateApiKeyResultV5 { - id: string; - note: string; - apiKey: string; - readOnly: 0 | 1; - secret: string; - permissions: PermissionsV5; - ips: string[]; -} +/** Futures stop loss order. */ ⋮---- -export interface SubAccountAllApiKeysResultV5 { - result: { - id: string; - ips?: string[]; - apiKey: string; - note: string; - status: number; - expiredAt?: string; - createdAt: string; - type: ApiKeyType; - permissions: PermissionsV5; - secret: string; - readOnly: 0 | 1; - deadlineDay?: number; - flag: string; - }[]; - nextPageCursor: string; -} +/** Futures partial stop loss order. */ ⋮---- -export interface AffiliateUserListItemV5 { - userId: string; - registerTime: string; - source: string; - remarks: string; - isKyc: boolean; - takerVol30Day: string; - makerVol30Day: string; - tradeVol30Day: string; - depositAmount30Day: string; - takerVol365Day: string; - makerVol365Day: string; - tradeVol365Day: string; - depositAmount365Day: string; - takerVol: string; - makerVol: string; - tradeVol: string; - startDate: string; - endDate: string; - /** tradfi trade volume in [startDate, endDate] when startDate/endDate in params */ - tradfiTradeVol?: string; - /** tradfi trade volume in last 30 days. 0 when startDate/endDate in params */ - tradfiTradeVol30Day?: string; - /** tradfi trade volume in past year. 0 when startDate/endDate in params */ - tradfiTradeVol365Day?: string; - /** Commission between startDate and endDate when startDate/endDate in params. Coin -> amount */ - commissionsVol?: Record; - /** Commission in last 30 days. Coin -> amount */ - commissions30Day?: Record; - /** Commission in past year. Coin -> amount */ - commissions365Day?: Record; -} +/** Futures trailing stop order. */ ⋮---- -/** tradfi trade volume in [startDate, endDate] when startDate/endDate in params */ +/** Laddered liquidation to reduce the required maintenance margin. */ ⋮---- -/** tradfi trade volume in last 30 days. 0 when startDate/endDate in params */ +/** + * If the position is still subject to liquidation (i.e., does not meet the required maintenance margin level), + * the position shall be taken over by the liquidation engine and closed at the bankruptcy price. + */ ⋮---- -/** tradfi trade volume in past year. 0 when startDate/endDate in params */ +/** Auto-Deleveraging(ADL) */ ⋮---- -/** Commission between startDate and endDate when startDate/endDate in params. Coin -> amount */ +/** Order placed via Paradigm. */ ⋮---- -/** Commission in last 30 days. Coin -> amount */ +/** Order created by move position. */ ⋮---- -/** Commission in past year. Coin -> amount */ +/** The close order placed via web or app position area - web/app. */ ⋮---- -export interface AffiliateUserInfoV5 { - uid: string; - vipLevel: string; - takerVol30Day: string; - makerVol30Day: string; - tradeVol30Day: string; - depositAmount30Day: string; - takerVol365Day: string; - makerVol365Day: string; - tradeVol365Day: string; - depositAmount365Day: string; - totalWalletBalance: '1' | '2' | '3' | '4'; - depositUpdateTime: string; - volUpdateTime: string; - KycLevel: 0 | 1 | 2; - /** tradfi trade volume in last 30 days (USDT) */ - tradfiTradeVol30Day?: string; - /** tradfi trade volume in past year (USDT) */ - tradfiTradeVol365Day?: string; - /** tradfi commissions in last 30 days. Coin -> amount */ - commissions30Day?: Record; - /** tradfi commissions in past year. Coin -> amount */ - commissions365Day?: Record; - /** Payment amount in the last 30 days */ - paySendAmount30Day: string; - /** Pay first transaction amount */ - payFtt: string; - /** Card first-time transaction amount */ - cardFtt: string; -} +/** Order created via grid bot - web/app. */ +⋮---- +/** Order closed via grid bot - web/app. */ ⋮---- -/** tradfi trade volume in last 30 days (USDT) */ +/** Order created by TWAP - web/app. */ ⋮---- -/** tradfi trade volume in past year (USDT) */ +/** Order created by TV webhook - web/app. */ ⋮---- -/** tradfi commissions in last 30 days. Coin -> amount */ +/** Order created by Mm rate close function - web/app. */ ⋮---- -/** tradfi commissions in past year. Coin -> amount */ +/** Order created by Martingale bot - web/app. */ ⋮---- -/** Payment amount in the last 30 days */ +/** Order closed by Martingale bot - web/app. */ ⋮---- -/** Pay first transaction amount */ +/** Order created by Ice berg strategy - web/app. */ ⋮---- -/** Card first-time transaction amount */ +/** Order created by arbitrage - web/app. */ ⋮---- -export interface AffiliateSubAffiliateListItemV5 { - subAffId: string; - userId: string; - name: string; - email: string; - /** Commission per currency (BTC, ETH, MNT, USDC, USDT) for the queried date range */ - commissionsVol: Record; - commissionsForUsdt: string; - becameAffTime: string; - startDate: string; - endDate: string; -} +/** Option dynamic delta hedge order - web/app */ ⋮---- -/** Commission per currency (BTC, ETH, MNT, USDC, USDT) for the queried date range */ +/** BBO Order - Best Bid/Offer order */ ⋮---- -export interface AffiliateSubAffiliateListResultV5 { - list: AffiliateSubAffiliateListItemV5[]; - nextPageCursor: string; -} +export type OrderCancelTypeV5 = + | 'CancelByUser' + | 'CancelByReduceOnly' + | 'CancelByPrepareLiq' + | 'CancelAllBeforeLiq' + | 'CancelByPrepareAdl' + | 'CancelAllBeforeAdl' + | 'CancelByAdmin' + | 'CancelByTpSlTsClear' + | 'CancelByPzSideCh' + | 'UNKNOWN'; ⋮---- -export interface FriendReferralRecordV5 { - id: string; - inviteeUid: string; - status: number; - createdAt: string; - updatedAt: string; -} - -================ -File: src/types/websockets/ws-events.ts -================ -import WebSocket from 'isomorphic-ws'; +export type OrderRejectReasonV5 = + | 'EC_NoError' + | 'EC_Others' + | 'EC_UnknownMessageType' + | 'EC_MissingClOrdID' + | 'EC_MissingOrigClOrdID' + | 'EC_ClOrdIDOrigClOrdIDAreTheSame' + | 'EC_DuplicatedClOrdID' + | 'EC_OrigClOrdIDDoesNotExist' + | 'EC_TooLateToCancel' + | 'EC_UnknownOrderType' + | 'EC_UnknownSide' + | 'EC_UnknownTimeInForce' + | 'EC_WronglyRouted' + | 'EC_MarketOrderPriceIsNotZero' + | 'EC_LimitOrderInvalidPrice' + | 'EC_NoEnoughQtyToFill' + | 'EC_NoImmediateQtyToFill' + | 'EC_PerCancelRequest' + | 'EC_MarketOrderCannotBePostOnly' + | 'EC_PostOnlyWillTakeLiquidity' + | 'EC_CancelReplaceOrder' + | 'EC_InvalidSymbolStatus'; ⋮---- -import { - RFQItemV5, - RFQPublicTradeV5, - RFQQuoteItemV5, - RFQTradeV5, -} from '../response/v5-rfq'; -import { - CategoryV5, - ExecTypeV5, - OCOTriggerTypeV5, - OrderCancelTypeV5, - OrderCreateTypeV5, - OrderRejectReasonV5, - OrderSideV5, - OrderSMPTypeV5, - OrderStatusV5, - OrderTimeInForceV5, - OrderTriggerByV5, - OrderTypeV5, - PositionIdx, - PositionSideV5, - PositionStatusV5, - StopOrderTypeV5, - SystemStatusItemV5, - TPSLModeV5, - TradeModeV5, -} from '../shared-v5'; -import { WsKey } from './ws-general'; +export type StopOrderTypeV5 = + | 'TakeProfit' + | 'StopLoss' + | 'TrailingStop' + | 'Stop' + | 'PartialTakeProfit' + | 'PartialStopLoss' + | 'tpslOrder' + | 'OcoOrder' + | 'MmRateClose' + | 'BidirectionalTpslOrder'; ⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; -} +/** + * Position index. Used to identify positions in different position modes. + * + * - 0 one-way mode position + * - 1 Buy side of hedge-mode position + * - 2 Sell side of hedge-mode position + */ +export type PositionIdx = 0 | 1 | 2; ⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike +/** + * Position status. + * + * - 'Normal' + * - 'Liq' in the liquidation progress + * - 'Adl' in the auto-deleverage progress + */ +export type PositionStatusV5 = 'Normal' | 'Liq' | 'Adl'; +export type PositionSideV5 = 'Buy' | 'Sell' | 'None' | ''; ⋮---- -export interface WSPublicTopicEventV5 { - id?: string; - topic: TTopic; - type: TType; - /** Cross sequence */ - cs?: number; - /** Event timestamp */ - ts: number; - data: TData; - /** - * matching engine timestamp (correlated with T from public trade channel) - */ - cts: number; - /** - * Internal reference, can be used to determine if this is spot/linear/inverse/etc - */ - wsKey: WsKey; -} +export type OptionTypeV5 = 'Call' | 'Put'; ⋮---- -/** Cross sequence */ +/** + * Trade mode. + * + * - 0 cross-margin, + * - 1 isolated margin + */ +export type TradeModeV5 = 0 | 1; +⋮---- +export type TPSLModeV5 = 'Full' | 'Partial'; +export type AccountMarginModeV5 = + | 'ISOLATED_MARGIN' + | 'REGULAR_MARGIN' + | 'PORTFOLIO_MARGIN'; +export type UnifiedUpdateStatusV5 = 'FAIL' | 'PROCESS' | 'SUCCESS'; +⋮---- +export type AccountTypeV5 = + | 'CONTRACT' + | 'SPOT' + | 'INVESTMENT' + | 'OPTION' + | 'UNIFIED' + | 'FUND' + | 'EARN'; +⋮---- +export type TransactionTypeV5 = + | 'TRANSFER_IN' + | 'TRANSFER_OUT' + | 'TRADE' + | 'SETTLEMENT' + | 'DELIVERY' + | 'LIQUIDATION' + | 'ADL' + | 'AIRDROP' + | 'BONUS_RECOLLECT' + | 'BONUS_RECOLLECT' + | 'FEE_REFUND' + | 'INTEREST' + | 'CURRENCY_BUY' + | 'CURRENCY_SELL' + | 'BORROWED_AMOUNT_INS_LOAN' + | 'PRINCIPLE_REPAYMENT_INS_LOAN' + | 'INTEREST_REPAYMENT_INS_LOAN' + | 'AUTO_SOLD_COLLATERAL_INS_LOAN' + | 'AUTO_BUY_LIABILITY_INS_LOAN' + | 'AUTO_PRINCIPLE_REPAYMENT_INS_LOAN' + | 'AUTO_INTEREST_REPAYMENT_INS_LOAN' + | 'TRANSFER_IN_INS_LOAN' + | 'TRANSFER_OUT_INS_LOAN' + | 'SPOT_REPAYMENT_SELL' + | 'SPOT_REPAYMENT_BUY' + | 'TOKENS_SUBSCRIPTION' + | 'TOKENS_REDEMPTION' + | 'AUTO_DEDUCTION' + | 'FLEXIBLE_STAKING_SUBSCRIPTION' + | 'FLEXIBLE_STAKING_REDEMPTION' + | 'FIXED_STAKING_SUBSCRIPTION' + | 'BORROWED_AMOUNT_INS_LOAN' + | 'PRINCIPLE_REPAYMENT_INS_LOAN' + | 'INTEREST_REPAYMENT_INS_LOAN' + | 'AUTO_SOLD_COLLATERAL_INS_LOAN' + | 'AUTO_BUY_LIABILITY_INS_LOAN' + | 'AUTO_PRINCIPLE_REPAYMENT_INS_LOAN' + | 'AUTO_INTEREST_REPAYMENT_INS_LOAN' + | 'TRANSFER_IN_INS_LOAN' + | 'TRANSFER_OUT_INS_LOAN' + | 'SPOT_REPAYMENT_SELL' + | 'SPOT_REPAYMENT_BUY' + | 'TOKENS_SUBSCRIPTION' + | 'TOKENS_REDEMPTION' + | 'AUTO_DEDUCTION' + | 'FLEXIBLE_STAKING_SUBSCRIPTION' + | 'FLEXIBLE_STAKING_REDEMPTION' + | 'FIXED_STAKING_SUBSCRIPTION' + | 'FLEXIBLE_STAKING_REFUND' + | 'FIXED_STAKING_REFUND' + | 'PREMARKET_TRANSFER_OUT' + | 'PREMARKET_DELIVERY_SELL_NEW_COIN' + | 'PREMARKET_DELIVERY_BUY_NEW_COIN' + | 'PREMARKET_DELIVERY_PLEDGE_PAY_SELLER' + | 'PREMARKET_DELIVERY_PLEDGE_BACK' + | 'PREMARKET_ROLLBACK_PLEDGE_BACK' + | 'PREMARKET_ROLLBACK_PLEDGE_PENALTY_TO_BUYER' + | 'CUSTODY_NETWORK_FEE' + | 'CUSTODY_SETTLE_FEE' + | 'CUSTODY_LOCK' + | 'CUSTODY_UNLOCK' + | 'CUSTODY_UNLOCK_REFUND' + | 'LOANS_BORROW_FUNDS' + | 'LOANS_PLEDGE_ASSET' + | 'BONUS_TRANSFER_IN' + | 'BONUS_TRANSFER_OUT' + | 'PEF_TRANSFER_IN' + | 'PEF_TRANSFER_OUT' + | 'PEF_PROFIT_SHARE' + | 'ONCHAINEARN_SUBSCRIPTION' + | 'ONCHAINEARN_REDEMPTION' + | 'ONCHAINEARN_REFUND' + | 'STRUCTURE_PRODUCT_SUBSCRIPTION' + | 'STRUCTURE_PRODUCT_REFUND' + | 'CLASSIC_WEALTH_MANAGEMENT_SUBSCRIPTION' + | 'PREMIMUM_WEALTH_MANAGEMENT_SUBSCRIPTION' + | 'PREMIMUM_WEALTH_MANAGEMENT_REFUND' + | 'LIQUIDITY_MINING_SUBSCRIPTION' + | 'LIQUIDITY_MINING_REFUND' + | 'PWM_SUBSCRIPTION' + | 'PWM_REFUND' + | 'DEFI_INVESTMENT_SUBSCRIPTION' + | 'DEFI_INVESTMENT_REFUND' + | 'DEFI_INVESTMENT_REDEMPTION' + | 'INSTITUTION_LOAN_IN' + | 'INSTITUTION_PAYBACK_PRINCIPAL_OUT' + | 'INSTITUTION_PAYBACK_INTEREST_OUT' + | 'INSTITUTION_EXCHANGE_SELL' + | 'INSTITUTION_EXCHANGE_BUY' + | 'INSTITUTION_LIQ_PRINCIPAL_OUT' + | 'INSTITUTION_LIQ_INTEREST_OUT' + | 'INSTITUTION_LOAN_TRANSFER_IN' + | 'INSTITUTION_LOAN_TRANSFER_OUT' + | 'INSTITUTION_LOAN_WITHOUT_WITHDRAW' + | 'INSTITUTION_LOAN_RESERVE_IN' + | 'INSTITUTION_LOAN_RESERVE_OUT' + | 'PLATFORM_TOKEN_MNT_LIQRECALLEDMMNT' + | 'PLATFORM_TOKEN_MNT_LIQRETURNEDMNT' + | 'DIVIDEND_SETTLEMENT'; ⋮---- -/** Event timestamp */ +export type PermissionTypeV5 = + | 'ContractTrade' + | 'Spot' + | 'Wallet' + | 'Options' + | 'Derivatives' + | 'Exchange' + | 'NFT'; ⋮---- /** - * matching engine timestamp (correlated with T from public trade channel) - */ + * Leveraged token status: + * + * - '1' LT can be purchased and redeemed + * - '2' LT can be purchased, but not redeemed + * - '3' LT can be redeemed, but not purchased + * - '4' LT cannot be purchased nor redeemed + * - '5' Adjusting position + */ +export type LeverageTokenStatusV5 = '1' | '2' | '3' | '4' | '5'; ⋮---- /** - * Internal reference, can be used to determine if this is spot/linear/inverse/etc - */ -⋮---- -export interface WSPrivateTopicEventV5 { - id?: string; - topic: TTopic; - creationTime: number; - data: TData; - wsKey: WsKey; -} -⋮---- -export interface WSOrderbookV5 { - /** Symbol */ - s: string; - /** [price, qty][] */ - b: [string, string][]; - /** [price, qty][] */ - a: [string, string][]; - /** Update ID */ - u: number; - /** Cross sequence */ - seq: number; -} -⋮---- -/** Symbol */ -⋮---- -/** [price, qty][] */ -⋮---- -/** [price, qty][] */ + * Leveraged token order type: '1': purchase, '2': redeem + */ +export type LTOrderTypeV5 = '1' | '2'; ⋮---- -/** Update ID */ +/** + * Leveraged token order status: '1': completed, '2': in progress, '3': failed + */ +export type LTOrderStatusV5 = '1' | '2' | '3'; ⋮---- -/** Cross sequence */ +export type ExecTypeV5 = + | 'Trade' + | 'AdlTrade' + | 'Funding' + | 'BustTrade' + | 'Settle' + | 'BlockTrade' + | 'MovePosition' + | 'CorporateAction' + | 'UNKNOWN'; ⋮---- -export type WSOrderbookEventV5 = WSPublicTopicEventV5< - string, - 'delta' | 'snapshot', - WSOrderbookV5 ->; +/** + * Withdraw type. 0(default): on chain. 1: off chain. 2: all. + */ +export type WithdrawalTypeV5 = '0' | '1' | '2'; ⋮---- -export interface WSTradeV5 { - T: number; - s: string; - S: OrderSideV5; - v: string; - p: string; - L?: string; - i: string; - BT: boolean; - RPI?: boolean; - mP?: string; - iP?: string; - mIv?: string; - iv?: string; +export interface PermissionsV5 { + ContractTrade?: string[]; + Spot?: string[]; + Wallet?: string[]; + Options?: string[]; + Derivatives?: string[]; + CopyTrading?: string[]; + BlockTrade?: string[]; + Exchange?: string[]; + /** @deprecated , always returns []*/ + NFT?: string[]; + Earn?: string[]; + Affiliate?: string[]; + FiatP2P?: string[]; + /** Bybit Pay (FaitPayOrder) */ + FiatBitPay?: string[]; + FiatConvertBroker?: string[]; + BitCard?: string[]; + ByXPost?: string[]; } ⋮---- -export type WSTradeEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSTradeV5[] ->; +/** @deprecated , always returns []*/ ⋮---- -/** - * WSTickerV5 is the data structure for the "linear" ticker channel - * */ -export interface WSTickerV5 { - symbol: string; - tickDirection: string; - price24hPcnt: string; - lastPrice: string; - prevPrice24h: string; - highPrice24h: string; - lowPrice24h: string; - prevPrice1h: string; - markPrice: string; - indexPrice: string; - openInterest: string; - openInterestValue: string; - singleOpenInterest?: string; - singleOpenInterestValue?: string; - turnover24h: string; - volume24h: string; - nextFundingTime: string; - fundingRate: string; - bid1Price: string; - bid1Size: string; - ask1Price: string; - ask1Size: string; - deliveryTime?: string; - basisRate?: string; - deliveryFeeRate?: string; - predictedDeliveryPrice?: string; - preOpenPrice?: string; - preQty?: string; - curPreListingPhase?: string; - fundingIntervalHour?: string; - fundingCap?: string; - basisRateYear?: string; -} +/** Bybit Pay (FaitPayOrder) */ ⋮---- -export interface WSTickerOptionV5 { - symbol: string; - bidPrice: string; - bidSize: string; - bidIv: string; - askPrice: string; - askSize: string; - askIv: string; - lastPrice: string; - highPrice24h: string; - lowPrice24h: string; - markPrice: string; - indexPrice: string; - markPriceIv: string; - underlyingPrice: string; - openInterest: string; - turnover24h: string; - volume24h: string; - totalVolume: string; - totalTurnover: string; - delta: string; - gamma: string; - vega: string; - theta: string; - predictedDeliveryPrice: string; - change24h: string; +export interface CategoryCursorListV5< + T extends unknown[], + TCategory extends CategoryV5 = CategoryV5, +> { + category: TCategory; + list: T; + nextPageCursor?: string; } ⋮---- -export interface WSTickerSpotV5 { - symbol: string; - lastPrice: string; - highPrice24h: string; - lowPrice24h: string; - prevPrice24h: string; - volume24h: string; - turnover24h: string; - price24hPcnt: string; - usdIndexPrice: string; +/** + * Next page cursor does not exist for spot! + */ +export interface CursorListV5 { + nextPageCursor: string; + list: T; } ⋮---- -export type WSTickerEventV5 = WSPublicTopicEventV5< - string, - 'snapshot' | 'delta', - WSTickerV5 | WSTickerOptionV5 | WSTickerSpotV5 ->; -⋮---- -export interface WSKlineV5 { - start: number; - end: number; - interval: string; - open: string; - close: string; - high: string; - low: string; - volume: string; - turnover: string; - confirm: boolean; - timestamp: number; +/** + * A wrapper type for any responses that have a "nextPageCursor" property, and a "rows" property with an array of elements + * + * ```{ nextPageCursor: "something", rows: someData[] }``` + */ +export interface CursorRowsV5 { + nextPageCursor: string; + rows: T; } ⋮---- -export type WSKlineEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSKlineV5[] ->; -⋮---- -export interface WSLiquidationV5 { - T: number; - s: string; - S: OrderSideV5; - v: string; - p: string; +export interface CategoryListV5< + T extends unknown[], + TCategory extends CategoryV5, +> { + category: TCategory; + list: T; } ⋮---- -export type WSLiquidationEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSLiquidationV5[] ->; -⋮---- -export interface WSPositionV5 { - category: string; +export interface CategorySymbolListV5< + T extends unknown[], + TCategory extends CategoryV5, +> { + category: TCategory; symbol: string; - side: PositionSideV5; - size: string; - positionIdx: PositionIdx; - tradeMode: TradeModeV5; - positionValue: string; - riskId: number; - riskLimitValue: string; - entryPrice: string; - markPrice: string; - leverage: string; - breakEvenPrice?: string; // Break even price, only for linear & inverse - positionBalance: string; - autoAddMargin: number; - positionMM: string; - positionIM: string; - positionIMByMp: string; - positionMMByMp: string; - liqPrice: string; - bustPrice: string; - tpslMode: string; - takeProfit: string; - stopLoss: string; - trailingStop: string; - unrealisedPnl: string; - curRealisedPnl: string; - sessionAvgPrice: string; - delta: string; - gamma: string; - vega: string; - theta: string; - cumRealisedPnl: string; - positionStatus: PositionStatusV5; - adlRankIndicator: number; - isReduceOnly: boolean; - mmrSysUpdatedTime: string; - leverageSysUpdatedTime: string; - createdTime: string; - updatedTime: string; - /** Position open timestamp (ms). Default `0` when not set. */ - openTime: number; - seq: number; + list: T; } ⋮---- -breakEvenPrice?: string; // Break even price, only for linear & inverse -⋮---- -/** Position open timestamp (ms). Default `0` when not set. */ -⋮---- -export type WSPositionEventV5 = WSPrivateTopicEventV5< - 'position', - WSPositionV5[] ->; +export interface GetSystemStatusParamsV5 { + id?: string; + state?: string; +} ⋮---- -export interface WSAccountOrderV5 { - category: CategoryV5; - orderId: string; - orderLinkId: string; - parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) - isLeverage: string; - blockTradeId: string; - symbol: string; - price: string; - qty: string; - side: OrderSideV5; - positionIdx: PositionIdx; - orderStatus: OrderStatusV5; - createType: OrderCreateTypeV5; - cancelType: OrderCancelTypeV5; - rejectReason?: OrderRejectReasonV5; - avgPrice?: string; - leavesQty?: string; - leavesValue?: string; - cumExecQty: string; - cumExecValue: string; - cumExecFee: string; - closedPnl: string; - feeCurrency: string; - timeInForce: OrderTimeInForceV5; - orderType: OrderTypeV5; - stopOrderType: StopOrderTypeV5; - ocoTriggerType?: OCOTriggerTypeV5; - orderIv: string; - marketUnit?: 'baseCoin' | 'quoteCoin'; - triggerPrice: string; - takeProfit: string; - stopLoss: string; - tpslMode?: TPSLModeV5; - tpLimitPrice?: string; - slLimitPrice?: string; - tpTriggerBy: string; - slTriggerBy: string; - triggerDirection: number; - triggerBy: OrderTriggerByV5; - lastPriceOnCreated: string; - reduceOnly: boolean; - closeOnTrigger: boolean; - placeType: string; - smpType: OrderSMPTypeV5; - smpGroup: number; - smpOrderId: string; - createdTime: string; - updatedTime: string; - cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency - rpiTakerAccess?: boolean; - rpiMatchedQty?: string; +export interface SystemStatusItemV5 { + id: string; + title: string; + state: string; + begin: string; + end: string; + href: string; + serviceTypes: number[]; + product: number[]; + uidSuffix: number[]; + maintainType: string; + env: string; +} + +================ +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 +dist +doc +bundleReport.html +.history/ +rawReq.ts +localtest.sh +localtest.ts +privaterepotracker +restClientRegex.ts +repomix.sh + +examples/ignored +examples/ts-testnet-private.ts +examples/ts-testnet-trade.ts +examples/ts-testnet.ts +*.pem +.issue* + +================ +File: docs/BYBIT_SDK_QUICKSTART_GUIDE.md +================ + +# Bybit API JavaScript Tutorial for Node.js and TypeScript + + +> [!TIP] +> This guide can be read in tutorial format on the Siebly Website: [Bybit JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/bybit/javascript/tutorial) + + +This tutorial walks through a practical Bybit REST API, WebSocket stream, and WebSocket API integration using [`bybit-api`](https://www.npmjs.com/package/bybit-api), the Bybit JavaScript and TypeScript SDK by Siebly.io. It also covers HTTP, HTTPS, and SOCKS proxy configuration for REST API calls, streams, and WebSocket API connections. + +The SDK handles the repetitive parts: HMAC and RSA request signing, Bybit API endpoint routing, testnet and demo trading differences, WebSocket authentication, heartbeats, reconnects, resubscribe behavior, WebSocket API request/response matching, and TypeScript request and response definitions. The sections below move from installation and client choice to public calls, private auth, trading flows, WebSocket API commands, environments, and production checks. + +**Key links** + +- Bybit JavaScript SDK by Siebly: [`bybit-api`](https://www.npmjs.com/package/bybit-api) +- GitHub Repository: [`tiagosiebler/bybit-api`](https://github.com/tiagosiebler/bybit-api) +- SDK function-endpoint map: [Bybit JavaScript Endpoint Reference](./endpointFunctionList.md) +- REST API examples: [Bybit SDK REST API examples](../examples/Rest/rest-v5-public.ts) +- WebSocket examples: [Bybit SDK WebSocket examples](../examples/Websocket/Public/ws-public-v5.ts) +- Bybit API docs: [Bybit API Documentation](https://bybit-exchange.github.io/docs/v5/intro) +- Position Management with Bybit APIs & WebSockets: [Siebly Position Management with Bybit APIs & WebSockets](https://siebly.io/ai/exchange-state/bybit) +- More SDKs: [Siebly.io](https://siebly.io) + +--- + + +## Why use the SDK + +The Bybit API is unified, but a real integration still has several moving parts: + +- The API spans Spot, Linear contracts, Inverse contracts, Options, account, asset, user, broker, Earn, P2P, RFQ, spread trading, spot margin, and loan workflows. + - Within the Bybit JavaScript SDK by Siebly.io, all product groups are available in one unified REST API client. +- Many market and trade calls use a `category` parameter such as `spot`, `linear`, `inverse`, or `option`. +- Public WebSocket streams are split across category-specific endpoints. +- Private WebSocket streams use a separate private endpoint. +- WebSocket API commands use a separate endpoint represented by `v5PrivateTrade`. +- Private REST API and WebSocket API requests are timestamp-sensitive and must be signed. +- Bybit supports both HMAC keys and self-generated RSA keys. The SDK has automatic support for all key types. +- Live, testnet, demo trading, and regional Bybit domains are separate routing choices. + +The SDK gives you the main surfaces needed for those workflows: + +- `RestClientV5` for Bybit REST API calls. +- `WebsocketClient` for public and private streams. +- `WebsocketAPIClient` for promise-driven WebSocket API commands. +- `SpotClientV3` for the remaining legacy Spot V3 endpoint. New integrations should use the current Bybit API surface. The V3 client might be removed at any time. + +The method names stay close to Bybit's endpoint names, while the SDK handles base URLs, request signatures, request routing, headers, WebSocket lifecycle, authentication, topic tracking, reconnects, and typed request shapes. It also lets you use the WebSocket API in a request/response style: send a command and await the matching response, similar to a REST API. + +--- + + +## Install and API keys + +If you do not have Node.js installed yet, install it first. The SDK is published to both [GitHub](https://github.com/tiagosiebler/bybit-api) and [npm](https://www.npmjs.com/package/bybit-api). + +Install the SDK with npm: + +```bash +npm install bybit-api +``` + +Or use another npm-compatible package manager: + +```bash +pnpm install bybit-api +yarn add bybit-api +``` + +Create API keys from the relevant Bybit page: + +- Bybit live API keys: [Bybit API Management](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1) +- Bybit testnet API keys: [Bybit Testnet API Management](https://testnet.bybit.com/app/user/api-management) +- Bybit demo trading notes: [Bybit Demo Trading Service](https://bybit-exchange.github.io/docs/v5/demo) + +> Always use the minimum permissions needed for your scenario. Trading does not require withdrawal permissions. Analytics does not require trading permissions. +> Always use strict IP whitelisting for API keys whenever your deployment environment allows it. + +The main auth and environment rules are: + +- Public market data does not usually require API keys. +- Private REST API calls require `key` and `secret`. +- Private WebSocket streams require `key` and `secret`. +- WebSocket API commands require `key` and `secret`. +- Live, testnet, and demo trading credentials are separate. +- API permissions must match the product and action your code is using. +- HMAC keys use a normal API key and API secret. +- RSA keys use a Bybit API key plus your PEM private key as `secret`. +- The SDK automatically detects RSA private keys when the secret contains a private-key PEM header. + +Typical environment variables: + +```bash +export BYBIT_API_KEY='your-api-key' +export BYBIT_API_SECRET='your-api-secret-or-rsa-private-key' +``` + +Create a private REST API client: + +```typescript +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, +}); +``` + +If you are only testing public endpoints, you do not need keys: + +```typescript +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5(); +``` + +For RSA setup details, see [examples/Auth/RSA-sign.md](../examples/Auth/RSA-sign.md). + +--- + + +## Products and clients + +For new Bybit integrations, start with the current API. Older Bybit SDK surfaces were split into many product-specific clients; this SDK now centers the current API around one REST API client plus WebSocket clients. + +| Use case | SDK surface | Common usage | +| -------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| REST API | `RestClientV5` | Public market data, account reads, order management, positions, wallet, asset transfers, user APIs, Earn, broker, P2P, RFQ, and other endpoint groups | +| Public and private streams | `WebsocketClient` | Live order books, trades, klines, tickers, liquidations, private orders, executions, positions, wallet, and greeks | +| WebSocket API commands | `WebsocketAPIClient` | Awaitable order create, amend, cancel, and batch order commands over Bybit's WebSocket API | +| Raw WebSocket API commands | `WebsocketClient.sendWSAPIRequest(...)` | Lower-level WebSocket API usage where you want to send an operation directly | + +The `category` parameter matters: + +| Category | Meaning | +| --------- | ----------------------------------------------- | +| `spot` | Spot market and Spot orders | +| `linear` | USDT and USDC linear contracts | +| `inverse` | Inverse perpetual and inverse futures contracts | +| `option` | Options | + +As a rule of thumb: + +- Use `RestClientV5` for current Bybit REST API endpoints. +- Use `WebsocketClient.subscribeV5(...)` when you want streaming data. +- Use `WebsocketAPIClient` when you want to send commands over WebSocket and await the response. +- Use `docs/endpointFunctionList.md` when you already know the Bybit endpoint path and need the matching SDK method. + +For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). + + +### REST API, streams, and WebSocket API + +Bybit exposes several different integration flows. Keep them separate in your architecture: + +| Flow | SDK surface | Best for | What the SDK handles | +| ------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| REST API | `RestClientV5` | Request/response calls, broad endpoint coverage, public reads, private account reads, order submission, reconciliation | Base URLs, timestamps, HMAC/RSA signing, headers, response parsing, optional rate-limit parsing | +| Public WebSocket streams | `WebsocketClient.subscribeV5(...)` | Real-time market data such as order books, trades, klines, tickers, and liquidations | Endpoint routing by category, subscribe requests, heartbeats, reconnects, resubscribe | +| Private WebSocket streams | `WebsocketClient.subscribeV5(...)` with keys | Account events such as orders, executions, wallet, positions, and greeks | Authentication, private endpoint routing, reconnects, resubscribe | +| WebSocket API commands | `WebsocketAPIClient` or `sendWSAPIRequest(...)` | Order create, amend, cancel, and batch order operations over a persistent WebSocket connection | Connection setup, authentication, request IDs, signing, promise resolution, response/error correlation | + +Use the REST API when you want maximum endpoint coverage or a simple one-off request. Use WebSocket streams when you need realtime lower-latency updates. Use the WebSocket API when you want a command path over an already-open WebSocket connection. + +--- + + +## Start building: first calls + +If you only want the fastest path to a working integration, start here. + +### 1. First public REST API request + + +```typescript +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5(); + +async function main() { + const serverTime = await client.getServerTime(); + const instruments = await client.getInstrumentsInfo({ + category: 'linear', + symbol: 'BTCUSDT', + }); + const ticker = await client.getTickers({ + category: 'linear', + symbol: 'BTCUSDT', + }); + const orderBook = await client.getOrderbook({ + category: 'linear', + symbol: 'BTCUSDT', + limit: 50, + }); + const candles = await client.getKline({ + category: 'linear', + symbol: 'BTCUSDT', + interval: '1', + limit: 5, + }); + + console.log({ + serverTime, + instrument: instruments.result.list[0]?.symbol, + ticker: ticker.result.list[0], + orderBook, + candles, + }); } -⋮---- -parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) -⋮---- -cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency -⋮---- -export type WSAccountOrderEventV5 = WSPrivateTopicEventV5< - 'order', - WSAccountOrderV5[] ->; -⋮---- -export interface WSExecutionV5 { - category: CategoryV5; - symbol: string; - isLeverage: string; - orderId: string; - orderLinkId: string; - side: OrderSideV5; - orderPrice: string; - orderQty: string; - leavesQty: string; - createType: OrderCreateTypeV5; - orderType: OrderTypeV5; - stopOrderType: StopOrderTypeV5; - execFee: string; - feeCurrency: string; // Trading fee currency - execId: string; - execPrice: string; - execQty: string; - execPnl: string; - execType: ExecTypeV5; - execValue: string; - execTime: string; - isMaker: boolean; - feeRate: string; - tradeIv: string; - markIv: string; - markPrice: string; - indexPrice: string; - underlyingPrice: string; - blockTradeId: string; - closedSize: string; - extraFees: string; - seq: number; - marketUnit: string; + +main().catch(console.error); +``` + +That confirms public REST API access is wired correctly. + +See also: [public REST API example](../examples/Rest/rest-v5-public.ts) + +### 2. First public WebSocket stream + + +```typescript +import { WebsocketClient, isWsOrderbookEventV5 } from 'bybit-api'; + +const ws = new WebsocketClient(); + +ws.on('open', (data) => console.log('connected', data.wsKey, data.wsUrl)); +ws.on('response', (data) => console.log('response', JSON.stringify(data))); +ws.on('update', (data) => { + if (isWsOrderbookEventV5(data)) { + console.log('orderbook update', data.data.s, data.type); + return; + } + + console.log('stream update', JSON.stringify(data)); +}); +ws.on('reconnect', (data) => console.log('reconnecting', data.wsKey)); +ws.on('reconnected', (data) => console.log('reconnected', data.wsKey)); +ws.on('exception', console.error); + +ws.subscribeV5(['orderbook.50.BTCUSDT', 'tickers.BTCUSDT', 'publicTrade.BTCUSDT'], 'linear'); +``` + +For public streams, pass the category so the SDK can route the topic to the right public endpoint. + +See also: [public WebSocket example](../examples/Websocket/Public/ws-public-v5.ts) + +### 3. First private account WebSocket stream + + +```typescript +import { WebsocketClient } from 'bybit-api'; + +const ws = new WebsocketClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, +}); + +ws.on('authenticated', (data) => { + console.log('authenticated', data.wsKey); +}); + +ws.on('update', (data) => { + console.log('account event', JSON.stringify(data)); +}); + +ws.on('reconnect', ({ wsKey }) => { + console.log('reconnecting', wsKey); +}); + +ws.on('reconnected', ({ wsKey }) => { + console.log('reconnected', wsKey); + // Fetch wallet, positions, open orders, or recent executions here if needed. +}); + +ws.on('exception', console.error); + +ws.subscribeV5(['order', 'execution', 'position', 'wallet'], 'linear'); +``` + +Private topics are routed to the private endpoint. The category argument is still required by `subscribeV5(...)`, but it is only used for public-topic routing. + +See also: [private WebSocket example](../examples/Websocket/Private/ws-private-v5.ts) + +### 4. First REST API order in demo trading + +Use demo trading before placing live orders. Demo trading uses a separate Bybit demo account and separate API keys. + + +```typescript +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + demoTrading: true, + throwExceptions: true, +}); + +async function placeDemoOrder() { + await client.requestDemoTradingFunds(); + + const orderRequest = { + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', + orderLinkId: `demo-${Date.now()}`, + } as const; + + const result = await client.submitOrder(orderRequest); + console.log(result); } -⋮---- -feeCurrency: string; // Trading fee currency -⋮---- -export type WSExecutionEventV5 = WSPrivateTopicEventV5< - 'execution', - WSExecutionV5[] ->; -⋮---- -export interface WSExecutionFastV5 { - category: CategoryV5; - symbol: string; - execId: string; - execPrice: string; - execQty: string; - orderId: string; - isMaker: boolean; - orderLinkId: string; - side: OrderSideV5; - execTime: string; - seq: number; - liquidity?: string; + +placeDemoOrder().catch(console.error); +``` + +This submits to Bybit demo trading because `demoTrading: true` is set. Do not remove that option or switch to live keys until you are ready to place real orders. + +For order workflows, prefer `throwExceptions: true` so non-zero Bybit business responses throw and can be handled in one structured catch path. If you intentionally set `throwExceptions: false`, a resolved REST promise can still be an exchange business rejection. Treat `retCode === 0` as acceptance and any non-zero `retCode` as a rejected or unknown submission state. + +See also: [Demo trading example](../examples/Rest/demo-trading.ts) + +### 5. First WebSocket API order command + +The WebSocket API lets you submit order commands over a persistent WebSocket connection and await responses. Bybit supports WebSocket API order commands in live and testnet environments, but not demo trading. + + +```typescript +import { WebsocketAPIClient } from 'bybit-api'; + +const wsApi = new WebsocketAPIClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + // Use testnet API keys with this option. + testnet: true, +}); + +const wsClient = wsApi.getWSClient(); + +wsClient.on('open', (data) => console.log('ws api open', data.wsKey)); +wsClient.on('authenticated', (data) => { + console.log('ws api authenticated', data.wsKey); +}); +wsClient.on('exception', console.error); + +async function main() { + await wsClient.connectWSAPI(); + + if (process.env.BYBIT_PLACE_ORDER !== 'true') { + console.log('Set BYBIT_PLACE_ORDER=true when you are ready to submit.'); + return; + } + + const result = await wsApi.submitNewOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', + orderLinkId: `wsapi-${Date.now()}`, + }); + + console.log(result); } -⋮---- -export type WSExecutionFastEventV5 = WSPrivateTopicEventV5< - 'execution.fast', - WSExecutionFastV5[] ->; -⋮---- -export interface WSCoinV5 { - coin: string; - equity: string; - usdValue: string; - walletBalance: string; - free?: string; - locked: string; - spotHedgingQty: string; - borrowAmount: string; - availableToBorrow: string; - availableToWithdraw: string; - accruedInterest: string; - totalOrderIM: string; - totalPositionIM: string; - totalPositionMM: string; - unrealisedPnl: string; - cumRealisedPnl: string; - bonus: string; - collateralSwitch: boolean; - marginCollateral: boolean; - spotBorrow: string; - colRes?: string; + +main().catch(console.error); +``` + +The WebSocket API acknowledgement tells you the command was accepted. Track the final order state through the private `order` and `execution` streams, or reconcile with the REST API. + +See also: [WebSocket API client example](../examples/Websocket/WS-API/ws-api-client.ts) + +--- + + +## REST API + +Most Bybit integrations start with `RestClientV5`. It covers the current REST API surface and uses Bybit's `category` parameter to distinguish product groups where the endpoint requires it. + +### Create a public `RestClientV5` + +```typescript +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5(); +``` + +Public market calls do not require keys. + +### Create a private `RestClientV5` + +```typescript +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + recv_window: 5000, + parseAPIRateLimits: true, +}); +``` + +Private REST API methods are signed automatically. You do not need to add timestamps, signatures, `X-BAPI-API-KEY` or `X-BAPI-SIGN` headers yourself. + +### Common public market data calls + +```typescript +const serverTime = await client.getServerTime(); + +const instruments = await client.getInstrumentsInfo({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +const orderBook = await client.getOrderbook({ + category: 'linear', + symbol: 'BTCUSDT', + limit: 50, +}); + +const ticker = await client.getTickers({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +const candles = await client.getKline({ + category: 'linear', + symbol: 'BTCUSDT', + interval: '5', + limit: 10, +}); + +const recentTrades = await client.getPublicTradingHistory({ + category: 'linear', + symbol: 'BTCUSDT', + limit: 10, +}); + +const funding = await client.getFundingRateHistory({ + category: 'linear', + symbol: 'BTCUSDT', + limit: 10, +}); + +const openInterest = await client.getOpenInterest({ + category: 'linear', + symbol: 'BTCUSDT', + intervalTime: '15min', +}); +``` + +For Spot market data, use `category: 'spot'`. For inverse contracts, use `category: 'inverse'`. For options, use `category: 'option'` where the endpoint supports it. + +### Common private account and order calls + +```typescript +const accountInfo = await client.getAccountInfo(); +const systemStatus = await client.getSystemStatus(); + +const wallet = await client.getWalletBalance({ + accountType: 'UNIFIED', +}); + +const positions = await client.getPositionInfo({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +const openOrders = await client.getActiveOrders({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +const orderHistory = await client.getHistoricOrders({ + category: 'linear', + symbol: 'BTCUSDT', + limit: 20, +}); + +const executions = await client.getExecutionList({ + category: 'linear', + symbol: 'BTCUSDT', + limit: 20, +}); + +const feeRate = await client.getFeeRate({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +const transactions = await client.getTransactionLog({ + accountType: 'UNIFIED', +}); +``` + +See also: + +- [Private REST API example](../examples/Rest/rest-v5-private.ts) +- [Cursor pagination example](../examples/Rest/rest-v5-next-cursor.ts) +- [Endpoint function map](./endpointFunctionList.md) + +### Order examples + +Market order: + +```typescript +await client.submitOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Market', + qty: '0.001', + orderLinkId: `market-${Date.now()}`, +}); +``` + +Limit order: + +```typescript +await client.submitOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'GTC', + orderLinkId: `limit-${Date.now()}`, +}); +``` + +Post-only limit order: + +```typescript +await client.submitOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', + orderLinkId: `postonly-${Date.now()}`, +}); +``` + +Amend an order: + +```typescript +await client.amendOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderId: 'existing-order-id', + price: '11000', + qty: '0.002', +}); +``` + +Cancel an order: + +```typescript +await client.cancelOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderId: 'existing-order-id', +}); +``` + +Cancel open orders for a category and symbol: + +```typescript +await client.cancelAllOrders({ + category: 'linear', + symbol: 'BTCUSDT', +}); +``` + +Batch submit orders: + +```typescript +await client.batchSubmitOrders('linear', [ + { + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', + orderLinkId: `batch-a-${Date.now()}`, + }, + { + symbol: 'ETHUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.01', + price: '1000', + timeInForce: 'PostOnly', + orderLinkId: `batch-b-${Date.now()}`, + }, +]); +``` + +Pre-check an order where your account mode and product support it: + +```typescript +await client.preCheckOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', +}); +``` + +Bybit order acknowledgements are asynchronous. After submitting, use private WebSocket `order` and `execution` events, or REST API reads such as `getActiveOrders(...)`, `getHistoricOrders(...)`, and `getExecutionList(...)`, to track what actually happened. + +### Positions and risk + +```typescript +const positions = await client.getPositionInfo({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +await client.setLeverage({ + category: 'linear', + symbol: 'BTCUSDT', + buyLeverage: '3', + sellLeverage: '3', +}); + +await client.switchPositionMode({ + category: 'linear', + coin: 'USDT', + mode: 3, +}); + +await client.setTradingStop({ + category: 'linear', + symbol: 'BTCUSDT', + positionIdx: 0, + stopLoss: '25000', + slTriggerBy: 'LastPrice', +}); + +const closedPnl = await client.getClosedPnL({ + category: 'linear', + symbol: 'BTCUSDT', +}); +``` + +Position mode, margin mode, leverage, risk limit, and TP/SL behavior are account-sensitive. Read your current state first, then apply changes intentionally. + +### Wallet, assets, and transfers + +```typescript +const wallet = await client.getWalletBalance({ + accountType: 'UNIFIED', +}); + +const allCoins = await client.getAllCoinsBalance({ + accountType: 'UNIFIED', + coin: 'USDT,BTC', +}); + +const coinBalance = await client.getCoinBalance({ + accountType: 'UNIFIED', + coin: 'USDT', +}); + +const transferableCoins = await client.getTransferableCoinList('UNIFIED', 'FUND'); + +const deposits = await client.getDepositRecords({ + coin: 'USDT', +}); + +const withdrawals = await client.getWithdrawalRecords({ + coin: 'USDT', +}); +``` + +Withdrawal and transfer permissions are high risk. Keep those on separate keys where possible, and do not grant withdrawal permissions to trading services that do not need them. + +### Other endpoint groups + +`RestClientV5` also includes many specialized parts of the Bybit API. The most useful way to find the exact method is usually the [endpoint map](./endpointFunctionList.md), but the groups below show the shape of the surface: + +| Group | Example SDK methods | +| -------------------- | ------------------------------------------------------------------------------------------------- | +| Spread trading | `getSpreadInstrumentsInfo(...)`, `submitSpreadOrder(...)`, `cancelAllSpreadOrders(...)` | +| Spot margin | `toggleSpotMarginTrade(...)`, `setSpotMarginLeverageV2(...)`, `getSpotMarginLoanAccountInfo(...)` | +| Crypto loans | `borrowCryptoLoan(...)`, `repayCryptoLoan(...)`, `getUnpaidLoanOrders(...)` | +| Earn | `getEarnProduct(...)`, `submitStakeRedeem(...)`, `getEarnPosition(...)` | +| Broker and affiliate | `getBrokerRateLimitCap(...)`, `setBrokerRateLimit(...)`, `getAffiliateUserList(...)` | +| User and sub-account | `getSubUIDList(...)`, `createSubMember(...)`, `createSubUIDAPIKey(...)` | +| Convert | `requestConvertQuote(...)`, `confirmConvertQuote(...)`, `getConvertHistory(...)` | +| P2P | `getP2POrders(...)`, `sendP2POrderMessage(...)`, `uploadP2PChatFile(...)` | +| RFQ | `createRFQ(...)`, `createRFQQuote(...)`, `executeRFQQuote(...)` | + +If an endpoint exists in Bybit's API docs, search for the endpoint path or method group in [docs/endpointFunctionList.md](./endpointFunctionList.md). + +--- + + +## WebSocket Streams + +Use `WebsocketClient` when you want event-driven updates instead of REST API polling. The same client handles public streams, private account streams, and raw WebSocket API commands. + +Typical setup is: create a client, attach event handlers, provide keys if private topics are needed, and subscribe to topics. The SDK opens the correct endpoint, authenticates when needed, sends subscribe requests, tracks topics, monitors heartbeats, reconnects dropped sockets, and resubscribes cached topics after reconnect. + +### Common `WebsocketClient` events + +| Event | Meaning | +| --------------- | ----------------------------------------------------------------- | +| `open` | Connection established | +| `update` | Streaming topic data received | +| `response` | Subscribe, unsubscribe, auth, or WebSocket API acknowledgement | +| `reconnect` | Connection dropped and the SDK is replacing it | +| `reconnected` | Replacement connection opened and cached subscriptions can resume | +| `close` | Socket closed | +| `authenticated` | Private authentication succeeded | +| `exception` | Errors and unexpected conditions | + +Use `exception`, not the deprecated `error` event. + +### Understanding `WS_KEY_MAP` + +[`WS_KEY_MAP`](/reference/glossary#ws-key) tells the SDK which Bybit WebSocket endpoint family a connection belongs to: + +| Key | Use | +| ----------------- | -------------------------- | +| `v5SpotPublic` | Spot public market data | +| `v5LinearPublic` | Linear public market data | +| `v5InversePublic` | Inverse public market data | +| `v5OptionPublic` | Options public market data | +| `v5Private` | Private account streams | +| `v5PrivateTrade` | WebSocket API commands | + +You normally do not need to pass these keys when subscribing to ordinary topics. `subscribeV5(...)` derives the correct connection from the topic and category. They are still useful for diagnostics, explicit connection calls, inspecting the internal topic store, and lower-level WebSocket API usage. + +### Public topics + +```typescript +import { WebsocketClient } from 'bybit-api'; + +const ws = new WebsocketClient(); + +ws.on('update', (data) => console.log('public update', JSON.stringify(data))); +ws.on('exception', console.error); + +ws.subscribeV5( + ['orderbook.50.BTCUSDT', 'publicTrade.BTCUSDT', 'tickers.BTCUSDT', 'kline.5.BTCUSDT'], + 'linear', +); +``` + +For Spot: + +```typescript +ws.subscribeV5(['orderbook.50.BTCUSDT', 'tickers.BTCUSDT'], 'spot'); +``` + +For inverse: + +```typescript +ws.subscribeV5(['orderbook.50.BTCUSD', 'tickers.BTCUSD'], 'inverse'); +``` + +For options: + +```typescript +ws.subscribeV5('publicTrade.BTC', 'option'); +``` + +See also: + +- [public WebSocket example](../examples/Websocket/Public/ws-public-v5.ts) +- [All liquidations WebSocket example](../examples/Websocket/Public/ws-public-allLiquidations.ts) + +### Private topics + +```typescript +import { WebsocketClient } from 'bybit-api'; + +const ws = new WebsocketClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, +}); + +ws.on('authenticated', (data) => console.log('authenticated', data.wsKey)); +ws.on('update', (data) => console.log('private update', JSON.stringify(data))); +ws.on('exception', console.error); + +ws.subscribeV5(['order', 'execution', 'position', 'wallet', 'greeks'], 'linear'); +``` + +Private topics currently share the private endpoint. The category parameter is ignored for private routing, but passing the category keeps your code consistent with `subscribeV5(...)`. + +### Unsubscribe and connection cleanup + +```typescript +ws.unsubscribeV5('kline.5.BTCUSDT', 'linear'); + +// Close all active WebSocket connections when shutting down a process. +ws.closeAll(); +``` + +`unsubscribeV5(...)` removes the topic from the SDK's subscription cache, so it will not be resubscribed after a reconnect. + +### Multiple connections for load isolation + +The SDK groups topics by Bybit endpoint. If you want to isolate heavy streams, create separate client instances and split topics yourself: + +```typescript +const marketDataA = new WebsocketClient(); +const marketDataB = new WebsocketClient(); + +marketDataA.subscribeV5(['orderbook.50.BTCUSDT'], 'linear'); +marketDataB.subscribeV5(['kline.1.BTCUSDT', 'publicTrade.BTCUSDT'], 'linear'); +``` + +Do not subscribe to the same topic in multiple clients unless you intentionally want duplicate events. + +--- + + +## WebSocket API + +Bybit's WebSocket API is a request/response API over a persistent WebSocket connection. In this SDK, you can use it in two ways: + +- `WebsocketAPIClient` for promise-driven methods such as `submitNewOrder(...)`, `amendOrder(...)`, and `cancelOrder(...)`. +- `WebsocketClient.sendWSAPIRequest(...)` for lower-level operation calls such as `order.create`. + +The promise-driven client is the easiest place to start. + +```typescript +import { WebsocketAPIClient } from 'bybit-api'; + +const wsApi = new WebsocketAPIClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + // Use testnet API keys with this option. + testnet: true, +}); + +await wsApi.getWSClient().connectWSAPI(); + +const createResult = await wsApi.submitNewOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', + orderLinkId: `wsapi-${Date.now()}`, +}); + +console.log(createResult); +``` + +Amend and cancel: + +```typescript +await wsApi.amendOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderId: createResult.data.orderId, + price: '11000', +}); + +await wsApi.cancelOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderId: createResult.data.orderId, +}); +``` + +Batch commands: + +```typescript +await wsApi.batchSubmitOrders('linear', [ + { + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', + orderLinkId: `wsapi-batch-a-${Date.now()}`, + }, +]); +``` + +Raw command style: + +```typescript +import { WS_KEY_MAP, WebsocketClient } from 'bybit-api'; + +const ws = new WebsocketClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + testnet: true, +}); + +const result = await ws.sendWSAPIRequest(WS_KEY_MAP.v5PrivateTrade, 'order.create', { + category: 'linear', + symbol: 'BTCUSDT', + side: 'Buy', + orderType: 'Limit', + qty: '0.001', + price: '10000', + timeInForce: 'PostOnly', +}); + +console.log(result); +``` + +Bybit's WebSocket API response means the request was accepted for processing. Use private streams to confirm order status and executions. + +See also: + +- [WebSocket API client example](../examples/Websocket/WS-API/ws-api-client.ts) +- [Raw WebSocket API promises example](../examples/Websocket/WS-API/ws-api-raw-promises.ts) +- [Raw WebSocket API events example](../examples/Websocket/WS-API/ws-api-raw-events.ts) +- [Bybit WebSocket API guideline](https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline) + +--- + + +## Environments and regions + +### Live + +Live is the default environment: + +```typescript +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, +}); +``` + +### Testnet + +Testnet uses separate credentials and separate API domains: + +```typescript +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + testnet: true, +}); + +const ws = new WebsocketClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + testnet: true, +}); +``` + +Use testnet for endpoint wiring, permissions, and safe integration checks. Do not treat testnet market behavior as representative of live market behavior. + +### Demo trading + +Demo trading uses a mainnet demo account with simulated trading and separate demo keys. + +```typescript +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + demoTrading: true, +}); +``` + +Private demo WebSocket streams are also supported: + +```typescript +const ws = new WebsocketClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + demoTrading: true, +}); + +ws.subscribeV5(['order', 'execution', 'position', 'wallet'], 'linear'); +``` + +Do not combine `testnet: true` with `demoTrading: true`. Bybit's demo trading docs also note that WebSocket API commands are not supported in demo trading, so use REST API demo trading or private demo streams for demo workflows, and use testnet for WebSocket API command testing. + +### Regional REST API domains + +By default, REST API calls use the global Bybit domain. If your account belongs to a regional Bybit domain, set `apiRegion`: + +```typescript +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + apiRegion: 'EU', +}); +``` + +Supported API region values in this SDK: + +- `default` +- `bytick` +- `NL` +- `TK` +- `KZ` +- `HK` +- `GE` +- `UAE` +- `EU` + +New API regions will be supported as they become available. If you're looking for a region not yet supported, please get in touch. + +You can also pass `baseUrl` for a custom REST API domain, or `wsUrl` for a custom WebSocket URL when needed. + +See also: [custom REST API URL example](../examples/Rest/rest-v5-custom-url.ts) + +--- + + +## Proxies for REST API and WebSocket + +Use a proxy when a deployment needs a fixed egress IP, must cross an approved corporate network, or has a controlled network failover path. A proxy does not change Bybit account eligibility, product categories, account mode, or the selected live, testnet, or demo environment. + +For REST API requests, `apiRegion` selects the Bybit domain associated with the account. A proxy only changes the network path used to reach that domain. Keep those settings separate. + +The broader [Using proxy with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) article covers the shared constructor pattern. The examples below use the current `bybit-api` options directly. + +Proxy agents are a Node.js networking feature. Browser applications cannot select a raw socket agent. + +### HTTP or HTTPS proxy + +Install the agent: + +```bash +npm install bybit-api https-proxy-agent +``` + +Set `BYBIT_PROXY_URL` to the full proxy URL, including URL-encoded credentials when required. + +This public check sends one REST API call and one linear WebSocket subscription through the same proxy: + + + +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { RestClientV5, WebsocketClient } from 'bybit-api'; + +const proxyUrl = process.env.BYBIT_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BYBIT_PROXY_URL before running this example.'); } -⋮---- -export interface WSWalletV5 { - accountType: string; - accountLTV: string; - accountIMRate: string; - accountMMRate: string; - accountIMRateByMp: string; - accountMMRateByMp: string; - totalInitialMarginByMp: string; - totalMaintenanceMarginByMp: string; - totalEquity: string; - totalWalletBalance: string; - totalMarginBalance: string; - totalAvailableBalance: string; - totalPerpUPL: string; - totalInitialMargin: string; - totalMaintenanceMargin: string; - coin: WSCoinV5[]; + +const proxyAgent = new HttpsProxyAgent(proxyUrl); + +const rest = new RestClientV5( + {}, + { + httpsAgent: proxyAgent, + proxy: false, + }, +); + +const ws = new WebsocketClient({ + wsOptions: { + agent: proxyAgent, + }, +}); + +ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through proxy:', wsKey); +}); +ws.on('update', (event) => { + console.log('stream update', event); +}); +ws.on('exception', console.error); + +async function main() { + const serverTime = await rest.getServerTime(); + console.log('REST API connected through proxy:', serverTime); + + ws.subscribeV5(['tickers.BTCUSDT'], 'linear'); } -⋮---- -export type WSWalletEventV5 = WSPrivateTopicEventV5<'wallet', WSWalletV5[]>; -⋮---- -export interface WSGreeksV5 { - baseCoin: string; - totalDelta: string; - totalGamma: string; - totalVega: string; - totalTheta: string; + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +REST API networking options belong in the second `RestClientV5` constructor argument: + +- `httpsAgent` sends the HTTPS request through the agent. +- `proxy: false` prevents Axios from applying another proxy configuration on top of that agent. + +WebSocket networking options belong in `wsOptions.agent`. The same setting applies to public streams, private streams, and `WebsocketAPIClient`. Bybit authenticates these connections over the socket and does not fetch a separate WebSocket token through REST API. + +Do not use `requestOptions.agent` in new code. It remains a legacy alias for the WebSocket agent, but `wsOptions.agent` is the current option. + +### Private streams and WebSocket API through a proxy + +This example authenticates a private stream and a WebSocket API connection without placing an order: + + + +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { WebsocketAPIClient, WebsocketClient } from 'bybit-api'; + +const proxyUrl = process.env.BYBIT_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BYBIT_PROXY_URL before running this example.'); } -⋮---- -export type WSGreeksEventV5 = WSPrivateTopicEventV5<'greeks', WSGreeksV5[]>; -⋮---- -export interface WSSpreadOrderV5 { - category: 'combination' | 'spot_leg' | 'future_leg'; - symbol: string; - parentOrderId: string; - orderId: string; - orderLinkId: string; - side: OrderSideV5; - orderStatus: OrderStatusV5; - cancelType: OrderCancelTypeV5; - rejectReason: OrderRejectReasonV5; - timeInForce: OrderTimeInForceV5; - price: string; - qty: string; - avgPrice: string; - leavesQty: string; - leavesValue: string; - cumExecQty: string; - cumExecValue: string; - cumExecFee: string; - orderType: OrderTypeV5; - isLeverage: string; - createdTime: string; - updatedTime: string; - feeCurrency: string; - createType: OrderCreateTypeV5; - closedPnl: string; - cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency + +const key = process.env.BYBIT_API_KEY; +const secret = process.env.BYBIT_API_SECRET; + +if (!key || !secret) { + throw new Error('Set BYBIT_API_KEY and BYBIT_API_SECRET before running this example.'); } -⋮---- -cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency -⋮---- -export type WSSpreadOrderEventV5 = WSPrivateTopicEventV5< - 'spread.order', - WSSpreadOrderV5[] ->; -⋮---- -export interface WSSpreadExecutionV5 { - category: 'combination' | 'spot_leg' | 'future_leg'; - symbol: string; - isLeverage: string; - orderId: string; - orderLinkId: string; - side: OrderSideV5; - orderPrice: string; - orderQty: string; - leavesQty: string; - createType: OrderCreateTypeV5; - orderType: OrderTypeV5; - execFee: string; - execFeeV2: string; - feeCurrency: string; // Trading fee currency - parentExecId: string; - execId: string; - execPrice: string; - execQty: string; - execPnl: string; - execType: ExecTypeV5; - execValue: string; - execTime: string; - isMaker: boolean; - feeRate: string; - markPrice: string; - closedSize: string; - seq: number; + +const proxyAgent = new HttpsProxyAgent(proxyUrl); +const credentials = { key, secret }; + +const streams = new WebsocketClient({ + ...credentials, + wsOptions: { + agent: proxyAgent, + }, +}); + +const wsApi = new WebsocketAPIClient({ + ...credentials, + attachEventListeners: false, + wsOptions: { + agent: proxyAgent, + }, +}); +const wsApiConnection = wsApi.getWSClient(); + +streams.on('authenticated', ({ wsKey }) => { + console.log('Private stream authenticated:', wsKey); +}); +streams.on('exception', console.error); +wsApiConnection.on('authenticated', ({ wsKey }) => { + console.log('WebSocket API authenticated:', wsKey); +}); +wsApiConnection.on('exception', console.error); + +async function main() { + streams.subscribeV5(['order', 'execution'], 'linear'); + await wsApiConnection.connectWSAPI(); + console.log('Private connections are ready'); } -⋮---- -feeCurrency: string; // Trading fee currency -⋮---- -export type WSSpreadExecutionEventV5 = WSPrivateTopicEventV5< - 'spread.execution', - WSSpreadExecutionV5[] ->; -⋮---- -export interface WSInsuranceV5 { - coin: string; - symbols: string; - balance: string; - updateTime: string; + +process.once('SIGINT', () => { + streams.closeAll(); + wsApiConnection.closeAll(); +}); + +main().catch(console.error); +``` + +Use matching testnet keys with `testnet: true` on both clients when testing against Bybit testnet. WebSocket API commands are not available in demo trading. + +### SOCKS5 proxy + +Install the SOCKS agent: + +```bash +npm install bybit-api socks-proxy-agent +``` + +Use `SocksProxyAgent` in the same REST API and WebSocket positions: + + + +```typescript +import { RestClientV5, WebsocketClient } from 'bybit-api'; +import { SocksProxyAgent } from 'socks-proxy-agent'; + +const proxyUrl = process.env.BYBIT_SOCKS_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BYBIT_SOCKS_PROXY_URL before running this example.'); } -⋮---- -export type WSInsuranceEventV5 = WSPublicTopicEventV5< - 'insurance.USDT' | 'insurance.USDC' | 'insurance.inverse', - 'snapshot' | 'delta', - WSInsuranceV5[] ->; -⋮---- -export interface WSPriceLimitV5 { - symbol: string; - buyLmt: string; - sellLmt: string; + +const proxyAgent = new SocksProxyAgent(proxyUrl); + +const rest = new RestClientV5( + {}, + { + httpsAgent: proxyAgent, + proxy: false, + }, +); + +const ws = new WebsocketClient({ + wsOptions: { + agent: proxyAgent, + }, +}); + +async function main() { + const serverTime = await rest.getServerTime(); + console.log('REST API connected through SOCKS5:', serverTime); + + ws.subscribeV5(['publicTrade.BTCUSDT'], 'linear'); } -⋮---- -export type WSPriceLimitEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSPriceLimitV5 ->; -⋮---- -export interface WSADLAlertV5 { - c: string; // Token of the insurance pool - s: string; // Trading pair name - b: string; // Balance of the insurance fund. For shared insurance pool, follows T+1 refresh (updated daily at 00:00 UTC) - mb: string; // Deprecated: always returns empty string. Previously: Maximum balance of the insurance pool in the last 8 hours - i_pr: string; // PnL ratio threshold for triggering contract PnL drawdown ADL - pr: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped - adl_tt: string; // Trigger threshold for contract PnL drawdown ADL - adl_sr: string; // Stop ratio threshold for contract PnL drawdown ADL + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +See also: + +- [Axios proxy configuration example](../examples/Rest/rest-v5-proxies.ts) +- [HTTPS proxy agent example](../examples/Rest/rest-v5-proxies2.ts) + +### Proxy checks + +- Keep proxy URLs and credentials in environment variables or a secret manager. +- URL-encode usernames and passwords when constructing a proxy URL from separate values. +- Make sure the proxy egress IP matches the Bybit API key's IP whitelist. +- Test a public REST API call and public WebSocket subscription before private authentication. +- Keep `apiRegion`, `baseUrl`, and `wsUrl` decisions separate from proxy configuration. +- Measure request, connection, and reconnect latency through the proxy. +- Treat repeated HTTP 407 responses, TLS errors, and WebSocket reconnect loops as network failures. +- Keep the host clock synchronized. Change `recv_window` only after measuring timestamp failures and proxy latency. +- The SDK does not rotate proxy endpoints. Handle endpoint selection outside the client when rotation is required. + +--- + + +## Production notes + +Before a Bybit integration trades unattended, make these decisions explicit. + +### 1. Roll out in layers + +Move from read-only behavior to order placement one layer at a time: + +1. Public REST API calls +2. Public WebSocket streams +3. Private REST API account reads +4. Private WebSocket account streams +5. Demo or testnet order placement +6. Tiny live trading tests + +Keep each layer observable before adding the next one. + +### 2. Reconnect, then backfill + +Listen for `reconnect` and `reconnected`. A dropped WebSocket connection is a normal production condition, especially during volatility or scheduled exchange-side disconnects. + +When the SDK emits `reconnect`, pause risky actions if your strategy depends on stream state. When it emits `reconnected`, query the REST API for the account state you may have missed: + +```typescript +ws.on('reconnected', async ({ wsKey }) => { + console.log('reconnected', wsKey); + + const [wallet, positions, regularOpenOrders, stopOpenOrders] = await Promise.all([ + client.getWalletBalance({ accountType: 'UNIFIED' }), + client.getPositionInfo({ category: 'linear', settleCoin: 'USDT' }), + client.getActiveOrders({ + category: 'linear', + settleCoin: 'USDT', + openOnly: 0, + orderFilter: 'Order', + }), + client.getActiveOrders({ + category: 'linear', + settleCoin: 'USDT', + openOnly: 0, + orderFilter: 'StopOrder', + }), + ]); + + const openOrders = [ + ...(regularOpenOrders.result?.list ?? []), + ...(stopOpenOrders.result?.list ?? []), + ]; + + // Reconcile these with your local state before resuming risky actions. + console.log({ wallet, positions, openOrders }); +}); +``` + +For linear position managers that depend on conditional stop orders, do not assume the no-`orderFilter` active-order response covers both regular orders and `StopOrder` rows unless you have captured and verified that response shape for the account mode. + +### 3. Check Bybit business acceptance + +TypeScript validates the request fields you pass to the SDK. It does not prove that Bybit accepted a live request, private stream payload, or hydrated order state. For order-management services, prefer `throwExceptions: true` on `RestClientV5` so non-zero Bybit `retCode` responses throw and flow through your normal SDK/API error classifier. Preserve `retCode`, `retMsg`, `result`, request context, and product/symbol scope from the thrown error where available. + +If you intentionally use `throwExceptions: false`, business rejections resolve as response objects and must be classified manually: + +```typescript +type BybitResponse = { + retCode: number; + retMsg: string; + result: T; +}; + +function classifyBybitResponse(response: BybitResponse) { + if (response.retCode === 0) return { ok: true as const, response }; + + return { + ok: false as const, + code: response.retCode, + message: response.retMsg, + response, + }; } -⋮---- -c: string; // Token of the insurance pool -s: string; // Trading pair name -b: string; // Balance of the insurance fund. For shared insurance pool, follows T+1 refresh (updated daily at 00:00 UTC) -mb: string; // Deprecated: always returns empty string. Previously: Maximum balance of the insurance pool in the last 8 hours -i_pr: string; // PnL ratio threshold for triggering contract PnL drawdown ADL -pr: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped -adl_tt: string; // Trigger threshold for contract PnL drawdown ADL -adl_sr: string; // Stop ratio threshold for contract PnL drawdown ADL -⋮---- -export type WSADLAlertEventV5 = WSPublicTopicEventV5< - 'adlAlert.USDT' | 'adlAlert.USDC' | 'adlAlert.inverse', - 'snapshot', - WSADLAlertV5[] ->; -⋮---- -export type WSSystemStatusEventV5 = WSPublicTopicEventV5< - 'system.status', - 'snapshot', - SystemStatusItemV5[] ->; -⋮---- -/** - * RFQ WebSocket Events - */ -⋮---- -/** - * RFQ Inquiry Channel - * Private push for RFQ inquiries sent or received by the user - * Topics: rfq.open.rfqs, rfq.site.rfqs - */ -export type WSRFQInquiryEventV5 = WSPrivateTopicEventV5< - 'rfq.open.rfqs' | 'rfq.site.rfqs', - RFQItemV5[] ->; -⋮---- -/** - * RFQ Quote Channel - * Private push for quotes sent or received by the user - * Topics: rfq.open.quotes, rfq.site.quotes - */ -export type WSRFQQuoteEventV5 = WSPrivateTopicEventV5< - 'rfq.open.quotes' | 'rfq.site.quotes', - RFQQuoteItemV5[] ->; -⋮---- -/** - * RFQ Trade Channel - * Private push for block trades executed by the user - * Topics: rfq.open.trades, rfq.site.trades - */ -export type WSRFQTradeEventV5 = WSPrivateTopicEventV5< - 'rfq.open.trades' | 'rfq.site.trades', - RFQTradeV5[] ->; -⋮---- -/** - * RFQ Public Trade Channel - * Public push for all block trades - * Topics: rfq.open.public.trades, rfq.site.public.trades - */ -export type WSRFQPublicTradeEventV5 = WSPublicTopicEventV5< - 'rfq.open.public.trades' | 'rfq.site.public.trades', - 'snapshot', - RFQPublicTradeV5[] ->; +``` + +For order-management services, stop later non-sent intents on any Bybit business rejection, log the sanitized error or response, block or surface deterministic request failures, and reconcile before submitting later exposure. + +### 4. Include `triggerDirection` for conditional stops + +For Bybit V5 triggered stop-loss orders, verify the current request type and include `triggerDirection`. For a long position, the stop-loss exit usually sells when price falls to the trigger, so `triggerDirection` is `2`. For a short position, the stop-loss exit usually buys when price rises to the trigger, so `triggerDirection` is `1`. + +```typescript +await client.submitOrder({ + category: 'linear', + symbol: 'BTCUSDT', + side: 'Sell', + orderType: 'Market', + qty: '0.001', + triggerPrice: '60000', + triggerDirection: 2, + triggerBy: 'MarkPrice', + orderFilter: 'StopOrder', + positionIdx: 0, + reduceOnly: true, + closeOnTrigger: true, + orderLinkId: `long-sl-${Date.now()}`, +}); +``` + +Hydrated active orders may include explicit defaults such as `closeOnTrigger: false`, `reduceOnly: false`, empty trigger fields, or stop-order defaults that were omitted from your original request. Compare desired and hydrated orders by order kind and normalize irrelevant defaults before deciding to cancel and replace an app-owned order. + +### 5. Watch clocks and receive windows + +Private requests are timestamp-sensitive. Keep your system clock synced first. If you still see receive-window errors, set the receive window intentionally. + +REST API calls use `recv_window`: + +```typescript +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + recv_window: 5000, +}); + +await client.fetchLatencySummary(); +``` + +WebSockets use `recvWindow`: + +```typescript +const ws = new WebsocketClient({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + recvWindow: 5000, +}); + +ws.setTimeOffsetMs(-500); +``` + +Use time offsets as a last resort. Fix host clock sync first. Refer to the timestamp guidance if you're having persistent issues with it: https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow + +### 6. Keep credentials scoped + +Live, testnet, and demo credentials are different. Keep them separate in your secrets manager and deployment configuration. + +Use separate keys for separate risk levels: + +- Read-only market and account monitoring. +- Trading without withdrawals. +- Transfers or withdrawals, only where absolutely required. + +Do not put private keys in frontend code. Use IP whitelisting. + +### 7. Monitor rate limits + +The SDK can parse Bybit REST API rate-limit headers into responses when `parseAPIRateLimits: true` is enabled: + +```typescript +const client = new RestClientV5({ + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + parseAPIRateLimits: true, +}); + +const response = await client.getPositionInfo({ + category: 'linear', + symbol: 'BTCUSDT', +}); + +console.log(response.rateLimitApi); +``` + +Bybit also returns rate-limit information in WebSocket API response headers. Use that data to reduce polling, back off safely, and prefer streaming updates where possible. + +### 8. Inject your own logger if needed + +If you want SDK logs in your own monitoring stack, pass a logger: + +```typescript +import { DefaultLogger, WebsocketClient } from 'bybit-api'; + +const customLogger: typeof DefaultLogger = { + ...DefaultLogger, + trace: () => {}, + info: (...params) => console.info(new Date(), ...params), + error: (...params) => console.error(new Date(), ...params), +}; + +const ws = new WebsocketClient( + { + key: process.env.BYBIT_API_KEY!, + secret: process.env.BYBIT_API_SECRET!, + }, + customLogger, +); +``` + +For raw HTTP request/response tracing during local debugging, the repo also supports the `BYBITTRACE` environment variable. Do not enable verbose tracing in production logs if it could expose sensitive request data. + +--- -================ -File: src/types/websockets/ws-general.ts -================ -import { AxiosRequestConfig } from 'axios'; -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; -⋮---- -import { RestClientOptions, WS_KEY_MAP } from '../../util'; -⋮---- -/** For spot markets, spotV3 is recommended */ -export type APIMarket = 'v5'; -⋮---- -// Same as inverse futures -export type WsPublicInverseTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'klineV2'; -⋮---- -export type WsPublicUSDTPerpTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'kline'; -⋮---- -export type WsPublicSpotV1Topic = - | 'trade' - | 'realtimes' - | 'kline' - | 'depth' - | 'mergedDepth' - | 'diffDepth'; -⋮---- -export type WsPublicSpotV2Topic = - | 'depth' - | 'kline' - | 'trade' - | 'bookTicker' - | 'realtimes'; -⋮---- -export type WsPublicTopics = - | WsPublicInverseTopic - | WsPublicUSDTPerpTopic - | WsPublicSpotV1Topic - | WsPublicSpotV2Topic - | string; -⋮---- -// Same as inverse futures -export type WsPrivateInverseTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order'; -⋮---- -export type WsPrivateUSDTPerpTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order' - | 'wallet'; -⋮---- -export type WsPrivateSpotTopic = - | 'outboundAccountInfo' - | 'executionReport' - | 'ticketInfo'; -⋮---- -export type WsPrivateTopic = - | WsPrivateInverseTopic - | WsPrivateUSDTPerpTopic - | WsPrivateSpotTopic - | string; -⋮---- -export type WsTopic = WsPublicTopics | WsPrivateTopic; -⋮---- -/** This is used to differentiate between each of the available websocket streams (as bybit has multiple websockets) */ -export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; -export type WsMarket = 'all'; -⋮---- -export interface WSClientConfigurableOptions { - /** Your API key */ - key?: string; + +## FAQ - /** Your API secret */ - secret?: string; +**Do I need API keys for public market data?** - /** - * Set to `true` to connect to Bybit's testnet environment. - * - * Notes: - * - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. - */ - testnet?: boolean; +No. Public REST API market data and public WebSocket market data do not usually require API keys. - /** - * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo - * - * Only the "V5" "market" is supported here. - */ - demoTrading?: boolean; +**Which REST API client should I use?** - /** - * The API group this client should connect to. The V5 market is currently used by default. - * - * Only the "V5" "market" is supported here. - */ - market?: APIMarket; +Use `RestClientV5` for new Bybit API work. `SpotClientV3` remains in the package for legacy compatibility, but new integrations should use the current API surface. - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; +**Why does every example use `category`?** - /** How often to check if the connection is alive */ - pingInterval?: number; +The Bybit API uses `category` to distinguish Spot, Linear, Inverse, and Options behavior. The same SDK method can often cover several product groups, so the category tells Bybit which product family the request belongs to. Refer to Bybit's API documentation for exact guidance on expected request parameters. - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; +**Why both `WebsocketClient` and `WebsocketAPIClient`?** - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; +- `WebsocketClient` is for subscriptions and streaming topics. +- `WebsocketAPIClient` is for commands over Bybit's WebSocket API. Think request/response methods over a persistent WebSocket connection. - restOptions?: RestClientOptions; - requestOptions?: AxiosRequestConfig; +**Can I use one key for everything?** - wsOptions?: { - protocols?: string[]; - agent?: any; - } & Partial; +Only if the key belongs to the correct environment and has the required permissions. For production systems, keep keys scoped by environment and permission level. Avoid withdrawal permissions unless your service truly needs them. - wsUrl?: string; +**Does the SDK support RSA authentication?** - /** - * Default: false. - * - * When enabled, any calls to the subscribe method will return a promise. - * Note: internally, subscription requests are sent in batches. This may not behave as expected when - * subscribing to a large number of topics, especially if you are not yet connected when subscribing. - */ - promiseSubscribeRequests?: boolean; +Yes. Pass your Bybit API key as `key` and your PEM private key as `secret`. The SDK detects RSA private keys automatically. - /** - * 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 */ -⋮---- -/** - * Set to `true` to connect to Bybit's testnet environment. - * - * Notes: - * - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. - */ -⋮---- -/** - * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo - * - * Only the "V5" "market" is supported here. - */ -⋮---- -/** - * The API group this client should connect to. The V5 market is currently used by default. - * - * Only the "V5" "market" is supported here. - */ -⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ -⋮---- -/** 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 */ -⋮---- -/** - * Default: false. - * - * When enabled, any calls to the subscribe method will return a promise. - * Note: internally, subscription requests are sent in batches. This may not behave as expected when - * subscribing to a large number of topics, especially if you are not yet connected when subscribing. - */ -⋮---- -/** - * 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. - */ -⋮---- -/** - * WS configuration that's always defined, regardless of user configuration - * (usually comes from defaults if there's no user-provided values) - */ -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - market: APIMarket; - pongTimeout: number; - pingInterval: number; - reconnectTimeout: number; - recvWindow: number; +**Should I use demo trading or testnet?** - /** - * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) - */ - requireConnectionReadyConfirmation: boolean; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequests: boolean; - reauthWSAPIOnReconnect: boolean; +Use demo trading for simulated trading with live-like market context where Bybit supports the endpoint. Use testnet for API wiring and WebSocket API command testing. Do not use testnet market behavior as evidence that a strategy will behave well live. Read more about CEX testnets here: https://github.com/sieblyio/awesome-crypto-examples/wiki/CEX-Testnets - /** - * Whether to use native WebSocket ping/pong frames for heartbeats - */ - useNativeHeartbeats: boolean; -} -⋮---- -/** - * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) - */ -⋮---- -/** - * Whether to use native WebSocket ping/pong frames for heartbeats - */ -⋮---- -export type WsEventInternalSrc = 'event' | 'function' | 'frame'; +**What happens if a WebSocket connection drops?** + +The SDK detects dead connections, opens a replacement connection, authenticates where needed, and resubscribes cached topics. Listen for `reconnect` and `reconnected`, then reconcile state with the REST API before resuming risky trading actions. + +**Does this guide cover every SDK method?** + +No. This guide covers the common first steps and production concerns. For full method coverage, see: + +- [Bybit JavaScript endpoint reference](./endpointFunctionList.md) +- [Bybit SDK examples](../examples) +- [Bybit SDK source on GitHub](https://github.com/tiagosiebler/bybit-api) + +--- + + +## Next steps + +If you want to learn more about integrating with the Bybit API and WebSockets: + +- Explore the [Bybit JavaScript examples on GitHub](../examples) +- Review the full endpoint list: [Bybit JavaScript endpoint reference](./endpointFunctionList.md) +- Check the Bybit JavaScript SDK on npm: [`bybit-api`](https://www.npmjs.com/package/bybit-api) +- Browse the source code of the Bybit JavaScript SDK on GitHub: [`tiagosiebler/bybit-api`](https://github.com/tiagosiebler/bybit-api) +- Review RSA auth: [Bybit RSA authentication example](../examples/Auth/RSA-sign.md) +- Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) ================ -File: src/websocket-client.ts +File: src/types/request/index.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { - CategoryV5, - MessageEventLike, - WSClientConfigurableOptions, - WsKey, - WsMarket, - WsTopic, -} from './types'; -import { - Exact, - WSAPIOperation, - WsAPIOperationResponseMap, - WSAPIRequest, - WsAPITopicRequestParamMap, - WsAPIWsKeyTopicMap, - WsOperation, - WsRequestOperationBybit, -} from './types/websockets/ws-api'; -import { - APIID, - DefaultLogger, - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getPromiseRefForWSAPIRequest, - getTopicsPerWSKey, - getWsKeyForTopic, - getWsUrl, - isPrivateWsTopic, - isTopicSubscriptionConfirmation, - isTopicSubscriptionSuccess, - isWSAPIResponse, - isWsPong, - neverGuard, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WSConnectedResult, - WsTopicRequest, -} from './util'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient'; -import { SignAlgorithm, signMessage } from './util/webCryptoAPI'; + + +================ +File: src/types/request/v5-asset.ts +================ +import { AccountTypeV5, CategoryV5 } from '../shared-v5'; ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; +export interface GetCoinExchangeRecordParamsV5 { + fromCoin?: string; + toCoin?: string; + limit?: number; + cursor?: string; } ⋮---- -/** If true, will skip auth requirement for WS API connection */ +export interface GetDeliveryRecordParamsV5 { + category: CategoryV5; + symbol?: string; + startTime?: number; + endTime?: number; + expDate?: string; + limit?: number; + cursor?: string; +} ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +export interface GetSettlementRecordParamsV5 { + category: CategoryV5; + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +export interface GetAssetInfoParamsV5 { + accountType: AccountTypeV5; + coin?: string; +} ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting - * for automatic connection by SDK. - */ -public connectAll(): Promise[] +export interface GetAllCoinsBalanceParamsV5 { + memberId?: string; + accountType: AccountTypeV5; + coin?: string; + withBonus?: number; +} ⋮---- -/** - * 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 +export interface GetAccountCoinBalanceParamsV5 { + memberId?: string; + toMemberId?: string; + accountType: AccountTypeV5; + coin: string; + toAccountType?: AccountTypeV5; + withBonus?: number; + withTransferSafeAmount?: 0 | 1; + withLtvTransferSafeAmount?: 0 | 1; +} ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +export interface GetInternalTransferParamsV5 { + transferId?: string; + coin?: string; + status?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -public connectPublic(): Promise[] +export interface UniversalTransferParamsV5 { + transferId: string; + coin: string; + amount: string; + fromMemberId: number; + toMemberId: number; + fromAccountType: AccountTypeV5; + toAccountType: AccountTypeV5; +} ⋮---- -public connectPrivate(): Promise +export interface GetUniversalTransferRecordsParamsV5 { + transferId?: string; + coin?: string; + status?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** - * Subscribe to V5 topics & track/persist them. - * @param wsTopics - topic or list of topics - * @param category - the API category this topic is for (e.g. "linear"). - * The value is only important when connecting to public topics and will be ignored for private 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 subscribeV5( - wsTopics: WsTopic[] | WsTopic, - category: CategoryV5, - isPrivateTopic?: boolean, -): Promise[] +export interface GetAllowedDepositCoinInfoParamsV5 { + coin?: string; + chain?: string; + limit?: number; + cursor?: string; +} ⋮---- -// Sort into per-WsKey batches, in case there is a mix of topics here +export interface GetDepositRecordParamsV5 { + id?: string; + txID?: string; + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -// Prevent duplicate requests to the same topic +export interface GetSubAccountDepositRecordParamsV5 { + id?: string; + txID?: string; + subMemberId: string; + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -// Batch sub topics per ws key +export interface GetInternalDepositRecordParamsV5 { + txID?: string; + startTime?: number; + endTime?: number; + coin?: string; + cursor?: string; + limit?: number; +} ⋮---- -// Return promise to resolve midflight WS request (only works if already connected before request) +export interface GetWithdrawalRecordsParamsV5 { + withdrawID?: string; + txID?: string; + coin?: string; + withdrawType?: number; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** - * Unsubscribe from V5 topics & remove them from memory. They won't be re-subscribed to if the - * connection reconnects. - * - * @param wsTopics - topic or list of topics - * @param category - the API category this topic is for (e.g. "linear"). The value is only - * important when connecting to public topics and will be ignored for private 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 unsubscribeV5( - wsTopics: WsTopic[] | WsTopic, - category: CategoryV5, - isPrivateTopic?: boolean, -): Promise[] +export interface GetWithdrawalAddressListParamsV5 { + coin?: string; + chain?: string; + addressType?: 0 | 1 | 2; + limit?: number; + cursor?: string; +} ⋮---- -// Sort into per-WsKey batches, in case there is a mix of topics here +export interface SubmitDepositOriginatorInfoParamsV5 { + depositId: number; + subAccountId?: number; + /** Travel Rule questionnaire JSON string. See Questionnaire docs. */ + questionnaire: string; +} ⋮---- -// Batch sub topics per ws key +/** Travel Rule questionnaire JSON string. See Questionnaire docs. */ ⋮---- -// Return promise to resolve midflight WS request (only works if already connected before request) +export interface WithdrawParamsV5 { + coin: string; + /** + * When forceChain is 0 or 1, required. When forceChain is 2 (Bybit UID withdraw), may be null/omitted. + */ + chain?: string; + address: string; + tag?: string; + amount: string; + timestamp: number; + forceChain?: number; + /** + * FUND, UTA, or EARN; or comma combo e.g. FUND,UTA,EARN (funding first, then UTA and Earn for remainder). + * SPOT is legacy if still supported for older integrations. + */ + accountType: string; + feeType?: 0 | 1; + requestId?: string; + /** + * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. + */ + transactionPurpose?: string; + /** + * Travel Rule questionnaire JSON string (max 16384 bytes). Takes precedence over `beneficiary` / `transactionPurpose` when both are set. + */ + questionnaire?: string; + beneficiary?: { + vaspEntityId?: string; + beneficiaryName?: string; + beneficiaryLegalType?: string; + beneficiaryWalletType?: string; + beneficiaryUnhostedWalletType?: string; + beneficiaryPoiNumber?: string; + beneficiaryPoiType?: string; + beneficiaryPoiIssuingCountry?: string; + beneficiaryPoiExpiredDate?: string; + }; +} ⋮---- /** - * Note: subscribeV5() might be simpler to use. The end result is the same. - * - * 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 + * When forceChain is 0 or 1, required. When forceChain is 2 (Bybit UID withdraw), may be null/omitted. */ -public subscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - requestedWsKey?: WsKey, -) -⋮---- -// Batch sub topics per ws key ⋮---- /** - * Note: unsubscribe() might be simpler to use. The end result is the same. - * 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. + * FUND, UTA, or EARN; or comma combo e.g. FUND,UTA,EARN (funding first, then UTA and Earn for remainder). + * SPOT is legacy if still supported for older integrations. */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey?: WsKey, -) -⋮---- -// Batch sub topics per ws key ⋮---- /** - * - * - * - * WS API Methods - similar to the REST API, but via WebSockets - * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline - * - * - * + * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. */ ⋮---- /** - * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. - * - * WS API Documentation for list of operations and parameters: - * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline - * - * Returned promise is rejected if: - * - an exception is detected in the reply, OR - * - the connection disconnects for any reason (even if automatic reconnect will happen). - * - * Authentication is automatic. If you didn't request authentication yourself, there might - * be a small delay after your first request, while the SDK automatically authenticates. - * - * @param wsKey - The connection this event is for. Currently only "v5PrivateTrade" is supported - * for Bybit, since that is the dedicated WS API connection. - * @param operation - The command being sent, e.g. "order.create" to submit a new order. - * @param params - Any request parameters for the command. E.g. `OrderParamsV5` to submit a new - * order. Only send parameters for the request body. Everything else is automatically handled. - * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response + * Travel Rule questionnaire JSON string (max 16384 bytes). Takes precedence over `beneficiary` / `transactionPurpose` when both are set. */ ⋮---- -// This overload allows the caller to omit the 3rd param, if it isn't required -sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact, - >( - wsKey: TWSKey, - operation: TWSOperation, - params?: TWSParams extends void | never ? undefined : TWSParams, - requestFlags?: WSAPIRequestFlags, - ): Promise; -⋮---- -// These overloads give stricter types than mapped generics, since generic constraints -// do not trigger excess property checks -// Without these overloads, TypeScript won't complain if you include an -// unexpected property with your request (if it doesn't clash with an existing property) -sendWSAPIRequest( - wsKey: typeof WS_KEY_MAP.v5PrivateTrade, - operation: TWSOperation, - params: WsAPITopicRequestParamMap[TWSOperation], - requestFlags?: WSAPIRequestFlags, - ): Promise; -⋮---- -sendWSAPIRequest( - wsKey: typeof WS_KEY_MAP.v5PrivateTrade, - operation: TWSOperation, - params: WsAPITopicRequestParamMap[TWSOperation], - requestFlags?: WSAPIRequestFlags, - ): Promise; -⋮---- -sendWSAPIRequest( - wsKey: typeof WS_KEY_MAP.v5PrivateTrade, - operation: TWSOperation, - params: WsAPITopicRequestParamMap[TWSOperation], - requestFlags?: WSAPIRequestFlags, - ): Promise; -⋮---- -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact, - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( - wsKey: WsKey = WS_KEY_MAP.v5PrivateTrade, - operation: TWSOperation, - params: TWSParams, - requestFlags?: WSAPIRequestFlags, -): Promise -⋮---- -// Some commands don't require authentication. -⋮---- -// Sign, if needed +export interface ConvertCoinsParamsV5 { + coin?: string; + side?: number; + accountType: + | 'eb_convert_funding' + | 'eb_convert_uta' + | 'eb_convert_spot' + | 'eb_convert_contract' + | 'eb_convert_inverse'; +} ⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +export interface RequestConvertQuoteParamsV5 { + fromCoin: string; + toCoin: string; + fromCoinType?: string; + toCoinType?: string; + requestCoin: string; + requestAmount: string; + accountType: + | 'eb_convert_funding' + | 'eb_convert_uta' + | 'eb_convert_spot' + | 'eb_convert_contract' + | 'eb_convert_inverse'; + requestId?: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface GetConvertHistoryParamsV5 { + accountType?: string; + index?: number; + limit?: number; +} ⋮---- -// Enrich returned promise with request context for easier debugging +export interface GetSmallBalanceListParamsV5 { + accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet + fromCoin?: string; // Source currency +} ⋮---- -// throw e; +accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet +fromCoin?: string; // Source currency ⋮---- -// Send event +export interface GetFiatTradingPairListParamsV5 { + side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) +} ⋮---- -// Return deferred promise, so caller can await this call +side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) ⋮---- -/** - * - * - * Internal methods - not intended for public use - * - * - */ +/** Funding Account Transaction History. Interval createTimeFrom-createTimeTo max 7 days. */ +export interface GetFundingAccountTransactionHistoryParamsV5 { + createTimeFrom?: string; + createTimeTo?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** - * Note: implementing this method will wipe the WsStore state for this WsKey, once this method returns - */ -protected isCustomReconnectionNeeded(): boolean +/** Asset Overview. memberId required when querying sub account via master API key. */ +export interface GetAssetOverviewParamsV5 { + memberId?: string; + /** Fiat currency for valuation; defaults to USD if omitted. */ + valuationCurrency?: string; + /** Account type filter; returns all if omitted. */ + accountType?: string; +} ⋮---- -protected async triggerCustomReconnectionWorkflow(): Promise +/** Fiat currency for valuation; defaults to USD if omitted. */ ⋮---- -/** - * @returns The WS URL to connect to for this WS key - */ -protected async getWsUrl(wsKey: WsKey): Promise +/** Account type filter; returns all if omitted. */ ⋮---- -// If auth is needed for this wsKey URL, this returns a suffix +/** GET /v5/asset/portfolio-margin */ +export interface GetPortfolioMarginInfoParamsV5 { + baseCoin?: string; +} ⋮---- -/** - * Return params required to make authorized request - */ -private async getWsAuthURLSuffix(): Promise +/** GET /v5/asset/total-members-assets */ +export interface GetTotalMembersAssetsParamsV5 { + /** If omitted, defaults to BTC. Total is quoted in this coin. */ + coin?: string; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method?: 'hex' | 'base64', - algorithm: SignAlgorithm = 'SHA-256', -): Promise +/** If omitted, defaults to BTC. Total is quoted in this coin. */ + +================ +File: src/types/request/v5-crypto-loan.ts +================ +export interface BorrowCryptoLoanParamsV5 { + loanCurrency: string; + loanAmount?: string; + loanTerm?: string; + collateralCurrency: string; + collateralAmount?: string; +} ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, -): Promise> +export interface GetUnpaidLoanOrdersParamsV5 { + orderId?: string; + loanCurrency?: string; + collateralCurrency?: string; + loanTermType?: string; + loanTerm?: string; + limit?: string; + cursor?: string; +} ⋮---- -private async getWsAuthSignature( - wsKey: WsKey, -): Promise< +export interface GetRepaymentHistoryParamsV5 { + orderId?: string; + repayId?: string; + loanCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -undefined, // Let the function automatically determine encoding based on key type +export interface GetCompletedLoanOrderHistoryParamsV5 { + orderId?: string; + loanCurrency?: string; + collateralCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -private async signWSAPIRequest( - requestEvent: WSAPIRequest, -): Promise> +export interface GetLoanLTVAdjustmentHistoryParamsV5 { + orderId?: string; + adjustId?: string; + collateralCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -// Not needed for Bybit. Auth happens only on connection open, automatically. +// New Crypto Loan Request Types ⋮---- -protected sendPingEvent(wsKey: WsKey) +export interface GetBorrowableCoinsParamsV5 { + vipLevel?: string; + currency?: string; +} ⋮---- -protected sendPongEvent(wsKey: WsKey) +export interface GetCollateralCoinsParamsV5 { + currency?: string; +} ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface GetMaxCollateralAmountParamsV5 { + currency: string; +} ⋮---- -protected authPrivateConnectionsOnConnect(_wsKey: WsKey): boolean +export interface AdjustCollateralAmountParamsV5 { + currency: string; + amount: string; + direction: '0' | '1'; +} ⋮---- -/** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected async getWsRequestEvents( - market: WsMarket, - operation: WsOperation, - requests: WsTopicRequest[], - // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars - _wsKey: WsKey, -): Promise>[]> +export interface GetCollateralAdjustmentHistoryParamsV5 { + adjustId?: string; + collateralCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars +// Flexible Loan Request Types ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +export interface BorrowFlexibleParamsV5 { + loanCurrency: string; + loanAmount: string; + collateralList?: { + currency: string; + amount: string; + }[]; +} ⋮---- -protected getPrivateWSKeys(): WsKey[] +export interface RepayFlexibleParamsV5 { + loanCurrency: string; + amount: string; +} ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +export interface RepayCollateralFlexibleParamsV5 { + loanCurrency: string; + collateralCoin: string; + amount: string; +} ⋮---- -/** - * Determines if a topic is for a private channel, using a hardcoded list of strings - */ -protected isPrivateTopicRequest(request: WsTopicRequest): boolean +export interface GetOngoingFlexibleLoansParamsV5 { + loanCurrency?: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPing(msg: any): boolean +export interface GetBorrowHistoryFlexibleParamsV5 { + orderId?: string; + loanCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPong(msg: any): boolean +export interface GetRepaymentHistoryFlexibleParamsV5 { + repayId?: string; + loanCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -// public ws connections +// Fixed Loan Request Types ⋮---- -// private ws connections +export interface GetSupplyOrderQuoteFixedParamsV5 { + orderCurrency: string; + term?: string; + orderBy: 'apy' | 'term' | 'quantity'; + sort?: number; + limit?: number; +} ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] +export interface GetBorrowOrderQuoteFixedParamsV5 { + orderCurrency: string; + term?: string; + orderBy: 'apy' | 'term' | 'quantity'; + sort?: number; + limit?: number; +} ⋮---- -// this.logger.trace('resolveEmittableEvents', { -// ...WS_LOGGER_CATEGORY, -// wsKey, -// parsed: JSON.stringify(parsed), -// }); +export interface CreateBorrowOrderFixedParamsV5 { + orderCurrency: string; + orderAmount: string; + annualRate: string; + term: string; + autoRepay?: string; // Deprecated + repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan + strategyType?: 'PARTIAL' | 'FULL'; + collateralList?: { + currency: string; + amount: string; + }[]; +} ⋮---- -// Only applies to the V5 WS topics +autoRepay?: string; // Deprecated +repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan ⋮---- -// WS API response +export interface GetFixedLoanAvailableInventoryParamsV5 { + currency: string; + term: string; + annualRate: string; +} ⋮---- -// eslint-disable-next-line max-len +export interface GetFlexibleLoanAvailableInventoryParamsV5 { + currency: string; +} ⋮---- -// WS API Exception +export interface CreateSupplyOrderFixedParamsV5 { + orderCurrency: string; + orderAmount: string; + annualRate: string; + term: string; + /** + * Source account for supply. 0: Funding Account; 1: Earn Flexible Account; 2: ALL. Default: 0 + */ + availableSource?: '0' | '1' | '2'; +} ⋮---- -// WS API Success +/** + * Source account for supply. 0: Funding Account; 1: Earn Flexible Account; 2: ALL. Default: 0 + */ ⋮---- -// Messages for a subscribed topic all include the "topic" property +export interface CancelBorrowOrderFixedParamsV5 { + orderId: string; +} ⋮---- -// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property +export interface CancelSupplyOrderFixedParamsV5 { + orderId: string; + /** + * Account to receive the refund. 0: Funding Account; 1: EasyEarn. Default: 0 + */ + refundedAccount?: '0' | '1'; +} ⋮---- -// Failed request +/** + * Account to receive the refund. 0: Funding Account; 1: EasyEarn. Default: 0 + */ ⋮---- -// These are r equest/reply pattern events (e.g. after subscribing to topics or authenticating) +export interface GetBorrowContractInfoFixedParamsV5 { + orderId?: string; + loanId?: string; + orderCurrency?: string; + term?: string; + limit?: string; + cursor?: string; +} ⋮---- -// Request/reply pattern for authentication success +export interface GetSupplyContractInfoFixedParamsV5 { + orderId?: string; + supplyId?: string; + supplyCurrency?: string; + term?: string; + limit?: string; + cursor?: string; +} ⋮---- -// In case of catastrophic failure, fallback to noisy emit update - -================ -File: src/types/response/v5-asset.ts -================ -import { AccountTypeV5, OrderSideV5, WithdrawalTypeV5 } from '../shared-v5'; +export interface GetBorrowOrderInfoFixedParamsV5 { + orderId?: string; + orderCurrency?: string; + state?: string; + term?: string; + limit?: string; + cursor?: string; +} ⋮---- -export interface CoinExchangeRecordV5 { - fromCoin: string; - fromAmount: string; - toCoin: string; - toAmount: string; - exchangeRate: string; - createdTime: string; - exchangeTxId: string; +export interface GetSupplyOrderInfoFixedParamsV5 { + orderId?: string; + orderCurrency?: string; + state?: string; + term?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface DeliveryRecordV5 { - deliveryTime: number; - symbol: string; - side: OrderSideV5; - position: string; - deliveryPrice: string; - strike: string; - fee: string; - deliveryRpl: string; - entryPrice: string; +export interface RepayFixedParamsV5 { + loanId?: string; + loanCurrency?: string; } ⋮---- -export interface SettlementRecordV5 { - symbol: string; - side: string; - size: number; - sessionAvgPrice: string; - markPrice: string; - realisedPnl: string; - createdTime: string; +export interface RepayCollateralFixedParamsV5 { + loanCurrency: string; + collateralCoin: string; + amount: string; } ⋮---- -export interface AssetInfoAssetV5 { - coin: string; - frozen: string; - free: string; - withdraw: string; +export interface GetRepaymentHistoryFixedParamsV5 { + repayId?: string; + loanCurrency?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface AssetInfoV5 { - status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED'; - assets: AssetInfoAssetV5[]; +export interface RenewBorrowOrderFixedParamsV5 { + loanId: string; + collateralList?: { + currency?: string; + amount?: string; + }[]; } ⋮---- -export interface CoinBalanceV5 { - coin: string; - walletBalance: string; - transferBalance: string; - bonus?: string; +export interface GetRenewOrderInfoFixedParamsV5 { + orderId?: string; + orderCurrency?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface AllCoinsBalanceV5 { - accountType: AccountTypeV5; - memberId?: string; - balance: CoinBalanceV5[]; +// Max Loan Amount Request Types +⋮---- +export interface GetMaxLoanAmountParamsV5 { + currency: string; // Coin to borrow + collateralList?: { + ccy: string; // Collateral coin + amount: string; // Collateral amount + }[]; } ⋮---- -export interface AccountCoinBalanceV5 { - accountType: AccountTypeV5; - bizType: number; - accountId: string; - memberId: string; - balance: { - coin: string; - walletBalance: string; - transferBalance: string; - bonus: string; - transferSafeAmount: string; - ltvTransferSafeAmount: string; - }; +currency: string; // Coin to borrow +⋮---- +ccy: string; // Collateral coin +amount: string; // Collateral amount +⋮---- +// Institutional Loan Request Types +⋮---- +export interface GetCoinDeltaAmountParamsV5 { + coin?: string; } ⋮---- -export interface InternalTransferRecordV5 { - transferId: string; - coin: string; - amount: string; - fromAccountType: AccountTypeV5; - toAccountType: AccountTypeV5; - timestamp: string; - status: string; +export interface RepayInstitutionalLoanParamsV5 { + token: string; // Coin name + quantity: string; // The qty to be repaid } ⋮---- -export interface UniversalTransferRecordV5 { - transferId: string; +token: string; // Coin name +quantity: string; // The qty to be repaid + +================ +File: src/types/response/index.ts +================ + + +================ +File: src/types/response/v5-earn.ts +================ +export interface EarnInterestCardV5 { + awardId: number; + specCode: string; coin: string; + apy: string; + duration: number; + claimedAt: number; + expireAt: number; + usedAt: number; + status: 'InUse' | 'NotUse' | 'Expired' | 'AlreadyUsed' | string; + currentPnl: string; + limitPnl: string; + positionEffectiveAmount: string; + productId: number; + category: 'FlexibleSaving' | 'DualAssets' | string; +} +⋮---- +export interface EarnAwardCardV5 { + awardId: number; + specCode: string; + claimedAt: number; + usedAt: number; + expireAt: number; + status: 'InUse' | 'NotUse' | 'Expired' | 'AlreadyUsed' | string; amount: string; - fromMemberId: string; - toMemberId: string; - fromAccountType: AccountTypeV5; - toAccountType: AccountTypeV5; - timestamp: string; - status: string; + limitPnlPercentage: string; + baseCoin: string; + quoteCoin: string; + direction: 1 | 2; + category: 'FlexibleSaving' | 'DualAssets' | string; } ⋮---- -export interface AllowedDepositCoinInfoV5 { +export interface EarnCouponListResultV5 { + interestCards: EarnInterestCardV5[]; + awardCards: EarnAwardCardV5[]; +} +⋮---- +export interface EarnProductV5 { + category: string; + estimateApr: string; coin: string; - chain: string; - coinShowName: string; - chainType: string; - blockConfirmNumber: number; - minDepositAmount: string; + minStakeAmount: string; + maxStakeAmount: string; + precision: string; + productId: string; + status: 'Available' | 'NotAvailable'; } ⋮---- -export interface DepositRecordV5 { - id: string; +export interface EarnOrderHistoryV5 { coin: string; - chain: string; - amount: string; - txID: string; - status: number; - toAddress: string; - tag: string; - depositFee: string; - successAt: string; - confirmations: string; - txIndex: string; - blockHash: string; - batchReleaseLimit: string; - depositType: string; - fromAddress: string; + orderValue: string; + orderType: 'Redeem' | 'Stake'; + orderId: string; + orderLinkId: string; + status: 'Success' | 'Fail' | 'Pending'; + createdAt: string; + productId: string; + updatedAt: string; + swapOrderValue: string; + estimateRedeemTime: string; + estimateStakeTime: string; } ⋮---- -export interface SubmitDepositOriginatorInfoResultV5 { - travelRuleStatus: number; +export interface EarnPositionFreezeDetailV5 { + amount: string; + description: string; } ⋮---- -export interface InternalDepositRecordV5 { - id: string; - type: 1; +export interface EarnPositionV5 { coin: string; + productId: string; amount: string; - status: 1 | 2 | 3; - address: string; - createdTime: string; - txID: string; + totalPnl: string; + claimableYield: string; + id?: string; + status?: string; + orderId?: string; + estimateRedeemTime?: string; + estimateStakeTime?: string; + estimateInterestCalculationTime?: string; + settlementTime?: string; + autoReinvest?: string; + /** Redeemable amount */ + availableAmount: string; + freezeDetails: EarnPositionFreezeDetailV5[]; } ⋮---- -export interface DepositAddressChainV5 { - chainType: string; - addressDeposit: string; - tagDeposit: string; - chain: string; - batchReleaseLimit: string; - contractAddress: string; -} +/** Redeemable amount */ ⋮---- -export interface DepositAddressResultV5 { +export interface EarnYieldHistoryV5 { + productId: string; coin: string; - chains: DepositAddressChainV5[]; + id: string; + amount: string; + yieldType: string; + distributionMode: string; + effectiveStakingAmount: string; + orderId: string; + status: 'Pending' | 'Success' | 'Fail'; + createdAt: string; } ⋮---- -export interface CoinInfoV5 { - name: string; +export interface EarnHourlyYieldHistoryV5 { + productId: string; coin: string; - /** @deprecated Use `chains[].withdrawMax` instead */ - remainAmount: string; - chains: { - chain: string; - chainType: string; - confirmation: string; - withdrawFee: string; - depositMin: string; - withdrawMin: string; - minAccuracy: string; - chainDeposit: string; - chainWithdraw: string; - withdrawPercentageFee: string; - contractAddress: string; - safeConfirmNumber: string; - /** Max withdraw amount per transaction per chain. `-1` means no limit */ - withdrawMax: string; - }[]; + id: string; + amount: string; + effectiveStakingAmount: string; + status: 'Pending' | 'Success' | 'Fail'; + hourlyDate: string; + createdAt: string; } ⋮---- -/** @deprecated Use `chains[].withdrawMax` instead */ +export interface EarnAprHistoryPointV5 { + timestamp: string; + apr: string; +} ⋮---- -/** Max withdraw amount per transaction per chain. `-1` means no limit */ +/** + * Advanced Earn — Dual Asset product (GET /v5/earn/advance/product). + */ +export interface AdvanceEarnDualAssetProductV5 { + category: string; + productId: string; + baseCoin: string; + quoteCoin: string; + expectReceiveAt: string; + duration: string; + status: 'Available' | 'NotAvailable'; + isVipProduct: boolean; + subscribeStartAt: string; + subscribeEndAt: string; + applyStartAt: string; + settlementTime: string; + minPurchaseQuoteAmount: string; + minPurchaseBaseAmount: string; + remainingAmountQuote: string; + remainingAmountBase: string; + orderPrecisionDigitalQuote: number; + orderPrecisionDigitalBase: number; +} ⋮---- -export interface WithdrawalRecordV5 { - withdrawId: string; - txID: string; - withdrawType: WithdrawalTypeV5; - coin: string; - chain: string; - amount: string; - withdrawFee: string; - status: string; - toAddress: string; - tag: string; - createTime: string; - updateTime: string; +export interface AdvanceEarnDualAssetProductInfoV5 { + category: string; + list: AdvanceEarnDualAssetProductV5[]; } ⋮---- -export interface WithdrawalAddressV5 { - coin: string; - chain: string; - address: string; - tag: string; - remark: string; - status: number; - addressType: number; - verified: number; - createdAt: string; +/** + * Advanced Earn — Double Win (GET /v5/earn/advance/product?category=DoubleWin). + */ +export interface AdvanceEarnDoubleWinProductV5 { + category: string; + productId: string; + investCoin: string; + underlyingAsset: string; + duration: string; + subscribeStartAt: string; + subscribeEndAt: string; + settlementTime: string; + expectReceiveAt: string; + minPurchaseAmount: string; + orderPrecisionDigital: number; + isRfqProduct: boolean; + lowerPriceBuffer: string; + upperPriceBuffer: string; + minDeviationRatio: string; + maxDeviationRatio: string; + priceTickSize: string; } ⋮---- -export interface WithdrawableAccountSliceV5 { - coin: string; - withdrawableAmount: string; - availableBalance: string; +/** + * Advanced Earn — Smart Leverage (GET /v5/earn/advance/product?category=SmartLeverage). + */ +export interface AdvanceEarnSmartLeverageProductV5 { + category: string; + productId: string; + investCoin: string; + underlyingAsset: string; + direction: 'Long' | 'Short'; + leverage: string; + duration: string; + subscribeStartAt: string; + subscribeEndAt: string; + settlementTime: string; + expectReceiveAt: string; + minPurchaseAmount: string; + remainingAmount: string; + orderPrecisionDigital: number; } ⋮---- /** - * GET /v5/asset/withdraw/withdrawable-amount. Only keys with data are returned - * (e.g. UTA, FUND, EARN; EARN when the coin can be withdrawn from Earn; SPOT if present). + * Advanced Earn — Discount Buy (GET /v5/earn/advance/product?category=DiscountBuy). */ -export interface WithdrawableAmountV5 { - limitAmountUsd: string; - withdrawableAmount: { - SPOT?: WithdrawableAccountSliceV5; - FUND?: WithdrawableAccountSliceV5; - UTA?: WithdrawableAccountSliceV5; - EARN?: WithdrawableAccountSliceV5; - }; +export interface AdvanceEarnDiscountBuyProductV5 { + category: string; + productId: string; + coin: string; + underlyingAsset: string; + settlementTime: string; + duration: string; + isVipProduct: boolean; + subscribeStartAt: string; + subscribeEndAt: string; + minPurchaseAmount: string; + remainingAmount: string; + orderPrecisionDigital: number; + expectReceiveAt: string; } ⋮---- -export interface VaspEntityV5 { - vaspEntityId: string; - vaspName: string; +export type AdvanceEarnAdvanceProductListItemV5 = + | AdvanceEarnDualAssetProductV5 + | AdvanceEarnDoubleWinProductV5 + | AdvanceEarnSmartLeverageProductV5 + | AdvanceEarnDiscountBuyProductV5; +⋮---- +export interface AdvanceEarnAdvanceProductInfoV5 { + category: string; + list: AdvanceEarnAdvanceProductListItemV5[]; } ⋮---- -export interface ConvertCoinSpecV5 { - coin: string; - fullName: string; - icon: string; - iconNight: string; - accuracyLength: number; - coinType: string; - balance: string; - uBalance: string; - singleFromMinLimit: string; - singleFromMaxLimit: string; - disableFrom: boolean; - disableTo: boolean; - timePeriod: number; - singleToMinLimit: string; - singleToMaxLimit: string; - dailyFromMinLimit: string; - dailyFromMaxLimit: string; - dailyToMinLimit: string; - dailyToMaxLimit: string; +/** GET /v5/earn/hold-to-earn/product — Hold to Earn airdrop products */ +export type HoldToEarnAirdropProductStatusV5 = + | 'NotStarted' + | 'Online' + | 'Ended'; +⋮---- +export interface HoldToEarnAirdropProductYieldV5 { + coinName: string; + /** Yesterday's APR for display, e.g. "10%", "0%" */ + apy: string; + personalApy?: string; + multiplier?: string; } ⋮---- -export interface ConvertQuoteV5 { - quoteTxId: string; - exchangeRate: string; - fromCoin: string; - fromCoinType: string; - toCoin: string; - toCoinType: string; - fromAmount: string; - toAmount: string; - expiredTime: string; - requestId: string; - extTaxAndFee: string[]; +/** Yesterday's APR for display, e.g. "10%", "0%" */ +⋮---- +export interface HoldToEarnAirdropProductV5 { + coinName: string; + yields: HoldToEarnAirdropProductYieldV5[]; + status: HoldToEarnAirdropProductStatusV5; + announcementUrl: string; + /** Yesterday's avg APR across yield coins */ + apy: string; + personalApy?: string; } ⋮---- -export interface ConvertStatusV5 { - accountType: string; - exchangeTxId: string; - userId: string; - fromCoin: string; - fromCoinType: string; - toCoin: string; - toCoinType: string; - fromAmount: string; - toAmount: string; - exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; - extInfo: { paramType: string; paramValue: string }; - convertRate: string; - createdAt: string; +/** Yesterday's avg APR across yield coins */ +⋮---- +export interface HoldToEarnAirdropProductsResultV5 { + products: HoldToEarnAirdropProductV5[]; } ⋮---- -export interface ConvertHistoryRecordV5 { - accountType: string; - exchangeTxId: string; - userId: string; - fromCoin: string; - fromCoinType: string; - toCoin: string; - toCoinType: string; - fromAmount: string; - toAmount: string; - exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; - extInfo: { paramType: string; paramValue: string }; - convertRate: string; - createdAt: string; +/** GET /v5/earn/hold-to-earn/yield-history */ +export interface HoldToEarnAirdropDailyPnlV5 { + coinName: string; + yieldCoinName: string; + effectiveAmount: string; + pnl: string; + apy: string; + createdAt: number; } ⋮---- -export interface SmallBalanceCoinV5 { - fromCoin: string; // Source currency - supportConvert: 1 | 2; // 1: support, 2: not supported - availableBalance: string; // Available balance - baseValue: string; // USDT equivalent value - toAmount: string; // Reserved field - exchangeRate: string; // Reserved field - feeInfo: null; // Reserved field - taxFeeInfo: null; // Reserved field +export interface HoldToEarnAirdropYieldHistoryResultV5 { + nextCursor: string; + airdropDailyPnls: HoldToEarnAirdropDailyPnlV5[]; +} + +================ +File: src/types/response/v5-position.ts +================ +import { + CategoryV5, + ExecTypeV5, + OrderSideV5, + OrderTypeV5, + PositionIdx, + PositionSideV5, + PositionStatusV5, + StopOrderTypeV5, + TPSLModeV5, + TradeModeV5, +} from '../shared-v5'; +⋮---- +export interface FuturesLeverageItemV5 { + symbol: string; + leverage: string; + side: OrderSideV5 | ''; + positionIdx: PositionIdx; } ⋮---- -fromCoin: string; // Source currency -supportConvert: 1 | 2; // 1: support, 2: not supported -availableBalance: string; // Available balance -baseValue: string; // USDT equivalent value -toAmount: string; // Reserved field -exchangeRate: string; // Reserved field -feeInfo: null; // Reserved field -taxFeeInfo: null; // Reserved field +export interface FuturesLeverageResultV5 { + category: 'linear' | 'inverse'; + list: FuturesLeverageItemV5[]; +} ⋮---- -export interface SmallBalanceListV5 { - smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info - supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) +export interface PositionV5 { + positionIdx: PositionIdx; + riskId: number; + riskLimitValue: string; + symbol: string; + side: PositionSideV5; + size: string; + avgPrice: string; + positionValue: string; + tradeMode: TradeModeV5; + autoAddMargin?: number; + positionStatus: PositionStatusV5; + leverage?: string; + breakEvenPrice?: string; // Break even price, only for linear & inverse + markPrice: string; + liqPrice: string | ''; + bustPrice?: string; + positionIM?: string; + positionMM?: string; + positionBalance?: string; + tpslMode?: TPSLModeV5; + takeProfit?: string; + stopLoss?: string; + trailingStop?: string; + sessionAvgPrice: string | ''; + delta?: string; + gamma?: string; + vega?: string; + theta?: string; + unrealisedPnl: string; + curRealisedPnl: string; + cumRealisedPnl: string; + adlRankIndicator: number; + isReduceOnly: boolean; + mmrSysUpdatedTime: string | ''; + leverageSysUpdatedTime: string | ''; + createdTime: string; + updatedTime: string; + /** Position open timestamp (ms). Default `0` when not set. */ + openTime: number; + positionIMByMp: string; + positionMMByMp: string; + seq: number; } ⋮---- -smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info -supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) +breakEvenPrice?: string; // Break even price, only for linear & inverse ⋮---- -export interface FiatCoinInfoV5 { - coin: string; // Fiat coin code - fullName: string; // Fiat full coin name - icon: string; // Coin icon url - iconNight: string; // Coin icon url (dark mode) - precision: number; // Fiat precision - disable: boolean; // true: the coin is disabled, false: the coin is allowed - singleFromMinLimit: string; // For buy side, minimum amount of fiatCoin per transaction - singleFromMaxLimit: string; // For buy side, maximum amount of fiatCoin per transaction +/** Position open timestamp (ms). Default `0` when not set. */ +⋮---- +export interface SetRiskLimitResultV5 { + category: CategoryV5; + riskId: number; + riskLimitValue: string; } ⋮---- -coin: string; // Fiat coin code -fullName: string; // Fiat full coin name -icon: string; // Coin icon url -iconNight: string; // Coin icon url (dark mode) -precision: number; // Fiat precision -disable: boolean; // true: the coin is disabled, false: the coin is allowed -singleFromMinLimit: string; // For buy side, minimum amount of fiatCoin per transaction -singleFromMaxLimit: string; // For buy side, maximum amount of fiatCoin per transaction +export interface AddOrReduceMarginResultV5 { + category: CategoryV5; + symbol: string; + positionIdx: PositionIdx; + riskId: number; + riskLimitValue: string; + size: string; + avgPrice: string; + liqPrice: string; + bustPrice: string; + markPrice: string; + positionValue: string; + leverage: string; + autoAddMargin: 0 | 1; + positionStatus: PositionStatusV5; + positionIM: string; + positionMM: string; + takeProfit: string; + stopLoss: string; + trailingStop: string; + unrealisedPnl: string; + cumRealisedPnl: string; + createdTime: string; + updatedTime: string; +} ⋮---- -export interface CryptoCoinInfoV5 { - coin: string; // Crypto coin code - fullName: string; // Crypto full coin name - icon: string; // Coin icon url - iconNight: string; // Coin icon url (dark mode) - precision: number; // Crypto precision - disable: boolean; // true: the coin is disabled, false: the coin is allowed - singleFromMinLimit: string; // For sell side, minimum amount of cryptoCoin per transaction - singleFromMaxLimit: string; // For sell side, maximum amount of cryptoCoin per transaction +export interface ExecutionV5 { + symbol: string; + orderId: string; + orderLinkId: string; + side: OrderSideV5; + orderPrice: string; + orderQty: string; + leavesQty: string; + orderType: OrderTypeV5; + stopOrderType?: StopOrderTypeV5; + execFee: string; + execFeeV2: string; + feeCurrency: string; // Trading fee currency + execId: string; + execPrice: string; + execQty: string; + execType: ExecTypeV5; + execValue: string; + execTime: string; + isMaker: boolean; + feeRate: string; + tradeIv?: string; + markIv?: string; + markPrice: string; + indexPrice: string; + underlyingPrice?: string; + blockTradeId?: string; + closedSize?: string; + seq: number; + extraFees: string; } ⋮---- -coin: string; // Crypto coin code -fullName: string; // Crypto full coin name -icon: string; // Coin icon url -iconNight: string; // Coin icon url (dark mode) -precision: number; // Crypto precision -disable: boolean; // true: the coin is disabled, false: the coin is allowed -singleFromMinLimit: string; // For sell side, minimum amount of cryptoCoin per transaction -singleFromMaxLimit: string; // For sell side, maximum amount of cryptoCoin per transaction +feeCurrency: string; // Trading fee currency ⋮---- -export interface FiatTradingPairListV5 { - fiats: FiatCoinInfoV5[]; // Fiat coin list - cryptos: CryptoCoinInfoV5[]; // Crypto coin list +export interface ClosedPnLV5 { + symbol: string; + orderId: string; + side: string; + qty: string; + orderPrice: string; + orderType: OrderTypeV5; + execType: ExecTypeV5; + closedSize: string; + openFee: string; + closeFee: string; + cumEntryValue: string; + avgEntryPrice: string; + cumExitValue: string; + avgExitPrice: string; + closedPnl: string; + fillCount: string; + leverage: string; + createdTime: string; + updatedTime: string; } ⋮---- -fiats: FiatCoinInfoV5[]; // Fiat coin list -cryptos: CryptoCoinInfoV5[]; // Crypto coin list -⋮---- -export interface FundingAccountTransactionRecordV5 { - memberId: string; - currency: string; - ioDirection: string; - txnAmt: string; - afterAmt: string; - createTime: string; - showBusiType: string; - showBusiTypeEn: string; - description: string; - descriptionEn: string; +export interface MovePositionResultV5 { + blockTradeId: string; + status: 'Processing' | 'Rejected'; + rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; } ⋮---- -/** When accountType=Alpha and category is farm, under `coinDetail` in sub-categories. */ -export interface AssetOverviewCoinExtMapV5 { - priceUpper?: string; - priceLower?: string; - equityUnit?: string; +export interface MovePositionHistoryV5 { + blockTradeId: string; + category: 'linear' | 'spot' | 'option'; + orderId: string; + userId: number; + symbol: string; + side: 'Buy' | 'Sell'; + price: string; + qty: string; + execFee: string; + status: 'Processing' | 'Filled' | 'Rejected'; + execId: string; + resultCode: number; + resultMessage: string; + createdAt: number; + updatedAt: number; + rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; } ⋮---- -export interface AssetOverviewCoinDetailV5 { - coin: string; - equity: string; - extMap?: AssetOverviewCoinExtMapV5; +export interface ClosedOptionsPositionV5 { + symbol: string; + side: 'Buy' | 'Sell'; + totalOpenFee: string; + deliveryFee: string; + totalCloseFee: string; + qty: string; + closeTime: number; + avgExitPrice: string; + deliveryPrice: string; + openTime: number; + avgEntryPrice: string; + totalPnl: string; } + +================ +File: src/types/response/v5-trade.ts +================ +import { + CategoryV5, + OrderCancelTypeV5, + OrderCreateTypeV5, + OrderRejectReasonV5, + OrderSideV5, + OrderStatusV5, + OrderTimeInForceV5, + OrderTriggerByV5, + OrderTypeV5, + PositionIdx, + StopOrderTypeV5, +} from '../shared-v5'; ⋮---- -export interface AssetOverviewCategoryV5 { - category: string; - equity: string; - coinDetail: AssetOverviewCoinDetailV5[]; +export interface OrderResultV5 { + orderId: string; + orderLinkId: string; } ⋮---- -export interface AssetOverviewAccountItemV5 { - accountType: string; - totalEquity: string; - valuationCurrency: string; - snapshotTime: string; - coinDetail?: AssetOverviewCoinDetailV5[]; - categories?: AssetOverviewCategoryV5[]; +export interface AccountOrderV5 { + orderId: string; + orderLinkId: string; + parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) + blockTradeId: string; + symbol: string; + price: string; + qty: string; + side: OrderSideV5; + isLeverage: '0' | '1'; + positionIdx: PositionIdx; + orderStatus: OrderStatusV5; + createType: OrderCreateTypeV5; + cancelType: OrderCancelTypeV5; + rejectReason: OrderRejectReasonV5; + avgPrice: string; + leavesQty: string; + leavesValue: string; + cumExecQty: string; + cumExecValue: string; + cumExecFee: string; + timeInForce: OrderTimeInForceV5; + orderType: OrderTypeV5; + stopOrderType: StopOrderTypeV5; + orderIv: string; + marketUnit: 'baseCoin' | 'quoteCoin'; + slippageToleranceType: string; + slippageTolerance: string; + triggerPrice: string; + takeProfit: string; + stopLoss: string; + tpslMode: 'Full' | 'Partial' | ''; + ocoTriggerType: + | 'OcoTriggerByUnknown' + | 'OcoTriggerTp' + | 'OcoTriggerBySl' + | ''; + tpLimitPrice: string; + slLimitPrice: string; + tpTriggerBy: OrderTriggerByV5; + slTriggerBy: OrderTriggerByV5; + triggerDirection: 1 | 2; + triggerBy: OrderTriggerByV5; + lastPriceOnCreated: string; + basePrice: string; + reduceOnly: boolean; + closeOnTrigger: boolean; + placeType: 'iv' | 'price' | ''; + smpType: string; + smpGroup: string; + smpOrderId: string; + createdTime: string; + updatedTime: string; + extraFees: string; + cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee + rpiTakerAccess?: boolean; + rpiMatchedQty?: string; + fromAccount?: string; + toAccount?: string; + externalEventType?: string; } ⋮---- -export interface AssetOverviewResultV5 { - totalEquity: string; - list: AssetOverviewAccountItemV5[]; -} +parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) ⋮---- -// --- GET /v5/asset/portfolio-margin (portfolio margin P&L ranges) --- +cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee ⋮---- -export interface PortfolioMarginWalletV5 { - equity: string; - cashBalance: string; - marginBalance: string; - availableBalance: string; - accountIM: string; - accountMM: string; - accountMMRate: string; - accountIMRate: string; +export interface BatchCreateOrderResultV5 { + category: CategoryV5; + symbol: string; + orderId: string; + orderLinkId: string; + createAt?: string; } ⋮---- -export interface PortfolioMarginPnlRangePointV5 { - priceScale: string; - pnls: string[]; +export interface BatchOrdersRetExtInfoV5 { + list: { + code: number; + msg: string; + }[]; } ⋮---- -export interface PortfolioMarginContractBucketPnlV5 { - pnlRanges: PortfolioMarginPnlRangePointV5[]; +export interface BatchAmendOrderResultV5 { + category: CategoryV5; + symbol: string; + orderId: string; + orderLinkId: string; } ⋮---- -export interface PortfolioMarginTotalPnlRangesV5 { - ALL?: PortfolioMarginContractBucketPnlV5; - PERPETUAL?: PortfolioMarginContractBucketPnlV5; - OPTION?: PortfolioMarginContractBucketPnlV5; +export interface BatchCancelOrderResultV5 { + category: CategoryV5; + symbol: string; + orderId: string; + orderLinkId: string; } ⋮---- -export interface PortfolioMarginPerpPositionPnlV5 { - symbolName: string; - position: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; - sessionAvgPrice: string; - markPrice: string; - orderSize: string; - contractType: number; - settleCoin: string; - symbolAlias?: string; +export interface SpotBorrowCheckResultV5 { + symbol: string; + side: OrderSideV5; + maxTradeQty: string; + maxTradeAmount: string; + spotMaxTradeQty: string; + spotMaxTradeAmount: string; + borrowCoin: string; } ⋮---- -export interface PortfolioMarginOptionPositionPnlV5 { - symbolName: string; - position: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; - sessionAvgPrice: string; - markPrice: string; - orderSize: string; - contractType: number; - settleCoin: string; +export interface PreCheckOrderResultV5 { + orderId: string; + orderLinkId: string; + preImrE4: number; // Initial margin rate before checking (in basis points) + preMmrE4: number; // Maintenance margin rate before checking (in basis points) + postImrE4: number; // Initial margin rate after checking (in basis points) + postMmrE4: number; // Maintenance margin rate after checking (in basis points) } ⋮---- -export interface PortfolioMarginOptionExpiryPnlV5 { - expiryDateRepresentation: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; - optionPositionPnlRanges: PortfolioMarginOptionPositionPnlV5[]; +preImrE4: number; // Initial margin rate before checking (in basis points) +preMmrE4: number; // Maintenance margin rate before checking (in basis points) +postImrE4: number; // Initial margin rate after checking (in basis points) +postMmrE4: number; // Maintenance margin rate after checking (in basis points) + +================ +File: src/types/response/v5-user.ts +================ +import { PermissionsV5 } from '../shared-v5'; +⋮---- +export interface CreateSubMemberResultV5 { + uid: string; + username: string; + memberType: number; + status: number; + remark: string; } ⋮---- -export interface PortfolioMarginContingencyV5 { - optionContingency: string; - futureDeltaContingency: string; - optionVegaContingency: string; - contingencyComponents: string; - usdtUsdcContingency: string; - futureContingency: string; +export interface CreateSubApiKeyResultV5 { + id: string; + note: string; + apiKey: string; + readOnly: number; + secret: string; + permissions: PermissionsV5; } ⋮---- -export interface PortfolioMarginAssetBlockV5 { - coin: string; - assetIM: string; - assetMM: string; +export interface SubMemberV5 { + uid: string; + username: string; + memberType: number; + status: number; + accountMode: number; + remark: string; } +export type ApiKeyType = 1 | 2; ⋮---- -export interface PortfolioMarginSpotHedgeInfoV5 { - hedgeSpotSize: string; - walletBalance: string; - usdIndexPrice: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; +export interface ApiKeyPermissionsV5 { + ContractTrade: string[]; + Spot: string[]; + Wallet: string[]; + Options: string[]; + Derivatives: string[]; + CopyTrading: string[]; + BlockTrade: string[]; + Exchange: string[]; + NFT: string[]; + Affiliate: string[]; + Earn?: string[]; + FiatP2P?: string[]; + FiatBitPay?: string[]; + FiatConvertBroker?: string[]; + /** @deprecated */ + FiatGlobalPay?: string[]; + BitCard?: string[]; + ByXPost?: string[]; } ⋮---- -export interface PortfolioMarginByBaseCoinV5 { - baseCoin: string; - totalPnlRanges: PortfolioMarginTotalPnlRangesV5; - perpPositionPnlRanges: PortfolioMarginPerpPositionPnlV5[]; - optionExpiryDatePnlRanges: PortfolioMarginOptionExpiryPnlV5[]; - contingency: PortfolioMarginContingencyV5; - asset: PortfolioMarginAssetBlockV5; - maxLossPriceMove: string; - maxLossIvShock: string; - totalClosePzFee: string; - spotHedgeInfo: PortfolioMarginSpotHedgeInfoV5; - maxLossIvShockList: string[]; +/** @deprecated */ +⋮---- +export interface ApiKeyInfoV5 { + id: string; + note: string; + apiKey: string; + readOnly: 0 | 1; + secret: string; + permissions: ApiKeyPermissionsV5; + ips: string[]; + type: 1 | 2; // 1: personal, 2: connected to third-party app + deadlineDay: number; + expiredAt: string; + createdAt: string; + /** @deprecated */ + unified: number; + uta: 0 | 1; // 0: regular account, 1: unified trade account + userID: number; + inviterID: number; + vipLevel: string; + mktMakerLevel: string; + affiliateID: number; + rsaPublicKey: string; + isMaster: boolean; + parentUid: string; + kycLevel: 'LEVEL_DEFAULT' | 'LEVEL_1' | 'LEVEL_2'; + kycRegion: string; } ⋮---- -export interface PortfolioMarginInfoResultV5 { - wallet: PortfolioMarginWalletV5; - assetPnlRange: PortfolioMarginByBaseCoinV5[]; -} +type: 1 | 2; // 1: personal, 2: connected to third-party app ⋮---- -// --- GET /v5/asset/total-members-assets --- +/** @deprecated */ ⋮---- -export interface TotalMembersAccountBreakdownItemV5 { - type: string; - origb: string; - quoteb: string; - stat: number; +uta: 0 | 1; // 0: regular account, 1: unified trade account +⋮---- +export interface UpdateApiKeyResultV5 { + id: string; + note: string; + apiKey: string; + readOnly: 0 | 1; + secret: string; + permissions: PermissionsV5; + ips: string[]; } ⋮---- -export interface TotalMembersMemberEntryV5 { - uid: number; - isM?: boolean; - type?: number; - stat: number; - origb: string; - quoteb?: string; - items: TotalMembersAccountBreakdownItemV5[]; +export interface SubAccountAllApiKeysResultV5 { + result: { + id: string; + ips?: string[]; + apiKey: string; + note: string; + status: number; + expiredAt?: string; + createdAt: string; + type: ApiKeyType; + permissions: PermissionsV5; + secret: string; + readOnly: 0 | 1; + deadlineDay?: number; + flag: string; + }[]; + nextPageCursor: string; } ⋮---- -export interface TotalMembersAssetsResultV5 { - total: string; - quoteTotal: string; - stat: number; - list: TotalMembersMemberEntryV5[]; +export interface AffiliateUserListItemV5 { + userId: string; + registerTime: string; + source: string; + remarks: string; + isKyc: boolean; + takerVol30Day: string; + makerVol30Day: string; + tradeVol30Day: string; + depositAmount30Day: string; + takerVol365Day: string; + makerVol365Day: string; + tradeVol365Day: string; + depositAmount365Day: string; + takerVol: string; + makerVol: string; + tradeVol: string; + startDate: string; + endDate: string; + /** tradfi trade volume in [startDate, endDate] when startDate/endDate in params */ + tradfiTradeVol?: string; + /** tradfi trade volume in last 30 days. 0 when startDate/endDate in params */ + tradfiTradeVol30Day?: string; + /** tradfi trade volume in past year. 0 when startDate/endDate in params */ + tradfiTradeVol365Day?: string; + /** Commission between startDate and endDate when startDate/endDate in params. Coin -> amount */ + commissionsVol?: Record; + /** Commission in last 30 days. Coin -> amount */ + commissions30Day?: Record; + /** Commission in past year. Coin -> amount */ + commissions365Day?: Record; +} +⋮---- +/** tradfi trade volume in [startDate, endDate] when startDate/endDate in params */ +⋮---- +/** tradfi trade volume in last 30 days. 0 when startDate/endDate in params */ +⋮---- +/** tradfi trade volume in past year. 0 when startDate/endDate in params */ +⋮---- +/** Commission between startDate and endDate when startDate/endDate in params. Coin -> amount */ +⋮---- +/** Commission in last 30 days. Coin -> amount */ +⋮---- +/** Commission in past year. Coin -> amount */ +⋮---- +export interface AffiliateUserInfoV5 { + uid: string; + vipLevel: string; + takerVol30Day: string; + makerVol30Day: string; + tradeVol30Day: string; + depositAmount30Day: string; + takerVol365Day: string; + makerVol365Day: string; + tradeVol365Day: string; + depositAmount365Day: string; + totalWalletBalance: '1' | '2' | '3' | '4'; + depositUpdateTime: string; + volUpdateTime: string; + KycLevel: 0 | 1 | 2; + /** tradfi trade volume in last 30 days (USDT) */ + tradfiTradeVol30Day?: string; + /** tradfi trade volume in past year (USDT) */ + tradfiTradeVol365Day?: string; + /** tradfi commissions in last 30 days. Coin -> amount */ + commissions30Day?: Record; + /** tradfi commissions in past year. Coin -> amount */ + commissions365Day?: Record; + /** Payment amount in the last 30 days */ + paySendAmount30Day: string; + /** Pay first transaction amount */ + payFtt: string; + /** Card first-time transaction amount */ + cardFtt: string; +} +⋮---- +/** tradfi trade volume in last 30 days (USDT) */ +⋮---- +/** tradfi trade volume in past year (USDT) */ +⋮---- +/** tradfi commissions in last 30 days. Coin -> amount */ +⋮---- +/** tradfi commissions in past year. Coin -> amount */ +⋮---- +/** Payment amount in the last 30 days */ +⋮---- +/** Pay first transaction amount */ +⋮---- +/** Card first-time transaction amount */ +⋮---- +export interface AffiliateSubAffiliateListItemV5 { + subAffId: string; + userId: string; + name: string; + email: string; + /** Commission per currency (BTC, ETH, MNT, USDC, USDT) for the queried date range */ + commissionsVol: Record; + commissionsForUsdt: string; + becameAffTime: string; + startDate: string; + endDate: string; +} +⋮---- +/** Commission per currency (BTC, ETH, MNT, USDC, USDT) for the queried date range */ +⋮---- +export interface AffiliateSubAffiliateListResultV5 { + list: AffiliateSubAffiliateListItemV5[]; + nextPageCursor: string; +} +⋮---- +export interface FriendReferralRecordV5 { + id: string; + inviteeUid: string; + status: number; + createdAt: string; + updatedAt: string; +} +⋮---- +export interface ReferralCodeItemV5 { + referralCode: string; + referralLink: string; + scene: number; +} +⋮---- +export interface ReferralCodesResultV5 { + referralCodes: ReferralCodeItemV5[]; } -================ -File: README.md -================ -# Node.js & JavaScript SDK for Bybit REST API, WebSocket API & WebSocket Events - -[![Build & Test](https://github.com/tiagosiebler/bybit-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/bybit-api/actions/workflows/e2etest.yml) -[![npm version](https://img.shields.io/npm/v/bybit-api)][1] -[![npm size](https://img.shields.io/bundlephobia/min/bybit-api/latest)][1] -[![npm downloads](https://img.shields.io/npm/dt/bybit-api)][1] -[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/bybit-api)][1] -[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/bybit-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/bybit-api) -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) -[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tiagosiebler/bybit-api) - -

- - - - SDK Logo - - -

- -[1]: https://www.npmjs.com/package/bybit-api - -> [!TIP] -> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK will soon be hosted under the [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. - -Professional Node.js, JavaScript & TypeScript SDK for the Bybit REST APIs, WebSocket APIs & WebSocket Events: - -- Complete integration with all Bybit REST APIs & WebSockets, including the WebSocket API. -- Actively maintained with a modern, promise-driven interface. -- Exclusive benefits with this Node.js, JavaScript & TypeScript SDK for Bybit: - - Higher API rate limits with this SDK than the highest VIP tier! - - All qualified API requests made with this SDK are automatically subject to significantly higher rate limits. - - Rate limits are raised to 400 requests per second, higher than the highest VIP tier. - - No action required. This is automatic for any API calls made with this SDK, for any user. - - Read more in the announcement: [here](https://github.com/tiagosiebler/bybit-api/issues/458). - - Lower minimum order notional value with this SDK!\* - - Place orders with a notional value as low as $1. - - Lower than the default minimum notional order value $5. - - \*Note: the lower min notional requirement is an undocumented benefit that may end at any time. -- Automatic support for HMAC & RSA authentication. -- TypeScript support (thorough type declarations for most API requests & responses, including WS API). -- JavaScript support (TypeScript not required but definitely recommended). -- Thorough & automatic end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm. -- Proxy support via axios integration. -- Robust WebSocket consumer integration with configurable heartbeats & automatic reconnect then resubscribe workflows. - - Event driven messaging - - Smart WebSocket persistence - - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - - Automatically handle authentication. - - Emit `reconnected` event when dropped connection is restored. -- WebSocket API integration, with two design patterns to choose from: - 1. Asynchronous **promise**-driven responses: - - Make requests like a REST API, using the WebSocket API. No need to subscribe to asynchronous events. - - Import the `WebsocketAPIClient` and use it like the REST API client. Call functions and await responses. - - See example for more details: [examples/ws-api-client.ts](./examples/ws-api-client.ts). - - Prefer something more raw? Use the `sendWSAPIRequest(...)` method and await responses - - See example for more details: [examples/ws-api-raw-promises.ts](./examples/ws-api-raw-promises.ts) - 2. Asynchronous **event**-driven responses: - - Subscribe to `response` and `error` events from WebsocketClient's event emitter. - - Send commands with the `sendWSAPIRequest(...)` method. - - Responses to commands will arrive via the `response` and `error` events emitted by the client. - - See example for more details: [examples/ws-api-raw-events.ts](./examples/ws-api-raw-events.ts) -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). -- QuickStart Guide: https://siebly.io/sdk/bybit/javascript -- Bybit JavaScript Tutorial: [Bybit JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/bybit/javascript/tutorial) - -# Table of Contents - -## Overview - -- [Installation](#installation) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation](#documentation) -- [Examples](#examples) - -## REST API Examples - -- [API Clients](#api-clients) -- [REST API Usage](#rest-api-usage) - -## WebSocket Integration & Examples - -- [WebSockets](#websockets) -- [WebSocket Subscriptions - Consuming Events](#websocket-subscriptions---consuming-events) -- [Websocket API - Sending Orders via WebSockets](#websocket-api---sending-orders-via-websockets) -- [Consumer Load Balancing](#balancing-load-across-multiple-connections) - -## Bybit EU & Other Regions - -- [REST API Usage with Bybit EU](#rest-api-usage-with-bybit-eu) - -## Additional Features - -- [Logging](#logging) - - [Customise Logging](#customise-logging) - - [Debug HTTP Requests](#debug-http-requests) -- [Browser Usage](#browser-usage) - - [Import](#import) - - [Webpack](#webpack) -- [Use with LLMs & AI](#use-with-llms--ai) -- [Used By](#used-by) - -## Contributing - -- [Contributions & Thanks](#contributions--thanks) - ---- - -## Installation - -`npm install --save bybit-api` - -## Issues & Discussion - -- Issues? Check the [issues tab](https://github.com/tiagosiebler/bybit-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/) -- 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 Bybit's API documentation, or check the type definition in each class within the github repository (see table below for convenient links to each class). TypeScript is definitely recommended, but not required. - -- [Bybit API Docs](https://bybit-exchange.github.io/docs/v5/intro) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) -- [TSDoc Documentation (generated using typedoc via npm module)](https://tsdocs.dev/docs/bybit-api) - -## Structure - -The SDK is written in TypeScript, but fully compatible with both TypeScript and pure JavaScript projects. A pure JavaScript version can be built using `npm run build`. The output of the `build` command is the version published to npm, packaged as a JavaScript module (with types available for you TypeScript users). - -- [src](./src) - the complete SDK written in TypeScript. -- [lib](./lib) - the JavaScript version of the project (built from TypeScript) that is published to npm. This should not be edited directly, as it will be overwritten with each release. -- [examples](./examples) - examples & demonstrations. Contributions are welcome! -- [test](./test) - automated end-to-end tests that run before every release, making real API calls. - ---- - -## Examples - -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. +================ +File: src/types/websockets/ws-general.ts +================ +import { AxiosRequestConfig } from 'axios'; +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; +⋮---- +import { RestClientOptions, WS_KEY_MAP } from '../../util'; +⋮---- +/** For spot markets, spotV3 is recommended */ +export type APIMarket = 'v5'; +⋮---- +// Same as inverse futures +export type WsPublicInverseTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'klineV2'; +⋮---- +export type WsPublicUSDTPerpTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'kline'; +⋮---- +export type WsPublicSpotV1Topic = + | 'trade' + | 'realtimes' + | 'kline' + | 'depth' + | 'mergedDepth' + | 'diffDepth'; +⋮---- +export type WsPublicSpotV2Topic = + | 'depth' + | 'kline' + | 'trade' + | 'bookTicker' + | 'realtimes'; +⋮---- +export type WsPublicTopics = + | WsPublicInverseTopic + | WsPublicUSDTPerpTopic + | WsPublicSpotV1Topic + | WsPublicSpotV2Topic + | string; +⋮---- +// Same as inverse futures +export type WsPrivateInverseTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order'; +⋮---- +export type WsPrivateUSDTPerpTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order' + | 'wallet'; +⋮---- +export type WsPrivateSpotTopic = + | 'outboundAccountInfo' + | 'executionReport' + | 'ticketInfo'; +⋮---- +export type WsPrivateTopic = + | WsPrivateInverseTopic + | WsPrivateUSDTPerpTopic + | WsPrivateSpotTopic + | string; +⋮---- +export type WsTopic = WsPublicTopics | WsPrivateTopic; +⋮---- +/** This is used to differentiate between each of the available websocket streams (as bybit has multiple websockets) */ +export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; +export type WsMarket = 'all'; +⋮---- +export interface WSClientConfigurableOptions { + /** Your API key */ + key?: string; -If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler). + /** Your API secret */ + secret?: string; -## API Clients + /** + * Set to `true` to connect to Bybit's testnet environment. + * + * Notes: + * + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + */ + testnet?: boolean; -You should be using the V5 APIs. If you aren't, you should upgrade your project to use the V5 APIs as soon as possible. Bybit used to have several API groups (originally one per product), but the V5 API is currently the latest standard. + /** + * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo + * + * Only the "V5" "market" is supported here. + */ + demoTrading?: boolean; -Refer to the [V5 interface mapping page](https://bybit-exchange.github.io/docs/v5/intro#v5-and-v3-interface-mapping-list) for more information on which V5 endpoints can be used instead of previous V3 endpoints. To learn more about the V5 API, please read the [V5 upgrade guideline](https://bybit-exchange.github.io/docs/v5/upgrade-guide). + /** + * The API group this client should connect to. The V5 market is currently used by default. + * + * Only the "V5" "market" is supported here. + */ + market?: APIMarket; -Here are the available REST clients and the corresponding API groups described in the documentation: + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; -| Class | Description | -| :-----------------------------------------------: | :------------------------------------------------------------------------------------------------------: | -| [ **V5 API** ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). | -| [RestClientV5](src/rest-client-v5.ts) | Unified V5 all-in-one REST client for all [V5 REST APIs](https://bybit-exchange.github.io/docs/v5/intro) | -| [WebsocketClient](src/websocket-client.ts) | All WebSocket features (Public & Private consumers for all API categories & the WebSocket API) | -| [WebsocketAPIClient](src/websocket-api-client.ts) | Use the WebSocket API like a REST API. Call functions and await responses, powered by WebSockets. | + /** How often to check if the connection is alive */ + pingInterval?: number; -## REST API Usage + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; -Create API credentials on Bybit's website: + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; -- [Livenet](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1) -- [Testnet](https://testnet.bybit.com/app/user/api-management) + restOptions?: RestClientOptions; + requestOptions?: AxiosRequestConfig; -The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the [examples](./examples/) folder in the repository on GitHub: + wsOptions?: { + protocols?: string[]; + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); -```typescript -const { RestClientV5 } = require('bybit-api'); -// or -// import { RestClientV5 } from 'bybit-api'; + wsUrl?: string; -const restClientOptions = { - /** supports HMAC & RSA API keys - automatically detected */ - /** Your API key */ - key: 'apiKeyHere', + /** + * Default: false. + * + * When enabled, any calls to the subscribe method will return a promise. + * Note: internally, subscription requests are sent in batches. This may not behave as expected when + * subscribing to a large number of topics, especially if you are not yet connected when subscribing. + */ + promiseSubscribeRequests?: boolean; - /** Your API secret */ - secret: 'apiSecretHere', + /** + * 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 */ +⋮---- +/** + * Set to `true` to connect to Bybit's testnet environment. + * + * Notes: + * + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + */ +⋮---- +/** + * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo + * + * Only the "V5" "market" is supported here. + */ +⋮---- +/** + * The API group this client should connect to. The V5 market is currently used by default. + * + * Only the "V5" "market" is supported here. + */ +⋮---- +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +⋮---- +/** 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 */ +⋮---- +/** + * Default: false. + * + * When enabled, any calls to the subscribe method will return a promise. + * Note: internally, subscription requests are sent in batches. This may not behave as expected when + * subscribing to a large number of topics, especially if you are not yet connected when subscribing. + */ +⋮---- +/** + * 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. + */ +⋮---- +/** + * WS configuration that's always defined, regardless of user configuration + * (usually comes from defaults if there's no user-provided values) + */ +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + market: APIMarket; + pongTimeout: number; + pingInterval: number; + reconnectTimeout: number; + recvWindow: number; - /** Set to `true` to connect to testnet. Uses the live environment by default. */ - // testnet: true, + /** + * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + */ + requireConnectionReadyConfirmation: boolean; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequests: boolean; + reauthWSAPIOnReconnect: boolean; /** - * Set to `true` to use Bybit's V5 demo trading: - * https://bybit-exchange.github.io/docs/v5/demo + * Whether to use native WebSocket ping/pong frames for heartbeats + */ + useNativeHeartbeats: boolean; +} +⋮---- +/** + * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + */ +⋮---- +/** + * Whether to use native WebSocket ping/pong frames for heartbeats + */ +⋮---- +export type WsEventInternalSrc = 'event' | 'function' | 'frame'; + +================ +File: src/websocket-client.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +⋮---- +import { + CategoryV5, + MessageEventLike, + WSClientConfigurableOptions, + WsKey, + WsMarket, + WsTopic, +} from './types'; +import { + Exact, + WSAPIOperation, + WsAPIOperationResponseMap, + WSAPIRequest, + WsAPITopicRequestParamMap, + WsAPIWsKeyTopicMap, + WsOperation, + WsRequestOperationBybit, +} from './types/websockets/ws-api'; +import { + APIID, + DefaultLogger, + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getPromiseRefForWSAPIRequest, + getTopicsPerWSKey, + getWsKeyForTopic, + getWsUrl, + isPrivateWsTopic, + isTopicSubscriptionConfirmation, + isTopicSubscriptionSuccess, + isWSAPIResponse, + isWsPong, + neverGuard, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WSConnectedResult, + WsTopicRequest, +} from './util'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient'; +import { SignAlgorithm, signMessage } from './util/webCryptoAPI'; +⋮---- +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; +} +⋮---- +/** If true, will skip auth requirement for WS API connection */ +⋮---- +export class WebsocketClient extends BaseWebsocketClient< +⋮---- +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +⋮---- +/** + * Request connection of all dependent (public & private) websockets, instead of waiting + * for automatic connection by SDK. + */ +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 */ +⋮---- +public connectPublic(): Promise[] +⋮---- +public connectPrivate(): Promise +⋮---- +/** + * Subscribe to V5 topics & track/persist them. + * @param wsTopics - topic or list of topics + * @param category - the API category this topic is for (e.g. "linear"). + * The value is only important when connecting to public topics and will be ignored for private 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 subscribeV5( + wsTopics: WsTopic[] | WsTopic, + category: CategoryV5, + isPrivateTopic?: boolean, +): Promise[] +⋮---- +// Sort into per-WsKey batches, in case there is a mix of topics here +⋮---- +// Prevent duplicate requests to the same topic +⋮---- +// Batch sub topics per ws key +⋮---- +// Return promise to resolve midflight WS request (only works if already connected before request) +⋮---- +/** + * Unsubscribe from V5 topics & remove them from memory. They won't be re-subscribed to if the + * connection reconnects. + * + * @param wsTopics - topic or list of topics + * @param category - the API category this topic is for (e.g. "linear"). The value is only + * important when connecting to public topics and will be ignored for private 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 unsubscribeV5( + wsTopics: WsTopic[] | WsTopic, + category: CategoryV5, + isPrivateTopic?: boolean, +): Promise[] +⋮---- +// Sort into per-WsKey batches, in case there is a mix of topics here +⋮---- +// Batch sub topics per ws key +⋮---- +// Return promise to resolve midflight WS request (only works if already connected before request) +⋮---- +/** + * Note: subscribeV5() might be simpler to use. The end result is the same. + * + * 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 | WsTopic) + | (WsTopicRequest | WsTopic)[], + requestedWsKey?: WsKey, +) +⋮---- +// Batch sub topics per ws key +⋮---- +/** + * Note: unsubscribe() might be simpler to use. The end result is the same. + * 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 | WsTopic) + | (WsTopicRequest | WsTopic)[], + wsKey?: WsKey, +) +⋮---- +// Batch sub topics per ws key +⋮---- +/** + * + * + * + * WS API Methods - similar to the REST API, but via WebSockets + * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline + * + * + * + */ +⋮---- +/** + * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. + * + * WS API Documentation for list of operations and parameters: + * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline * - * Note: to use demo trading, you should have `testnet` disabled. + * Returned promise is rejected if: + * - an exception is detected in the reply, OR + * - the connection disconnects for any reason (even if automatic reconnect will happen). * - * You can find a detailed demoTrading example in the examples folder on GitHub. - */ - // demoTrading: true, - - /** Override the max size of the request window (in ms) */ - // recv_window: 5000, // 5000 = 5 seconds - - /** - * Enable keep alive for REST API requests (via axios). - * See: https://github.com/tiagosiebler/bybit-api/issues/368 - */ - // keepAlive: true, - - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over - * sockets being kept alive. Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) + * Authentication is automatic. If you didn't request authentication yourself, there might + * be a small delay after your first request, while the SDK automatically authenticates. + * + * @param wsKey - The connection this event is for. Currently only "v5PrivateTrade" is supported + * for Bybit, since that is the dedicated WS API connection. + * @param operation - The command being sent, e.g. "order.create" to submit a new order. + * @param params - Any request parameters for the command. E.g. `OrderParamsV5` to submit a new + * order. Only send parameters for the request body. Everything else is automatically handled. + * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response */ - // keepAliveMsecs: 1000, // 1000 = 1 second - - /** - * Optionally override API domain used: - * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', - **/ - - // apiRegion: 'bytick', - - /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ - // parseAPIRateLimits: true, - - /** - * Allows you to provide a custom "signMessage" function, - * e.g. to use node crypto's much faster createHmac method +⋮---- +// This overload allows the caller to omit the 3rd param, if it isn't required +sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact, + >( + wsKey: TWSKey, + operation: TWSOperation, + params?: TWSParams extends void | never ? undefined : TWSParams, + requestFlags?: WSAPIRequestFlags, + ): Promise; +⋮---- +// These overloads give stricter types than mapped generics, since generic constraints +// do not trigger excess property checks +// Without these overloads, TypeScript won't complain if you include an +// unexpected property with your request (if it doesn't clash with an existing property) +sendWSAPIRequest( + wsKey: typeof WS_KEY_MAP.v5PrivateTrade, + operation: TWSOperation, + params: WsAPITopicRequestParamMap[TWSOperation], + requestFlags?: WSAPIRequestFlags, + ): Promise; +⋮---- +sendWSAPIRequest( + wsKey: typeof WS_KEY_MAP.v5PrivateTrade, + operation: TWSOperation, + params: WsAPITopicRequestParamMap[TWSOperation], + requestFlags?: WSAPIRequestFlags, + ): Promise; +⋮---- +sendWSAPIRequest( + wsKey: typeof WS_KEY_MAP.v5PrivateTrade, + operation: TWSOperation, + params: WsAPITopicRequestParamMap[TWSOperation], + requestFlags?: WSAPIRequestFlags, + ): Promise; +⋮---- +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact, + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: WsKey = WS_KEY_MAP.v5PrivateTrade, + operation: TWSOperation, + params: TWSParams, + requestFlags?: WSAPIRequestFlags, +): Promise +⋮---- +// Some commands don't require authentication. +⋮---- +// Sign, if needed +⋮---- +// 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 +⋮---- +/** + * + * + * Internal methods - not intended for public use + * * - * Look at examples/fasterHmacSign.ts for a demonstration: */ - // customSignMessageFn: (message: string, secret: string) => Promise; -}; - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -const client = new RestClientV5( - { - key: API_KEY, - secret: API_SECRET, - // demoTrading: true, - - // Optional: enable to try parsing rate limit values from responses - // parseAPIRateLimits: true - }, - // requestLibraryOptions -); - -// For public-only API calls, simply don't provide a key & secret or set them to undefined -// const client = new RestClientV5(); - -client - .getAccountInfo() - .then((result) => { - console.log('getAccountInfo result: ', result); - }) - .catch((err) => { - console.error('getAccountInfo error: ', err); - }); - -client - .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) - .then((result) => { - console.log('getOrderBook result: ', result); - }) - .catch((err) => { - console.error('getOrderBook error: ', err); - }); -``` - ---- - -## WebSockets - -The WebsocketClient will automatically use the latest V5 WebSocket endpoints by default. To use a different endpoint, use the `market` parameter. Except for the WebSocket API - this can be accessed without any special configuration. - -## WebSocket Subscriptions - Consuming events - -Here's a minimal example for using the websocket client. For more complete examples, look into the ws-\* examples in the [examples](./examples/) folder in the repo on GitHub. - -```javascript -const { WebsocketClient } = require('bybit-api'); -// or -// import { WebsocketClient } from 'bybit-api'; - -const API_KEY = 'xxx'; -const PRIVATE_KEY = 'yyy'; - -const wsConfig = { - /** - * API credentials are optional. They are only required if you plan on using - * any account-specific topics or the WS API - * supports HMAC & RSA API keys - automatically detected +⋮---- +/** + * Note: implementing this method will wipe the WsStore state for this WsKey, once this method returns */ - key: 'yourAPIKeyHere', - secret: 'yourAPISecretHere', - - /* - The following parameters are optional: - */ - - /** - * Set to `true` to connect to Bybit's testnet environment. - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market - * data is very different from real market conditions. +protected isCustomReconnectionNeeded(): boolean +⋮---- +protected async triggerCustomReconnectionWorkflow(): Promise +⋮---- +/** + * @returns The WS URL to connect to for this WS key */ - // testnet: true - - /** - * Set to `true` to connect to Bybit's V5 demo trading: - * https://bybit-exchange.github.io/docs/v5/demo - * - * Refer to the examples folder on GitHub for a more detailed demonstration. +protected async getWsUrl(wsKey: WsKey): Promise +⋮---- +// If auth is needed for this wsKey URL, this returns a suffix +⋮---- +/** + * Return params required to make authorized request */ - // demoTrading: true, - - // recv window size for websocket authentication (higher latency connections - // (VPN) can cause authentication to fail if the recv window is too small) - // recvWindow: 5000, - - /** How often to check if the connection is alive (in ms) */ - // pingInterval: 10000, - - /** - * How long to wait (in ms) for a pong (heartbeat reply) before assuming the - * connection is dead +private async getWsAuthURLSuffix(): Promise +⋮---- +private async signMessage( + paramsStr: string, + secret: string, + method?: 'hex' | 'base64', + algorithm: SignAlgorithm = 'SHA-256', +): Promise +⋮---- +protected async getWsAuthRequestEvent( + wsKey: WsKey, +): Promise> +⋮---- +private async getWsAuthSignature( + wsKey: WsKey, +): Promise< +⋮---- +undefined, // Let the function automatically determine encoding based on key type +⋮---- +private async signWSAPIRequest( + requestEvent: WSAPIRequest, +): Promise> +⋮---- +// Not needed for Bybit. Auth happens only on connection open, automatically. +⋮---- +protected sendPingEvent(wsKey: WsKey) +⋮---- +protected sendPongEvent(wsKey: WsKey) +⋮---- +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +⋮---- +protected authPrivateConnectionsOnConnect(_wsKey: WsKey): boolean +⋮---- +/** + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ - // pongTimeout: 1000, - - /** Delay in milliseconds before respawning the connection */ - // reconnectTimeout: 500, - - // override which URL to use for websocket connections - // wsUrl: 'wss://stream.bytick.com/realtime' - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's - * much faster createHmac method - * - * Look at examples/fasterHmacSign.ts for a demonstration: +protected async getWsRequestEvents( + market: WsMarket, + operation: WsOperation, + requests: WsTopicRequest[], + // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars + _wsKey: WsKey, +): Promise>[]> +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars +⋮---- +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +⋮---- +protected getPrivateWSKeys(): WsKey[] +⋮---- +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +⋮---- +/** + * Determines if a topic is for a private channel, using a hardcoded list of strings */ - // customSignMessageFn: (message: string, secret: string) => Promise; -}; - -const ws = new WebsocketClient(wsConfig); - -// (v5) subscribe to multiple topics at once -ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); - -// Or one at a time -ws.subscribeV5('kline.5.BTCUSDT', 'linear'); -ws.subscribeV5('kline.5.ETHUSDT', 'linear'); - -// Private/public topics can be used in the same WS client instance, even for -// different API groups (linear, options, spot, etc) -ws.subscribeV5('position', 'linear'); -ws.subscribeV5('publicTrade.BTC', 'option'); +protected isPrivateTopicRequest(request: WsTopicRequest): boolean +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPing(msg: any): boolean +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPong(msg: any): boolean +⋮---- +// public ws connections +⋮---- +// private ws connections +⋮---- +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] +⋮---- +// this.logger.trace('resolveEmittableEvents', { +// ...WS_LOGGER_CATEGORY, +// wsKey, +// parsed: JSON.stringify(parsed), +// }); +⋮---- +// Only applies to the V5 WS topics +⋮---- +// WS API response +⋮---- +// eslint-disable-next-line max-len +⋮---- +// WS API Exception +⋮---- +// WS API Success +⋮---- +// Messages for a subscribed topic all include the "topic" property +⋮---- +// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property +⋮---- +// Failed request +⋮---- +// These are r equest/reply pattern events (e.g. after subscribing to topics or authenticating) +⋮---- +// Request/reply pattern for authentication success +⋮---- +// In case of catastrophic failure, fallback to noisy emit update +================ +File: src/types/response/v5-asset.ts +================ +import { AccountTypeV5, OrderSideV5, WithdrawalTypeV5 } from '../shared-v5'; +⋮---- +export interface CoinExchangeRecordV5 { + fromCoin: string; + fromAmount: string; + toCoin: string; + toAmount: string; + exchangeRate: string; + createdTime: string; + exchangeTxId: string; +} +⋮---- +export interface DeliveryRecordV5 { + deliveryTime: number; + symbol: string; + side: OrderSideV5; + position: string; + deliveryPrice: string; + strike: string; + fee: string; + deliveryRpl: string; + entryPrice: string; +} +⋮---- +export interface SettlementRecordV5 { + symbol: string; + side: string; + size: number; + sessionAvgPrice: string; + markPrice: string; + realisedPnl: string; + createdTime: string; +} +⋮---- +export interface AssetInfoAssetV5 { + coin: string; + frozen: string; + free: string; + withdraw: string; +} +⋮---- +export interface AssetInfoV5 { + status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED'; + assets: AssetInfoAssetV5[]; +} +⋮---- +export interface CoinBalanceV5 { + coin: string; + walletBalance: string; + transferBalance: string; + bonus?: string; +} +⋮---- +export interface AllCoinsBalanceV5 { + accountType: AccountTypeV5; + memberId?: string; + balance: CoinBalanceV5[]; +} +⋮---- +export interface AccountCoinBalanceV5 { + accountType: AccountTypeV5; + bizType: number; + accountId: string; + memberId: string; + balance: { + coin: string; + walletBalance: string; + transferBalance: string; + bonus: string; + transferSafeAmount: string; + ltvTransferSafeAmount: string; + }; +} +⋮---- +export interface InternalTransferRecordV5 { + transferId: string; + coin: string; + amount: string; + fromAccountType: AccountTypeV5; + toAccountType: AccountTypeV5; + timestamp: string; + status: string; +} +⋮---- +export interface UniversalTransferRecordV5 { + transferId: string; + coin: string; + amount: string; + fromMemberId: string; + toMemberId: string; + fromAccountType: AccountTypeV5; + toAccountType: AccountTypeV5; + timestamp: string; + status: string; +} +⋮---- +export interface AllowedDepositCoinInfoV5 { + coin: string; + chain: string; + coinShowName: string; + chainType: string; + blockConfirmNumber: number; + minDepositAmount: string; +} +⋮---- +export interface DepositRecordV5 { + id: string; + coin: string; + chain: string; + amount: string; + txID: string; + status: number; + toAddress: string; + tag: string; + depositFee: string; + successAt: string; + confirmations: string; + txIndex: string; + blockHash: string; + batchReleaseLimit: string; + depositType: string; + fromAddress: string; + travelRuleStatus?: string; +} +⋮---- +export interface SubmitDepositOriginatorInfoResultV5 { + travelRuleStatus: number; +} +⋮---- +export interface InternalDepositRecordV5 { + id: string; + type: 1; + coin: string; + amount: string; + status: 1 | 2 | 3; + address: string; + createdTime: string; + txID: string; + complianceStatus?: string; +} +⋮---- +export interface DepositAddressChainV5 { + chainType: string; + addressDeposit: string; + tagDeposit: string; + chain: string; + batchReleaseLimit: string; + contractAddress: string; +} +⋮---- +export interface DepositAddressResultV5 { + coin: string; + chains: DepositAddressChainV5[]; +} +⋮---- +export interface CoinInfoV5 { + name: string; + coin: string; + /** @deprecated Use `chains[].withdrawMax` instead */ + remainAmount: string; + chains: { + chain: string; + chainType: string; + confirmation: string; + withdrawFee: string; + depositMin: string; + withdrawMin: string; + minAccuracy: string; + chainDeposit: string; + chainWithdraw: string; + withdrawPercentageFee: string; + contractAddress: string; + safeConfirmNumber: string; + /** Max withdraw amount per transaction per chain. `-1` means no limit */ + withdrawMax: string; + }[]; +} +⋮---- +/** @deprecated Use `chains[].withdrawMax` instead */ +⋮---- +/** Max withdraw amount per transaction per chain. `-1` means no limit */ +⋮---- +export interface WithdrawalRecordV5 { + withdrawId: string; + txID: string; + withdrawType: WithdrawalTypeV5; + coin: string; + chain: string; + amount: string; + withdrawFee: string; + status: string; + toAddress: string; + tag: string; + createTime: string; + updateTime: string; +} +⋮---- +export interface WithdrawalAddressV5 { + coin: string; + chain: string; + address: string; + tag: string; + remark: string; + status: number; + addressType: number; + verified: number; + createdAt: string; +} +⋮---- +export interface WithdrawableAccountSliceV5 { + coin: string; + withdrawableAmount: string; + availableBalance: string; +} +⋮---- /** - * The Websocket Client will automatically manage all connectivity & authentication for you. - * - * If a network issue occurs, it will automatically: - * - detect it, - * - remove the dead connection, - * - replace it with a new one, - * - resubscribe to everything you were subscribed to. - * - * When this happens, you will see the "reconnected" event. + * GET /v5/asset/withdraw/withdrawable-amount. Only keys with data are returned + * (e.g. UTA, FUND, EARN; EARN when the coin can be withdrawn from Earn; SPOT if present). */ +export interface WithdrawableAmountV5 { + limitAmountUsd: string; + withdrawableAmount: { + SPOT?: WithdrawableAccountSliceV5; + FUND?: WithdrawableAccountSliceV5; + UTA?: WithdrawableAccountSliceV5; + EARN?: WithdrawableAccountSliceV5; + }; +} +⋮---- +export interface VaspEntityV5 { + vaspEntityId: string; + vaspName: string; +} +⋮---- +export interface ConvertCoinSpecV5 { + coin: string; + fullName: string; + icon: string; + iconNight: string; + accuracyLength: number; + coinType: string; + balance: string; + uBalance: string; + singleFromMinLimit: string; + singleFromMaxLimit: string; + disableFrom: boolean; + disableTo: boolean; + timePeriod: number; + singleToMinLimit: string; + singleToMaxLimit: string; + dailyFromMinLimit: string; + dailyFromMaxLimit: string; + dailyToMinLimit: string; + dailyToMaxLimit: string; +} +⋮---- +export interface ConvertQuoteV5 { + quoteTxId: string; + exchangeRate: string; + fromCoin: string; + fromCoinType: string; + toCoin: string; + toCoinType: string; + fromAmount: string; + toAmount: string; + expiredTime: string; + requestId: string; + extTaxAndFee: string[]; +} +⋮---- +export interface ConvertStatusV5 { + accountType: string; + exchangeTxId: string; + userId: string; + fromCoin: string; + fromCoinType: string; + toCoin: string; + toCoinType: string; + fromAmount: string; + toAmount: string; + exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; + extInfo: { paramType: string; paramValue: string }; + convertRate: string; + createdAt: string; +} +⋮---- +export interface ConvertHistoryRecordV5 { + accountType: string; + exchangeTxId: string; + userId: string; + fromCoin: string; + fromCoinType: string; + toCoin: string; + toCoinType: string; + fromAmount: string; + toAmount: string; + exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; + extInfo: { paramType: string; paramValue: string }; + convertRate: string; + createdAt: string; +} +⋮---- +export interface SmallBalanceCoinV5 { + fromCoin: string; // Source currency + supportConvert: 1 | 2; // 1: support, 2: not supported + availableBalance: string; // Available balance + baseValue: string; // USDT equivalent value + toAmount: string; // Reserved field + exchangeRate: string; // Reserved field + feeInfo: null; // Reserved field + taxFeeInfo: null; // Reserved field +} +⋮---- +fromCoin: string; // Source currency +supportConvert: 1 | 2; // 1: support, 2: not supported +availableBalance: string; // Available balance +baseValue: string; // USDT equivalent value +toAmount: string; // Reserved field +exchangeRate: string; // Reserved field +feeInfo: null; // Reserved field +taxFeeInfo: null; // Reserved field +⋮---- +export interface SmallBalanceListV5 { + smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info + supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) +} +⋮---- +smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info +supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) +⋮---- +export interface FiatCoinInfoV5 { + coin: string; // Fiat coin code + fullName: string; // Fiat full coin name + icon: string; // Coin icon url + iconNight: string; // Coin icon url (dark mode) + precision: number; // Fiat precision + disable: boolean; // true: the coin is disabled, false: the coin is allowed + singleFromMinLimit: string; // For buy side, minimum amount of fiatCoin per transaction + singleFromMaxLimit: string; // For buy side, maximum amount of fiatCoin per transaction +} +⋮---- +coin: string; // Fiat coin code +fullName: string; // Fiat full coin name +icon: string; // Coin icon url +iconNight: string; // Coin icon url (dark mode) +precision: number; // Fiat precision +disable: boolean; // true: the coin is disabled, false: the coin is allowed +singleFromMinLimit: string; // For buy side, minimum amount of fiatCoin per transaction +singleFromMaxLimit: string; // For buy side, maximum amount of fiatCoin per transaction +⋮---- +export interface CryptoCoinInfoV5 { + coin: string; // Crypto coin code + fullName: string; // Crypto full coin name + icon: string; // Coin icon url + iconNight: string; // Coin icon url (dark mode) + precision: number; // Crypto precision + disable: boolean; // true: the coin is disabled, false: the coin is allowed + singleFromMinLimit: string; // For sell side, minimum amount of cryptoCoin per transaction + singleFromMaxLimit: string; // For sell side, maximum amount of cryptoCoin per transaction +} +⋮---- +coin: string; // Crypto coin code +fullName: string; // Crypto full coin name +icon: string; // Coin icon url +iconNight: string; // Coin icon url (dark mode) +precision: number; // Crypto precision +disable: boolean; // true: the coin is disabled, false: the coin is allowed +singleFromMinLimit: string; // For sell side, minimum amount of cryptoCoin per transaction +singleFromMaxLimit: string; // For sell side, maximum amount of cryptoCoin per transaction +⋮---- +export interface FiatTradingPairListV5 { + fiats: FiatCoinInfoV5[]; // Fiat coin list + cryptos: CryptoCoinInfoV5[]; // Crypto coin list +} +⋮---- +fiats: FiatCoinInfoV5[]; // Fiat coin list +cryptos: CryptoCoinInfoV5[]; // Crypto coin list +⋮---- +export interface FundingAccountTransactionRecordV5 { + memberId: string; + currency: string; + ioDirection: string; + txnAmt: string; + afterAmt: string; + createTime: string; + showBusiType: string; + showBusiTypeEn: string; + description: string; + descriptionEn: string; +} +⋮---- +/** When accountType=Alpha and category is farm, under `coinDetail` in sub-categories. */ +export interface AssetOverviewCoinExtMapV5 { + priceUpper?: string; + priceLower?: string; + equityUnit?: string; +} +⋮---- +export interface AssetOverviewCoinDetailV5 { + coin: string; + equity: string; + extMap?: AssetOverviewCoinExtMapV5; +} +⋮---- +export interface AssetOverviewCategoryV5 { + category: string; + equity: string; + coinDetail: AssetOverviewCoinDetailV5[]; +} +⋮---- +export interface AssetOverviewAccountItemV5 { + accountType: string; + totalEquity: string; + valuationCurrency: string; + snapshotTime: string; + coinDetail?: AssetOverviewCoinDetailV5[]; + categories?: AssetOverviewCategoryV5[]; +} +⋮---- +export interface AssetOverviewResultV5 { + totalEquity: string; + list: AssetOverviewAccountItemV5[]; +} +⋮---- +// --- GET /v5/asset/portfolio-margin (portfolio margin P&L ranges) --- +⋮---- +export interface PortfolioMarginWalletV5 { + equity: string; + cashBalance: string; + marginBalance: string; + availableBalance: string; + accountIM: string; + accountMM: string; + accountMMRate: string; + accountIMRate: string; +} +⋮---- +export interface PortfolioMarginPnlRangePointV5 { + priceScale: string; + pnls: string[]; +} +⋮---- +export interface PortfolioMarginContractBucketPnlV5 { + pnlRanges: PortfolioMarginPnlRangePointV5[]; +} +⋮---- +export interface PortfolioMarginTotalPnlRangesV5 { + ALL?: PortfolioMarginContractBucketPnlV5; + PERPETUAL?: PortfolioMarginContractBucketPnlV5; + OPTION?: PortfolioMarginContractBucketPnlV5; +} +⋮---- +export interface PortfolioMarginPerpPositionPnlV5 { + symbolName: string; + position: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; + sessionAvgPrice: string; + markPrice: string; + orderSize: string; + contractType: number; + settleCoin: string; + symbolAlias?: string; +} +⋮---- +export interface PortfolioMarginOptionPositionPnlV5 { + symbolName: string; + position: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; + sessionAvgPrice: string; + markPrice: string; + orderSize: string; + contractType: number; + settleCoin: string; +} +⋮---- +export interface PortfolioMarginOptionExpiryPnlV5 { + expiryDateRepresentation: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; + optionPositionPnlRanges: PortfolioMarginOptionPositionPnlV5[]; +} +⋮---- +export interface PortfolioMarginContingencyV5 { + optionContingency: string; + futureDeltaContingency: string; + optionVegaContingency: string; + contingencyComponents: string; + usdtUsdcContingency: string; + futureContingency: string; +} +⋮---- +export interface PortfolioMarginAssetBlockV5 { + coin: string; + assetIM: string; + assetMM: string; +} +⋮---- +export interface PortfolioMarginSpotHedgeInfoV5 { + hedgeSpotSize: string; + walletBalance: string; + usdIndexPrice: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; +} +⋮---- +export interface PortfolioMarginByBaseCoinV5 { + baseCoin: string; + totalPnlRanges: PortfolioMarginTotalPnlRangesV5; + perpPositionPnlRanges: PortfolioMarginPerpPositionPnlV5[]; + optionExpiryDatePnlRanges: PortfolioMarginOptionExpiryPnlV5[]; + contingency: PortfolioMarginContingencyV5; + asset: PortfolioMarginAssetBlockV5; + maxLossPriceMove: string; + maxLossIvShock: string; + totalClosePzFee: string; + spotHedgeInfo: PortfolioMarginSpotHedgeInfoV5; + maxLossIvShockList: string[]; +} +⋮---- +export interface PortfolioMarginInfoResultV5 { + wallet: PortfolioMarginWalletV5; + assetPnlRange: PortfolioMarginByBaseCoinV5[]; +} +⋮---- +// --- GET /v5/asset/total-members-assets --- +⋮---- +export interface TotalMembersAccountBreakdownItemV5 { + type: string; + origb: string; + quoteb: string; + stat: number; +} +⋮---- +export interface TotalMembersMemberEntryV5 { + uid: number; + isM?: boolean; + type?: number; + stat: number; + origb: string; + quoteb?: string; + items: TotalMembersAccountBreakdownItemV5[]; +} +⋮---- +export interface TotalMembersAssetsResultV5 { + total: string; + quoteTotal: string; + stat: number; + list: TotalMembersMemberEntryV5[]; +} -// Listen to events coming from websockets. This is the primary data source -ws.on('update', (data) => { - console.log('data received', JSON.stringify(data, null, 2)); -}); - -// Optional: Listen to websocket connection open event -// (automatic after subscribing to one or more topics) -ws.on('open', ({ wsKey, event }) => { - console.log('connection open for websocket with ID: ', wsKey); -}); - -// Optional: Listen to responses to websocket queries -// (e.g. the response after subscribing to a topic) -ws.on('response', (response) => { - console.log('response', response); -}); - -// Optional: Listen to connection close event. -// Unexpected connection closes are automatically reconnected. -ws.on('close', () => { - console.log('connection closed'); -}); - -// Listen to raw error events. Recommended. -ws.on('exception', (err) => { - console.error('exception', err); -}); - -ws.on('reconnect', ({ wsKey }) => { - console.log('ws automatically reconnecting.... ', wsKey); -}); - -ws.on('reconnected', (data) => { - console.log('ws has reconnected ', data?.wsKey); -}); -``` - -## Websocket API - Sending orders via WebSockets - -Bybit supports sending, amending and cancelling orders over a WebSocket connection. The [WebsocketClient](./src/WebsocketClient.ts) fully supports Bybit's WebSocket API via the `sendWSAPIRequest(...)` method. There is also a dedicated [WebsocketAPIClient](./src/websocket-api-client.ts), built over the WSClient's sendWSAPIRequest mechanism for a simpler experience. - -Links for reference: - -- [Bybit WebSocket API Documentation](https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline) -- [WebsocketAPIClient example, use the Websocket API like a REST API](./examples/ws-api-client.ts) -- [Raw Asynchronous Websocket API Node.js/TypeScript/JavaScript example](./examples/ws-api-raw-promises.ts) - -Note: as of January 2025, the demo trading environment does not support the WebSocket API. - -There are two ways to use the WS API, depending on individual preference: - -1. event-driven: - - send requests via `client.sendWSAPIRequest(wsKey, operation, params)`, fire and forget - - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` - - See example for more details: [examples/ws-api-raw-events.ts](./examples/ws-api-raw-events.ts) -2. promise-driven: - - import the `WebsocketAPIClient` and use it much like a REST API. - - make an instance & call the Websocket API with a function. - - await responses, much like a REST API. - - use try/catch blocks to handle promise rejections - - See example for more details: [examples/ws-api-client.ts](./examples/ws-api-client.ts) - -The below example demonstrates the promise-driven approach, which behaves similar to a REST API. The WebSocket API even accepts the same parameters as the corresponding REST API endpoints, so this approach should be compatible with existing REST implementations. - -Connectivity, authentication and connecting requests & responses to promises - these are all handled automatically without additional configuration by the WebsocketClient. The WebsocketAPIClient is a wrapper built on top of this, providing dedicated methods for every available Websocket API command. Each method has fully typed requests & responses. Benefit from the capabilities of the WebSocket API without the complexity of managing asynchronous messaging over WebSockets. - -```javascript -const { WS_KEY_MAP, WebsocketAPIClient } = require('bybit-api'); - -// or -// import { WS_KEY_MAP, WebsocketAPIClient } from 'bybit-api'; - -// Create an instance of the WebsocketAPIClient. This is built on -// top of the WebsocketClient and will automatically handle WebSocket -// persistence and authentication for you. -// supports HMAC & RSA API keys - automatically detected -const wsClient = new WebsocketAPIClient({ - key: 'yourApiKeyHere', - secret: 'yourApiSecretHere', - - // Whether to use the testnet environment. - // Create testnet API keys here: https://testnet.bybit.com/app/user/api-management - // testnet: true, - - // Whether to use the livenet demo trading environment - // Note: As of Jan 2025, demo trading only supports consuming events, it does - // NOT support the WS API. - // demoTrading: false, - - // If you want your own event handlers instead of the default ones with logs, - // disable this setting and see ws-api-client example for more details. - // attachEventListeners: false -}); - -// This example is wrapped in an async function, so "await" can be used -async function main() { +================ +File: src/types/websockets/ws-events.ts +================ +import WebSocket from 'isomorphic-ws'; +⋮---- +import { + RFQItemV5, + RFQPublicTradeV5, + RFQQuoteItemV5, + RFQTradeV5, +} from '../response/v5-rfq'; +import { + CategoryV5, + ExecTypeV5, + OCOTriggerTypeV5, + OrderCancelTypeV5, + OrderCreateTypeV5, + OrderRejectReasonV5, + OrderSideV5, + OrderSMPTypeV5, + OrderStatusV5, + OrderTimeInForceV5, + OrderTriggerByV5, + OrderTypeV5, + PositionIdx, + PositionSideV5, + PositionStatusV5, + StopOrderTypeV5, + SystemStatusItemV5, + TPSLModeV5, + TradeModeV5, +} from '../shared-v5'; +import { WsKey } from './ws-general'; +⋮---- +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} +⋮---- +export function isMessageEvent(msg: unknown): msg is MessageEventLike +⋮---- +export interface WSPublicTopicEventV5 { + id?: string; + topic: TTopic; + type: TType; + /** Cross sequence */ + cs?: number; + /** Event timestamp */ + ts: number; + data: TData; /** - * Optional. Can be used to prepare a connection before sending - * commands (e.g. as part of your startup process). - * - * This is not necessary and will happen automatically when - * sending a command, if you aren't connected/authenticated yet. + * matching engine timestamp (correlated with T from public trade channel) */ - // await wsClient.getWSClient().connectWSAPI(); - - try { - console.log('Step 1: Create an order'); - const response = await wsClient.submitNewOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderType: 'Limit', - qty: '0.001', - side: 'Buy', - price: '50000', - }); - console.log('submitNewOrder response: ', response); - } catch (e) { - console.log('submitNewOrder error: ', e); - } - - try { - console.log('Step 2: Amend an order'); - const response = await wsClient.amendOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', - qty: '0.001', - price: '60000', - }); - console.log('amendOrder response: ', response); - } catch (e) { - console.log('amendOrder error: ', e); - } - - try { - console.log('Step 3: Cancel an order'); - const response = await wsClient.cancelOrder({ - category: 'linear', - symbol: 'BTCUSDT', - orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', - }); - console.log('cancelOrder response: ', response); - } catch (e) { - console.log('cancelOrder error: ', e); - } + cts: number; + /** + * Internal reference, can be used to determine if this is spot/linear/inverse/etc + */ + wsKey: WsKey; +} +⋮---- +/** Cross sequence */ +⋮---- +/** Event timestamp */ +⋮---- +/** + * matching engine timestamp (correlated with T from public trade channel) + */ +⋮---- +/** + * Internal reference, can be used to determine if this is spot/linear/inverse/etc + */ +⋮---- +export interface WSPrivateTopicEventV5 { + id?: string; + topic: TTopic; + creationTime: number; + data: TData; + wsKey: WsKey; +} +⋮---- +export interface WSOrderbookV5 { + /** Symbol */ + s: string; + /** [price, qty][] */ + b: [string, string][]; + /** [price, qty][] */ + a: [string, string][]; + /** Update ID */ + u: number; + /** Cross sequence */ + seq: number; +} +⋮---- +/** Symbol */ +⋮---- +/** [price, qty][] */ +⋮---- +/** [price, qty][] */ +⋮---- +/** Update ID */ +⋮---- +/** Cross sequence */ +⋮---- +export type WSOrderbookEventV5 = WSPublicTopicEventV5< + string, + 'delta' | 'snapshot', + WSOrderbookV5 +>; +⋮---- +export interface WSTradeV5 { + T: number; + s: string; + S: OrderSideV5; + v: string; + p: string; + L?: string; + i: string; + BT: boolean; + RPI?: boolean; + mP?: string; + iP?: string; + mIv?: string; + iv?: string; +} +⋮---- +export type WSTradeEventV5 = WSPublicTopicEventV5< + string, + 'snapshot', + WSTradeV5[] +>; +⋮---- +/** + * WSTickerV5 is the data structure for the "linear" ticker channel + * */ +export interface WSTickerV5 { + symbol: string; + tickDirection: string; + price24hPcnt: string; + lastPrice: string; + prevPrice24h: string; + highPrice24h: string; + lowPrice24h: string; + prevPrice1h: string; + markPrice: string; + indexPrice: string; + openInterest: string; + openInterestValue: string; + singleOpenInterest?: string; + singleOpenInterestValue?: string; + turnover24h: string; + volume24h: string; + nextFundingTime: string; + fundingRate: string; + bid1Price: string; + bid1Size: string; + ask1Price: string; + ask1Size: string; + deliveryTime?: string; + basisRate?: string; + deliveryFeeRate?: string; + predictedDeliveryPrice?: string; + preOpenPrice?: string; + preQty?: string; + curPreListingPhase?: string; + fundingIntervalHour?: string; + fundingCap?: string; + basisRateYear?: string; +} +⋮---- +export interface WSTickerOptionV5 { + symbol: string; + bidPrice: string; + bidSize: string; + bidIv: string; + askPrice: string; + askSize: string; + askIv: string; + lastPrice: string; + highPrice24h: string; + lowPrice24h: string; + markPrice: string; + indexPrice: string; + markPriceIv: string; + underlyingPrice: string; + openInterest: string; + turnover24h: string; + volume24h: string; + totalVolume: string; + totalTurnover: string; + delta: string; + gamma: string; + vega: string; + theta: string; + predictedDeliveryPrice: string; + change24h: string; +} +⋮---- +export interface WSTickerSpotV5 { + symbol: string; + lastPrice: string; + highPrice24h: string; + lowPrice24h: string; + prevPrice24h: string; + volume24h: string; + turnover24h: string; + price24hPcnt: string; + usdIndexPrice: string; +} +⋮---- +export type WSTickerEventV5 = WSPublicTopicEventV5< + string, + 'snapshot' | 'delta', + WSTickerV5 | WSTickerOptionV5 | WSTickerSpotV5 +>; +⋮---- +export interface WSKlineV5 { + start: number; + end: number; + interval: string; + open: string; + close: string; + high: string; + low: string; + volume: string; + turnover: string; + confirm: boolean; + timestamp: number; +} +⋮---- +export type WSKlineEventV5 = WSPublicTopicEventV5< + string, + 'snapshot', + WSKlineV5[] +>; +⋮---- +export interface WSLiquidationV5 { + T: number; + s: string; + S: OrderSideV5; + v: string; + p: string; +} +⋮---- +export type WSLiquidationEventV5 = WSPublicTopicEventV5< + string, + 'snapshot', + WSLiquidationV5[] +>; +⋮---- +export interface WSPositionV5 { + category: string; + symbol: string; + side: PositionSideV5; + size: string; + positionIdx: PositionIdx; + tradeMode: TradeModeV5; + positionValue: string; + riskId: number; + riskLimitValue: string; + entryPrice: string; + markPrice: string; + leverage: string; + breakEvenPrice?: string; // Break even price, only for linear & inverse + positionBalance: string; + autoAddMargin: number; + positionMM: string; + positionIM: string; + positionIMByMp: string; + positionMMByMp: string; + liqPrice: string; + bustPrice: string; + tpslMode: string; + takeProfit: string; + stopLoss: string; + trailingStop: string; + unrealisedPnl: string; + curRealisedPnl: string; + sessionAvgPrice: string; + delta: string; + gamma: string; + vega: string; + theta: string; + cumRealisedPnl: string; + positionStatus: PositionStatusV5; + adlRankIndicator: number; + isReduceOnly: boolean; + mmrSysUpdatedTime: string; + leverageSysUpdatedTime: string; + createdTime: string; + updatedTime: string; + /** Position open timestamp (ms). Default `0` when not set. */ + openTime: number; + seq: number; +} +⋮---- +breakEvenPrice?: string; // Break even price, only for linear & inverse +⋮---- +/** Position open timestamp (ms). Default `0` when not set. */ +⋮---- +export type WSPositionEventV5 = WSPrivateTopicEventV5< + 'position', + WSPositionV5[] +>; +⋮---- +export interface WSAccountOrderV5 { + category: CategoryV5; + orderId: string; + orderLinkId: string; + parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) + isLeverage: string; + blockTradeId: string; + symbol: string; + price: string; + qty: string; + side: OrderSideV5; + positionIdx: PositionIdx; + orderStatus: OrderStatusV5; + createType: OrderCreateTypeV5; + cancelType: OrderCancelTypeV5; + rejectReason?: OrderRejectReasonV5; + avgPrice?: string; + leavesQty?: string; + leavesValue?: string; + cumExecQty: string; + cumExecValue: string; + cumExecFee: string; + closedPnl: string; + feeCurrency: string; + timeInForce: OrderTimeInForceV5; + orderType: OrderTypeV5; + stopOrderType: StopOrderTypeV5; + ocoTriggerType?: OCOTriggerTypeV5; + orderIv: string; + marketUnit?: 'baseCoin' | 'quoteCoin'; + triggerPrice: string; + takeProfit: string; + stopLoss: string; + tpslMode?: TPSLModeV5; + tpLimitPrice?: string; + slLimitPrice?: string; + tpTriggerBy: string; + slTriggerBy: string; + triggerDirection: number; + triggerBy: OrderTriggerByV5; + lastPriceOnCreated: string; + reduceOnly: boolean; + closeOnTrigger: boolean; + placeType: string; + smpType: OrderSMPTypeV5; + smpGroup: string; + smpOrderId: string; + createdTime: string; + updatedTime: string; + cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency + rpiTakerAccess?: boolean; + rpiMatchedQty?: string; +} +⋮---- +parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) +⋮---- +cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency +⋮---- +export type WSAccountOrderEventV5 = WSPrivateTopicEventV5< + 'order', + WSAccountOrderV5[] +>; +⋮---- +export interface WSExecutionV5 { + category: CategoryV5; + symbol: string; + isLeverage: string; + orderId: string; + orderLinkId: string; + side: OrderSideV5; + orderPrice: string; + orderQty: string; + leavesQty: string; + createType: OrderCreateTypeV5; + orderType: OrderTypeV5; + stopOrderType: StopOrderTypeV5; + execFee: string; + feeCurrency: string; // Trading fee currency + execId: string; + execPrice: string; + execQty: string; + execPnl: string; + execType: ExecTypeV5; + execValue: string; + execTime: string; + isMaker: boolean; + feeRate: string; + tradeIv: string; + markIv: string; + markPrice: string; + indexPrice: string; + underlyingPrice: string; + blockTradeId: string; + closedSize: string; + extraFees: string; + seq: number; + marketUnit: string; +} +⋮---- +feeCurrency: string; // Trading fee currency +⋮---- +export type WSExecutionEventV5 = WSPrivateTopicEventV5< + 'execution', + WSExecutionV5[] +>; +⋮---- +export interface WSExecutionFastV5 { + category: CategoryV5; + symbol: string; + execId: string; + execPrice: string; + execQty: string; + orderId: string; + isMaker: boolean; + orderLinkId: string; + side: OrderSideV5; + execTime: string; + seq: number; + liquidity?: string; +} +⋮---- +export type WSExecutionFastEventV5 = WSPrivateTopicEventV5< + 'execution.fast', + WSExecutionFastV5[] +>; +⋮---- +export interface WSCoinV5 { + coin: string; + equity: string; + usdValue: string; + walletBalance: string; + free?: string; + locked: string; + spotHedgingQty: string; + borrowAmount: string; + availableToBorrow: string; + availableToWithdraw: string; + accruedInterest: string; + totalOrderIM: string; + totalPositionIM: string; + totalPositionMM: string; + unrealisedPnl: string; + cumRealisedPnl: string; + bonus: string; + collateralSwitch: boolean; + marginCollateral: boolean; + spotBorrow: string; + colRes?: string; +} +⋮---- +export interface WSWalletV5 { + accountType: string; + accountLTV: string; + accountIMRate: string; + accountMMRate: string; + accountIMRateByMp: string; + accountMMRateByMp: string; + totalInitialMarginByMp: string; + totalMaintenanceMarginByMp: string; + totalEquity: string; + totalWalletBalance: string; + totalMarginBalance: string; + totalAvailableBalance: string; + totalPerpUPL: string; + totalInitialMargin: string; + totalMaintenanceMargin: string; + coin: WSCoinV5[]; +} +⋮---- +export type WSWalletEventV5 = WSPrivateTopicEventV5<'wallet', WSWalletV5[]>; +⋮---- +export interface WSGreeksV5 { + baseCoin: string; + totalDelta: string; + totalGamma: string; + totalVega: string; + totalTheta: string; +} +⋮---- +export type WSGreeksEventV5 = WSPrivateTopicEventV5<'greeks', WSGreeksV5[]>; +⋮---- +export interface WSSpreadOrderV5 { + category: 'combination' | 'spot_leg' | 'future_leg'; + symbol: string; + parentOrderId: string; + orderId: string; + orderLinkId: string; + side: OrderSideV5; + orderStatus: OrderStatusV5; + cancelType: OrderCancelTypeV5; + rejectReason: OrderRejectReasonV5; + timeInForce: OrderTimeInForceV5; + price: string; + qty: string; + avgPrice: string; + leavesQty: string; + leavesValue: string; + cumExecQty: string; + cumExecValue: string; + cumExecFee: string; + orderType: OrderTypeV5; + isLeverage: string; + createdTime: string; + updatedTime: string; + feeCurrency: string; + createType: OrderCreateTypeV5; + closedPnl: string; + cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency } - -// Start executing the example workflow -main(); -``` - ---- - -### Balancing load across multiple connections - -The WebsocketClient will automatically prepare one connection per API group, for all topics in that API group. Any topics that you subscribe to on that WebSocket client will automatically be added to the same connection. - -To spread your subscribed topics over multiple connections, e.g. to reduce the throughput of an individual connectionk, you can make one instance of the WebsocketClient per connection group. - -```typescript -const wsClientGroup1 = new WebsocketClient(); -const wsClientGroup2 = new WebsocketClient(); - -// Attach event listeners to each WS Client -// Divide your desired topics into separate groups -``` - -Important: do not subscribe to the same topics on both clients or you will receive duplicate messages (once per WS client). - ---- - -## Bybit EU & Other Regions - -By default, this Node.js, JavaScript & TypeScript SDK uses the Bybit Global API & WebSocket domains. For regions where Bybit has dedicated regional domains, including the alternative Bybit Global domain (bytick), these can be configured in the REST Client using the `apiRegion` property. - -The following values are currently supported in this option: - -- `apiRegion: undefined`: if missing or undefined, this SDK will default to the Bybit Global domain `api.bybit.com`. -- `apiRegion: "default"`: the Bybit Global domain (same behaviour as above). -- `apiRegion: "bytick"`: the alternative Bybit Global domain `api.bytick.com`. -- `apiRegion: "NL"`: the dedicated Bybit Netherlands domain `api.bytick.nl`. -- `apiRegion: "TK"`: the dedicated Bybit Turkey domain `api.bybit-tr.com`. -- `apiRegion: "KZ"`: the dedicated Bybit Kazakhstan domain `api.bybit.kz`. -- `apiRegion: "HK"`: the dedicated Bybit HK domain `api.byhkbit.com`. -- `apiRegion: "GE"`: the dedicated Bybit Georgia domain `api.bybitgeorgia.ge`. -- `apiRegion: "UAE"`: the dedicated Bybit United Arab Emirates domain `api.bybit.ae`. -- `apiRegion: "EU"`: the dedicated Bybit EU/EEA domain `api.bybit.eu`. - -New regions will be supported when they become available in the Bybit API. If you notice any regions that have not been added yet, please open a new issue on GitHub. - -### REST API Usage with Bybit EU - -Below is an example for using this Node.js, TypeScript & JavaScript SDK for Bybit's APIs, using an account registered on the Bybit EU domain: - -```typescript -const { RestClientV5 } = require('bybit-api'); -// or -// import { RestClientV5 } from 'bybit-api'; - -const client = new RestClientV5({ - key: API_KEY, - secret: API_SECRET, - // demoTrading: true, - - apiRegion: 'EU', -}); - -client - .getAccountInfo() - .then((result) => { - console.log('getAccountInfo result: ', result); - }) - .catch((err) => { - console.error('getAccountInfo error: ', err); - }); -``` - ---- - -## Logging - -### Customise logging - -Pass a custom logger (or mutate the imported DefaultLogger class) which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired, as in the example below: - -```javascript -const { WebsocketClient, DefaultLogger } = require('bybit-api'); - -// Enable all logging on the trace level (disabled by default) -const customLogger = { - ...DefaultLogger, - trace: (...params) => console.log('trace', ...params), -}; - -const wsClient = new WebsocketClient( - { key: 'xxx', secret: 'yyy' }, - 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 `BYBITTRACE` 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 stream-browserify - ``` -2. Add this to your `tsconfig.json` - ```json - { - "compilerOptions": { - "paths": { - "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/bybit-api/image)](https://github.com/tiagosiebler/bybit-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` -- 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 - - - - -### 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) - - +⋮---- +cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency +⋮---- +export type WSSpreadOrderEventV5 = WSPrivateTopicEventV5< + 'spread.order', + WSSpreadOrderV5[] +>; +⋮---- +export interface WSSpreadExecutionV5 { + category: 'combination' | 'spot_leg' | 'future_leg'; + symbol: string; + isLeverage: string; + orderId: string; + orderLinkId: string; + side: OrderSideV5; + orderPrice: string; + orderQty: string; + leavesQty: string; + createType: OrderCreateTypeV5; + orderType: OrderTypeV5; + execFee: string; + execFeeV2: string; + feeCurrency: string; // Trading fee currency + parentExecId: string; + execId: string; + execPrice: string; + execQty: string; + execPnl: string; + execType: ExecTypeV5; + execValue: string; + execTime: string; + isMaker: boolean; + feeRate: string; + markPrice: string; + closedSize: string; + seq: number; +} +⋮---- +feeCurrency: string; // Trading fee currency +⋮---- +export type WSSpreadExecutionEventV5 = WSPrivateTopicEventV5< + 'spread.execution', + WSSpreadExecutionV5[] +>; +⋮---- +export interface WSInsuranceV5 { + coin: string; + symbols: string; + balance: string; + updateTime: string; +} +⋮---- +export type WSInsuranceEventV5 = WSPublicTopicEventV5< + 'insurance.USDT' | 'insurance.USDC' | 'insurance.inverse', + 'snapshot' | 'delta', + WSInsuranceV5[] +>; +⋮---- +export interface WSPriceLimitV5 { + symbol: string; + buyLmt: string; + sellLmt: string; +} +⋮---- +export type WSPriceLimitEventV5 = WSPublicTopicEventV5< + string, + 'snapshot', + WSPriceLimitV5 +>; +⋮---- +export interface WSADLAlertV5 { + c: string; // Token of the insurance pool + s: string; // Trading pair name + b: string; // Balance of the insurance fund. For shared insurance pool, follows T+1 refresh (updated daily at 00:00 UTC) + mb: string; // Deprecated: always returns empty string. Previously: Maximum balance of the insurance pool in the last 8 hours + i_pr: string; // PnL ratio threshold for triggering contract PnL drawdown ADL + pr: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped + adl_tt: string; // Trigger threshold for contract PnL drawdown ADL + adl_sr: string; // Stop ratio threshold for contract PnL drawdown ADL +} +⋮---- +c: string; // Token of the insurance pool +s: string; // Trading pair name +b: string; // Balance of the insurance fund. For shared insurance pool, follows T+1 refresh (updated daily at 00:00 UTC) +mb: string; // Deprecated: always returns empty string. Previously: Maximum balance of the insurance pool in the last 8 hours +i_pr: string; // PnL ratio threshold for triggering contract PnL drawdown ADL +pr: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped +adl_tt: string; // Trigger threshold for contract PnL drawdown ADL +adl_sr: string; // Stop ratio threshold for contract PnL drawdown ADL +⋮---- +export type WSADLAlertEventV5 = WSPublicTopicEventV5< + 'adlAlert.USDT' | 'adlAlert.USDC' | 'adlAlert.inverse', + 'snapshot', + WSADLAlertV5[] +>; +⋮---- +export type WSSystemStatusEventV5 = WSPublicTopicEventV5< + 'system.status', + 'snapshot', + SystemStatusItemV5[] +>; +⋮---- +/** + * RFQ WebSocket Events + */ +⋮---- +/** + * RFQ Inquiry Channel + * Private push for RFQ inquiries sent or received by the user + * Topics: rfq.open.rfqs, rfq.site.rfqs + */ +export type WSRFQInquiryEventV5 = WSPrivateTopicEventV5< + 'rfq.open.rfqs' | 'rfq.site.rfqs', + RFQItemV5[] +>; +⋮---- +/** + * RFQ Quote Channel + * Private push for quotes sent or received by the user + * Topics: rfq.open.quotes, rfq.site.quotes + */ +export type WSRFQQuoteEventV5 = WSPrivateTopicEventV5< + 'rfq.open.quotes' | 'rfq.site.quotes', + RFQQuoteItemV5[] +>; +⋮---- +/** + * RFQ Trade Channel + * Private push for block trades executed by the user + * Topics: rfq.open.trades, rfq.site.trades + */ +export type WSRFQTradeEventV5 = WSPrivateTopicEventV5< + 'rfq.open.trades' | 'rfq.site.trades', + RFQTradeV5[] +>; +⋮---- +/** + * RFQ Public Trade Channel + * Public push for all block trades + * Topics: rfq.open.public.trades, rfq.site.public.trades + */ +export type WSRFQPublicTradeEventV5 = WSPublicTopicEventV5< + 'rfq.open.public.trades' | 'rfq.site.public.trades', + 'snapshot', + RFQPublicTradeV5[] +>; ================ File: src/rest-client-v5.ts @@ -16861,6 +16936,8 @@ import { FeeGroupStructureResponseV5, FeeRateV5, FiatTradingPairListV5, + FixedLoanAvailableInventoryV5, + FixedRateAvailableInventoryV5, FixedRateBorrowContractInfoV5, FixedRateBorrowOrderInfoV5, FixedRateBorrowParamsV5, @@ -16870,6 +16947,8 @@ import { FixedTermEarnPlaceOrderResultV5, FixedTermEarnPositionListV5, FixedTermEarnProductListV5, + FlexibleAvailableInventoryV5, + FlexibleLoanAvailableInventoryV5, FriendReferralRecordV5, FundingAccountTransactionRecordV5, FundingRateHistoryResponseV5, @@ -16956,13 +17035,18 @@ import { GetFeeGroupStructureParamsV5, GetFeeRateParamsV5, GetFiatTradingPairListParamsV5, + GetFixedLoanAvailableInventoryParamsV5, + GetFixedRateAvailableInventoryParamsV5, GetFixedRateBorrowContractInfoParamsV5, GetFixedRateBorrowOrderInfoParamsV5, GetFixedRateBorrowOrderQuoteParamsV5, GetFixedTermEarnOrderListParamsV5, GetFixedTermEarnPositionParamsV5, GetFixedTermEarnProductParamsV5, + GetFlexibleAvailableInventoryParamsV5, + GetFlexibleLoanAvailableInventoryParamsV5, GetFriendReferralsParamsV5, + GetFullDepthOrderbookParamsV5, GetFundingAccountTransactionHistoryParamsV5, GetFundingRateHistoryParamsV5, GetFuturesLeverageParamsV5, @@ -16975,6 +17059,9 @@ import { GetInternalDepositRecordParamsV5, GetInternalTransferParamsV5, GetKlineParamsV5, + GetLaunchpoolProjectListParamsV5, + GetLaunchpoolUserActivityLogParamsV5, + GetLaunchpoolUserHistoryParamsV5, GetLiquidityMiningProductParamsV5, GetLoanLTVAdjustmentHistoryParamsV5, GetLongShortRatioParamsV5, @@ -17005,6 +17092,7 @@ import { GetPreUpgradeTransactionLogParamsV5, GetPreUpgradeUSDCSessionParamsV5, GetPublicTradingHistoryParamsV5, + GetPuzzleProjectListParamsV5, GetPwmAllFundOrdersParamsV5, GetPwmAllFundsParamsV5, GetPwmAssetManagerInvestmentPlansParamsV5, @@ -17018,6 +17106,7 @@ import { GetRepaymentHistoryFixedParamsV5, GetRepaymentHistoryFlexibleParamsV5, GetRepaymentHistoryParamsV5, + GetRFQDetailsParamsV5, GetRFQHistoryParamsV5, GetRFQListParamsV5, GetRFQPublicTradesParamsV5, @@ -17048,6 +17137,8 @@ import { GetSupplyOrderQuoteFixedParamsV5, GetSystemStatusParamsV5, GetTickersParamsV5, + GetTokenSplashProjectListParamsV5, + GetTokenSplashUserActivityParamsV5, GetTotalMembersAssetsParamsV5, GetTradeInfoForAnalysisParamsV5, GetTransactionLogParamsV5, @@ -17071,6 +17162,10 @@ import { InvestMorePwmInvestmentPlanParamsV5, InvestMorePwmInvestmentPlanResultV5, IssueVoucherParamsV5, + LaunchpoolActivityLogResultV5, + LaunchpoolCurrentStakingResultV5, + LaunchpoolProjectListResultV5, + LaunchpoolUserHistoryResultV5, LiquidityMiningProductResultV5, LoanLTVAdjustmentHistoryV5, LongShortRatioV5, @@ -17128,6 +17223,7 @@ import { PreUpgradeTransaction, PreUpgradeUSDCSessionSettlement, PublicTradeV5, + PuzzleProjectListResultV5, PwmAllFundOrdersResultV5, PwmAllFundsResultV5, PwmAssetManagerInvestmentPlansResultV5, @@ -17149,6 +17245,7 @@ import { RedeemFixedTermEarnResultV5, RedeemPwmInvestmentPlanParamsV5, RedeemPwmInvestmentPlanResultV5, + ReferralCodesResultV5, RenewBorrowOrderFixedParamsV5, RenewBorrowOrderFixedV5, RenewFixedRateBorrowParamsV5, @@ -17168,6 +17265,7 @@ import { RepaymentHistoryV5, RequestConvertQuoteParamsV5, RFQConfigV5, + RFQDetailItemV5, RFQHistory, RFQPublicTradeV5, RFQQuoteItemV5, @@ -17231,6 +17329,8 @@ import { TickerLinearInverseV5, TickerOptionV5, TickerSpotV5, + TokenSplashProjectListResultV5, + TokenSplashUserActivityResultV5, TotalMembersAssetsResultV5, TPSLModeV5, TradeInfoForAnalysisResultV5, @@ -17559,6 +17659,10 @@ getOrderbook( params: GetOrderbookParamsV5, ): Promise> ⋮---- +getFullDepthOrderbook( + params: GetFullDepthOrderbookParamsV5, +): Promise> +⋮---- /** * Get RPI Orderbook * Query for orderbook depth data with RPI (Retail Price Improvement) information. @@ -18428,7 +18532,7 @@ getClassicTransactionLogs( */ getSMPGroup(): Promise< APIResponseV3WithTime<{ - smpGroup: number; + smpGroup: string; }> > { return this.getPrivate('/v5/account/smp-group'); @@ -19216,6 +19320,8 @@ getFriendReferrals(params?: GetFriendReferralsParamsV5): Promise< > { return this.getPrivate('/v5/user/invitation/referrals', params); ⋮---- +getReferralCode(): Promise> +⋮---- /** * Sign Agreement * To trade commodity contracts (e.g. metals XAU/XAG perps, crude oil perps), complete the agreement signing first. @@ -19755,6 +19861,14 @@ renewFixedRateBorrow( params: RenewFixedRateBorrowParamsV5, ): Promise> ⋮---- +getFlexibleAvailableInventory( + params: GetFlexibleAvailableInventoryParamsV5, +): Promise> +⋮---- +getFixedRateAvailableInventory( + params: GetFixedRateAvailableInventoryParamsV5, +): Promise> +⋮---- /** * ****** Spot Margin Trade APIs (Normal) @@ -20281,6 +20395,10 @@ getRepaymentHistoryFlexible( params, ); ⋮---- +getFlexibleLoanAvailableInventory( + params: GetFlexibleLoanAvailableInventoryParamsV5, +): Promise> +⋮---- /** * ****** Fixed Loan @@ -20463,6 +20581,10 @@ getRenewOrderInfoFixed(params?: GetRenewOrderInfoFixedParamsV5): Promise< > { return this.getPrivate('/v5/crypto-loan-fixed/renew-info', params); ⋮---- +getFixedLoanAvailableInventory( + params: GetFixedLoanAvailableInventoryParamsV5, +): Promise> +⋮---- /** * ****** Institutional Lending @@ -21457,286 +21579,1061 @@ acceptNonLPQuote( params: AcceptNonLPQuoteParamsV5, ): Promise> ⋮---- +getRFQDetails(params?: GetRFQDetailsParamsV5): Promise< + APIResponseV3WithTime<{ + cursor: string; + list: RFQDetailItemV5[]; + }> + > { + return this.getPrivate('/v5/rfq/rfq-detail-list', params); +⋮---- +/** + * + ****** P2P TRADING + * + */ +⋮---- +/** + * + * General P2P + */ +⋮---- +/** + * Get coin balance of all account types under the master account, and sub account. + * + * Note: this field is mandatory for accountType=UNIFIED, and supports up to 10 coins each request + */ +getP2PAccountCoinsBalance( + params: GetP2PAccountCoinsBalanceParamsV5, +): Promise> +⋮---- +/** + * + * Advertisement P2P + */ +⋮---- +/** + * Get market online ads list + */ +getP2POnlineAds( + params: GetP2POnlineAdsParamsV5, +): Promise> +⋮---- +/** + * Post new P2P advertisement + */ +createP2PAd( + params: CreateP2PAdParamsV5, +): Promise> +⋮---- +/** + * Cancel P2P advertisement + */ +cancelP2PAd(params: { itemId: string }): Promise< + APIResponseV3WithTime<{ + securityRiskToken: string; + riskTokenType: string; + riskVersion: string; + needSecurityRisk: boolean; + }> + > { + return this.postPrivate('/v5/p2p/item/cancel', params); +⋮---- +/** + * Update or relist P2P advertisement + */ +updateP2PAd( + params: UpdateP2PAdParamsV5, +): Promise> +⋮---- +/** + * Get personal P2P ads list + * + */ +getP2PPersonalAds( + params: GetP2PPersonalAdsParamsV5, +): Promise> +⋮---- +/** + * Get P2P ad details + */ +getP2PAdDetail(params: { + itemId: string; +}): Promise> +⋮---- +/** + * + * Orders P2P + */ +⋮---- +/** + * Get all P2P orders + * + */ +getP2POrders( + params: GetP2POrdersParamsV5, +): Promise> +⋮---- +/** + * Get P2P order details + * + */ +getP2POrderDetail(params: { + orderId: string; +}): Promise> +⋮---- +/** + * Get pending P2P orders + */ +getP2PPendingOrders( + params: GetP2PPendingOrdersParamsV5, +): Promise> +⋮---- +/** + * Mark P2P order as paid + */ +markP2POrderAsPaid( + params: MarkP2POrderAsPaidParamsV5, +): Promise> +⋮---- +/** + * Release digital assets in a P2P order + */ +releaseP2POrder(params: { + orderId: string; +}): Promise> +⋮---- +/** + * Send chat message in a P2P order + */ +sendP2POrderMessage( + params: SendP2POrderMessageParamsV5, +): Promise> +⋮---- +/** + * Upload chat file for P2P order (Node.js only) + * + * Note: You must provide a Buffer. To upload from a file path, read it into a Buffer first: + * ```typescript + * import fs from 'fs'; + * const buffer = fs.readFileSync('./path/to/file.png'); + * await client.uploadP2PChatFile({ fileBuffer: buffer, fileName: 'file.png' }); + * ``` + * + * Supported file types: jpg, png, jpeg, pdf, mp4 + */ +uploadP2PChatFile(params: { + fileBuffer: Buffer; + fileName: string; // Required: the filename (used for MIME type detection) + }): Promise< + APIResponseV3WithTime<{ + url: string; + type: string; + uploadId: string | null; + }> + > { + return this.postPrivateFile('/v5/p2p/oss/upload_file', params); +⋮---- +fileName: string; // Required: the filename (used for MIME type detection) +⋮---- /** - * - ****** P2P TRADING - * + * Get chat messages in a P2P order */ +getP2POrderMessages( + params: GetP2POrderMessagesParamsV5, +): Promise> ⋮---- /** * - * General P2P + * User P2P */ ⋮---- /** - * Get coin balance of all account types under the master account, and sub account. - * - * Note: this field is mandatory for accountType=UNIFIED, and supports up to 10 coins each request + * Get P2P user account information */ -getP2PAccountCoinsBalance( - params: GetP2PAccountCoinsBalanceParamsV5, -): Promise> +getP2PUserInfo(): Promise> ⋮---- /** - * - * Advertisement P2P + * Get counterparty user information in a P2P order */ +getP2PCounterpartyUserInfo( + params: GetP2PCounterpartyUserInfoParamsV5, +): Promise> ⋮---- /** - * Get market online ads list + * Get user payment information */ -getP2POnlineAds( - params: GetP2POnlineAdsParamsV5, -): Promise> +getP2PUserPayments(): Promise> ⋮---- /** - * Post new P2P advertisement + * + ****** API Rate Limit Management APIs + * */ -createP2PAd( - params: CreateP2PAdParamsV5, -): Promise> ⋮---- /** - * Cancel P2P advertisement + * Set API rate limit + * + * API rate limit: 50 req per second + * + * INFO + * - If UID requesting this endpoint is a master account, uids in the input parameter must be subaccounts of the master account. + * - If UID requesting this endpoint is not a master account, uids in the input parameter must be the UID requesting this endpoint + * - UID requesting this endpoint must be an institutional user. */ -cancelP2PAd(params: { itemId: string }): Promise< +setApiRateLimit(params: { + list: { + uids: string; + bizType: string; + rate: number; + }[]; + }): Promise< APIResponseV3WithTime<{ - securityRiskToken: string; - riskTokenType: string; - riskVersion: string; - needSecurityRisk: boolean; + result: { + uids: string; + bizType: string; + rate: number; + success: boolean; + msg: string; + }[]; }> > { - return this.postPrivate('/v5/p2p/item/cancel', params); + return this.postPrivate('/v5/apilimit/set', params); ⋮---- /** - * Update or relist P2P advertisement + * Query API rate limit + * + * API rate limit: 50 req per second + * + * INFO + * - A master account can query api rate limit of its own and subaccounts. + * - A subaccount can only query its own api rate limit. */ -updateP2PAd( - params: UpdateP2PAdParamsV5, -): Promise> +queryApiRateLimit(params: { uids: string }): Promise< + APIResponseV3WithTime<{ + list: { + uids: string; + bizType: string; + rate: number; + }[]; + }> + > { + return this.getPrivate('/v5/apilimit/query', params); ⋮---- /** - * Get personal P2P ads list + * Get Rate Limit Cap + * Get your institution's total rate limit usage and cap, across the board. * + * API rate limit: 50 req per second + * Main UIDs or sub UIDs can query this endpoint, but a main UID can only see the rate limits of subs below it. */ -getP2PPersonalAds( - params: GetP2PPersonalAdsParamsV5, -): Promise> +getRateLimitCap(): Promise< + APIResponseV3WithTime<{ + list: { + bizType: string; + totalRate: number; + insCap: number; + uidCap: number; + }[]; + }> + > { + return this.getPrivate('/v5/apilimit/query-cap'); ⋮---- /** - * Get P2P ad details + * Get All Rate Limits + * Query for all your UID-level rate limits, including all master accounts and subaccounts. + * + * API rate limit: 50 req per second */ -getP2PAdDetail(params: { - itemId: string; -}): Promise> +getAllRateLimits(params?: { + limit?: string; + cursor?: string; + uids?: string; + }): Promise< + APIResponseV3WithTime<{ + list: { + uids: string; + bizType: string; + rate: number; + }[]; + nextPageCursor: string; + }> + > { + return this.getPrivate('/v5/apilimit/query-all', params); ⋮---- /** * - * Orders P2P + ****** Spot-X (Launchpool / Puzzle / Token Splash) + * */ ⋮---- -/** - * Get all P2P orders +getLaunchpoolProjectList( + params: GetLaunchpoolProjectListParamsV5, +): Promise> +⋮---- +getLaunchpoolUserActivityLog( + params?: GetLaunchpoolUserActivityLogParamsV5, +): Promise> +⋮---- +getLaunchpoolCurrentStaking(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/spot-x/launchpool/user/current-staking'); +⋮---- +getLaunchpoolUserHistory( + params?: GetLaunchpoolUserHistoryParamsV5, +): Promise> +⋮---- +getPuzzleProjectList( + params: GetPuzzleProjectListParamsV5, +): Promise> +⋮---- +getTokenSplashProjectList( + params: GetTokenSplashProjectListParamsV5, +): Promise> +⋮---- +getTokenSplashUserActivityParams( + params?: GetTokenSplashUserActivityParamsV5, +): Promise> + +================ +File: README.md +================ +# Node.js & JavaScript SDK for Bybit REST API, WebSocket API & WebSocket Events + +[![Build & Test](https://github.com/sieblyio/bybit-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/sieblyio/bybit-api/actions/workflows/e2etest.yml) +[![npm version](https://img.shields.io/npm/v/bybit-api)][1] +[![npm size](https://img.shields.io/bundlephobia/min/bybit-api/latest)][1] +[![npm downloads](https://img.shields.io/npm/dt/bybit-api)][1] +[![last commit](https://img.shields.io/github/last-commit/sieblyio/bybit-api)][1] +[![CodeFactor](https://www.codefactor.io/repository/github/sieblyio/bybit-api/badge)](https://www.codefactor.io/repository/github/sieblyio/bybit-api) +[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/sieblyio/bybit-api) + +

+ + + + SDK Logo + + +

+ +[1]: https://www.npmjs.com/package/bybit-api + +> [!TIP] +> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK is now hosted under our [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. + +Professional Node.js, JavaScript & TypeScript SDK for the Bybit REST APIs, WebSocket APIs & WebSocket Events: + +- Complete integration with all Bybit REST APIs & WebSockets, including the WebSocket API. +- Actively maintained with a modern, promise-driven interface. +- Exclusive benefits with this Node.js, JavaScript & TypeScript SDK for Bybit: + - Higher API rate limits with this SDK than the highest VIP tier! + - All qualified API requests made with this SDK are automatically subject to significantly higher rate limits. + - Rate limits are raised to 400 requests per second, higher than the highest VIP tier. + - No action required. This is automatic for any API calls made with this SDK, for any user. + - Read more in the announcement: [here](https://github.com/sieblyio/bybit-api/issues/458). + - Lower minimum order notional value with this SDK!\* + - Place orders with a notional value as low as $1. + - Lower than the default minimum notional order value $5. + - \*Note: the lower min notional requirement is an undocumented benefit that may end at any time. +- Automatic support for HMAC & RSA authentication. +- TypeScript support (thorough type declarations for most API requests & responses, including WS API). +- JavaScript support (TypeScript not required but definitely recommended). +- Thorough & automatic end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm. +- Proxy support via axios integration. +- Robust WebSocket consumer integration with configurable heartbeats & automatic reconnect then resubscribe workflows. + - Event driven messaging + - Smart WebSocket persistence + - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. + - Automatically handle authentication. + - Emit `reconnected` event when dropped connection is restored. +- WebSocket API integration, with two design patterns to choose from: + 1. Asynchronous **promise**-driven responses: + - Make requests like a REST API, using the WebSocket API. No need to subscribe to asynchronous events. + - Import the `WebsocketAPIClient` and use it like the REST API client. Call functions and await responses. + - See example for more details: [examples/ws-api-client.ts](./examples/ws-api-client.ts). + - Prefer something more raw? Use the `sendWSAPIRequest(...)` method and await responses + - See example for more details: [examples/ws-api-raw-promises.ts](./examples/ws-api-raw-promises.ts) + 2. Asynchronous **event**-driven responses: + - Subscribe to `response` and `error` events from WebsocketClient's event emitter. + - Send commands with the `sendWSAPIRequest(...)` method. + - Responses to commands will arrive via the `response` and `error` events emitted by the client. + - See example for more details: [examples/ws-api-raw-events.ts](./examples/ws-api-raw-events.ts) +- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). +- QuickStart Guide: https://siebly.io/sdk/bybit/javascript +- Bybit JavaScript Tutorial: [Bybit JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/bybit/javascript/tutorial) + +# Table of Contents + +## Overview + +- [Installation](#installation) +- [Issues & Discussion](#issues--discussion) +- [Related Projects](#related-projects) +- [Documentation](#documentation) +- [Examples](#examples) + +## REST API Examples + +- [API Clients](#api-clients) +- [REST API Usage](#rest-api-usage) + +## WebSocket Integration & Examples + +- [WebSockets](#websockets) +- [WebSocket Subscriptions - Consuming Events](#websocket-subscriptions---consuming-events) +- [Websocket API - Sending Orders via WebSockets](#websocket-api---sending-orders-via-websockets) +- [Consumer Load Balancing](#balancing-load-across-multiple-connections) + +## Bybit EU & Other Regions + +- [REST API Usage with Bybit EU](#rest-api-usage-with-bybit-eu) + +## Additional Features + +- [Logging](#logging) + - [Customise Logging](#customise-logging) + - [Debug HTTP Requests](#debug-http-requests) +- [Browser Usage](#browser-usage) + - [Import](#import) + - [Webpack](#webpack) +- [Use with LLMs & AI](#use-with-llms--ai) +- [Used By](#used-by) + +## Contributing + +- [Contributions & Thanks](#contributions--thanks) + +--- + +## Installation + +`npm install --save bybit-api` + +## Issues & Discussion + +- Issues? Check the [issues tab](https://github.com/sieblyio/bybit-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/) +- 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/sieblyio/awesome-crypto-examples) + + +## Documentation + +Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within the github repository (see table below for convenient links to each class). TypeScript is definitely recommended, but not required. + +- [Bybit API Docs](https://bybit-exchange.github.io/docs/v5/intro) +- [REST Endpoint Function List](./docs/endpointFunctionList.md) +- [TSDoc Documentation (generated using typedoc via npm module)](https://tsdocs.dev/docs/bybit-api) + +## Structure + +The SDK is written in TypeScript, but fully compatible with both TypeScript and pure JavaScript projects. A pure JavaScript version can be built using `npm run build`. The output of the `build` command is the version published to npm, packaged as a JavaScript module (with types available for you TypeScript users). + +- [src](./src) - the complete SDK written in TypeScript. +- [lib](./lib) - the JavaScript version of the project (built from TypeScript) that is published to npm. This should not be edited directly, as it will be overwritten with each release. +- [examples](./examples) - examples & demonstrations. Contributions are welcome! +- [test](./test) - automated end-to-end tests that run before every release, making real API calls. + +--- + +## Examples + +Examples for using each client can be found in: + +- the [examples](./examples) folder. +- the [awesome-crypto-examples](https://github.com/sieblyio/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). + +## API Clients + +You should be using the V5 APIs. If you aren't, you should upgrade your project to use the V5 APIs as soon as possible. Bybit used to have several API groups (originally one per product), but the V5 API is currently the latest standard. + +Refer to the [V5 interface mapping page](https://bybit-exchange.github.io/docs/v5/intro#v5-and-v3-interface-mapping-list) for more information on which V5 endpoints can be used instead of previous V3 endpoints. To learn more about the V5 API, please read the [V5 upgrade guideline](https://bybit-exchange.github.io/docs/v5/upgrade-guide). + +Here are the available REST clients and the corresponding API groups described in the documentation: + +| Class | Description | +| :-----------------------------------------------: | :------------------------------------------------------------------------------------------------------: | +| [ **V5 API** ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). | +| [RestClientV5](src/rest-client-v5.ts) | Unified V5 all-in-one REST client for all [V5 REST APIs](https://bybit-exchange.github.io/docs/v5/intro) | +| [WebsocketClient](src/websocket-client.ts) | All WebSocket features (Public & Private consumers for all API categories & the WebSocket API) | +| [WebsocketAPIClient](src/websocket-api-client.ts) | Use the WebSocket API like a REST API. Call functions and await responses, powered by WebSockets. | + +## REST API Usage + +Create API credentials on Bybit's website: + +- [Livenet](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1) +- [Testnet](https://testnet.bybit.com/app/user/api-management) + +The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the [examples](./examples/) folder in the repository on GitHub: + +```typescript +const { RestClientV5 } = require('bybit-api'); +// or +// import { RestClientV5 } from 'bybit-api'; + +const restClientOptions = { + /** supports HMAC & RSA API keys - automatically detected */ + /** Your API key */ + key: 'apiKeyHere', + + /** Your API secret */ + secret: 'apiSecretHere', + + /** Set to `true` to connect to testnet. Uses the live environment by default. */ + // testnet: true, + + /** + * Set to `true` to use Bybit's V5 demo trading: + * https://bybit-exchange.github.io/docs/v5/demo * - */ -getP2POrders( - params: GetP2POrdersParamsV5, -): Promise> -⋮---- -/** - * Get P2P order details + * Note: to use demo trading, you should have `testnet` disabled. * + * You can find a detailed demoTrading example in the examples folder on GitHub. */ -getP2POrderDetail(params: { - orderId: string; -}): Promise> -⋮---- -/** - * Get pending P2P orders - */ -getP2PPendingOrders( - params: GetP2PPendingOrdersParamsV5, -): Promise> -⋮---- -/** - * Mark P2P order as paid - */ -markP2POrderAsPaid( - params: MarkP2POrderAsPaidParamsV5, -): Promise> -⋮---- -/** - * Release digital assets in a P2P order - */ -releaseP2POrder(params: { - orderId: string; -}): Promise> -⋮---- -/** - * Send chat message in a P2P order - */ -sendP2POrderMessage( - params: SendP2POrderMessageParamsV5, -): Promise> -⋮---- -/** - * Upload chat file for P2P order (Node.js only) - * - * Note: You must provide a Buffer. To upload from a file path, read it into a Buffer first: - * ```typescript - * import fs from 'fs'; - * const buffer = fs.readFileSync('./path/to/file.png'); - * await client.uploadP2PChatFile({ fileBuffer: buffer, fileName: 'file.png' }); - * ``` - * - * Supported file types: jpg, png, jpeg, pdf, mp4 + // demoTrading: true, + + /** Override the max size of the request window (in ms) */ + // recv_window: 5000, // 5000 = 5 seconds + + /** + * Enable keep alive for REST API requests (via axios). + * See: https://github.com/sieblyio/bybit-api/issues/368 */ -uploadP2PChatFile(params: { - fileBuffer: Buffer; - fileName: string; // Required: the filename (used for MIME type detection) - }): Promise< - APIResponseV3WithTime<{ - url: string; - type: string; - uploadId: string | null; - }> - > { - return this.postPrivateFile('/v5/p2p/oss/upload_file', params); -⋮---- -fileName: string; // Required: the filename (used for MIME type detection) -⋮---- -/** - * Get chat messages in a P2P order + // keepAlive: true, + + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over + * sockets being kept alive. Only relevant if keepAlive is set to true. + * Default: 1000 (defaults comes from https agent) */ -getP2POrderMessages( - params: GetP2POrderMessagesParamsV5, -): Promise> -⋮---- -/** + // keepAliveMsecs: 1000, // 1000 = 1 second + + /** + * Optionally override API domain used: + * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', + **/ + + // apiRegion: 'bytick', + + /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ + // parseAPIRateLimits: true, + + /** + * Allows you to provide a custom "signMessage" function, + * e.g. to use node crypto's much faster createHmac method * - * User P2P - */ -⋮---- -/** - * Get P2P user account information - */ -getP2PUserInfo(): Promise> -⋮---- -/** - * Get counterparty user information in a P2P order + * Look at examples/fasterHmacSign.ts for a demonstration: */ -getP2PCounterpartyUserInfo( - params: GetP2PCounterpartyUserInfoParamsV5, -): Promise> -⋮---- -/** - * Get user payment information + // customSignMessageFn: (message: string, secret: string) => Promise; +}; + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new RestClientV5( + { + key: API_KEY, + secret: API_SECRET, + // demoTrading: true, + + // Optional: enable to try parsing rate limit values from responses + // parseAPIRateLimits: true + }, + // requestLibraryOptions +); + +// For public-only API calls, simply don't provide a key & secret or set them to undefined +// const client = new RestClientV5(); + +client + .getAccountInfo() + .then((result) => { + console.log('getAccountInfo result: ', result); + }) + .catch((err) => { + console.error('getAccountInfo error: ', err); + }); + +client + .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) + .then((result) => { + console.log('getOrderBook result: ', result); + }) + .catch((err) => { + console.error('getOrderBook error: ', err); + }); +``` + +--- + +## WebSockets + +The WebsocketClient will automatically use the latest V5 WebSocket endpoints by default. To use a different endpoint, use the `market` parameter. Except for the WebSocket API - this can be accessed without any special configuration. + +## WebSocket Subscriptions - Consuming events + +Here's a minimal example for using the websocket client. For more complete examples, look into the ws-\* examples in the [examples](./examples/) folder in the repo on GitHub. + +```javascript +const { WebsocketClient } = require('bybit-api'); +// or +// import { WebsocketClient } from 'bybit-api'; + +const API_KEY = 'xxx'; +const PRIVATE_KEY = 'yyy'; + +const wsConfig = { + /** + * API credentials are optional. They are only required if you plan on using + * any account-specific topics or the WS API + * supports HMAC & RSA API keys - automatically detected */ -getP2PUserPayments(): Promise> -⋮---- -/** - * - ****** API Rate Limit Management APIs - * + key: 'yourAPIKeyHere', + secret: 'yourAPISecretHere', + + /* + The following parameters are optional: + */ + + /** + * Set to `true` to connect to Bybit's testnet environment. + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market + * data is very different from real market conditions. */ -⋮---- -/** - * Set API rate limit - * - * API rate limit: 50 req per second + // testnet: true + + /** + * Set to `true` to connect to Bybit's V5 demo trading: + * https://bybit-exchange.github.io/docs/v5/demo * - * INFO - * - If UID requesting this endpoint is a master account, uids in the input parameter must be subaccounts of the master account. - * - If UID requesting this endpoint is not a master account, uids in the input parameter must be the UID requesting this endpoint - * - UID requesting this endpoint must be an institutional user. + * Refer to the examples folder on GitHub for a more detailed demonstration. */ -setApiRateLimit(params: { - list: { - uids: string; - bizType: string; - rate: number; - }[]; - }): Promise< - APIResponseV3WithTime<{ - result: { - uids: string; - bizType: string; - rate: number; - success: boolean; - msg: string; - }[]; - }> - > { - return this.postPrivate('/v5/apilimit/set', params); -⋮---- -/** - * Query API rate limit - * - * API rate limit: 50 req per second - * - * INFO - * - A master account can query api rate limit of its own and subaccounts. - * - A subaccount can only query its own api rate limit. + // demoTrading: true, + + // recv window size for websocket authentication (higher latency connections + // (VPN) can cause authentication to fail if the recv window is too small) + // recvWindow: 5000, + + /** How often to check if the connection is alive (in ms) */ + // pingInterval: 10000, + + /** + * How long to wait (in ms) for a pong (heartbeat reply) before assuming the + * connection is dead */ -queryApiRateLimit(params: { uids: string }): Promise< - APIResponseV3WithTime<{ - list: { - uids: string; - bizType: string; - rate: number; - }[]; - }> - > { - return this.getPrivate('/v5/apilimit/query', params); -⋮---- -/** - * Get Rate Limit Cap - * Get your institution's total rate limit usage and cap, across the board. + // pongTimeout: 1000, + + /** Delay in milliseconds before respawning the connection */ + // reconnectTimeout: 500, + + // override which URL to use for websocket connections + // wsUrl: 'wss://stream.bytick.com/realtime' + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's + * much faster createHmac method * - * API rate limit: 50 req per second - * Main UIDs or sub UIDs can query this endpoint, but a main UID can only see the rate limits of subs below it. + * Look at examples/fasterHmacSign.ts for a demonstration: */ -getRateLimitCap(): Promise< - APIResponseV3WithTime<{ - list: { - bizType: string; - totalRate: number; - insCap: number; - uidCap: number; - }[]; - }> - > { - return this.getPrivate('/v5/apilimit/query-cap'); -⋮---- + // customSignMessageFn: (message: string, secret: string) => Promise; +}; + +const ws = new WebsocketClient(wsConfig); + +// (v5) subscribe to multiple topics at once +ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); + +// Or one at a time +ws.subscribeV5('kline.5.BTCUSDT', 'linear'); +ws.subscribeV5('kline.5.ETHUSDT', 'linear'); + +// Private/public topics can be used in the same WS client instance, even for +// different API groups (linear, options, spot, etc) +ws.subscribeV5('position', 'linear'); +ws.subscribeV5('publicTrade.BTC', 'option'); + /** - * Get All Rate Limits - * Query for all your UID-level rate limits, including all master accounts and subaccounts. + * The Websocket Client will automatically manage all connectivity & authentication for you. + * + * If a network issue occurs, it will automatically: + * - detect it, + * - remove the dead connection, + * - replace it with a new one, + * - resubscribe to everything you were subscribed to. + * + * When this happens, you will see the "reconnected" event. + */ + +// Listen to events coming from websockets. This is the primary data source +ws.on('update', (data) => { + console.log('data received', JSON.stringify(data, null, 2)); +}); + +// Optional: Listen to websocket connection open event +// (automatic after subscribing to one or more topics) +ws.on('open', ({ wsKey, event }) => { + console.log('connection open for websocket with ID: ', wsKey); +}); + +// Optional: Listen to responses to websocket queries +// (e.g. the response after subscribing to a topic) +ws.on('response', (response) => { + console.log('response', response); +}); + +// Optional: Listen to connection close event. +// Unexpected connection closes are automatically reconnected. +ws.on('close', () => { + console.log('connection closed'); +}); + +// Listen to raw error events. Recommended. +ws.on('exception', (err) => { + console.error('exception', err); +}); + +ws.on('reconnect', ({ wsKey }) => { + console.log('ws automatically reconnecting.... ', wsKey); +}); + +ws.on('reconnected', (data) => { + console.log('ws has reconnected ', data?.wsKey); +}); +``` + +## Websocket API - Sending orders via WebSockets + +Bybit supports sending, amending and cancelling orders over a WebSocket connection. The [WebsocketClient](./src/WebsocketClient.ts) fully supports Bybit's WebSocket API via the `sendWSAPIRequest(...)` method. There is also a dedicated [WebsocketAPIClient](./src/websocket-api-client.ts), built over the WSClient's sendWSAPIRequest mechanism for a simpler experience. + +Links for reference: + +- [Bybit WebSocket API Documentation](https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline) +- [WebsocketAPIClient example, use the Websocket API like a REST API](./examples/ws-api-client.ts) +- [Raw Asynchronous Websocket API Node.js/TypeScript/JavaScript example](./examples/ws-api-raw-promises.ts) + +Note: as of January 2025, the demo trading environment does not support the WebSocket API. + +There are two ways to use the WS API, depending on individual preference: + +1. event-driven: + - send requests via `client.sendWSAPIRequest(wsKey, operation, params)`, fire and forget + - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` + - See example for more details: [examples/ws-api-raw-events.ts](./examples/ws-api-raw-events.ts) +2. promise-driven: + - import the `WebsocketAPIClient` and use it much like a REST API. + - make an instance & call the Websocket API with a function. + - await responses, much like a REST API. + - use try/catch blocks to handle promise rejections + - See example for more details: [examples/ws-api-client.ts](./examples/ws-api-client.ts) + +The below example demonstrates the promise-driven approach, which behaves similar to a REST API. The WebSocket API even accepts the same parameters as the corresponding REST API endpoints, so this approach should be compatible with existing REST implementations. + +Connectivity, authentication and connecting requests & responses to promises - these are all handled automatically without additional configuration by the WebsocketClient. The WebsocketAPIClient is a wrapper built on top of this, providing dedicated methods for every available Websocket API command. Each method has fully typed requests & responses. Benefit from the capabilities of the WebSocket API without the complexity of managing asynchronous messaging over WebSockets. + +```javascript +const { WS_KEY_MAP, WebsocketAPIClient } = require('bybit-api'); + +// or +// import { WS_KEY_MAP, WebsocketAPIClient } from 'bybit-api'; + +// Create an instance of the WebsocketAPIClient. This is built on +// top of the WebsocketClient and will automatically handle WebSocket +// persistence and authentication for you. +// supports HMAC & RSA API keys - automatically detected +const wsClient = new WebsocketAPIClient({ + key: 'yourApiKeyHere', + secret: 'yourApiSecretHere', + + // Whether to use the testnet environment. + // Create testnet API keys here: https://testnet.bybit.com/app/user/api-management + // testnet: true, + + // Whether to use the livenet demo trading environment + // Note: As of Jan 2025, demo trading only supports consuming events, it does + // NOT support the WS API. + // demoTrading: false, + + // If you want your own event handlers instead of the default ones with logs, + // disable this setting and see ws-api-client example for more details. + // attachEventListeners: false +}); + +// This example is wrapped in an async function, so "await" can be used +async function main() { + /** + * Optional. Can be used to prepare a connection before sending + * commands (e.g. as part of your startup process). * - * API rate limit: 50 req per second + * This is not necessary and will happen automatically when + * sending a command, if you aren't connected/authenticated yet. */ -getAllRateLimits(params?: { - limit?: string; - cursor?: string; - uids?: string; - }): Promise< - APIResponseV3WithTime<{ - list: { - uids: string; - bizType: string; - rate: number; - }[]; - nextPageCursor: string; - }> - > { - return this.getPrivate('/v5/apilimit/query-all', params); + // await wsClient.getWSClient().connectWSAPI(); + + try { + console.log('Step 1: Create an order'); + const response = await wsClient.submitNewOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderType: 'Limit', + qty: '0.001', + side: 'Buy', + price: '50000', + }); + console.log('submitNewOrder response: ', response); + } catch (e) { + console.log('submitNewOrder error: ', e); + } + + try { + console.log('Step 2: Amend an order'); + const response = await wsClient.amendOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', + qty: '0.001', + price: '60000', + }); + console.log('amendOrder response: ', response); + } catch (e) { + console.log('amendOrder error: ', e); + } + + try { + console.log('Step 3: Cancel an order'); + const response = await wsClient.cancelOrder({ + category: 'linear', + symbol: 'BTCUSDT', + orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', + }); + console.log('cancelOrder response: ', response); + } catch (e) { + console.log('cancelOrder error: ', e); + } +} + +// Start executing the example workflow +main(); +``` + +--- + +### Balancing load across multiple connections + +The WebsocketClient will automatically prepare one connection per API group, for all topics in that API group. Any topics that you subscribe to on that WebSocket client will automatically be added to the same connection. + +To spread your subscribed topics over multiple connections, e.g. to reduce the throughput of an individual connectionk, you can make one instance of the WebsocketClient per connection group. + +```typescript +const wsClientGroup1 = new WebsocketClient(); +const wsClientGroup2 = new WebsocketClient(); + +// Attach event listeners to each WS Client +// Divide your desired topics into separate groups +``` + +Important: do not subscribe to the same topics on both clients or you will receive duplicate messages (once per WS client). + +--- + +## Bybit EU & Other Regions + +By default, this Node.js, JavaScript & TypeScript SDK uses the Bybit Global API & WebSocket domains. For regions where Bybit has dedicated regional domains, including the alternative Bybit Global domain (bytick), these can be configured in the REST Client using the `apiRegion` property. + +The following values are currently supported in this option: + +- `apiRegion: undefined`: if missing or undefined, this SDK will default to the Bybit Global domain `api.bybit.com`. +- `apiRegion: "default"`: the Bybit Global domain (same behaviour as above). +- `apiRegion: "bytick"`: the alternative Bybit Global domain `api.bytick.com`. +- `apiRegion: "NL"`: the dedicated Bybit Netherlands domain `api.bytick.nl`. +- `apiRegion: "TK"`: the dedicated Bybit Turkey domain `api.bybit-tr.com`. +- `apiRegion: "KZ"`: the dedicated Bybit Kazakhstan domain `api.bybit.kz`. +- `apiRegion: "HK"`: the dedicated Bybit HK domain `api.byhkbit.com`. +- `apiRegion: "GE"`: the dedicated Bybit Georgia domain `api.bybitgeorgia.ge`. +- `apiRegion: "UAE"`: the dedicated Bybit United Arab Emirates domain `api.bybit.ae`. +- `apiRegion: "EU"`: the dedicated Bybit EU/EEA domain `api.bybit.eu`. + +New regions will be supported when they become available in the Bybit API. If you notice any regions that have not been added yet, please open a new issue on GitHub. + +### REST API Usage with Bybit EU + +Below is an example for using this Node.js, TypeScript & JavaScript SDK for Bybit's APIs, using an account registered on the Bybit EU domain: + +```typescript +const { RestClientV5 } = require('bybit-api'); +// or +// import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + key: API_KEY, + secret: API_SECRET, + // demoTrading: true, + + apiRegion: 'EU', +}); + +client + .getAccountInfo() + .then((result) => { + console.log('getAccountInfo result: ', result); + }) + .catch((err) => { + console.error('getAccountInfo error: ', err); + }); +``` + +--- + +## Logging + +### Customise logging + +Pass a custom logger (or mutate the imported DefaultLogger class) which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired, as in the example below: + +```javascript +const { WebsocketClient, DefaultLogger } = require('bybit-api'); + +// Enable all logging on the trace level (disabled by default) +const customLogger = { + ...DefaultLogger, + trace: (...params) => console.log('trace', ...params), +}; + +const wsClient = new WebsocketClient( + { key: 'xxx', secret: 'yyy' }, + 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 `BYBITTRACE` 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 stream-browserify + ``` +2. Add this to your `tsconfig.json` + ```json + { + "compilerOptions": { + "paths": { + "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/sieblyio/bybit-api/image)](https://github.com/sieblyio/bybit-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` +- 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 + + + + +### 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=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/htx-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/htx-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) + + ================ File: package.json ================ { "name": "bybit-api", - "version": "4.6.6", + "version": "4.7.4", "description": "Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", @@ -21760,9 +22657,10 @@ File: package.json "author": "Tiago Siebler (https://siebly.io)", "contributors": [], "dependencies": { + "@types/ws": "^8.18.1", "axios": "^1.13.2", "isomorphic-ws": "^4.0.1", - "ws": "^7.4.0" + "ws": "8.21.1" }, "devDependencies": { "@types/jest": "^29.5.11", @@ -21781,7 +22679,6 @@ File: package.json "ts-node": "^10.9.2", "typescript": "^5.7.3", "webpack": "^5.4.0", - "webpack-bundle-analyzer": "^4.10.2", "webpack-cli": "^4.2.0" }, "keywords": [ @@ -21809,12 +22706,12 @@ File: package.json "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/tiagosiebler/bybit-api" + "url": "git+https://github.com/sieblyio/bybit-api.git" }, "bugs": { - "url": "https://github.com/tiagosiebler/bybit-api/issues" + "url": "https://github.com/bybit/bybit-api/issues" }, - "homepage": "https://github.com/tiagosiebler/bybit-api#readme" + "homepage": "https://siebly.io/sdk/bybit/javascript/tutorial" } diff --git a/package-lock.json b/package-lock.json index cd969b3b..74e4c973 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bybit-api", - "version": "4.7.3", + "version": "4.7.4", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "bybit-api", - "version": "4.7.3", + "version": "4.7.4", "license": "MIT", "dependencies": { "@types/ws": "^8.18.1", diff --git a/package.json b/package.json index e16d0228..dc21cafb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bybit-api", - "version": "4.7.3", + "version": "4.7.4", "description": "Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", diff --git a/src/rest-client-v5.ts b/src/rest-client-v5.ts index 75960f0f..bffda0aa 100644 --- a/src/rest-client-v5.ts +++ b/src/rest-client-v5.ts @@ -187,6 +187,8 @@ import { FeeGroupStructureResponseV5, FeeRateV5, FiatTradingPairListV5, + FixedLoanAvailableInventoryV5, + FixedRateAvailableInventoryV5, FixedRateBorrowContractInfoV5, FixedRateBorrowOrderInfoV5, FixedRateBorrowParamsV5, @@ -196,6 +198,8 @@ import { FixedTermEarnPlaceOrderResultV5, FixedTermEarnPositionListV5, FixedTermEarnProductListV5, + FlexibleAvailableInventoryV5, + FlexibleLoanAvailableInventoryV5, FriendReferralRecordV5, FundingAccountTransactionRecordV5, FundingRateHistoryResponseV5, @@ -282,13 +286,18 @@ import { GetFeeGroupStructureParamsV5, GetFeeRateParamsV5, GetFiatTradingPairListParamsV5, + GetFixedLoanAvailableInventoryParamsV5, + GetFixedRateAvailableInventoryParamsV5, GetFixedRateBorrowContractInfoParamsV5, GetFixedRateBorrowOrderInfoParamsV5, GetFixedRateBorrowOrderQuoteParamsV5, GetFixedTermEarnOrderListParamsV5, GetFixedTermEarnPositionParamsV5, GetFixedTermEarnProductParamsV5, + GetFlexibleAvailableInventoryParamsV5, + GetFlexibleLoanAvailableInventoryParamsV5, GetFriendReferralsParamsV5, + GetFullDepthOrderbookParamsV5, GetFundingAccountTransactionHistoryParamsV5, GetFundingRateHistoryParamsV5, GetFuturesLeverageParamsV5, @@ -301,6 +310,9 @@ import { GetInternalDepositRecordParamsV5, GetInternalTransferParamsV5, GetKlineParamsV5, + GetLaunchpoolProjectListParamsV5, + GetLaunchpoolUserActivityLogParamsV5, + GetLaunchpoolUserHistoryParamsV5, GetLiquidityMiningProductParamsV5, GetLoanLTVAdjustmentHistoryParamsV5, GetLongShortRatioParamsV5, @@ -331,6 +343,7 @@ import { GetPreUpgradeTransactionLogParamsV5, GetPreUpgradeUSDCSessionParamsV5, GetPublicTradingHistoryParamsV5, + GetPuzzleProjectListParamsV5, GetPwmAllFundOrdersParamsV5, GetPwmAllFundsParamsV5, GetPwmAssetManagerInvestmentPlansParamsV5, @@ -344,6 +357,7 @@ import { GetRepaymentHistoryFixedParamsV5, GetRepaymentHistoryFlexibleParamsV5, GetRepaymentHistoryParamsV5, + GetRFQDetailsParamsV5, GetRFQHistoryParamsV5, GetRFQListParamsV5, GetRFQPublicTradesParamsV5, @@ -374,6 +388,8 @@ import { GetSupplyOrderQuoteFixedParamsV5, GetSystemStatusParamsV5, GetTickersParamsV5, + GetTokenSplashProjectListParamsV5, + GetTokenSplashUserActivityParamsV5, GetTotalMembersAssetsParamsV5, GetTradeInfoForAnalysisParamsV5, GetTransactionLogParamsV5, @@ -397,6 +413,10 @@ import { InvestMorePwmInvestmentPlanParamsV5, InvestMorePwmInvestmentPlanResultV5, IssueVoucherParamsV5, + LaunchpoolActivityLogResultV5, + LaunchpoolCurrentStakingResultV5, + LaunchpoolProjectListResultV5, + LaunchpoolUserHistoryResultV5, LiquidityMiningProductResultV5, LoanLTVAdjustmentHistoryV5, LongShortRatioV5, @@ -454,6 +474,7 @@ import { PreUpgradeTransaction, PreUpgradeUSDCSessionSettlement, PublicTradeV5, + PuzzleProjectListResultV5, PwmAllFundOrdersResultV5, PwmAllFundsResultV5, PwmAssetManagerInvestmentPlansResultV5, @@ -475,6 +496,7 @@ import { RedeemFixedTermEarnResultV5, RedeemPwmInvestmentPlanParamsV5, RedeemPwmInvestmentPlanResultV5, + ReferralCodesResultV5, RenewBorrowOrderFixedParamsV5, RenewBorrowOrderFixedV5, RenewFixedRateBorrowParamsV5, @@ -494,6 +516,7 @@ import { RepaymentHistoryV5, RequestConvertQuoteParamsV5, RFQConfigV5, + RFQDetailItemV5, RFQHistory, RFQPublicTradeV5, RFQQuoteItemV5, @@ -557,6 +580,8 @@ import { TickerLinearInverseV5, TickerOptionV5, TickerSpotV5, + TokenSplashProjectListResultV5, + TokenSplashUserActivityResultV5, TotalMembersAssetsResultV5, TPSLModeV5, TradeInfoForAnalysisResultV5, @@ -960,6 +985,12 @@ export class RestClientV5 extends BaseRestClient { return this.get('/v5/market/orderbook', params); } + getFullDepthOrderbook( + params: GetFullDepthOrderbookParamsV5, + ): Promise> { + return this.get('/v5/market/full_orderbook', params); + } + /** * Get RPI Orderbook * Query for orderbook depth data with RPI (Retail Price Improvement) information. @@ -1968,7 +1999,7 @@ export class RestClientV5 extends BaseRestClient { */ getSMPGroup(): Promise< APIResponseV3WithTime<{ - smpGroup: number; + smpGroup: string; }> > { return this.getPrivate('/v5/account/smp-group'); @@ -2893,6 +2924,10 @@ export class RestClientV5 extends BaseRestClient { return this.getPrivate('/v5/user/invitation/referrals', params); } + getReferralCode(): Promise> { + return this.getPrivate('/v5/user/invitation/code'); + } + /** * Sign Agreement * To trade commodity contracts (e.g. metals XAU/XAG perps, crude oil perps), complete the agreement signing first. @@ -3555,6 +3590,24 @@ export class RestClientV5 extends BaseRestClient { return this.postPrivate('/v5/spot-margin-trade/fixedborrow-renew', params); } + getFlexibleAvailableInventory( + params: GetFlexibleAvailableInventoryParamsV5, + ): Promise> { + return this.getPrivate( + '/v5/spot-margin-trade/flexible-available-inventory', + params, + ); + } + + getFixedRateAvailableInventory( + params: GetFixedRateAvailableInventoryParamsV5, + ): Promise> { + return this.getPrivate( + '/v5/spot-margin-trade/fixed-available-inventory', + params, + ); + } + /** * ****** Spot Margin Trade APIs (Normal) @@ -4128,6 +4181,15 @@ export class RestClientV5 extends BaseRestClient { ); } + getFlexibleLoanAvailableInventory( + params: GetFlexibleLoanAvailableInventoryParamsV5, + ): Promise> { + return this.getPrivate( + '/v5/crypto-loan-flexible/available-inventory', + params, + ); + } + /** * ****** Fixed Loan @@ -4341,6 +4403,12 @@ export class RestClientV5 extends BaseRestClient { return this.getPrivate('/v5/crypto-loan-fixed/renew-info', params); } + getFixedLoanAvailableInventory( + params: GetFixedLoanAvailableInventoryParamsV5, + ): Promise> { + return this.getPrivate('/v5/crypto-loan-fixed/available-inventory', params); + } + /** * ****** Institutional Lending @@ -5497,6 +5565,15 @@ export class RestClientV5 extends BaseRestClient { return this.postPrivate('/v5/rfq/accept-other-quote', params); } + getRFQDetails(params?: GetRFQDetailsParamsV5): Promise< + APIResponseV3WithTime<{ + cursor: string; + list: RFQDetailItemV5[]; + }> + > { + return this.getPrivate('/v5/rfq/rfq-detail-list', params); + } + /** * ****** P2P TRADING @@ -5809,4 +5886,55 @@ export class RestClientV5 extends BaseRestClient { > { return this.getPrivate('/v5/apilimit/query-all', params); } + + /** + * + ****** Spot-X (Launchpool / Puzzle / Token Splash) + * + */ + + getLaunchpoolProjectList( + params: GetLaunchpoolProjectListParamsV5, + ): Promise> { + return this.get('/v5/spot-x/launchpool/project/list', params); + } + + getLaunchpoolUserActivityLog( + params?: GetLaunchpoolUserActivityLogParamsV5, + ): Promise> { + return this.postPrivate('/v5/spot-x/launchpool/user/activity-log', params); + } + + getLaunchpoolCurrentStaking(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/spot-x/launchpool/user/current-staking'); + } + + getLaunchpoolUserHistory( + params?: GetLaunchpoolUserHistoryParamsV5, + ): Promise> { + return this.postPrivate('/v5/spot-x/launchpool/user/history', params); + } + + getPuzzleProjectList( + params: GetPuzzleProjectListParamsV5, + ): Promise> { + return this.get('/v5/spot-x/puzzle/project/list', params); + } + + getTokenSplashProjectList( + params: GetTokenSplashProjectListParamsV5, + ): Promise> { + return this.get('/v5/spot-x/token-splash/project/list', params); + } + + getTokenSplashUserActivityParams( + params?: GetTokenSplashUserActivityParamsV5, + ): Promise> { + return this.getPrivate( + '/v5/spot-x/token-splash/user/activity-params', + params, + ); + } } diff --git a/src/types/request/index.ts b/src/types/request/index.ts index 0a3c0313..863d522e 100644 --- a/src/types/request/index.ts +++ b/src/types/request/index.ts @@ -28,6 +28,7 @@ export * from './v5-pre-upgrade'; export * from './v5-rfq'; export * from './v5-rwa'; export * from './v5-spot-leverage-token'; +export * from './v5-spot-x'; export * from './v5-spreadtrading'; export * from './v5-strategy'; export * from './v5-trade'; diff --git a/src/types/request/v5-crypto-loan.ts b/src/types/request/v5-crypto-loan.ts index f1e4d635..d67536e7 100644 --- a/src/types/request/v5-crypto-loan.ts +++ b/src/types/request/v5-crypto-loan.ts @@ -133,12 +133,23 @@ export interface CreateBorrowOrderFixedParamsV5 { term: string; autoRepay?: string; // Deprecated repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan + strategyType?: 'PARTIAL' | 'FULL'; collateralList?: { currency: string; amount: string; }[]; } +export interface GetFixedLoanAvailableInventoryParamsV5 { + currency: string; + term: string; + annualRate: string; +} + +export interface GetFlexibleLoanAvailableInventoryParamsV5 { + currency: string; +} + export interface CreateSupplyOrderFixedParamsV5 { orderCurrency: string; orderAmount: string; diff --git a/src/types/request/v5-market.ts b/src/types/request/v5-market.ts index 27e7ab13..53430dc2 100644 --- a/src/types/request/v5-market.ts +++ b/src/types/request/v5-market.ts @@ -169,3 +169,8 @@ export interface GetLongShortRatioParamsV5 { limit?: number; cursor?: string; } + +export interface GetFullDepthOrderbookParamsV5 { + category: 'spot' | 'linear' | 'inverse'; + symbol: string; +} diff --git a/src/types/request/v5-rfq.ts b/src/types/request/v5-rfq.ts index 58b829c3..9bdd9854 100644 --- a/src/types/request/v5-rfq.ts +++ b/src/types/request/v5-rfq.ts @@ -6,12 +6,21 @@ export interface RFQTransactionV5 { isLeverage?: boolean; // For spot lending, default false } +export interface RFQHedgeLegV5 { + category: string; + symbol: string; + side: string; + qty: string; + price?: string; +} + export interface CreateRFQParamsV5 { counterparties: string[]; // Array of deskCode rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters anonymous?: boolean; // Whether it is anonymous inquiry, default false strategyType?: string; // Inquiry label, max 36 characters list: RFQTransactionV5[]; // Transaction list, up to 10 sets + hedge?: RFQHedgeLegV5[]; } export interface CancelRFQParamsV5 { @@ -39,6 +48,24 @@ export interface ExecuteRFQQuoteParamsV5 { rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteSide: 'buy' | 'sell'; // The direction of the quote + isHedge?: boolean; +} + +export interface GetRFQDetailsParamsV5 { + rfqId?: string; + rfqLinkId?: string; + status?: + | 'Active' + | 'PendingFill' + | 'Canceled' + | 'Filled' + | 'Expired' + | 'Failed'; + traderType?: 'quote' | 'request'; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } export interface CancelRFQQuoteParamsV5 { diff --git a/src/types/request/v5-spot-leverage-token.ts b/src/types/request/v5-spot-leverage-token.ts index 9b06654f..f9de1dca 100644 --- a/src/types/request/v5-spot-leverage-token.ts +++ b/src/types/request/v5-spot-leverage-token.ts @@ -120,3 +120,13 @@ export interface RenewFixedRateBorrowParamsV5 { loanId: string; qty?: string; } + +export interface GetFlexibleAvailableInventoryParamsV5 { + currency: string; +} + +export interface GetFixedRateAvailableInventoryParamsV5 { + currency: string; + term: string; + annualRate: string; +} diff --git a/src/types/request/v5-spot-x.ts b/src/types/request/v5-spot-x.ts new file mode 100644 index 00000000..20eef266 --- /dev/null +++ b/src/types/request/v5-spot-x.ts @@ -0,0 +1,47 @@ +export interface GetLaunchpoolProjectListParamsV5 { + status: number; + activityCoin?: string; + projectId?: string; + cursor?: string; + limit?: number; +} + +export interface GetLaunchpoolUserActivityLogParamsV5 { + stakeCoin?: string; + type?: number; + status?: number; + startTime?: string; + endTime?: string; + pageSize?: number; + current?: number; +} + +export interface GetLaunchpoolUserHistoryParamsV5 { + stakeCoin?: string; + rewardCoin?: string; + startTime?: string; + endTime?: string; + pageSize?: number; + current?: number; +} + +export interface GetPuzzleProjectListParamsV5 { + status: number; + projectId?: string; + activityCoin?: string; + cursor?: string; + limit?: number; +} + +export interface GetTokenSplashProjectListParamsV5 { + status: number; + projectId?: string; + activityCoin?: string; + cursor?: string; + limit?: number; +} + +export interface GetTokenSplashUserActivityParamsV5 { + projectId?: string; + activityCoin?: string; +} diff --git a/src/types/response/contract.ts b/src/types/response/contract.ts index 1a77dddb..8782b67c 100644 --- a/src/types/response/contract.ts +++ b/src/types/response/contract.ts @@ -45,7 +45,7 @@ export interface ContractHistoricOrder { closeOnTrigger: boolean; blockTradeId: string; smpType: string; - smpGroup: number; + smpGroup: string; smpOrderId: string; } diff --git a/src/types/response/index.ts b/src/types/response/index.ts index 05049f7a..53a00317 100644 --- a/src/types/response/index.ts +++ b/src/types/response/index.ts @@ -25,6 +25,7 @@ export * from './v5-preupgrade'; export * from './v5-rfq'; export * from './v5-rwa'; export * from './v5-spot-leverage-token'; +export * from './v5-spot-x'; export * from './v5-spreadtrading'; export * from './v5-strategy'; export * from './v5-trade'; diff --git a/src/types/response/v5-account.ts b/src/types/response/v5-account.ts index b5f33743..20a9e8f4 100644 --- a/src/types/response/v5-account.ts +++ b/src/types/response/v5-account.ts @@ -117,6 +117,7 @@ export interface UserSettingConfigV5 { fmsef?: boolean; /** Delta Neutral mode; may be absent on older API responses. */ deltaEnable?: boolean; + smpType?: '0' | '1' | '2' | '3' | string; } export interface TransactionLogV5 { @@ -141,6 +142,7 @@ export interface TransactionLogV5 { orderLinkId: string; extraFees: string; transSubType: string; + displayType?: string; } export interface MMPStateV5 { diff --git a/src/types/response/v5-asset.ts b/src/types/response/v5-asset.ts index 13736ae8..ebf05977 100644 --- a/src/types/response/v5-asset.ts +++ b/src/types/response/v5-asset.ts @@ -120,6 +120,7 @@ export interface DepositRecordV5 { batchReleaseLimit: string; depositType: string; fromAddress: string; + travelRuleStatus?: string; } export interface SubmitDepositOriginatorInfoResultV5 { @@ -135,6 +136,7 @@ export interface InternalDepositRecordV5 { address: string; createdTime: string; txID: string; + complianceStatus?: string; } export interface DepositAddressChainV5 { diff --git a/src/types/response/v5-crypto-loan.ts b/src/types/response/v5-crypto-loan.ts index a5296689..bb44b392 100644 --- a/src/types/response/v5-crypto-loan.ts +++ b/src/types/response/v5-crypto-loan.ts @@ -281,6 +281,21 @@ export interface BorrowOrderInfoFixedV5 { state: number; term: number; repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment + strategyType?: 'PARTIAL' | 'FULL' | string; +} + +export interface FixedLoanAvailableInventoryV5 { + currency: string; + term: string; + annualRate: string; + availableInventory: string; + updateTime: string; +} + +export interface FlexibleLoanAvailableInventoryV5 { + currency: string; + availableInventory: string; + updateTime: string; } export interface SupplyOrderInfoFixedV5 { @@ -374,6 +389,7 @@ export interface InstitutionalLendingCoinDeltaItemV5 { export interface InstitutionalLendingCoinDeltaAmountV5 { riskUnitDeltaAmount: string; riskUnitDeltaAvailableAmount: string; + riskUnitDelta?: string; list: InstitutionalLendingCoinDeltaItemV5[]; } diff --git a/src/types/response/v5-earn.ts b/src/types/response/v5-earn.ts index fb14af64..a17d5359 100644 --- a/src/types/response/v5-earn.ts +++ b/src/types/response/v5-earn.ts @@ -226,6 +226,8 @@ export interface HoldToEarnAirdropProductYieldV5 { coinName: string; /** Yesterday's APR for display, e.g. "10%", "0%" */ apy: string; + personalApy?: string; + multiplier?: string; } export interface HoldToEarnAirdropProductV5 { @@ -235,6 +237,7 @@ export interface HoldToEarnAirdropProductV5 { announcementUrl: string; /** Yesterday's avg APR across yield coins */ apy: string; + personalApy?: string; } export interface HoldToEarnAirdropProductsResultV5 { diff --git a/src/types/response/v5-rfq.ts b/src/types/response/v5-rfq.ts index 6a2bc23d..7259d2d4 100644 --- a/src/types/response/v5-rfq.ts +++ b/src/types/response/v5-rfq.ts @@ -83,6 +83,14 @@ export interface RFQLegV5 { isLeverage?: boolean; // For spot lending } +export interface RFQHedgeLegItemV5 { + category: string; + symbol: string; + side: string; + qty: string; + price?: string; +} + export interface RFQItemV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Custom ID for inquiry form @@ -98,9 +106,11 @@ export interface RFQItemV5 { | 'Failed'; // Status acceptOtherQuoteStatus?: string; // Whether to accept non-LP quotes. "false": do not accept, "true": accept deskCode: string; // Unique identification code of the inquiry party + anonymous?: boolean; createdAt: number; // Time when the trade is created in epoch updatedAt: number; // Time when the trade is updated in epoch legs: RFQLegV5[]; // Combination transaction + hedge?: RFQHedgeLegItemV5[]; } export interface GetRFQRealtimeResultV5 { @@ -118,6 +128,7 @@ export interface QuoteLegV5 { price: string; // Order price or quote price qty?: string; // Order quantity isLeverage?: boolean; // For spot lending + isHedge?: boolean; } export interface RFQQuoteItemV5 { @@ -127,6 +138,7 @@ export interface RFQQuoteItemV5 { quoteLinkId: string; // Quotation custom ID expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Unique identification code of quotation party + anonymous?: boolean; status: | 'Active' | 'Canceled' @@ -190,3 +202,59 @@ export interface RFQPublicTradeV5 { export interface AcceptNonLPQuoteResultV5 { rfqId: string; // Inquiry ID } + +export interface RFQDetailQuoteLegV5 { + category: string; + symbol: string; + price: string; + qty: string; + isHedge?: boolean; +} + +export interface RFQDetailQuoteV5 { + quoteId: string; + deskCode: string; + anonymous?: boolean; + status: string; + createdAt: string; + updatedAt: string; + expiresAt: string; + quoteBuyList?: RFQDetailQuoteLegV5[]; + quoteSellList?: RFQDetailQuoteLegV5[]; +} + +export interface RFQDetailTradeLegV5 { + category: string; + orderId: string; + symbol: string; + side: string; + price: string; + qty: string; + markPrice: string; + execFee: string; + extraFees: string; + execId: string; + resultCode: number; + resultMessage: string; + rejectParty: string; +} + +export interface RFQDetailItemV5 { + rfqId: string; + rfqLinkId: string; + counterparties: string[]; + expiresAt: string; + strategyType: string; + status: string; + acceptOtherQuoteStatus?: boolean; + execQuoteId?: string; + execQuoteSide?: string; + deskCode: string; + anonymous?: boolean; + createdAt: string; + updatedAt: string; + legs: RFQLegV5[]; + hedge?: RFQHedgeLegItemV5[]; + quoteList?: RFQDetailQuoteV5[]; + tradeLegs?: RFQDetailTradeLegV5[]; +} diff --git a/src/types/response/v5-spot-leverage-token.ts b/src/types/response/v5-spot-leverage-token.ts index 318dfc2a..707cbbdd 100644 --- a/src/types/response/v5-spot-leverage-token.ts +++ b/src/types/response/v5-spot-leverage-token.ts @@ -204,3 +204,17 @@ export interface FixedRateBorrowQuoteV5 { annualRate: string; qty: string; } + +export interface FlexibleAvailableInventoryV5 { + currency: string; + availableInventory: string; + updateTime: string; +} + +export interface FixedRateAvailableInventoryV5 { + currency: string; + term: string; + annualRate: string; + availableInventory: string; + updateTime: string; +} diff --git a/src/types/response/v5-spot-x.ts b/src/types/response/v5-spot-x.ts new file mode 100644 index 00000000..a6020a7b --- /dev/null +++ b/src/types/response/v5-spot-x.ts @@ -0,0 +1,122 @@ +export interface LaunchpoolPoolV5 { + poolId: string; + stakeCoin: string; + apr: string; + totalStakedAmount: string; + participantCount: string; +} + +export interface LaunchpoolProjectV5 { + projectId: string; + activityCoin: string; + rewardCoin: string; + status: number; + totalReward: string; + stakeStartTime: string; + stakeEndTime: string; + totalParticipantCount: string; + pools: LaunchpoolPoolV5[]; +} + +export interface LaunchpoolProjectListResultV5 { + list: LaunchpoolProjectV5[]; + nextPageCursor: string; +} + +export interface LaunchpoolActivityLogItemV5 { + stakeCoin: string; + rewardCoin: string; + amount: string; + type: number; + status: number; + createdTime: string; + orderId: string; +} + +export interface LaunchpoolActivityLogResultV5 { + list: LaunchpoolActivityLogItemV5[]; + total: number; + pageSize: number; + current: number; +} + +export interface LaunchpoolStakingPositionV5 { + stakeCoin: string; + rewardCoin: string; + stakeAmount: string; + totalReward: string; + autoRedeemDate: string; +} + +export interface LaunchpoolCurrentStakingResultV5 { + totalInvestmentUsd: string; + totalEarningsUsd: string; + todayEarningsUsd: string; + list: LaunchpoolStakingPositionV5[]; +} + +export interface LaunchpoolUserHistoryItemV5 { + stakeCoin: string; + rewardCoin: string; + totalReward: string; + stakeStartTime: string; + stakeEndTime: string; +} + +export interface LaunchpoolUserHistoryResultV5 { + list: LaunchpoolUserHistoryItemV5[]; + total: number; + pageSize: number; + current: number; +} + +export interface PuzzleProjectV5 { + projectId: string; + activityCoin: string; + rewardCoin: string; + status: number; + startTime: string; + endTime: string; + totalReward: string; + participantCount: string; +} + +export interface PuzzleProjectListResultV5 { + list: PuzzleProjectV5[]; + nextPageCursor: string; +} + +export interface TokenSplashProjectV5 { + status: number; + projectId: string; + activityCoin: string; + rewardCoin: string; + totalReward: string; + participantCount: string; + registrationStartTime: string; + activityEndTime: string; +} + +export interface TokenSplashProjectListResultV5 { + list: TokenSplashProjectV5[]; + nextPageCursor: string; +} + +export interface TokenSplashTradeTaskV5 { + tradeRequiredAmount: string; + tradeUnit: string; + tradedAmount: string; + maxRewardAmount: string; + estimatedRewardAmount: string; + rewardCoin: string; +} + +export interface TokenSplashUserActivityItemV5 { + projectId: string; + activityCoin: string; + tradeTask: TokenSplashTradeTaskV5; +} + +export interface TokenSplashUserActivityResultV5 { + list: TokenSplashUserActivityItemV5[]; +} diff --git a/src/types/response/v5-trade.ts b/src/types/response/v5-trade.ts index a111c40e..487d5e85 100644 --- a/src/types/response/v5-trade.ts +++ b/src/types/response/v5-trade.ts @@ -66,7 +66,7 @@ export interface AccountOrderV5 { closeOnTrigger: boolean; placeType: 'iv' | 'price' | ''; smpType: string; - smpGroup: number; + smpGroup: string; smpOrderId: string; createdTime: string; updatedTime: string; diff --git a/src/types/response/v5-user.ts b/src/types/response/v5-user.ts index 34d257b6..ac71b949 100644 --- a/src/types/response/v5-user.ts +++ b/src/types/response/v5-user.ts @@ -193,3 +193,13 @@ export interface FriendReferralRecordV5 { createdAt: string; updatedAt: string; } + +export interface ReferralCodeItemV5 { + referralCode: string; + referralLink: string; + scene: number; +} + +export interface ReferralCodesResultV5 { + referralCodes: ReferralCodeItemV5[]; +} diff --git a/src/types/shared-v5.ts b/src/types/shared-v5.ts index 8d8a5ed2..05f96778 100644 --- a/src/types/shared-v5.ts +++ b/src/types/shared-v5.ts @@ -327,7 +327,8 @@ export type TransactionTypeV5 = | 'INSTITUTION_LOAN_RESERVE_IN' | 'INSTITUTION_LOAN_RESERVE_OUT' | 'PLATFORM_TOKEN_MNT_LIQRECALLEDMMNT' - | 'PLATFORM_TOKEN_MNT_LIQRETURNEDMNT'; + | 'PLATFORM_TOKEN_MNT_LIQRETURNEDMNT' + | 'DIVIDEND_SETTLEMENT'; export type PermissionTypeV5 = | 'ContractTrade' @@ -367,6 +368,7 @@ export type ExecTypeV5 = | 'Settle' | 'BlockTrade' | 'MovePosition' + | 'CorporateAction' | 'UNKNOWN'; /** diff --git a/src/types/websockets/ws-events.ts b/src/types/websockets/ws-events.ts index ca7ac430..2424f877 100644 --- a/src/types/websockets/ws-events.ts +++ b/src/types/websockets/ws-events.ts @@ -326,7 +326,7 @@ export interface WSAccountOrderV5 { closeOnTrigger: boolean; placeType: string; smpType: OrderSMPTypeV5; - smpGroup: number; + smpGroup: string; smpOrderId: string; createdTime: string; updatedTime: string; diff --git a/src/util/BaseRestClient.ts b/src/util/BaseRestClient.ts index 6135cf47..c1d178d2 100644 --- a/src/util/BaseRestClient.ts +++ b/src/util/BaseRestClient.ts @@ -149,6 +149,9 @@ export default abstract class BaseRestClient { headers: { ...networkOptions.headers, 'x-referer': isEUAPIRegion(this.options) ? APIIDEU : APIID, + ...(this.options.siteId + ? { 'x-site-id': this.options.siteId } + : undefined), }, }; diff --git a/src/util/requestUtils.ts b/src/util/requestUtils.ts index 2b8a5977..80e807f6 100644 --- a/src/util/requestUtils.ts +++ b/src/util/requestUtils.ts @@ -11,7 +11,8 @@ export type APIRegion = | 'HK' | 'GE' | 'UAE' - | 'EU'; + | 'EU' + | 'JP'; export interface RestClientOptions { /** Your API key */ @@ -76,6 +77,9 @@ export interface RestClientOptions { apiRegion?: APIRegion; + /** Site ID header for regional access (e.g. 'ARG_BTL' for Argentina) */ + siteId?: string; + /** Default: true. whether to try and post-process request exceptions. */ parse_exceptions?: boolean; @@ -146,6 +150,7 @@ export function getRestBaseUrl( GE: 'https://api.bybitgeorgia.ge', UAE: 'https://api.bybit.ae', EU: 'https://api.bybit.eu', + JP: 'https://api.manepa.jp', }; const exchangeBaseUrls = { @@ -163,6 +168,9 @@ export function getRestBaseUrl( } if (useTestnet) { + if (restClientOptions.apiRegion === 'JP') { + return 'https://api-testnet.manepa.jp'; + } return exchangeBaseUrls.testnet; } diff --git a/src/util/websockets/websocket-util.ts b/src/util/websockets/websocket-util.ts index 7d95a660..bfa6975f 100644 --- a/src/util/websockets/websocket-util.ts +++ b/src/util/websockets/websocket-util.ts @@ -279,30 +279,55 @@ export function getWsUrl( const isDemoTrading = wsClientOptions.demoTrading; const isTestnet = wsClientOptions.testnet; const networkKey = isTestnet ? 'testnet' : 'livenet'; + const isJP = wsClientOptions.restOptions?.apiRegion === 'JP'; switch (wsKey) { case WS_KEY_MAP.v5Private: { if (isDemoTrading) { return DEMO_TRADING_ENDPOINT; } + if (isJP) { + const base = isTestnet + ? 'stream-testnet.manepa.jp' + : 'stream.manepa.jp'; + return `wss://${base}/v5/private`; + } return WS_BASE_URL_MAP.v5.private[networkKey]; } case WS_KEY_MAP.v5PrivateTrade: { if (isDemoTrading) { return DEMO_TRADING_ENDPOINT; } + if (isJP) { + const base = isTestnet + ? 'stream-testnet.manepa.jp' + : 'stream.manepa.jp'; + return `wss://${base}/v5/trade`; + } return WS_BASE_URL_MAP[wsKey].private[networkKey]; } case WS_KEY_MAP.v5SpotPublic: { + if (isJP) { + return 'wss://stream.manepa.jp/v5/public/spot'; + } return WS_BASE_URL_MAP.v5SpotPublic.public[networkKey]; } case WS_KEY_MAP.v5LinearPublic: { + if (isJP) { + return 'wss://stream.manepa.jp/v5/public/linear'; + } return WS_BASE_URL_MAP.v5LinearPublic.public[networkKey]; } case WS_KEY_MAP.v5InversePublic: { + if (isJP) { + return 'wss://stream.manepa.jp/v5/public/inverse'; + } return WS_BASE_URL_MAP.v5InversePublic.public[networkKey]; } case WS_KEY_MAP.v5OptionPublic: { + if (isJP) { + return 'wss://stream.manepa.jp/v5/public/option'; + } return WS_BASE_URL_MAP.v5OptionPublic.public[networkKey]; } default: {