diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index f35f3880..09406268 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -49,358 +49,392 @@ 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#L595) | :closed_lock_with_key: | GET | `/v5/system/status` | -| [getServerTime()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L612) | | GET | `/v5/market/time` | -| [requestDemoTradingFunds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L624) | :closed_lock_with_key: | POST | `/v5/account/demo-apply-money` | -| [createDemoAccount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L637) | :closed_lock_with_key: | POST | `/v5/user/create-demo-member` | -| [getSpreadInstrumentsInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L650) | | GET | `/v5/spread/instrument` | -| [getSpreadOrderbook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L662) | | GET | `/v5/spread/orderbook` | -| [getSpreadTickers()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L672) | | GET | `/v5/spread/tickers` | -| [getSpreadRecentTrades()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L683) | | GET | `/v5/spread/recent-trade` | -| [getSpreadMaxQty()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L695) | :closed_lock_with_key: | GET | `/v5/spread/max-qty` | -| [submitSpreadOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L704) | :closed_lock_with_key: | POST | `/v5/spread/order/create` | -| [amendSpreadOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L717) | :closed_lock_with_key: | POST | `/v5/spread/order/amend` | -| [cancelSpreadOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L729) | :closed_lock_with_key: | POST | `/v5/spread/order/cancel` | -| [cancelAllSpreadOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L747) | :closed_lock_with_key: | POST | `/v5/spread/order/cancel-all` | -| [getSpreadOpenOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L766) | :closed_lock_with_key: | GET | `/v5/spread/order/realtime` | -| [getSpreadOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L783) | :closed_lock_with_key: | GET | `/v5/spread/order/history` | -| [getSpreadTradeHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L799) | :closed_lock_with_key: | GET | `/v5/spread/execution/list` | -| [getKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L819) | | GET | `/v5/market/kline` | -| [getMarkPriceKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L836) | | GET | `/v5/market/mark-price-kline` | -| [getIndexPriceKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L851) | | GET | `/v5/market/index-price-kline` | -| [getPremiumIndexPriceKline()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L866) | | GET | `/v5/market/premium-index-price-kline` | -| [getInstrumentsInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L882) | | GET | `/v5/market/instruments-info` | -| [getOrderbook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L893) | | GET | `/v5/market/orderbook` | -| [getRPIOrderbook()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L907) | | GET | `/v5/market/rpi_orderbook` | -| [getTickers()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L913) | | GET | `/v5/market/tickers` | -| [getFundingRateHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L951) | | GET | `/v5/market/funding/history` | -| [getPublicTradingHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L966) | | GET | `/v5/market/recent-trade` | -| [getOpenInterest()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L979) | | GET | `/v5/market/open-interest` | -| [getHistoricalVolatility()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L989) | | GET | `/v5/market/historical-volatility` | -| [getInsurance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1000) | | GET | `/v5/market/insurance` | -| [getRiskLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1011) | | GET | `/v5/market/risk-limit` | -| [getOptionDeliveryPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1026) | | GET | `/v5/market/delivery-price` | -| [getDeliveryPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1039) | | GET | `/v5/market/delivery-price` | -| [getNewDeliveryPrice()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1055) | | GET | `/v5/market/new-delivery-price` | -| [getLongShortRatio()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1071) | | GET | `/v5/market/account-ratio` | -| [getIndexPriceComponents()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1081) | | GET | `/v5/market/index-price-components` | -| [getOrderPriceLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1087) | | GET | `/v5/market/price-limit` | -| [getADLAlert()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1101) | | GET | `/v5/market/adlAlert` | -| [getFeeGroupStructure()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1114) | | GET | `/v5/market/fee-group-info` | -| [submitOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1126) | :closed_lock_with_key: | POST | `/v5/order/create` | -| [amendOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1132) | :closed_lock_with_key: | POST | `/v5/order/amend` | -| [cancelOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1138) | :closed_lock_with_key: | POST | `/v5/order/cancel` | -| [getActiveOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1147) | :closed_lock_with_key: | GET | `/v5/order/realtime` | -| [cancelAllOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1153) | :closed_lock_with_key: | POST | `/v5/order/cancel-all` | -| [getHistoricOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1166) | :closed_lock_with_key: | GET | `/v5/order/history` | -| [getExecutionList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1178) | :closed_lock_with_key: | GET | `/v5/execution/list` | -| [batchSubmitOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1196) | :closed_lock_with_key: | POST | `/v5/order/create-batch` | -| [batchAmendOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1221) | :closed_lock_with_key: | POST | `/v5/order/amend-batch` | -| [batchCancelOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1246) | :closed_lock_with_key: | POST | `/v5/order/cancel-batch` | -| [getSpotBorrowCheck()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1268) | :closed_lock_with_key: | GET | `/v5/order/spot-borrow-check` | -| [setDisconnectCancelAllWindow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1289) | :closed_lock_with_key: | POST | `/v5/order/disconnected-cancel-all` | -| [setDisconnectCancelAllWindowV2()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1307) | :closed_lock_with_key: | POST | `/v5/order/disconnected-cancel-all` | -| [preCheckOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1322) | :closed_lock_with_key: | POST | `/v5/order/pre-check` | -| [createStrategyOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1339) | :closed_lock_with_key: | POST | `/v5/strategy/create` | -| [getStrategyList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1350) | :closed_lock_with_key: | GET | `/v5/strategy/list` | -| [getStrategyOrderList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1361) | :closed_lock_with_key: | GET | `/v5/strategy/order-list` | -| [stopStrategy()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1372) | :closed_lock_with_key: | POST | `/v5/strategy/stop` | -| [getPositionInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1397) | :closed_lock_with_key: | GET | `/v5/position/list` | -| [setLeverage()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1412) | :closed_lock_with_key: | POST | `/v5/position/set-leverage` | -| [switchIsolatedMargin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1425) | :closed_lock_with_key: | POST | `/v5/position/switch-isolated` | -| [setTPSLMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1439) | :closed_lock_with_key: | POST | `/v5/position/set-tpsl-mode` | -| [switchPositionMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1454) | :closed_lock_with_key: | POST | `/v5/position/switch-mode` | -| [setRiskLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1468) | :closed_lock_with_key: | POST | `/v5/position/set-risk-limit` | -| [setTradingStop()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1483) | :closed_lock_with_key: | POST | `/v5/position/trading-stop` | -| [setAutoAddMargin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1494) | :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#L1506) | :closed_lock_with_key: | POST | `/v5/position/add-margin` | -| [getClosedPnL()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1518) | :closed_lock_with_key: | GET | `/v5/position/closed-pnl` | -| [getClosedOptionsPositions()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1532) | :closed_lock_with_key: | GET | `/v5/position/get-closed-positions` | -| [movePosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1557) | :closed_lock_with_key: | POST | `/v5/position/move-positions` | -| [getMovePositionHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1568) | :closed_lock_with_key: | GET | `/v5/position/move-history` | -| [confirmNewRiskLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1587) | :closed_lock_with_key: | POST | `/v5/position/confirm-pending-mmr` | -| [getPreUpgradeOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1607) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/order/history` | -| [getPreUpgradeTradeHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1622) | :closed_lock_with_key: | GET | `/v5/pre-upgrade/execution/list` | -| [getPreUpgradeClosedPnl()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1633) | :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#L1647) | :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#L1664) | :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#L1678) | :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#L1699) | :closed_lock_with_key: | GET | `/v5/account/wallet-balance` | -| [getTransferableAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1710) | :closed_lock_with_key: | GET | `/v5/account/withdrawal` | -| [getAccountInstrumentsInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1727) | :closed_lock_with_key: | GET | `/v5/account/instruments-info` | -| [upgradeToUnifiedAccount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1738) | :closed_lock_with_key: | POST | `/v5/account/upgrade-to-uta` | -| [getBorrowHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1749) | :closed_lock_with_key: | GET | `/v5/account/borrow-history` | -| [repayLiability()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1770) | :closed_lock_with_key: | POST | `/v5/account/quick-repayment` | -| [manualRepay()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1795) | :closed_lock_with_key: | POST | `/v5/account/repay` | -| [setCollateralCoin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1804) | :closed_lock_with_key: | POST | `/v5/account/set-collateral-switch` | -| [batchSetCollateralCoin()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1810) | :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#L1820) | :closed_lock_with_key: | GET | `/v5/account/collateral-info` | -| [getCoinGreeks()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1829) | :closed_lock_with_key: | GET | `/v5/asset/coin-greeks` | -| [getFeeRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1842) | :closed_lock_with_key: | GET | `/v5/account/fee-rate` | -| [getAccountInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1851) | :closed_lock_with_key: | GET | `/v5/account/info` | -| [getDCPInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1864) | :closed_lock_with_key: | GET | `/v5/account/query-dcp-info` | -| [getTransactionLog()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1871) | :closed_lock_with_key: | GET | `/v5/account/transaction-log` | -| [getClassicTransactionLogs()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1882) | :closed_lock_with_key: | GET | `/v5/account/contract-transaction-log` | -| [getSMPGroup()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1893) | :closed_lock_with_key: | GET | `/v5/account/smp-group` | -| [setMarginMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1906) | :closed_lock_with_key: | POST | `/v5/account/set-margin-mode` | -| [setSpotHedging()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1923) | :closed_lock_with_key: | POST | `/v5/account/set-hedging-mode` | -| [setLimitPriceAction()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1936) | :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#L1947) | :closed_lock_with_key: | GET | `/v5/account/user-setting-config` | -| [setDeltaNeutralMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1955) | :closed_lock_with_key: | POST | `/v5/account/set-delta-mode` | -| [setMMP()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1964) | :closed_lock_with_key: | POST | `/v5/account/mmp-modify` | -| [resetMMP()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1971) | :closed_lock_with_key: | POST | `/v5/account/mmp-reset` | -| [getMMPState()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1978) | :closed_lock_with_key: | GET | `/v5/account/mmp-state` | -| [getOptionAssetInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1988) | :closed_lock_with_key: | GET | `/v5/account/option-asset-info` | -| [getPayInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L1998) | :closed_lock_with_key: | GET | `/v5/account/pay-info` | -| [getTradeInfoForAnalysis()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2008) | :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#L2028) | :closed_lock_with_key: | GET | `/v5/asset/asset-overview` | -| [getPortfolioMarginInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2038) | :closed_lock_with_key: | GET | `/v5/asset/portfolio-margin` | -| [getTotalMembersAssets()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2048) | :closed_lock_with_key: | GET | `/v5/asset/total-members-assets` | -| [getFundingAccountTransactionHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2060) | :closed_lock_with_key: | GET | `/v5/asset/fundinghistory` | -| [getDeliveryRecord()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2076) | :closed_lock_with_key: | GET | `/v5/asset/delivery-record` | -| [getSettlementRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2087) | :closed_lock_with_key: | GET | `/v5/asset/settlement-record` | -| [getCoinExchangeRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2100) | :closed_lock_with_key: | GET | `/v5/asset/exchange/order-record` | -| [getCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2115) | :closed_lock_with_key: | GET | `/v5/asset/coin/query-info` | -| [getSubUID()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2129) | :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#L2144) | :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#L2155) | :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#L2169) | :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#L2183) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/withdrawable-amount` | -| [getTransferableCoinList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2192) | :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#L2208) | :closed_lock_with_key: | POST | `/v5/asset/transfer/inter-transfer` | -| [getInternalTransferRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2227) | :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#L2247) | :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#L2258) | :closed_lock_with_key: | POST | `/v5/asset/transfer/universal-transfer` | -| [getUniversalTransferRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2270) | :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#L2283) | :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#L2298) | :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#L2314) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-record` | -| [getSubAccountDepositRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2329) | :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#L2345) | :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#L2357) | :closed_lock_with_key: | GET | `/v5/asset/deposit/query-address` | -| [getSubDepositAddress()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2375) | :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#L2400) | :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#L2420) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/query-record` | -| [getWithdrawalAddressList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2432) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/query-address` | -| [getExchangeEntities()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2446) | :closed_lock_with_key: | GET | `/v5/asset/withdraw/vasp/list` | -| [submitWithdrawal()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2461) | :closed_lock_with_key: | POST | `/v5/asset/withdraw/create` | -| [cancelWithdrawal()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2472) | :closed_lock_with_key: | POST | `/v5/asset/withdraw/cancel` | -| [getConvertCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2481) | :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#L2492) | :closed_lock_with_key: | POST | `/v5/asset/exchange/quote-apply` | -| [confirmConvertQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2501) | :closed_lock_with_key: | POST | `/v5/asset/exchange/convert-execute` | -| [getConvertStatus()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2513) | :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#L2532) | :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#L2549) | :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#L2563) | :closed_lock_with_key: | GET | `/v5/fiat/query-coin-list` | -| [createSubMember()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2581) | :closed_lock_with_key: | POST | `/v5/user/create-sub-member` | -| [createSubUIDAPIKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2593) | :closed_lock_with_key: | POST | `/v5/user/create-sub-api` | -| [getSubUIDList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2602) | :closed_lock_with_key: | GET | `/v5/user/query-sub-members` | -| [getSubUIDListUnlimited()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2611) | :closed_lock_with_key: | GET | `/v5/user/submembers` | -| [setSubUIDFrozenState()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2629) | :closed_lock_with_key: | POST | `/v5/user/frozen-sub-member` | -| [getQueryApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2644) | :closed_lock_with_key: | GET | `/v5/user/query-api` | -| [getSubAccountAllApiKeys()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2651) | :closed_lock_with_key: | GET | `/v5/user/sub-apikeys` | -| [getUIDWalletType()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2660) | :closed_lock_with_key: | GET | `/v5/user/get-member-type` | -| [updateMasterApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2679) | :closed_lock_with_key: | POST | `/v5/user/update-api` | -| [updateSubApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2693) | :closed_lock_with_key: | POST | `/v5/user/update-sub-api` | -| [deleteSubMember()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2706) | :closed_lock_with_key: | POST | `/v5/user/del-submember` | -| [deleteMasterApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2721) | :closed_lock_with_key: | POST | `/v5/user/delete-api` | -| [deleteSubApiKey()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2735) | :closed_lock_with_key: | POST | `/v5/user/delete-sub-api` | -| [getAffiliateUserList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2755) | :closed_lock_with_key: | GET | `/v5/affiliate/aff-user-list` | -| [getAffiliateSubAffiliateList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2773) | :closed_lock_with_key: | GET | `/v5/affiliate/affiliate-sub-list` | -| [getAffiliateUserInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2789) | :closed_lock_with_key: | GET | `/v5/user/aff-customer-info` | -| [getFriendReferrals()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2801) | :closed_lock_with_key: | GET | `/v5/user/invitation/referrals` | -| [signAgreement()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2822) | :closed_lock_with_key: | POST | `/v5/user/agreement` | -| [getAlphaTradeQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2839) | :closed_lock_with_key: | POST | `/v5/alpha/trade/quote` | -| [executeAlphaTradePurchase()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2850) | :closed_lock_with_key: | POST | `/v5/alpha/trade/purchase` | -| [executeAlphaTradeRedeem()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2861) | :closed_lock_with_key: | POST | `/v5/alpha/trade/redeem` | -| [getAlphaPayTokenList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2871) | :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#L2881) | :closed_lock_with_key: | POST | `/v5/alpha/trade/order-list` | -| [getAlphaBizTokenList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2891) | :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#L2901) | :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#L2911) | :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#L2921) | :closed_lock_with_key: | POST | `/v5/alpha/trade/asset-list` | -| [getAlphaAssetDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2929) | :closed_lock_with_key: | POST | `/v5/alpha/trade/asset-detail` | -| [getVIPMarginData()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2949) | | GET | `/v5/spot-margin-trade/data` | -| [getHistoricalInterestRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L2960) | :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#L2985) | :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#L2997) | :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#L3008) | :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#L3016) | :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#L3027) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/state` | -| [manualBorrow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3034) | :closed_lock_with_key: | POST | `/v5/account/borrow` | -| [getMaxBorrowableAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3043) | :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#L3052) | :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#L3063) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/coinstate` | -| [getAvailableAmountToRepay()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3074) | :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#L3093) | :closed_lock_with_key: | POST | `/v5/account/no-convert-repay` | -| [getAutoRepayMode()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3106) | :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#L3122) | :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#L3134) | :closed_lock_with_key: | GET | `/v5/spot-margin-trade/liability` | -| [submitFixedRateBorrow()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3143) | :closed_lock_with_key: | POST | `/v5/spot-margin-trade/fixedborrow` | -| [getFixedRateBorrowOrderInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3152) | :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#L3169) | :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#L3186) | :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#L3198) | :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#L3213) | :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#L3230) | :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#L3247) | :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#L3265) | :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#L3289) | :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#L3300) | :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#L3315) | :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#L3344) | :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#L3373) | :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#L3393) | | GET | `/v5/crypto-loan/collateral-data` | -| [getBorrowableCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3410) | | GET | `/v5/crypto-loan/loanable-data` | -| [getAccountBorrowCollateralLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3428) | :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#L3448) | :closed_lock_with_key: | POST | `/v5/crypto-loan/borrow` | -| [repayCryptoLoan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3469) | :closed_lock_with_key: | POST | `/v5/crypto-loan/repay` | -| [getUnpaidLoanOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3485) | :closed_lock_with_key: | GET | `/v5/crypto-loan/ongoing-orders` | -| [getRepaymentHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3506) | :closed_lock_with_key: | GET | `/v5/crypto-loan/repayment-history` | -| [getCompletedLoanOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3526) | :closed_lock_with_key: | GET | `/v5/crypto-loan/borrow-history` | -| [getMaxAllowedReductionCollateralAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3545) | :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#L3564) | :closed_lock_with_key: | POST | `/v5/crypto-loan/adjust-ltv` | -| [getLoanLTVAdjustmentHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3588) | :closed_lock_with_key: | GET | `/v5/crypto-loan/adjustment-history` | -| [getLoanBorrowableCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3609) | | GET | `/v5/crypto-loan-common/loanable-data` | -| [getLoanCollateralCoins()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3621) | | GET | `/v5/crypto-loan-common/collateral-data` | -| [getMaxCollateralAmount()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3631) | :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#L3650) | :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#L3660) | :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#L3671) | :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#L3686) | :closed_lock_with_key: | GET | `/v5/crypto-loan-common/position` | -| [borrowFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3703) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/borrow` | -| [repayFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3714) | :closed_lock_with_key: | POST | `/v5/crypto-loan-flexible/repay` | -| [repayCollateralFlexible()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3724) | :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#L3738) | :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#L3750) | :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#L3763) | :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#L3788) | | GET | `/v5/crypto-loan-fixed/supply-order-quote` | -| [getBorrowOrderQuoteFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3801) | | GET | `/v5/crypto-loan-fixed/borrow-order-quote` | -| [createBorrowOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3814) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/borrow` | -| [createSupplyOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3827) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/supply` | -| [cancelBorrowOrderFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3837) | :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#L3851) | :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#L3864) | :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#L3882) | :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#L3900) | :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#L3913) | :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#L3927) | :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#L3938) | :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#L3951) | :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#L3968) | :closed_lock_with_key: | POST | `/v5/crypto-loan-fixed/renew` | -| [getRenewOrderInfoFixed()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L3981) | :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#L3999) | | GET | `/v5/ins-loan/product-infos` | -| [getInstitutionalLendingMarginCoinInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4009) | | GET | `/v5/ins-loan/ensure-tokens` | -| [getInstitutionalLendingMarginCoinInfoWithConversionRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4018) | | GET | `/v5/ins-loan/ensure-tokens-convert` | -| [getInstitutionalLendingLoanOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4027) | :closed_lock_with_key: | GET | `/v5/ins-loan/loan-order` | -| [getInstitutionalLendingRepayOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4039) | :closed_lock_with_key: | GET | `/v5/ins-loan/repaid-history` | -| [getInstitutionalLendingLTV()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4051) | :closed_lock_with_key: | GET | `/v5/ins-loan/ltv` | -| [getInstitutionalLendingLTVWithLadderConversionRate()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4060) | :closed_lock_with_key: | GET | `/v5/ins-loan/ltv-convert` | -| [bindOrUnbindUID()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4075) | :closed_lock_with_key: | POST | `/v5/ins-loan/association-uid` | -| [repayInstitutionalLoan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4095) | :closed_lock_with_key: | POST | `/v5/ins-loan/repay-loan` | -| [getExchangeBrokerEarnings()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4116) | :closed_lock_with_key: | GET | `/v5/broker/earnings-info` | -| [getExchangeBrokerAccountInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4129) | :closed_lock_with_key: | GET | `/v5/broker/account-info` | -| [getBrokerSubAccountDeposits()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4145) | :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#L4160) | :closed_lock_with_key: | POST | `/v5/broker/award/info` | -| [issueBrokerVoucher()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4172) | :closed_lock_with_key: | POST | `/v5/broker/award/distribute-award` | -| [getBrokerIssuedVoucher()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4184) | :closed_lock_with_key: | POST | `/v5/broker/award/distribution-record` | -| [setBrokerRateLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4201) | :closed_lock_with_key: | POST | `/v5/broker/apilimit/set` | -| [getBrokerRateLimitCap()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4220) | :closed_lock_with_key: | GET | `/v5/broker/apilimit/query-cap` | -| [getAllBrokerRateLimits()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4238) | :closed_lock_with_key: | GET | `/v5/broker/apilimit/query-all` | -| [getEarnProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4258) | | GET | `/v5/earn/product` | -| [getHoldToEarnAirdropProducts()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4271) | | GET | `/v5/earn/hold-to-earn/product` | -| [getAdvanceEarnProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4282) | | GET | `/v5/earn/advance/product` | -| [getLiquidityMiningProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4293) | | GET | `/v5/earn/liquidity-mining/product` | -| [getFixedTermEarnProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4304) | | GET | `/v5/earn/fixed-term/product` | -| [getAdvanceEarnProductExtraInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4316) | | GET | `/v5/earn/advance/product-extra-info` | -| [submitAdvanceEarnPlaceOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4327) | :closed_lock_with_key: | POST | `/v5/earn/advance/place-order` | -| [getAdvanceEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4338) | :closed_lock_with_key: | GET | `/v5/earn/advance/position` | -| [getAdvanceEarnOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4349) | :closed_lock_with_key: | GET | `/v5/earn/advance/order` | -| [submitFixedTermEarnOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4360) | :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#L4371) | :closed_lock_with_key: | POST | `/v5/earn/fixed-term/redeem` | -| [getFixedTermEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4382) | :closed_lock_with_key: | GET | `/v5/earn/fixed-term/position` | -| [getFixedTermEarnOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4393) | :closed_lock_with_key: | GET | `/v5/earn/fixed-term/order` | -| [setFixedTermEarnAutoInvest()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4404) | :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#L4420) | :closed_lock_with_key: | POST | `/v5/earn/place-order` | -| [getEarnOrderHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4439) | :closed_lock_with_key: | GET | `/v5/earn/order` | -| [getEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4457) | :closed_lock_with_key: | GET | `/v5/earn/position` | -| [modifyEarnPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4470) | :closed_lock_with_key: | POST | `/v5/earn/position/modify` | -| [getEarnYieldHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4483) | :closed_lock_with_key: | GET | `/v5/earn/yield` | -| [getHoldToEarnAirdropYieldHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4497) | :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#L4508) | :closed_lock_with_key: | GET | `/v5/earn/hourly-yield` | -| [getEarnAprHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4522) | | GET | `/v5/earn/apr-history` | -| [getEarnTokenProduct()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4532) | | GET | `/v5/earn/token/product` | -| [submitEarnTokenOrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4541) | :closed_lock_with_key: | POST | `/v5/earn/token/place-order` | -| [getEarnTokenOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4550) | :closed_lock_with_key: | GET | `/v5/earn/token/order` | -| [getEarnTokenPosition()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4562) | :closed_lock_with_key: | GET | `/v5/earn/token/position` | -| [getEarnTokenDailyYield()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4571) | :closed_lock_with_key: | GET | `/v5/earn/token/yield` | -| [getEarnTokenHourlyYield()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4583) | :closed_lock_with_key: | GET | `/v5/earn/token/hourly-yield` | -| [getEarnTokenHistoryApr()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4595) | | GET | `/v5/earn/token/history-apr` | -| [getPwmInvestmentPlanList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4610) | :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#L4619) | :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#L4628) | :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#L4637) | :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#L4646) | :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#L4655) | :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#L4664) | :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#L4673) | :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#L4682) | :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#L4691) | :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#L4700) | | GET | `/v5/earn/pwm/customize-plan/product` | -| [createPwmCustomizeInvestmentPlan()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4709) | :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#L4724) | :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#L4733) | :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#L4742) | :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#L4751) | :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#L4765) | :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#L4777) | :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#L4791) | :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#L4800) | :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#L4809) | :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#L4821) | :closed_lock_with_key: | POST | `/v5/earn/pwm/fund-transfer` | -| [getPwmFundTransferRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4830) | :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#L4845) | :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#L4854) | :closed_lock_with_key: | POST | `/v5/card/reward/points/balance` | -| [queryCardPointsRecords()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4861) | :closed_lock_with_key: | POST | `/v5/card/reward/points/records` | -| [queryCardPointsTier()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4870) | :closed_lock_with_key: | POST | `/v5/card/reward/points/tier` | -| [queryCardMallItemList()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4877) | :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#L4886) | :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#L4902) | :closed_lock_with_key: | POST | `/v5/rfq/create-rfq` | -| [getRFQConfig()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4913) | :closed_lock_with_key: | GET | `/v5/rfq/config` | -| [cancelRFQ()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4922) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-rfq` | -| [cancelAllRFQ()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4932) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-all-rfq` | -| [createRFQQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4941) | :closed_lock_with_key: | POST | `/v5/rfq/create-quote` | -| [executeRFQQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4952) | :closed_lock_with_key: | POST | `/v5/rfq/execute-quote` | -| [cancelRFQQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4963) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-quote` | -| [cancelAllRFQQuotes()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4973) | :closed_lock_with_key: | POST | `/v5/rfq/cancel-all-quotes` | -| [getRFQRealtimeInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4987) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-realtime` | -| [getRFQHistory()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L4999) | :closed_lock_with_key: | GET | `/v5/rfq/rfq-list` | -| [getRFQRealtimeQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5013) | :closed_lock_with_key: | GET | `/v5/rfq/quote-realtime` | -| [getRFQHistoryQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5028) | :closed_lock_with_key: | GET | `/v5/rfq/quote-list` | -| [getRFQTrades()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5041) | :closed_lock_with_key: | GET | `/v5/rfq/trade-list` | -| [getRFQPublicTrades()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5054) | :closed_lock_with_key: | GET | `/v5/rfq/public-trades` | -| [acceptNonLPQuote()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5070) | :closed_lock_with_key: | POST | `/v5/rfq/accept-other-quote` | -| [getP2PAccountCoinsBalance()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5092) | :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#L5109) | :closed_lock_with_key: | POST | `/v5/p2p/item/online` | -| [createP2PAd()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5118) | :closed_lock_with_key: | POST | `/v5/p2p/item/create` | -| [cancelP2PAd()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5127) | :closed_lock_with_key: | POST | `/v5/p2p/item/cancel` | -| [updateP2PAd()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5141) | :closed_lock_with_key: | POST | `/v5/p2p/item/update` | -| [getP2PPersonalAds()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5151) | :closed_lock_with_key: | POST | `/v5/p2p/item/personal/list` | -| [getP2PAdDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5160) | :closed_lock_with_key: | POST | `/v5/p2p/item/info` | -| [getP2POrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5175) | :closed_lock_with_key: | POST | `/v5/p2p/order/simplifyList` | -| [getP2POrderDetail()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5185) | :closed_lock_with_key: | POST | `/v5/p2p/order/info` | -| [getP2PPendingOrders()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5194) | :closed_lock_with_key: | POST | `/v5/p2p/order/pending/simplifyList` | -| [markP2POrderAsPaid()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5203) | :closed_lock_with_key: | POST | `/v5/p2p/order/pay` | -| [releaseP2POrder()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5212) | :closed_lock_with_key: | POST | `/v5/p2p/order/finish` | -| [sendP2POrderMessage()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5221) | :closed_lock_with_key: | POST | `/v5/p2p/order/message/send` | -| [getP2POrderMessages()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5255) | :closed_lock_with_key: | POST | `/v5/p2p/order/message/listpage` | -| [getP2PUserInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5269) | :closed_lock_with_key: | POST | `/v5/p2p/user/personal/info` | -| [getP2PCounterpartyUserInfo()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5276) | :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#L5285) | :closed_lock_with_key: | POST | `/v5/p2p/user/payment/list` | -| [setApiRateLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5305) | :closed_lock_with_key: | POST | `/v5/apilimit/set` | -| [queryApiRateLimit()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5334) | :closed_lock_with_key: | GET | `/v5/apilimit/query` | -| [getRateLimitCap()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5353) | :closed_lock_with_key: | GET | `/v5/apilimit/query-cap` | -| [getAllRateLimits()](https://github.com/tiagosiebler/bybit-api/blob/master/src/rest-client-v5.ts#L5372) | :closed_lock_with_key: | GET | `/v5/apilimit/query-all` | +| [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` | # websocket-api-client.ts diff --git a/examples/apidoc/V5/Alpha/LP/execute-redeem.js b/examples/apidoc/V5/Alpha/LP/execute-redeem.js new file mode 100644 index 00000000..3f3a1cac --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/execute-redeem.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.executeAlphaLPRedeem({ positionId: 12345, poolAddress: '0x1234567890abcdef', dercRatio: '0.5' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/execute-stake.js b/examples/apidoc/V5/Alpha/LP/execute-stake.js new file mode 100644 index 00000000..34ceba1d --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/execute-stake.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.executeAlphaLPStake({ positionId: 0, poolAddress: '0x1234567890abcdef', payTokenAmount: '1000', payTokenCode: 'CEX_1', rangeUpper: '2000', rangeLower: '1800' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/get-order-list.js b/examples/apidoc/V5/Alpha/LP/get-order-list.js new file mode 100644 index 00000000..95f54188 --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/get-order-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getAlphaLPOrderList({ orderType: 0, days: 7, limit: 20, pageIndex: 1 }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/get-pay-token-list.js b/examples/apidoc/V5/Alpha/LP/get-pay-token-list.js new file mode 100644 index 00000000..f4c9081d --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/get-pay-token-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getAlphaLPPayTokenList({}) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/get-pay-token-price.js b/examples/apidoc/V5/Alpha/LP/get-pay-token-price.js new file mode 100644 index 00000000..e22d72ce --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/get-pay-token-price.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getAlphaLPPayTokenPrice({ tokenCode: ['CEX_1', 'CEX_2'] }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/get-pool-info.js b/examples/apidoc/V5/Alpha/LP/get-pool-info.js new file mode 100644 index 00000000..e772abe8 --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/get-pool-info.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getAlphaLPPoolInfo({ poolAddress: '0x1234567890abcdef' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/get-pool-list.js b/examples/apidoc/V5/Alpha/LP/get-pool-list.js new file mode 100644 index 00000000..9632f8db --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/get-pool-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getAlphaLPPoolList({ tokenSymbol: 'ETH' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/LP/get-position-list.js b/examples/apidoc/V5/Alpha/LP/get-position-list.js new file mode 100644 index 00000000..51128040 --- /dev/null +++ b/examples/apidoc/V5/Alpha/LP/get-position-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getAlphaLPPositionList() + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/execute-buy.js b/examples/apidoc/V5/Alpha/Prediction/execute-buy.js new file mode 100644 index 00000000..ba20e2e3 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/execute-buy.js @@ -0,0 +1,23 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .executeAlphaPredictionBuy({ + tokenId: 'token_yes_123', + amount: '100', + payTokenCode: 'USDC', + orderType: 1, + slippage: '0.05', + eventId: 'event_123', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/execute-sell.js b/examples/apidoc/V5/Alpha/Prediction/execute-sell.js new file mode 100644 index 00000000..8321c622 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/execute-sell.js @@ -0,0 +1,23 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .executeAlphaPredictionSell({ + tokenId: 'token_yes_123', + size: '50', + orderType: 1, + slippage: '0.05', + eventId: 'event_123', + toTokenCode: 'USDC', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-engine-status.js b/examples/apidoc/V5/Alpha/Prediction/get-engine-status.js new file mode 100644 index 00000000..58f679ac --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-engine-status.js @@ -0,0 +1,16 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionEngineStatus() + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-event-detail.js b/examples/apidoc/V5/Alpha/Prediction/get-event-detail.js new file mode 100644 index 00000000..9a4bc3f8 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-event-detail.js @@ -0,0 +1,18 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionEventDetail({ + slug: 'will-argentina-win-world-cup-2026', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-order-book.js b/examples/apidoc/V5/Alpha/Prediction/get-order-book.js new file mode 100644 index 00000000..f5df9f0e --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-order-book.js @@ -0,0 +1,18 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionOrderBook({ + tokenIds: ['token_yes_123'], + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-order-estimate.js b/examples/apidoc/V5/Alpha/Prediction/get-order-estimate.js new file mode 100644 index 00000000..6899fd59 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-order-estimate.js @@ -0,0 +1,23 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionOrderEstimate({ + tokenId: 'token_yes_123', + side: 1, + eventId: 'event_123', + amount: '100', + orderType: 1, + payTokenCode: 'USDC', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-order-list.js b/examples/apidoc/V5/Alpha/Prediction/get-order-list.js new file mode 100644 index 00000000..ee565a62 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-order-list.js @@ -0,0 +1,20 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionOrderList({ + limit: 20, + pageIndex: 1, + days: 7, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-pay-token-list.js b/examples/apidoc/V5/Alpha/Prediction/get-pay-token-list.js new file mode 100644 index 00000000..a2d93b2b --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-pay-token-list.js @@ -0,0 +1,16 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionPayTokenList() + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-portfolio-summary.js b/examples/apidoc/V5/Alpha/Prediction/get-portfolio-summary.js new file mode 100644 index 00000000..d3edc951 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-portfolio-summary.js @@ -0,0 +1,16 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionPortfolioSummary({}) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-position-history.js b/examples/apidoc/V5/Alpha/Prediction/get-position-history.js new file mode 100644 index 00000000..3ccac955 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-position-history.js @@ -0,0 +1,20 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionPositionHistory({ + limit: 20, + pageIndex: 1, + days: 30, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-position-list.js b/examples/apidoc/V5/Alpha/Prediction/get-position-list.js new file mode 100644 index 00000000..a0bf3008 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-position-list.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionPositionList({ + limit: 20, + pageIndex: 1, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-price-history.js b/examples/apidoc/V5/Alpha/Prediction/get-price-history.js new file mode 100644 index 00000000..6010e57e --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-price-history.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionPriceHistory({ + tokenId: 'token_yes_123', + interval: '1h', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-side-market-list.js b/examples/apidoc/V5/Alpha/Prediction/get-side-market-list.js new file mode 100644 index 00000000..408707b8 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-side-market-list.js @@ -0,0 +1,21 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionSideMarketList({ + eventId: 'event_123', + sortBy: 'volume', + limit: 20, + pageIndex: 1, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-sports-group-stage-detail.js b/examples/apidoc/V5/Alpha/Prediction/get-sports-group-stage-detail.js new file mode 100644 index 00000000..b7abfc3a --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-sports-group-stage-detail.js @@ -0,0 +1,19 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionSportsGroupStageDetail({ + eventType: 1, + groupName: 'A', + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-sports-match-list.js b/examples/apidoc/V5/Alpha/Prediction/get-sports-match-list.js new file mode 100644 index 00000000..433e6178 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-sports-match-list.js @@ -0,0 +1,21 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionSportsMatchList({ + eventType: 1, + status: 2, + limit: 20, + pageIndex: 1, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-sports-timeline-stages.js b/examples/apidoc/V5/Alpha/Prediction/get-sports-timeline-stages.js new file mode 100644 index 00000000..9e3c7a03 --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-sports-timeline-stages.js @@ -0,0 +1,18 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionSportsTimelineStages({ + eventType: 1, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Alpha/Prediction/get-token-price.js b/examples/apidoc/V5/Alpha/Prediction/get-token-price.js new file mode 100644 index 00000000..07603fbf --- /dev/null +++ b/examples/apidoc/V5/Alpha/Prediction/get-token-price.js @@ -0,0 +1,18 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getAlphaPredictionTokenPrice({ + tokenIds: ['token_yes_123', 'token_no_123'], + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Asset/submit-deposit-originator-info.js b/examples/apidoc/V5/Asset/submit-deposit-originator-info.js new file mode 100644 index 00000000..7a5ef97b --- /dev/null +++ b/examples/apidoc/V5/Asset/submit-deposit-originator-info.js @@ -0,0 +1,26 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.submitDepositOriginatorInfo({ + depositId: 1234567890, + subAccountId: 0, + questionnaire: JSON.stringify({ + walletType: 0, + vaspCode: 'BINANCEUS_VASP', + legalType: 'individual', + firstName: 'John', + lastName: 'Smith', + transactionPurpose: 'Personal investment in long-term holdings', + }), + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Earn/RWA/get-nav-chart.js b/examples/apidoc/V5/Earn/RWA/get-nav-chart.js new file mode 100644 index 00000000..2bb0792d --- /dev/null +++ b/examples/apidoc/V5/Earn/RWA/get-nav-chart.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getRWANavChart({ productId: 1001 }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Earn/RWA/get-order-list.js b/examples/apidoc/V5/Earn/RWA/get-order-list.js new file mode 100644 index 00000000..41ecb796 --- /dev/null +++ b/examples/apidoc/V5/Earn/RWA/get-order-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getRWAOrderList({ orderType: 'Stake', limit: 20 }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Earn/RWA/get-position-list.js b/examples/apidoc/V5/Earn/RWA/get-position-list.js new file mode 100644 index 00000000..9b6b9849 --- /dev/null +++ b/examples/apidoc/V5/Earn/RWA/get-position-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getRWAPositionList() + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Earn/RWA/get-product-list.js b/examples/apidoc/V5/Earn/RWA/get-product-list.js new file mode 100644 index 00000000..a5b85922 --- /dev/null +++ b/examples/apidoc/V5/Earn/RWA/get-product-list.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.getRWAProductList({ coin: 'USDC' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Earn/RWA/place-order.js b/examples/apidoc/V5/Earn/RWA/place-order.js new file mode 100644 index 00000000..48ba65d3 --- /dev/null +++ b/examples/apidoc/V5/Earn/RWA/place-order.js @@ -0,0 +1,15 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client.placeRWAOrder({ productId: 1001, orderType: 'Stake', coin: 'USDC', stakeAmount: '100', accountType: 'FUND', orderLinkId: 'my-stake-001' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Earn/get-coupon-list.js b/examples/apidoc/V5/Earn/get-coupon-list.js new file mode 100644 index 00000000..f555376f --- /dev/null +++ b/examples/apidoc/V5/Earn/get-coupon-list.js @@ -0,0 +1,16 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getEarnCouponList({ category: 'FlexibleSaving' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Institutional-Loan/get-coin-delta-amount.js b/examples/apidoc/V5/Institutional-Loan/get-coin-delta-amount.js new file mode 100644 index 00000000..61376870 --- /dev/null +++ b/examples/apidoc/V5/Institutional-Loan/get-coin-delta-amount.js @@ -0,0 +1,16 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getInstitutionalLendingCoinDeltaAmount({ coin: 'BTC' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/V5/Position/get-futures-leverage.js b/examples/apidoc/V5/Position/get-futures-leverage.js new file mode 100644 index 00000000..14818719 --- /dev/null +++ b/examples/apidoc/V5/Position/get-futures-leverage.js @@ -0,0 +1,16 @@ +import { RestClientV5 } from 'bybit-api'; + +const client = new RestClientV5({ + testnet: true, + key: 'apikey', + secret: 'apisecret', +}); + +client + .getFuturesLeverage({ category: 'linear', symbol: 'BTCUSDT' }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index 13679651..9ad57953 100644 --- a/llms.txt +++ b/llms.txt @@ -94,6 +94,8 @@ src/ usdc-perp.ts usdc-shared.ts v5-account.ts + v5-alpha-lp.ts + v5-alpha-prediction.ts v5-alpha-trade.ts v5-asset.ts v5-broker.ts @@ -110,6 +112,7 @@ src/ v5-position.ts v5-pre-upgrade.ts v5-rfq.ts + v5-rwa.ts v5-spot-leverage-token.ts v5-spreadtrading.ts v5-strategy.ts @@ -124,6 +127,8 @@ src/ unified-margin.ts usdt-perp.ts v5-account.ts + v5-alpha-lp.ts + v5-alpha-prediction.ts v5-alpha-trade.ts v5-asset.ts v5-broker.ts @@ -140,6 +145,7 @@ src/ v5-position.ts v5-preupgrade.ts v5-rfq.ts + v5-rwa.ts v5-spot-leverage-token.ts v5-spreadtrading.ts v5-strategy.ts @@ -1550,209 +1556,166 @@ export interface USDCPositionsRequest { } ================ -File: src/types/request/v5-earn-pwm.ts +File: src/types/request/v5-alpha-lp.ts ================ -/** GET /v5/earn/pwm/investment-plan/detail */ -export interface GetPwmInvestmentPlanDetailParamsV5 { - planId: string; -} +/** + * V5 private Alpha LP requests. + */ ⋮---- -/** GET /v5/earn/pwm/investment-plan/new-plan */ -export interface GetPwmPendingInvestmentPlanDetailParamsV5 { - planId: string; +export interface GetAlphaLPPoolListParamsV5 { + tokenSymbol?: string; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/claim */ -export interface ClaimPwmWithdrawableFundsParamsV5 { - planId: string; - /** Default: FUND */ - toAccountType?: string; - orderLinkId: string; +export interface GetAlphaLPPoolInfoParamsV5 { + poolAddress: string; } ⋮---- -/** Default: FUND */ -⋮---- -/** GET /v5/earn/pwm/investment-plan/asset-trend */ -export interface GetPwmInvestmentPlanAssetTrendParamsV5 { - planId: string; - startTime?: number; - endTime?: number; +export interface ExecuteAlphaLPStakeParamsV5 { + positionId: number; + poolAddress: string; + payTokenAmount: string; + payTokenCode: string; + rangeUpper?: string; + rangeLower?: string; + priceUpper?: string; + priceLower?: string; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/fund-nav */ -export interface GetPwmFundHistoricalNavParamsV5 { - fundId: string; - startTime?: number; - endTime?: number; +export interface ExecuteAlphaLPRedeemParamsV5 { + positionId: number; + poolAddress: string; + dercRatio: string; + receiveTokenCode?: string; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/subscribe */ -export interface SubscribePwmInvestmentPlanParamsV5 { - planId: string; - /** Default: FUND */ - accountType?: string; - orderLinkId: string; +export interface GetAlphaLPOrderListParamsV5 { + orderType?: 0 | 1 | 2; + tokenCode?: string; + orderStatus?: number[]; + days?: number; + limit?: number; + pageIndex?: number; + poolAddress?: string; } ⋮---- -/** Default: FUND */ -⋮---- -/** POST /v5/earn/pwm/investment-plan/invest-more */ -export interface InvestMorePwmInvestmentPlanParamsV5 { - planId: string; - /** Default: FUND */ - accountType?: string; - category: string; - productId: string; - amount: string; - orderLinkId: string; +export interface GetAlphaLPPayTokenListParamsV5 { + chainCode?: string; + tokenAddress?: string; } ⋮---- -/** Default: FUND */ -⋮---- -/** POST /v5/earn/pwm/investment-plan/redeem */ -export interface RedeemPwmInvestmentPlanParamsV5 { - planId: string; - category: string; - productId: string; - orderLinkId: string; - /** Required for fund products */ - shares?: string; - /** Required for non-fund products */ - amount?: string; - /** Required for FundPool and On-chain Earn */ - positionId?: string; +export interface GetAlphaLPPayTokenPriceParamsV5 { + tokenCode: string[]; + chainCode?: string; } + +================ +File: src/types/request/v5-alpha-prediction.ts +================ +/** + * V5 private Alpha prediction market requests. + */ ⋮---- -/** Required for fund products */ -⋮---- -/** Required for non-fund products */ -⋮---- -/** Required for FundPool and On-chain Earn */ +export interface GetAlphaPredictionEventDetailParamsV5 { + eventId?: string; + slug?: string; + hasMoreMarkets?: boolean; +} ⋮---- -/** GET /v5/earn/pwm/investment-plan/order */ -export interface GetPwmInvestmentPlanOrdersParamsV5 { - planId?: string; - category?: string; - type?: 'Subscribe' | 'Redeem' | 'AutoReinvest' | string; - status?: 'Completed' | 'Pending' | 'Failed' | string; - startTime?: string; - endTime?: string; - limit?: number; - cursor?: string; - orderLinkId?: string; +export interface GetAlphaPredictionOrderEstimateParamsV5 { + tokenId: string; + side: 1 | 2; + eventId: string; + amount: string; + orderType: 1; + payTokenCode?: string; } ⋮---- -/** POST /v5/earn/pwm/customize-plan/create */ -export interface CreatePwmCustomizeInvestmentPlanProductV5 { - category: string; - productId: string; - fundName: string; +export interface ExecuteAlphaPredictionBuyParamsV5 { + tokenId: string; amount: string; + payTokenCode: string; + orderType: 1; + slippage: string; + eventId: string; } ⋮---- -export interface CreatePwmCustomizeInvestmentPlanParamsV5 { - accountType?: string; - products: CreatePwmCustomizeInvestmentPlanProductV5[]; +export interface ExecuteAlphaPredictionSellParamsV5 { + tokenId: string; + size: string; + orderType: 1; + slippage: string; + eventId: string; + toTokenCode?: string; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/all-funds */ -export interface GetPwmAllFundsParamsV5 { - coin?: string; - fundId?: string; - status?: string; +export interface GetAlphaPredictionOrderListParamsV5 { + status?: number; + tokenId?: string; + eventId?: string; + side?: 1 | 2; + days?: number; limit?: number; - cursor?: string; + pageIndex?: number; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/settle-profit */ -export interface SettlePwmFundProfitParamsV5 { - fundId: string; - reqLinkId: string; +export interface GetAlphaPredictionOrderBookParamsV5 { + tokenIds: string[]; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/create-fund */ -export interface CreatePwmFundParamsV5 { - fundName: string; - coin: string; - profitShareRate: string; - managementFeeRate: string; - fundIntroduction?: string; - reqLinkId: string; +export interface GetAlphaPredictionTokenPriceParamsV5 { + tokenIds: string[]; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/create-investment-plan */ -export interface CreatePwmAssetManagerInvestmentPlanDistributionV5 { - productId: string; - amount: string; +export interface GetAlphaPredictionPriceHistoryParamsV5 { + tokenId: string; + interval: string; } ⋮---- -export interface CreatePwmAssetManagerInvestmentPlanParamsV5 { - accountUid: string; - planName: string; - planType: 'stable' | 'advanced' | string; - investmentDistribution: CreatePwmAssetManagerInvestmentPlanDistributionV5[]; - reqLinkId: string; +export interface GetAlphaPredictionPositionListParamsV5 { + tokenId?: string; + eventId?: string; + limit?: number; + pageIndex?: number; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/get-investment-plan */ -export interface GetPwmAssetManagerInvestmentPlansParamsV5 { - planId?: string; - status?: string; - subscriptionUid?: string; +export interface GetAlphaPredictionPositionHistoryParamsV5 { + tokenId?: string; + eventId?: string; + result?: number; + days?: number; limit?: number; - cursor?: string; + pageIndex?: number; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/manage-investment-plan */ -export interface ManagePwmAssetManagerInvestmentPlanFundV5 { - fundId: string; - amount: string; +export interface GetAlphaPredictionPortfolioSummaryParamsV5 { + eventType?: number; } ⋮---- -export interface ManagePwmAssetManagerInvestmentPlanParamsV5 { - planId: string; - updateStatus?: 'Closed' | 'Deleted' | string; - updateFunds?: ManagePwmAssetManagerInvestmentPlanFundV5[]; - reqLinkId: string; +export interface GetAlphaPredictionSideMarketListParamsV5 { + eventId: string; + sortBy?: string; + marketType?: number; + limit?: number; + pageIndex?: number; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/all-order */ -export interface GetPwmAllFundOrdersParamsV5 { - fundId?: string; - orderType?: 'Subscribe' | 'Redeem' | string; - status?: string; +export interface GetAlphaPredictionSportsMatchListParamsV5 { + eventType: number; + status?: number; startTime?: number; endTime?: number; + stageCode?: string; limit?: number; - cursor?: string; -} -⋮---- -/** POST /v5/earn/pwm/asset-manager/manage-order */ -export interface ManagePwmFundOrderParamsV5 { - orderId: string; - action: 'approve' | 'reject' | string; - reqLinkId: string; -} -⋮---- -/** POST /v5/earn/pwm/asset-manager/create-sub-account */ -export interface CreatePwmFundSubAccountParamsV5 { - fundId: string; - reqLinkId: string; + pageIndex?: number; } ⋮---- -/** POST /v5/earn/pwm/fund-transfer */ -export interface PwmFundTransferParamsV5 { - transferId: string; - fromUserId: number; - toUserId: number; - amount: string; - coin: string; +export interface GetAlphaPredictionSportsTimelineStagesParamsV5 { + eventType: number; } ⋮---- -/** GET /v5/earn/pwm/query-fund-transfer-result */ -export interface GetPwmFundTransferRecordsParamsV5 { - transferId?: string; - fromUserId?: number; +export interface GetAlphaPredictionSportsGroupStageDetailParamsV5 { + eventType: number; + groupName?: string; } ================ @@ -1957,136 +1920,41 @@ export interface GetPreUpgradeUSDCSessionParamsV5 { } ================ -File: src/types/request/v5-strategy.ts +File: src/types/request/v5-rwa.ts ================ -import { - OrderSideV5, - PositionIdx, - PovModeV5, - StrategyCategoryV5, - StrategyPreferV5, - StrategyTypeV5, -} from '../shared-v5'; +/** + * V5 RWA (Real World Assets) earn requests. + */ ⋮---- -/** 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; +export interface GetRWAProductListParamsV5 { + coin?: string; } ⋮---- -/** Total order quantity (coin). Either size or positionValue is required */ +export interface PlaceRWAOrderParamsV5 { + productId: number; + orderType: 'Stake' | 'Redeem'; + coin: string; + orderLinkId: string; + stakeAmount?: string; + redeemShares?: string; + accountType?: 'FUND' | 'UNIFIED'; +} ⋮---- -/** 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 */ -⋮---- -/** 1: market, 2: limit */ -⋮---- -/** POV execution mode */ -⋮---- -/** POV participation rate */ -⋮---- -/** POV: historical traded volume window (seconds), range [60, 14400] */ -⋮---- -/** POV: book depth reference levels [1, 10] */ -⋮---- -/** GET /v5/strategy/list */ -export interface GetStrategyListParamsV5 { - strategyId?: string; - symbol?: string; - /** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ - status?: '2' | '3' | '4' | '5' | '6'; - category?: StrategyCategoryV5; - strategyType?: StrategyTypeV5; - beginTimeE0?: number; - endTimeE0?: number; - pageSize?: number; - cursor?: string; -} -⋮---- -/** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ -⋮---- -/** GET /v5/strategy/order-list */ -export interface GetStrategyOrderListParamsV5 { - strategyId: string; - /** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ - status?: '2' | '3' | '4' | '5' | '6' | '7'; - symbol?: string; - strategyType?: StrategyTypeV5; - beginTimeE0?: number; - endTimeE0?: number; - pageSize?: number; +export interface GetRWAOrderListParamsV5 { + orderId?: string; + orderLinkId?: string; + orderType?: 'Stake' | 'Redeem'; + productId?: number; + startTime?: number; + endTime?: number; + limit?: number; cursor?: string; } ⋮---- -/** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ -⋮---- -/** POST /v5/strategy/stop */ -export interface StopStrategyParamsV5 { - strategyId: string; +export interface GetRWANavChartParamsV5 { + productId: number; + startTime?: number; + endTime?: number; } ================ @@ -2589,481 +2457,400 @@ export interface LinearOrder { } ================ -File: src/types/response/v5-earn-pwm.ts +File: src/types/response/v5-alpha-lp.ts ================ -export interface PwmCoinAmountV5 { - coin: string; - amount: string; -} +/** + * V5 private Alpha LP responses. + */ ⋮---- -export interface PwmMultiCoinsEarningPositionItemV5 { - category: string; - productId: string; - coin: string; - currentAmount: string; - accumulateYield: string; - apr: string; - positionId: string; - status?: 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 PwmMultiCoinsEarningPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - items: PwmMultiCoinsEarningPositionItemV5[]; +export interface AlphaLPPoolListResultV5 { + pools: AlphaLPPoolV5[]; } ⋮---- -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 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 PwmFixedYieldPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - items: PwmFixedYieldPositionItemV5[]; +export interface ExecuteAlphaLPStakeResultV5 { + positionId: number; + orderNo: string; } ⋮---- -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 ExecuteAlphaLPRedeemResultV5 { + orderNo: string; } ⋮---- -export interface PwmEquityFundsPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - weightedAvgApr: string; - items: PwmEquityFundPositionItemV5[]; +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 PwmOnchainEarnPositionItemV5 { - category: string; - productId: string; - coin: string; - stakeAmount: string; - apr: string; - positionId: string; - status?: string; +export interface AlphaLPOrderListResultV5 { + total: number; + pageIndex: number; + orders: AlphaLPOrderV5[]; } ⋮---- -export interface PwmOnchainEarnPositionsV5 { - totalInvestmentUsd: string; - accumulateYieldUsd: string; - items: PwmOnchainEarnPositionItemV5[]; +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 PwmInvestmentPlanPositionsV5 { - multiCoinsEarning?: PwmMultiCoinsEarningPositionsV5; - fixedYield?: PwmFixedYieldPositionsV5; - equityFunds?: PwmEquityFundsPositionsV5; - onchainEarn?: PwmOnchainEarnPositionsV5; - fundingAccount?: PwmCoinAmountV5[]; +export interface AlphaLPPayTokenListResultV5 { + tokens: AlphaLPPayTokenV5[]; } ⋮---- -/** 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 AlphaLPPayTokenPriceV5 { + tokenCode: string; + tokenSymbol: string; + priceUsd: string; + chainCode: string; + updateTime: number; } ⋮---- -export interface PwmInvestmentPlanListResultV5 { - list: PwmInvestmentPlanSummaryV5[]; +export interface AlphaLPPayTokenPriceResultV5 { + prices: AlphaLPPayTokenPriceV5[]; } ⋮---- -/** 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 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 PwmEquityFundIntroductionV5 { - description: string; - historicalYieldRateMax: string; - historicalYieldRateMin: string; - sharpRatio: string; - maxDrawback: string; - lockupPeriod: string; +export interface AlphaLPPositionListResultV5 { + positions: AlphaLPPositionV5[]; } + +================ +File: src/types/response/v5-alpha-prediction.ts +================ +/** + * V5 private Alpha prediction market responses. + */ ⋮---- -export interface PwmPendingMultiCoinsEarningItemV5 { - category: string; - productId: string; - coin: string; - configuredAmount: string; - apr: string; +export interface AlphaPredictionEngineStatusV5 { + available: boolean; } ⋮---- -export interface PwmPendingFixedYieldItemV5 { - category: string; - productId: string; - coin: string; - configuredAmount: string; - apr: string; - duration: number; +export interface AlphaPredictionPayTokenV5 { + tokenCode: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + supportChains: string[]; } ⋮---- -export interface PwmPendingEquityFundItemV5 { - category: string; - productId: string; - fundName: string; - coin: string; - configuredAmount: string; - tags: string[]; - introduction: PwmEquityFundIntroductionV5; +export interface AlphaPredictionMarketV5 { + tokenId: string; + outcome: string; + price: string; + side: number; + volume: string; + liquidity: string; } ⋮---- -export interface PwmPendingOnchainEarnItemV5 { +export interface AlphaPredictionEventDetailV5 { + eventId: string; + slug: string; + title: string; + description: string; category: string; - productId: string; - coin: string; - configuredAmount: string; - apr: string; + endDate: number; + resolved: boolean; + volume: string; + liquidity: string; + markets: AlphaPredictionMarketV5[]; } ⋮---- -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 AlphaPredictionOrderEstimateFeeDetailV5 { + serverFee: string; + polymarketFee: 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; +export interface AlphaPredictionOrderEstimateV5 { + avgPrice: string; + estimatedCost: string; + estimatedReceive: string; + toWin?: string; + feeAmount: string; + feeDetail: AlphaPredictionOrderEstimateFeeDetailV5; + slippage: string; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/claim */ -export interface ClaimPwmWithdrawableFundsResultV5 { - planId: string; - toAccountType: number; - status: string; - createdTime: string; +export interface ExecuteAlphaPredictionOrderResultV5 { + orderNo: string; } ⋮---- -export interface PwmAssetTrendDataPointV5 { - date: string; - assetValueUsd: 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; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/asset-trend */ -export interface PwmInvestmentPlanAssetTrendResultV5 { - planId: string; - dataPoints: PwmAssetTrendDataPointV5[]; +export interface AlphaPredictionOrderListResultV5 { + orders: AlphaPredictionOrderV5[]; + total: number; + pageIndex: number; } ⋮---- -export interface PwmFundNavDataPointV5 { - date: string; - nav: string; +export interface AlphaPredictionOrderBookLevelV5 { + price: string; + size: string; } ⋮---- -/** GET /v5/earn/pwm/investment-plan/fund-nav */ -export interface PwmFundHistoricalNavResultV5 { - fundId: string; - fundName: string; - coin: string; - currentNav: string; - dataPoints: PwmFundNavDataPointV5[]; +export interface AlphaPredictionOrderBookV5 { + tokenId: string; + bids: AlphaPredictionOrderBookLevelV5[]; + asks: AlphaPredictionOrderBookLevelV5[]; } ⋮---- -/** POST /v5/earn/pwm/investment-plan/subscribe */ -export interface SubscribePwmInvestmentPlanResultV5 { - planId: string; - status: string; - orderLinkId: string; +export interface AlphaPredictionTokenPriceV5 { + tokenId: string; + bestBid: string; + bestAsk: string; + lastPrice: string; + volume24h: string; + updateTime: number; } ⋮---- -/** 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 AlphaPredictionPriceHistoryCandleV5 { + openTime: number; + open: string; + high: string; + low: string; + close: string; + volume: string; } ⋮---- -/** 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; +export interface AlphaPredictionPriceHistoryV5 { + tokenId: string; + interval: string; + list: AlphaPredictionPriceHistoryCandleV5[]; } ⋮---- -/** 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 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 PwmInvestmentPlanOrdersResultV5 { - list: PwmInvestmentPlanOrderV5[]; - nextPageCursor: string; +export interface AlphaPredictionPositionListResultV5 { + positions: AlphaPredictionPositionV5[]; + total: number; + totalAssetUsd: string; } ⋮---- -/** 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 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 PwmSubscribableProductGroupV5 { - type: string; - cards: PwmSubscribableProductCardV5[]; +export interface AlphaPredictionPositionHistoryResultV5 { + positions: AlphaPredictionPositionHistoryV5[]; + total: number; } ⋮---- -export interface PwmSubscribableProductInfoResultV5 { - products: PwmSubscribableProductGroupV5[]; +export interface AlphaPredictionPortfolioSummaryV5 { + positionValue: string; + positionValueUsd: string; + biggestWin: string; + winRate: string; + winCount: number; + lossCount: number; } ⋮---- -/** POST /v5/earn/pwm/customize-plan/create */ -export interface CreatePwmCustomizeInvestmentPlanResultV5 { - planId: string; - planName: string; - status: string; - orderLinkId?: string; +export interface AlphaPredictionSideMarketTokenV5 { + tokenId: string; + outcome: string; + price: string; + liquidity: 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 AlphaPredictionSideMarketV5 { + marketId: string; + eventId: string; + marketType: number; + question: string; + tokens: AlphaPredictionSideMarketTokenV5[]; + volume24h: string; + endDate: number; + status: number; } ⋮---- -export interface PwmAllFundsResultV5 { - list: PwmAssetManagerFundV5[]; - nextPageCursor: string; +export interface AlphaPredictionSideMarketListResultV5 { + list: AlphaPredictionSideMarketV5[]; + total: number; + pageIndex: number; + pageSize: number; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/settle-profit */ -export interface SettlePwmFundProfitResultV5 { - fundId: string; - status: string; - totalProfitShared: string; - instIncome: string; - coin: string; - createdTime: string; +export interface AlphaPredictionSportsMatchV5 { + matchId: string; + eventType: number; + stageCode: string; + homeTeam: string; + awayTeam: string; + matchTime: number; + status: number; + eventId: string; } ⋮---- -/** 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 AlphaPredictionSportsMatchListResultV5 { + list: AlphaPredictionSportsMatchV5[]; + total: number; + pageIndex: number; + pageSize: number; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/create-investment-plan */ -export interface CreatePwmAssetManagerInvestmentPlanResultV5 { - planId: string; - planType: string; - accountUid: string; - status: string; - createdTime: string; +export interface AlphaPredictionSportsTimelineStageV5 { + stageCode: string; + stageName: string; + status: number; + matchCount: number; + startTime: number; + endTime: number; } ⋮---- -/** GET /v5/earn/pwm/asset-manager/get-investment-plan */ -export interface PwmAssetManagerInvestmentPlanDistributionV5 { - category: string; - coin: string; - productId: string; - currentAmount: string; +export interface AlphaPredictionSportsTimelineStagesV5 { + eventType: number; + stages: AlphaPredictionSportsTimelineStageV5[]; } ⋮---- -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[]; -} -⋮---- -/** 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; -} -⋮---- -export interface PwmAllFundOrdersResultV5 { - list: PwmAssetManagerFundOrderV5[]; - 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; - coin: string; - amount: string; - shares: string; - updatedTime: string; +export interface AlphaPredictionSportsGroupStandingV5 { + rank: number; + teamName: string; + played: number; + won: number; + drawn: number; + lost: number; + goalsFor: number; + goalsAgainst: number; + goalDifference: number; + points: number; } ⋮---- -/** POST /v5/earn/pwm/asset-manager/create-sub-account */ -export interface CreatePwmFundSubAccountResultV5 { - fundId: string; - subAccountUid: string; - createdTime: string; - status: string; +export interface AlphaPredictionSportsGroupMatchV5 { + matchId: string; + homeTeam: string; + awayTeam: string; + matchTime: number; + status: number; + homeScore: number; + awayScore: number; + eventId: string; } ⋮---- -/** POST /v5/earn/pwm/fund-transfer */ -export interface PwmFundTransferResultV5 { - transferId: string; - status: string; +export interface AlphaPredictionSportsGroupV5 { + groupName: string; + standings: AlphaPredictionSportsGroupStandingV5[]; + matches: AlphaPredictionSportsGroupMatchV5[]; } ⋮---- -/** 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 AlphaPredictionSportsGroupStageDetailV5 { + groups: AlphaPredictionSportsGroupV5[]; } ================ @@ -3721,124 +3508,89 @@ export interface PreUpgradeUSDCSessionSettlement { } ================ -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[]; } ================ @@ -4434,5480 +4186,5783 @@ File: tsconfig.test.json } ================ -File: docs/BYBIT_SDK_QUICKSTART_GUIDE.md +File: examples/Auth/fasterHmacSign.ts ================ -# 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) -- 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: +import { createHmac } from 'crypto'; +⋮---- +import { DefaultLogger, RestClientV5, WebsocketClient } from '../../src/index'; +⋮---- +// or +// import { createHmac } from 'crypto'; +// import { DefaultLogger, RestClientV5, WebsocketClient } from 'bybit-api'; +⋮---- +/** + * Injecting a custom signMessage function. + * + * As of version 4.0.0 of the bybit-api Node.js/TypeScript/JavaScript + * SDK for Bybit, the SDK uses the Web Crypto API for signing requests. + * While it is compatible with Node and Browser environments, it is + * slightly slower than using Node's native crypto module (only + * available in backend Node environments). + * + * For latency sensitive users, you can inject the previous node crypto sign + * method (or your own even faster-implementation), if this change affects you. + * + * This example demonstrates how to inject a custom sign function, to achieve + * the same peformance as seen before the Web Crypto API was introduced. + * + * For context on standard usage, the "signMessage" function is used: + * - During every single API call + * - After opening a new private WebSocket connection + * + */ +⋮---- +/** + * Set this to true to enable demo trading: + */ +⋮---- +/** + * Overkill in almost every case, but if you need any optimisation available, + * you can inject a faster sign mechanism such as node's native createHmac: + */ +⋮---- +// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing +⋮---- +// trace: (...params) => console.log('trace', ...params), +⋮---- +/** + * Set this to true to enable demo trading for the private account data WS + * Topics: order,execution,position,wallet,greeks + */ +⋮---- +/** + * Overkill in almost every case, but if you need any optimisation available, + * you can inject a faster sign mechanism such as node's native createHmac: + */ +⋮---- +function setWsClientEventListeners( + websocketClient: WebsocketClient, + accountRef: string, +): Promise +⋮---- +// console.log('raw message received ', JSON.stringify(data, null, 2)); +⋮---- +// Simple promise to ensure we're subscribed before trying anything else +⋮---- +// Start trading +⋮---- +/** Simple examples for private REST API calls with bybit's V5 REST APIs */ +⋮---- +// Trade USDT linear perps -```bash -npm install bybit-api -``` +================ +File: examples/Rest/demo-trading.ts +================ +import { DefaultLogger, RestClientV5, WebsocketClient } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +/** + * + * + * This example demonstrates how to use Bybit's demo trading functionality, both for REST and WS. + * + * Refer to the API docs for more information: https://bybit-exchange.github.io/docs/v5/demo + * + * + */ +⋮---- +/** + * Set this to true to enable demo trading: + */ +⋮---- +// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing +⋮---- +// trace: (...params) => console.log('trace', ...params), +⋮---- +/** + * Set this to true to enable demo trading for the private account data WS + * Topics: order,execution,position,wallet,greeks + */ +⋮---- +function setWsClientEventListeners( + websocketClient: WebsocketClient, + accountRef: string, +): Promise +⋮---- +// console.log('raw message received ', JSON.stringify(data, null, 2)); +⋮---- +// Simple promise to ensure we're subscribed before trying anything else +⋮---- +// Start trading +⋮---- +/** Simple examples for private REST API calls with bybit's V5 REST APIs */ +⋮---- +// Trade USDT linear perps -Or use another npm-compatible package manager: +================ +File: examples/Rest/rest-v5-all.ts +================ +import { RestClientV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +/** + * If you don't plan on making any private api calls, + * you can instance the REST client without any parameters: + * + * const client = new RestClientV5(); + */ -```bash -pnpm install bybit-api -yarn add bybit-api -``` +================ +File: examples/Rest/rest-v5-custom-url.ts +================ +import { RestClientV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +/** + * The first parameter of the REST client allows you to pass any configuration parameters supported by the SDK. + * + * These include API keys, if you wish to use private endpoints, but also expose other features such as + * setting a custom base URL (e.g. for Turkish users). + * + * Refer to the API documentation for a complete list of domains: https://bybit-exchange.github.io/docs/v5/guide#authentication + */ +⋮---- +/** + * You can pass a completely custom base URL, + * e.g. if you're trying to use a domain that hasn't been added yet (please let us know) + */ +// baseUrl: 'https://api5.bybit.com', +// +// +/** + * + * There are also predefined API regions, which you can easily use with the "apiRegion" property: + * + */ +// +// +// default: routes to api.bybit.com +// apiRegion: 'default', +// +// +// bytick: routes to api.bytick.com +// apiRegion: 'bytick', +// +// +// NL: routes to api.bybit.nl (for Netherland users) +// apiRegion: 'NL', +// +// +// HK: routes to api.byhkbit.com (for Hong Kong users) +// apiRegion: 'HK', +// +// +// TK: routes to api.bybit-tr.com (for Turkey users) +// apiRegion: 'TK', -Create API keys from the relevant Bybit page: +================ +File: examples/Rest/rest-v5-next-cursor.ts +================ +import { RestClientV5, UniversalTransferRecordV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +async function getAllUniversalTransfers() +⋮---- +limit: 50, // Maximum page size per request +cursor: nextCursor || undefined, // Only send cursor if we have one +⋮---- +// Optional: Add a small delay to avoid rate limits -- 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) +================ +File: examples/Rest/rest-v5-p2p.ts +================ +import fs from 'fs'; +import path from 'path'; +⋮---- +import { RestClientV5 } from '../../src'; +⋮---- +// ENDPOINT: /v5/p2p/oss/upload_file +// METHOD: POST +// PUBLIC: NO +// NOTE: Node.js only (Buffer required) +⋮---- +async function uploadP2PChatFile() +⋮---- +// You must read the file yourself and pass the Buffer + filename +⋮---- +/** + * + * + * + * + * + * + */ +⋮---- +// Test basic P2P API connectivity +⋮---- +// Example 1: Upload from file path +⋮---- +fileName: path.basename(filePath), // Extract filename from path +⋮---- +// Example 2: Upload with custom filename +// You control the filename sent to Bybit +⋮---- +fileName: 'custom-name.png', // Use any filename you want +⋮---- +// Example 3: Upload different file +⋮---- +// Supported file types (determined by filename extension): +// - Images: jpg, jpeg, png +// - Documents: pdf +// - Videos: mp4 -> 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. +================ +File: examples/Rest/rest-v5-private.ts +================ +import { RestClientV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +/** Simple examples for private REST API calls with bybit's V5 REST APIs */ +⋮---- +// Trade USDT linear perps -The main auth and environment rules are: +================ +File: examples/Rest/rest-v5-proxies.ts +================ +import { RestClientV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +// 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, +⋮---- +/** + * Axios has a native way of supporting http/https proxies. It works for most proxy services but not all. + * If you have issues making any proxied requests this way, take a look at the rest-v5-proxies2.ts example using the https-proxy-agent. + */ +⋮---- +protocol: 'http', // or 'https' +⋮---- +// const orders = await client.batchSubmitOrders('linear', [ +// { +// symbol: 'ETHUSDT', +// orderType: 'Limit', +// side: 'Buy', +// qty: '1', +// orderIv: '6', +// timeInForce: 'GTC', +// orderLinkId: 'option-test-001', +// mmp: false, +// reduceOnly: false, +// }, +// { +// symbol: 'ETHUSDT', +// orderType: 'Limit', +// side: 'Sell', +// qty: '2', +// price: '700', +// timeInForce: 'GTC', +// orderLinkId: 'option-test-001', +// mmp: false, +// reduceOnly: false, +// }, +// ]); +⋮---- +// console.log('orders: ', JSON.stringify(orders, null, 2)); -- 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. +================ +File: examples/Rest/rest-v5-public.ts +================ +import { RestClientV5 } from '../../src/index'; +⋮---- +// or +// import { RestClientV5 } from 'bybit-api'; +⋮---- +/** + * If you don't plan on making any private api calls, + * you can instance the REST client without any parameters + */ +⋮---- +// const klineResult = await client.getKline({ +// category: 'linear', +// interval: '15', +// symbol: 'BTCUSDT', +// }); +// console.log('klineResult: ', klineResult); +⋮---- +// const markPriceKlineResult = await client.getMarkPriceKline({ +// category: 'linear', +// interval: '15', +// symbol: 'BTCUSDT', +// }); +// console.log('markPriceKlineResult: ', markPriceKlineResult); +⋮---- +// const indexPriceKline = await client.getIndexPriceKline({ +// category: 'linear', +// interval: '15', +// symbol: 'BTCUSDT', +// }); +// console.log('indexPriceKline: ', indexPriceKline); +⋮---- +// const openInterest = await client.getOpenInterest({ +// category: 'linear', +// symbol: 'BTCUSDT', +// intervalTime: '5min', +// }); +⋮---- +// console.log( +// JSON.stringify( +// tickers.result.list.map((ticker) => ticker.symbol), +// null, +// 2, +// ), +// ); +⋮---- +// openInterest.result.list.forEach((row) => { +// console.log('int: ', { +// timestamp: row.timestamp, +// value: row.openInterest, +// }); +// }); +// console.log('openInterest: ', openInterest.result.list); -Typical environment variables: +================ +File: examples/Websocket/WS-API/ws-api-client.ts +================ +import { DefaultLogger, WebsocketAPIClient } from '../../../src'; +⋮---- +// or +// import { DefaultLogger, WebsocketAPIClient } from 'bybit-api'; +// const { DefaultLogger, WebsocketAPIClient } = require('bybit-api'); +⋮---- +// function attachEventHandlers( +// wsClient: TWSClient, +// ): void { +// wsClient.on('update', (data) => { +// console.log('raw message received ', JSON.stringify(data)); +// }); +// wsClient.on('open', (data) => { +// console.log('ws connected', data.wsKey); +// }); +// wsClient.on('reconnect', ({ wsKey }) => { +// console.log('ws automatically reconnecting.... ', wsKey); +// }); +// wsClient.on('reconnected', (data) => { +// console.log('ws has reconnected ', data?.wsKey); +// }); +// wsClient.on('authenticated', (data) => { +// console.log('ws has authenticated ', data?.wsKey); +// }); +// } +⋮---- +async function main() +⋮---- +// Optional +⋮---- +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +// trace: (...params) => console.log('trace', ...params), +⋮---- +// testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management +⋮---- +// 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 the `attachEventHandlers` example below: +// attachEventListeners: false +⋮---- +logger, // Optional: inject a custom logger +⋮---- +// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled +// attachEventHandlers(wsClient.getWSClient()); +⋮---- +// Optional, if you see RECV Window errors, you can use this to manage time issues. +// ! However, make sure you sync your system clock first! +// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow +// wsClient.setTimeOffsetMs(-5000); +⋮---- +// Optional: prepare the WebSocket API connection in advance. +// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. +// await wsClient.getWSClient().connectWSAPI(); -```bash -export BYBIT_API_KEY='your-api-key' -export BYBIT_API_SECRET='your-api-secret-or-rsa-private-key' -``` +================ +File: examples/Websocket/WS-API/ws-api-raw-events.ts +================ +import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; +⋮---- +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +// trace: (...params) => console.log('trace', ...params), +⋮---- +// testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management +// demoTrading: false, // note: As of Jan 2025, demo trading does NOT support the WS API +⋮---- +logger, // Optional: inject a custom logger +⋮---- +/** + * General event handlers for monitoring the WebsocketClient + */ +⋮---- +async function main() +⋮---- +/** + * + * This SDK's WebSocket API integration is event-driven at its core. You can treat the sentWSAPIRquest(...) method as + * a fire-and-forget method, to submit commands (create/amend/cancel order) via a WebSocket Connection. + * + * Replies to commands will show in the `response` event from the WebsocketClient's EventEmitter. Exceptions, however, + * will show in the `error` event from the WebsocketClient's EventEmitter. + * + * - Fire-and-forget a command. + * - Handle command results in the `response` event handler asynchronously as desired. + * - Handle any exceptions in a catch block. + * + * This is a more "raw" workflow in how WebSockets behave. For a more convenient & REST-like approach, using the + * promise-driven interface is recommended. See the `ws-api-raw-promises.ts` and `ws-api-client.ts` examples for a + * demonstration you can compare. + * + * Note: even without using promises, you should still tie on a .catch handler to each sendWSAPIRequest call, to prevent + * any unnecessary "unhandled promise rejection" exceptions. + * + */ +⋮---- +// To make it easier to watch, wait a few seconds before sending the amend order +⋮---- +// Then wait a few more before sending the cancel order +⋮---- +// Exceptions including rejected commands will show here (as well as the catch handler used below) +⋮---- +// Replies to commands will show here +⋮---- +/** + * + * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send + * your first command. That connection will then be reused for every command you send, unless the connection drops - then + * it will automatically be replaced with a healthy connection. + * + * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection + * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands. This is optional. + * + * Repeated note: even without using promises, you should still tie on a .catch handler to each sendWSAPIRequest call, to prevent + * any unnecessary "unhandled promise rejection" exceptions. + * + */ +⋮---- +// Optional, see above. Can be used to prepare a connection before sending commands +⋮---- +// Fire and forget the create.order command +// Even without using promises, you should still "catch" exceptions (although no need to await anything you send) +⋮---- +// +⋮---- +// Fire and forget the order.amend command +// For simplicity, the orderId is hardcoded here (and will probably not work) +⋮---- +// +⋮---- +// Fire and forget the order.cancel command +// For simplicity, the orderId is hardcoded here (and will probably not work) +⋮---- +// Start executing the example workflow -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 +================ +File: examples/Websocket/WS-API/ws-api-raw-promises.ts +================ +import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; +⋮---- +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +// trace: (...params) => console.log('trace', ...params), +⋮---- +// testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management +// demoTrading: false, // note: As of Jan 2025, demo trading does NOT support the WS API +⋮---- +logger, // Optional: inject a custom logger +⋮---- +/** + * General event handlers for monitoring the WebsocketClient + */ +⋮---- +async function main() +⋮---- +/** + * + * This SDK's WebSocket API integration can connect WS API responses to the request that caused them. Each call + * to the `sendWSAPIRequest(...)` method returns a promise. + * + * This promise will resolve when the matching response is detected, and reject if an exception for that request + * is detected. This allows using Bybit's Websocket API in the same way that a REST API normally works. + * + * Send a command and immediately await the result. Handle any exceptions in a catch block. + * + * TypeScript users can benefit from smart type flowing for increased type safety & convenience: + * - Request parameters are fully typed, depending on the operation in the second parameter to the call. E.g. + * the `order.create` operation will automatically require the params to match the `OrderParamsV5` interface. + * + * - Response parameters are fully typed, depending on the operation in the second parameter. E.g the `order.create` + * operation will automatically map the returned value to `WSAPIResponse`. + * + */ +⋮---- +// To make it easier to watch, wait a few seconds before sending the amend order +⋮---- +// Then wait a few more before sending the cancel order +⋮---- +/** + * + * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send + * your first command. That connection will then be reused for every command you send, unless the connection drops - then + * it will automatically be replaced with a healthy connection. + * + * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection + * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands. This is optional. + * + */ +⋮---- +// Optional, see above. Can be used to prepare a connection before sending commands +⋮---- +/** + * Create a new order + */ +⋮---- +// The type for `wsAPISubmitOrderResult` is automatically resolved to `WSAPIResponse` +⋮---- +// Save the orderId for the next call +⋮---- +// The type for `wsAPIAmendOrderResult` is automatically resolved to `WSAPIResponse` +⋮---- +// Save the orderId for the next call +⋮---- +// The type for `wsAPICancelOrderResult` is automatically resolved to `WSAPIResponse` +⋮---- +// Start executing the example workflow -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. +================ +File: src/constants/enum.ts +================ +/** Full take profit/stop loss mode (a single TP order and a single SL order can be placed, covering the entire position) */ +⋮---- +/** Partial take profit/stop loss mode (multiple TP and SL orders can be placed, covering portions of the position) */ +⋮---- +/** This could mean bad request, incorrect value types or even incorrect/missing values */ +⋮---- +/** API key requires specific whitelisted IPs, and this IP was not in the list */ +⋮---- +/** Account not unified margin, update required */ +⋮---- +/** Seen when placing an order */ +⋮---- +/** Seen if a conditional order is too large */ +⋮---- +/** E.g. trying to change position margin while on cross */ +⋮---- +/** E.g. USDC Options trading, trying to access a symbol that is no longer active */ +⋮---- +/** E.g. USDC Options trading when the account hasn't been opened for USDC Options yet */ +⋮---- +/** + * Position idx, used to identify positions in different position modes. + * Required if you are under One-Way Mode: + */ +export enum LinearPositionIdx { + OneWayMode = 0, + BuySide = 1, + SellSide = 2, +} -| 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 | +================ +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; + slippage: string; + quoteData: string; + gas: string; + quoteMode: 0 | 1 | 2; + correctingCode: string; + tenant?: string; +} +⋮---- +export interface GetAlphaPayTokenListParamsV5 { + chainCode: string; + tokenAddress: string; +} +⋮---- +export interface GetAlphaTradeOrderListParamsV5 { + limit: number; + pageIndex: number; + tradeType?: number; + tokenCode?: string; + orderStatus?: number[]; + days?: number; + direction?: 'prev' | 'next'; +} +⋮---- +export interface GetAlphaBizTokenListParamsV5 { + tokenTag?: number; +} +⋮---- +export interface AlphaTokenAddressInfoV5 { + chainCode: string; + tokenAddress: string; +} +⋮---- +export interface GetAlphaBizTokenPriceListParamsV5 { + tokenAddressInfo: AlphaTokenAddressInfoV5[]; +} +⋮---- +export interface GetAlphaBizTokenDetailsParamsV5 { + chainCode: string; + tokenAddress: string; +} +⋮---- +export interface GetAlphaAssetDetailParamsV5 { + chainCode: string; + tokenAddress: string; +} -The `category` parameter matters: +================ +File: src/types/request/v5-broker.ts +================ +export interface GetExchangeBrokerEarningsParamsV5 { + bizType?: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; + begin?: string; + end?: string; + uid?: string; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetBrokerSubAccountDepositsV5 { + id?: string; + txID?: string; + subMemberId?: string; + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +export interface IssueVoucherParamsV5 { + accountId: string; + awardId: string; + specCode: string; + amount: string; + brokerId: string; +} +⋮---- +export interface GetBrokerIssuedVoucherParamsV5 { + accountId: string; + awardId: string; + specCode: string; + withUsedAmount?: boolean; +} +⋮---- +/** Set Rate Limit - exchange broker only. API rate limit: 1 req per second. */ +export interface SetBrokerRateLimitParamsV5 { + list: { + uids: string; + bizType: string; + rate: number; + }[]; +} +⋮---- +/** Get All Rate Limits - exchange broker only. API rate limit: 1 req per second. */ +export interface GetAllBrokerRateLimitsParamsV5 { + limit?: string; + cursor?: string; + uids?: string; +} -| 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. +================ +File: src/types/request/v5-card.ts +================ +/** + * Bybit Card — /v5/card/* + * Authenticated; API key permission per Bybit (often card-related). + */ +⋮---- +export interface QueryCardAssetRecordsParamsV5 { + /** 0: Pending, 1: Cleared, 2: Declined */ + statusCode?: string; + /** Default 100, range [1, 500] */ + limit?: number; + /** Default 1, min 1 */ + page?: number; + /** Last 2/4 digits of card number */ + pan4?: string; + createBeginTime?: number; + createEndTime?: number; + /** Fuzzy search */ + merchName?: string; + /** Authorization / Clearing / Refund (see Bybit) */ + type?: string; + txnId?: string; + cardToken?: string; + orderNo?: string; +} +⋮---- +/** 0: Pending, 1: Cleared, 2: Declined */ +⋮---- +/** Default 100, range [1, 500] */ +⋮---- +/** Default 1, min 1 */ +⋮---- +/** Last 2/4 digits of card number */ +⋮---- +/** Fuzzy search */ +⋮---- +/** Authorization / Clearing / Refund (see Bybit) */ +⋮---- +export interface QueryCardPointRecordsParamsV5 { + type?: string; + pageSize?: number; + pageNo?: number; + startTime?: number; + endTime?: number; + outOrderId?: string; + bizId?: string; + bizTxnId?: string; + /** 1: Earn, 2: Deduct */ + side?: string; +} +⋮---- +/** 1: Earn, 2: Deduct */ +⋮---- +export interface QueryCardMallItemListParamsV5 { + pageNo?: number; + pageSize?: number; + /** 1: Virtual, 2: Physical */ + itemType?: number; + /** 1: POINTS, 2: CURRENCY */ + itemBizType?: number; + /** 1: Priority, 2: Listing time, 3: Price */ + orderBy?: number; + asc?: boolean; + /** 0: Default, 1: VIP */ + source?: number; +} +⋮---- +/** 1: Virtual, 2: Physical */ +⋮---- +/** 1: POINTS, 2: CURRENCY */ +⋮---- +/** 1: Priority, 2: Listing time, 3: Price */ +⋮---- +/** 0: Default, 1: VIP */ +⋮---- +export interface QueryCardPointCashbackDetailParamsV5 { + bizTxnId: string; +} -For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). +================ +File: src/types/request/v5-earn-advance-discount.ts +================ +/** + * /v5/earn/advance/ — product-extra, place order, position, order (Discount Buy, Dual Assets, etc.) + */ +export type GetAdvanceEarnProductExtraInfoParamsV5 = + | { + category: 'DiscountBuy'; + productId?: string; + } + | { + category: 'DualAssets'; + /** Required for Dual Assets quote. */ + productId: string; + }; +⋮---- +/** Required for Dual Assets quote. */ +⋮---- +export interface AdvanceEarnDiscountBuyExtraV5 { + initialPrice: string; + purchasePrice: string; + knockoutPrice: string; + knockoutCouponE8: string; + settleType: 'Base' | 'Quote'; + instUid: string; +} +⋮---- +export interface AdvanceEarnDualAssetsExtraV5 { + orderDirection: 'BuyLow' | 'SellHigh'; + selectPrice: string; + /** Expected APY in e8 precision; API may return int. */ + apyE8: string | number; +} +⋮---- +/** Expected APY in e8 precision; API may return int. */ +⋮---- +export interface AdvanceEarnInterestCardExtraV5 { + awardId: string | number; + specCode: string; +} +⋮---- +/** + * POST /v5/earn/advance/place-order — Discount Buy + */ +export interface SubmitAdvanceEarnPlaceOrderDiscountBuyV5 { + category: 'DiscountBuy'; + productId: string; + orderType: 'Stake'; + amount: string; + coin: string; + accountType: 'FUND' | 'UNIFIED'; + orderLinkId: string; + discountBuyExtra: AdvanceEarnDiscountBuyExtraV5; +} +⋮---- +/** + * POST /v5/earn/advance/place-order — Dual Assets + */ +export interface SubmitAdvanceEarnPlaceOrderDualAssetsV5 { + category: 'DualAssets'; + productId: string; + orderType: 'Stake'; + amount: string; + coin: string; + accountType: 'FUND' | 'UNIFIED'; + orderLinkId: string; + dualAssetsExtra: AdvanceEarnDualAssetsExtraV5; + interestCard?: AdvanceEarnInterestCardExtraV5; +} +⋮---- +export type SubmitAdvanceEarnPlaceOrderParamsV5 = + | SubmitAdvanceEarnPlaceOrderDiscountBuyV5 + | SubmitAdvanceEarnPlaceOrderDualAssetsV5; +⋮---- +export interface GetAdvanceEarnPositionListParamsV5 { + category: 'DiscountBuy' | 'DualAssets' | string; + productId?: string; + coin?: string; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetAdvanceEarnOrderListParamsV5 { + category: 'DiscountBuy' | 'DualAssets' | string; + orderId?: string; + orderLinkId?: string; + productId?: string; + /** Dual Assets docs use string ms; other categories may use number. */ + startTime?: string | number; + endTime?: string | number; + limit?: number; + cursor?: string; +} +⋮---- +/** Dual Assets docs use string ms; other categories may use number. */ -### REST API, streams, and WebSocket API +================ +File: src/types/request/v5-earn-fixed-term.ts +================ +/** + * /v5/earn/fixed-term/* + */ +export interface GetFixedTermEarnProductParamsV5 { + coin?: string; +} +⋮---- +export interface SubmitFixedTermEarnOrderParamsV5 { + productId: string; + category: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; + coin: string; + amount: string; + accountType: 'FUND' | 'UNIFIED'; + orderLinkId: string; + autoInvest?: boolean; +} +⋮---- +export interface RedeemFixedTermEarnParamsV5 { + productId: string; + /** Early redemption: FundPool only */ + category: 'FundPool'; + positionId: string; +} +⋮---- +/** Early redemption: FundPool only */ +⋮---- +export interface GetFixedTermEarnPositionParamsV5 { + productId?: string; + category?: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; + coin?: string; +} +⋮---- +export interface GetFixedTermEarnOrderListParamsV5 { + orderType?: 'Stake' | 'Redeem' | 'Reinvest'; + productId?: string; + category?: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; + orderId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +export interface SetFixedTermEarnAutoInvestParamsV5 { + productId: string; + category: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; + positionId: string; + status: 'Enable' | 'Disable'; +} -Bybit exposes several different integration flows. Keep them separate in your architecture: +================ +File: src/types/request/v5-earn-liquidity-mining.ts +================ +/** + * GET /v5/earn/liquidity-mining/product (public, 50 req/s per IP) + */ +export interface GetLiquidityMiningProductParamsV5 { + baseCoin?: string; + quoteCoin?: string; +} -| 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-earn-pwm.ts +================ +/** GET /v5/earn/pwm/investment-plan/detail */ +export interface GetPwmInvestmentPlanDetailParamsV5 { + planId: 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, -}); - -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); +⋮---- +/** GET /v5/earn/pwm/investment-plan/new-plan */ +export interface GetPwmPendingInvestmentPlanDetailParamsV5 { + planId: 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. - -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); +⋮---- +/** POST /v5/earn/pwm/investment-plan/claim */ +export interface ClaimPwmWithdrawableFundsParamsV5 { + planId: string; + /** Default: FUND */ + toAccountType?: string; + orderLinkId: string; +} +⋮---- +/** Default: FUND */ +⋮---- +/** GET /v5/earn/pwm/investment-plan/asset-trend */ +export interface GetPwmInvestmentPlanAssetTrendParamsV5 { + planId: string; + startTime?: number; + endTime?: number; +} +⋮---- +/** GET /v5/earn/pwm/investment-plan/fund-nav */ +export interface GetPwmFundHistoricalNavParamsV5 { + fundId: string; + startTime?: number; + endTime?: number; +} +⋮---- +/** POST /v5/earn/pwm/investment-plan/subscribe */ +export interface SubscribePwmInvestmentPlanParamsV5 { + planId: string; + /** Default: FUND */ + accountType?: string; + orderLinkId: string; +} +⋮---- +/** Default: FUND */ +⋮---- +/** POST /v5/earn/pwm/investment-plan/invest-more */ +export interface InvestMorePwmInvestmentPlanParamsV5 { + planId: string; + /** Default: FUND */ + accountType?: string; + category: string; + productId: string; + amount: string; + orderLinkId: string; +} +⋮---- +/** Default: FUND */ +⋮---- +/** POST /v5/earn/pwm/investment-plan/redeem */ +export interface RedeemPwmInvestmentPlanParamsV5 { + planId: string; + category: string; + productId: string; + orderLinkId: string; + /** Required for fund products */ + shares?: string; + /** Required for non-fund products */ + amount?: string; + /** Required for FundPool and On-chain Earn */ + positionId?: string; +} +⋮---- +/** Required for fund products */ +⋮---- +/** Required for non-fund products */ +⋮---- +/** Required for FundPool and On-chain Earn */ +⋮---- +/** GET /v5/earn/pwm/investment-plan/order */ +export interface GetPwmInvestmentPlanOrdersParamsV5 { + planId?: string; + category?: string; + type?: 'Subscribe' | 'Redeem' | 'AutoReinvest' | string; + status?: 'Completed' | 'Pending' | 'Failed' | string; + startTime?: string; + endTime?: string; + limit?: number; + cursor?: string; + orderLinkId?: string; +} +⋮---- +/** POST /v5/earn/pwm/customize-plan/create */ +export interface CreatePwmCustomizeInvestmentPlanProductV5 { + category: string; + productId: string; + fundName: string; + amount: string; +} +⋮---- +export interface CreatePwmCustomizeInvestmentPlanParamsV5 { + accountType?: string; + products: CreatePwmCustomizeInvestmentPlanProductV5[]; +} +⋮---- +/** GET /v5/earn/pwm/asset-manager/all-funds */ +export interface GetPwmAllFundsParamsV5 { + coin?: string; + fundId?: string; + status?: string; + limit?: number; + cursor?: string; +} +⋮---- +/** POST /v5/earn/pwm/asset-manager/settle-profit */ +export interface SettlePwmFundProfitParamsV5 { + fundId: string; + reqLinkId: string; +} +⋮---- +/** POST /v5/earn/pwm/asset-manager/create-fund */ +export interface CreatePwmFundParamsV5 { + fundName: string; + coin: string; + profitShareRate: string; + managementFeeRate: string; + fundIntroduction?: string; + reqLinkId: string; +} +⋮---- +/** POST /v5/earn/pwm/asset-manager/create-investment-plan */ +export interface CreatePwmAssetManagerInvestmentPlanDistributionV5 { + productId: string; + amount: string; +} +⋮---- +export interface CreatePwmAssetManagerInvestmentPlanParamsV5 { + accountUid: string; + planName: string; + planType: 'stable' | 'advanced' | string; + investmentDistribution: CreatePwmAssetManagerInvestmentPlanDistributionV5[]; + reqLinkId: string; +} +⋮---- +/** GET /v5/earn/pwm/asset-manager/get-investment-plan */ +export interface GetPwmAssetManagerInvestmentPlansParamsV5 { + planId?: string; + status?: string; + subscriptionUid?: string; + limit?: number; + cursor?: string; +} +⋮---- +/** POST /v5/earn/pwm/asset-manager/manage-investment-plan */ +export interface ManagePwmAssetManagerInvestmentPlanFundV5 { + fundId: string; + amount: string; +} +⋮---- +export interface ManagePwmAssetManagerInvestmentPlanParamsV5 { + planId: string; + updateStatus?: 'Closed' | 'Deleted' | string; + updateFunds?: ManagePwmAssetManagerInvestmentPlanFundV5[]; + reqLinkId: string; +} +⋮---- +/** GET /v5/earn/pwm/asset-manager/all-order */ +export interface GetPwmAllFundOrdersParamsV5 { + fundId?: string; + orderType?: 'Subscribe' | 'Redeem' | string; + status?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +/** POST /v5/earn/pwm/asset-manager/manage-order */ +export interface ManagePwmFundOrderParamsV5 { + orderId: string; + action: 'approve' | 'reject' | string; + reqLinkId: string; +} +⋮---- +/** POST /v5/earn/pwm/asset-manager/create-sub-account */ +export interface CreatePwmFundSubAccountParamsV5 { + fundId: string; + reqLinkId: string; +} +⋮---- +/** POST /v5/earn/pwm/fund-transfer */ +export interface PwmFundTransferParamsV5 { + transferId: string; + fromUserId: number; + toUserId: number; + amount: string; + coin: string; +} +⋮---- +/** GET /v5/earn/pwm/query-fund-transfer-result */ +export interface GetPwmFundTransferRecordsParamsV5 { + transferId?: string; + fromUserId?: number; } -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`, `X-BAPI-SIGN`, or SDK referer 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 +================ +File: src/types/request/v5-earn-token.ts +================ +/** + * Earn token product (e.g. BYUSDT) — /v5/earn/token/* + */ +⋮---- +export interface GetEarnTokenProductParamsV5 { + /** Currently only BYUSDT */ + coin: string; +} +⋮---- +/** Currently only BYUSDT */ +⋮---- +export interface PlaceEarnTokenOrderParamsV5 { + coin: string; + orderLinkId: string; + orderType: 'Mint' | 'Redeem'; + amount: string; + /** Mint: FlexibleSaving; Redeem: UNIFIED */ + accountType: 'FlexibleSaving' | 'UNIFIED'; +} +⋮---- +/** Mint: FlexibleSaving; Redeem: UNIFIED */ +⋮---- +export interface GetEarnTokenOrderListParamsV5 { + coin: string; + orderLinkId?: string; + orderId?: string; + orderType?: 'Mint' | 'Redeem'; + /** seconds */ + startTime?: number; + /** seconds */ + endTime?: number; + cursor?: string; + limit?: number; +} +⋮---- +/** seconds */ +⋮---- +/** seconds */ +⋮---- +export interface GetEarnTokenPositionParamsV5 { + coin: string; +} +⋮---- +export interface GetEarnTokenDailyYieldParamsV5 { + coin: string; + startTime?: number; + endTime?: number; + cursor?: string; + limit?: number; +} +⋮---- +export interface GetEarnTokenHourlyYieldParamsV5 { + coin: string; + startTime?: number; + endTime?: number; + cursor?: string; + limit?: number; +} +⋮---- +export interface GetEarnTokenHistoryAprParamsV5 { + coin: string; + /** 1 = 7d, 2 = 30d, 3 = 180d */ + range: 1 | 2 | 3; +} +⋮---- +/** 1 = 7d, 2 = 30d, 3 = 180d */ -Market order: +================ +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; +} +⋮---- +export interface PositionInfoParamsV5 { + category: CategoryV5; + symbol?: string; + baseCoin?: string; + settleCoin?: string; + limit?: number; + cursor?: string; +} +⋮---- +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; +} -```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: +================ +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 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 +} +⋮---- +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 +} +⋮---- +rfqId: string; // Inquiry ID +quoteId: string; // Quotation ID +quoteSide: 'buy' | 'sell'; // The direction of the quote +⋮---- +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 -```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', -}); +================ +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; +} -await client.switchPositionMode({ - category: 'linear', - coin: 'USDT', - mode: 3, -}); +================ +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 */ +⋮---- +/** 1: market, 2: limit */ +⋮---- +/** POV execution mode */ +⋮---- +/** POV participation rate */ +⋮---- +/** POV: historical traded volume window (seconds), range [60, 14400] */ +⋮---- +/** POV: book depth reference levels [1, 10] */ +⋮---- +/** GET /v5/strategy/list */ +export interface GetStrategyListParamsV5 { + strategyId?: string; + symbol?: string; + /** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ + status?: '2' | '3' | '4' | '5' | '6'; + category?: StrategyCategoryV5; + strategyType?: StrategyTypeV5; + beginTimeE0?: number; + endTimeE0?: number; + pageSize?: number; + cursor?: string; +} +⋮---- +/** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ +⋮---- +/** GET /v5/strategy/order-list */ +export interface GetStrategyOrderListParamsV5 { + strategyId: string; + /** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ + status?: '2' | '3' | '4' | '5' | '6' | '7'; + symbol?: string; + strategyType?: StrategyTypeV5; + beginTimeE0?: number; + endTimeE0?: number; + pageSize?: number; + cursor?: string; +} +⋮---- +/** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ +⋮---- +/** POST /v5/strategy/stop */ +export interface StopStrategyParamsV5 { + strategyId: string; +} -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` tells the SDK which Bybit WebSocket endpoint family a connection belongs to: +================ +File: src/types/request/v5-trade.ts +================ +import { + CategoryV5, + OrderFilterV5, + OrderSideV5, + OrderSMPTypeV5, + OrderStatusV5, + OrderTimeInForceV5, + OrderTriggerByV5, + OrderTypeV5, + PositionIdx, + StopOrderTypeV5, +} from '../shared-v5'; +⋮---- +export interface OrderParamsV5 { + category: CategoryV5; + symbol: string; + isLeverage?: 0 | 1; + side: OrderSideV5; + orderType: OrderTypeV5; + qty: string; + marketUnit?: 'baseCoin' | 'quoteCoin'; + slippageToleranceType?: string; + slippageTolerance?: string; + price?: string; + triggerDirection?: 1 | 2; + orderFilter?: OrderFilterV5; + triggerPrice?: string; + triggerBy?: OrderTriggerByV5; + orderIv?: string; + timeInForce?: OrderTimeInForceV5; + positionIdx?: PositionIdx; + orderLinkId?: string; + takeProfit?: string; + stopLoss?: string; + tpTriggerBy?: OrderTriggerByV5; + slTriggerBy?: OrderTriggerByV5; + reduceOnly?: boolean; + closeOnTrigger?: boolean; + smpType?: OrderSMPTypeV5; + mmp?: boolean; + tpslMode?: 'Full' | 'Partial'; + tpLimitPrice?: string; + slLimitPrice?: string; + tpOrderType?: OrderTypeV5; + slOrderType?: OrderTypeV5; + bboSideType?: 'Queue' | 'Counterparty'; + bboLevel?: '1' | '2' | '3' | '4' | '5'; + rpiTakerAccess?: boolean; +} +⋮---- +export interface AmendOrderParamsV5 { + category: CategoryV5; + symbol: string; + orderId?: string; + orderLinkId?: string; + orderIv?: string; + triggerPrice?: string; + qty?: string; + price?: string; + tpslMode?: 'Full' | 'Partial'; + takeProfit?: string; + stopLoss?: string; + tpTriggerBy?: OrderTriggerByV5; + slTriggerBy?: OrderTriggerByV5; + triggerBy?: OrderTriggerByV5; + tpLimitPrice?: string; + slLimitPrice?: string; +} +⋮---- +export interface CancelOrderParamsV5 { + category: CategoryV5; + symbol: string; + orderId?: string; + orderLinkId?: string; + orderFilter?: OrderFilterV5; +} +⋮---- +export interface GetAccountOrdersParamsV5 { + category: CategoryV5; + symbol?: string; + baseCoin?: string; + settleCoin?: string; + orderId?: string; + orderLinkId?: string; + openOnly?: 0 | 1 | 2; + orderFilter?: OrderFilterV5; + orderStatus?: OrderStatusV5; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetAccountHistoricOrdersParamsV5 { + category: CategoryV5; + symbol?: string; + baseCoin?: string; + settleCoin?: string; + orderId?: string; + orderLinkId?: string; + orderFilter?: OrderFilterV5; + orderStatus?: OrderStatusV5; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} +⋮---- +export interface CancelAllOrdersParamsV5 { + category: CategoryV5; + symbol?: string; + baseCoin?: string; + settleCoin?: string; + orderFilter?: OrderFilterV5; + stopOrderType?: StopOrderTypeV5; +} +⋮---- +export interface BatchOrderParamsV5 { + symbol: string; + side: OrderSideV5; + isLeverage?: 0 | 1; + orderType: OrderTypeV5; + qty: string; + price?: string; + triggerDirection?: 1 | 2; + triggerBy?: OrderTriggerByV5; + orderIv?: string; + timeInForce?: OrderTimeInForceV5; + positionIdx?: PositionIdx; + orderLinkId?: string; + takeProfit?: string; + stopLoss?: string; + tpTriggerBy?: OrderTriggerByV5; + slTriggerBy?: OrderTriggerByV5; + reduceOnly?: boolean; + closeOnTrigger?: boolean; + smpType?: OrderSMPTypeV5; + mmp?: boolean; + tpslMode?: 'Full' | 'Partial'; + tpLimitPrice?: string; + slLimitPrice?: string; + tpOrderType?: OrderTypeV5; + slOrderType?: OrderTypeV5; +} +⋮---- +export interface BatchAmendOrderParamsV5 { + symbol: string; + orderId?: string; + orderLinkId?: string; + orderIv?: string; + triggerPrice?: string; + qty?: string; + price?: string; + tpslMode?: 'Full' | 'Partial'; + takeProfit?: string; + stopLoss?: string; + tpTriggerBy?: OrderTriggerByV5; + slTriggerBy?: OrderTriggerByV5; + triggerBy?: OrderTriggerByV5; + tpLimitPrice?: string; + slLimitPrice?: string; +} +⋮---- +export interface BatchCancelOrderParamsV5 { + symbol: string; + orderId?: string; + orderLinkId?: string; +} -| 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 +================ +File: src/types/response/v5-alpha-trade.ts +================ +/** + * V5 private Alpha / on-chain (Web3) trade responses. + */ +⋮---- +export interface AlphaTradeQuoteModeEstimationV5 { + quoteMode: number; + estimatedGas: string; + estimatedGasUsd: string; + estimatedSlippage: 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 ExecuteAlphaTradeResultV5 { + orderNo: string; +} +⋮---- +export interface AlphaPayTokenV5 { + tokenCode: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + limit: string; + supportChains: 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 AlphaTradeOrderListResultV5 { + total: number; + pageIndex: number; + orders: AlphaTradeOrderV5[]; +} +⋮---- +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 AlphaBizTokenPriceV5 { + chainCode: string; + tokenAddress: string; + price: string; + change24h: string; + vol24h: string; + marketCap: string; + liquidity: string; + holders: string; +} +⋮---- +export interface AlphaBizTokenPriceListResultV5 { + tokenPriceInfoList: AlphaBizTokenPriceV5[]; +} +⋮---- +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 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 AlphaAssetListResultV5 { + totalAssetUsd: string; + assetList: AlphaAssetV5[]; +} +⋮---- +export interface AlphaAssetDetailResultV5 { + assetList: AlphaAssetV5[]; +} -```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: +================ +File: src/types/response/v5-broker.ts +================ +interface EarningDetailV5 { + userId: string; + bizType: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; + symbol: string; + coin: string; + earning: string; + markupEarning: string; + baseFeeEarning: string; + orderId: string; + execTime: string; +} +⋮---- +interface TotalEarningCategoryV5 { + coin: string; + earning: string; +} +⋮---- +export interface ExchangeBrokerEarningResultV5 { + totalEarningCat: { + spot: TotalEarningCategoryV5[]; + derivatives: TotalEarningCategoryV5[]; + options: TotalEarningCategoryV5[]; + convert: TotalEarningCategoryV5[]; + total: TotalEarningCategoryV5[]; + }; + details: EarningDetailV5[]; + nextPageCursor: string; +} +⋮---- +export interface ExchangeBrokerAccountInfoV5 { + subAcctQty: string; + maxSubAcctQty: string; + baseFeeRebateRate: { + spot: string; + derivatives: string; + }; + markupFeeRebateRate: { + spot: string; + derivatives: string; + convert: string; + }; + ts: 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 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 BrokerIssuedVoucherV5 { + accountId: string; + awardId: string; + specCode: string; + amount: string; + isClaimed: boolean; + startAt: string; + endAt: string; + effectiveAt: string; + ineffectiveAt: string; + usedAmount: string; +} +⋮---- +export interface BrokerRateLimitSetResultItemV5 { + uids: string; + bizType: string; + rate: number; + success: boolean; + msg: string; +} +⋮---- +export interface BrokerRateLimitCapItemV5 { + bizType: string; + totalRate: string; + ebCap: string; + uidCap: string; +} +⋮---- +export interface BrokerRateLimitAllItemV5 { + uids: string; + bizType: string; + rate: number; +} -```typescript -const marketDataA = new WebsocketClient(); -const marketDataB = new WebsocketClient(); +================ +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 CardAssetRecordsResultV5 { + pageSize: number; + pageNo: number; + totalCount: number; + data: CardAssetRecordV5[]; +} +⋮---- +export interface CardPointBalanceV5 { + accountId: string; + availablePoint: string | number; + pendingPoint: string | number; + status: string; + updateTime: string | number; + settlementPeriod: number; +} +⋮---- +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 CardPointRecordsResultV5 { + pageSize: number; + pageNo: number; + totalCount: number; + data: CardPointRecordV5[]; +} +⋮---- +export interface CardPointTierInfoV5 { + usedLimit: string; + limit: string; + unit: string; + tier: string; + autoCashback: boolean; +} +⋮---- +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 CardMallItemListResultV5 { + pageNo: number; + pageSize: number; + totalCount: number; + data: CardMallItemV5[]; +} +⋮---- +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; +} -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', -}); +================ +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; +} +⋮---- +/** GET /v5/earn/advance/product-extra-info?category=DiscountBuy */ +export interface AdvanceEarnProductExtraInfoDiscountBuyV5 { + offers: AdvanceEarnDiscountBuyOfferV5[]; +} +⋮---- +export interface AdvanceEarnDualAssetQuoteLevelV5 { + selectPrice: string; + apyE8: string; + maxInvestmentAmount: string; + expiredAt: string; +} +⋮---- +export interface AdvanceEarnDualAssetQuoteProductV5 { + productId: string; + currentPrice: string; + buyLowPrice: AdvanceEarnDualAssetQuoteLevelV5[]; + sellHighPrice: AdvanceEarnDualAssetQuoteLevelV5[]; +} +⋮---- +/** GET /v5/earn/advance/product-extra-info?category=DualAssets&productId= */ +export interface AdvanceEarnProductExtraInfoDualAssetsV5 { + category: 'DualAssets'; + list: AdvanceEarnDualAssetQuoteProductV5[]; +} +⋮---- +export type AdvanceEarnProductExtraInfoV5 = + | AdvanceEarnProductExtraInfoDiscountBuyV5 + | AdvanceEarnProductExtraInfoDualAssetsV5; +⋮---- +export interface AdvanceEarnPlaceOrderResultV5 { + orderId: string; + orderLinkId: 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 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 AdvanceEarnPositionListV5 { + category: string; + list: (AdvanceEarnDiscountBuyPositionV5 | AdvanceEarnDualAssetsPositionV5)[]; + nextPageCursor: string; +} +⋮---- +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 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 AdvanceEarnOrderListV5 { + category: string; + list: (AdvanceEarnDiscountBuyOrderV5 | AdvanceEarnDualAssetsOrderV5)[]; + nextPageCursor: string; +} -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) +================ +File: src/types/response/v5-earn-fixed-term.ts +================ +export interface FixedTermEarnTieredApyV5 { + min: string; + max: string; + apy: string; +} +⋮---- +export interface FixedTermEarnInterestCoinApyV5 { + coin: string; + apy: string; + expectUnitEarning: string; + currentPrice: 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 FixedTermEarnProductListV5 { + list: FixedTermEarnProductV5[]; +} +⋮---- +export interface FixedTermEarnPlaceOrderResultV5 { + orderId: string; + orderLinkId: string; +} +⋮---- +export interface RedeemFixedTermEarnResultV5 { + redeemAmount: string; + estEarnings: string; +} +⋮---- +export interface FixedTermEarnEarlyRedeemInfoV5 { + allowEarlyRedeem: boolean; + earlyRedeemEarning: string; + returnCoin: string; + redemptionLimitDuration: string; +} +⋮---- +export interface FixedTermEarnPositionInterestV5 { + coin: string; + apy: string; + expectReturnEarning: string; + price: 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 FixedTermEarnPositionListV5 { + list: FixedTermEarnPositionV5[]; +} +⋮---- +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 FixedTermEarnOrderListV5 { + list: FixedTermEarnOrderV5[]; + nextPageCursor: string; +} ---- - -## 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, openOrders] = await Promise.all([ - client.getWalletBalance({ accountType: 'UNIFIED' }), - client.getPositionInfo({ category: 'linear', settleCoin: 'USDT' }), - client.getActiveOrders({ category: 'linear', settleCoin: 'USDT' }), - ]); - - // Reconcile these with your local state before resuming risky actions. - console.log({ wallet, positions, openOrders }); -}); -``` - -### 3. Use `orderLinkId` deliberately - -For order workflows, generate and store your own `orderLinkId` when you need idempotency, retries, or reconciliation. - -```typescript -const orderLinkId = `entry-btc-${Date.now()}`; - -await client.submitOrder({ - category: 'linear', - symbol: 'BTCUSDT', - side: 'Buy', - orderType: 'Limit', - qty: '0.001', - price: '10000', - timeInForce: 'PostOnly', - orderLinkId, -}); -``` - -Persist the ID before sending the request. Then match it against REST API order history and private WebSocket order/execution events. That gives your system a stable way to connect local intent with exchange-side order state. - -### 4. 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 - -### 5. 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. - -### 6. 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. - -### 7. 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: src/types/response/v5-earn-liquidity-mining.ts +================ +export interface LiquidityMiningApyBreakdownV5 { + coin: string; + apy: 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[]; +} +⋮---- +export interface LiquidityMiningProductResultV5 { + products: LiquidityMiningProductV5[]; +} ================ -File: examples/Auth/fasterHmacSign.ts +File: src/types/response/v5-earn-pwm.ts ================ -import { createHmac } from 'crypto'; +export interface PwmCoinAmountV5 { + coin: string; + amount: string; +} ⋮---- -import { DefaultLogger, RestClientV5, WebsocketClient } from '../../src/index'; +export interface PwmMultiCoinsEarningPositionItemV5 { + category: string; + productId: string; + coin: string; + currentAmount: string; + accumulateYield: string; + apr: string; + positionId: string; + status?: string; +} ⋮---- -// or -// import { createHmac } from 'crypto'; -// import { DefaultLogger, RestClientV5, WebsocketClient } from 'bybit-api'; +export interface PwmMultiCoinsEarningPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + items: PwmMultiCoinsEarningPositionItemV5[]; +} ⋮---- -/** - * Injecting a custom signMessage function. - * - * As of version 4.0.0 of the bybit-api Node.js/TypeScript/JavaScript - * SDK for Bybit, the SDK uses the Web Crypto API for signing requests. - * While it is compatible with Node and Browser environments, it is - * slightly slower than using Node's native crypto module (only - * available in backend Node environments). - * - * For latency sensitive users, you can inject the previous node crypto sign - * method (or your own even faster-implementation), if this change affects you. - * - * This example demonstrates how to inject a custom sign function, to achieve - * the same peformance as seen before the Web Crypto API was introduced. - * - * For context on standard usage, the "signMessage" function is used: - * - During every single API call - * - After opening a new private WebSocket connection - * - */ +export interface PwmFixedYieldPositionItemV5 { + category: string; + productId: string; + coin: string; + currentAmount: string; + accumulateYield: string; + apr: string; + duration: number; + maturityTime: string; + autoReinvest: boolean; + positionId: string; + status?: string; +} ⋮---- -/** - * Set this to true to enable demo trading: - */ -⋮---- -/** - * Overkill in almost every case, but if you need any optimisation available, - * you can inject a faster sign mechanism such as node's native createHmac: - */ +export interface PwmFixedYieldPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + items: PwmFixedYieldPositionItemV5[]; +} ⋮---- -// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing +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; +} ⋮---- -// trace: (...params) => console.log('trace', ...params), +export interface PwmEquityFundsPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + weightedAvgApr: string; + items: PwmEquityFundPositionItemV5[]; +} ⋮---- -/** - * Set this to true to enable demo trading for the private account data WS - * Topics: order,execution,position,wallet,greeks - */ +export interface PwmOnchainEarnPositionItemV5 { + category: string; + productId: string; + coin: string; + stakeAmount: string; + apr: string; + positionId: string; + status?: string; +} ⋮---- -/** - * Overkill in almost every case, but if you need any optimisation available, - * you can inject a faster sign mechanism such as node's native createHmac: - */ +export interface PwmOnchainEarnPositionsV5 { + totalInvestmentUsd: string; + accumulateYieldUsd: string; + items: PwmOnchainEarnPositionItemV5[]; +} ⋮---- -function setWsClientEventListeners( - websocketClient: WebsocketClient, - accountRef: string, -): Promise +export interface PwmInvestmentPlanPositionsV5 { + multiCoinsEarning?: PwmMultiCoinsEarningPositionsV5; + fixedYield?: PwmFixedYieldPositionsV5; + equityFunds?: PwmEquityFundsPositionsV5; + onchainEarn?: PwmOnchainEarnPositionsV5; + fundingAccount?: PwmCoinAmountV5[]; +} ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +/** 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; +} ⋮---- -// Simple promise to ensure we're subscribed before trying anything else +export interface PwmInvestmentPlanListResultV5 { + list: PwmInvestmentPlanSummaryV5[]; +} ⋮---- -// Start trading +/** 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; +} ⋮---- -/** Simple examples for private REST API calls with bybit's V5 REST APIs */ +export interface PwmEquityFundIntroductionV5 { + description: string; + historicalYieldRateMax: string; + historicalYieldRateMin: string; + sharpRatio: string; + maxDrawback: string; + lockupPeriod: string; +} ⋮---- -// Trade USDT linear perps - -================ -File: examples/Rest/demo-trading.ts -================ -import { DefaultLogger, RestClientV5, WebsocketClient } from '../../src/index'; +export interface PwmPendingMultiCoinsEarningItemV5 { + category: string; + productId: string; + coin: string; + configuredAmount: string; + apr: string; +} ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; +export interface PwmPendingFixedYieldItemV5 { + category: string; + productId: string; + coin: string; + configuredAmount: string; + apr: string; + duration: number; +} ⋮---- -/** - * - * - * This example demonstrates how to use Bybit's demo trading functionality, both for REST and WS. - * - * Refer to the API docs for more information: https://bybit-exchange.github.io/docs/v5/demo - * - * - */ +export interface PwmPendingEquityFundItemV5 { + category: string; + productId: string; + fundName: string; + coin: string; + configuredAmount: string; + tags: string[]; + introduction: PwmEquityFundIntroductionV5; +} ⋮---- -/** - * Set this to true to enable demo trading: - */ +export interface PwmPendingOnchainEarnItemV5 { + category: string; + productId: string; + coin: string; + configuredAmount: string; + apr: string; +} ⋮---- -// Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing +export interface PwmPendingInvestmentPlanProductsV5 { + multiCoinsEarning?: { + configuredAmountUsd: string; + items: PwmPendingMultiCoinsEarningItemV5[]; + }; + fixedYield?: { + configuredAmountUsd: string; + items: PwmPendingFixedYieldItemV5[]; + }; + equityFunds?: { + configuredAmountUsd: string; + items: PwmPendingEquityFundItemV5[]; + }; + onchainEarn?: { + configuredAmountUsd: string; + items: PwmPendingOnchainEarnItemV5[]; + }; +} ⋮---- -// trace: (...params) => console.log('trace', ...params), +/** 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; +} ⋮---- -/** - * Set this to true to enable demo trading for the private account data WS - * Topics: order,execution,position,wallet,greeks - */ +/** POST /v5/earn/pwm/investment-plan/claim */ +export interface ClaimPwmWithdrawableFundsResultV5 { + planId: string; + toAccountType: number; + status: string; + createdTime: string; +} ⋮---- -function setWsClientEventListeners( - websocketClient: WebsocketClient, - accountRef: string, -): Promise +export interface PwmAssetTrendDataPointV5 { + date: string; + assetValueUsd: string; +} ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +/** GET /v5/earn/pwm/investment-plan/asset-trend */ +export interface PwmInvestmentPlanAssetTrendResultV5 { + planId: string; + dataPoints: PwmAssetTrendDataPointV5[]; +} ⋮---- -// Simple promise to ensure we're subscribed before trying anything else +export interface PwmFundNavDataPointV5 { + date: string; + nav: string; +} ⋮---- -// Start trading +/** GET /v5/earn/pwm/investment-plan/fund-nav */ +export interface PwmFundHistoricalNavResultV5 { + fundId: string; + fundName: string; + coin: string; + currentNav: string; + dataPoints: PwmFundNavDataPointV5[]; +} ⋮---- -/** Simple examples for private REST API calls with bybit's V5 REST APIs */ +/** POST /v5/earn/pwm/investment-plan/subscribe */ +export interface SubscribePwmInvestmentPlanResultV5 { + planId: string; + status: string; + orderLinkId: string; +} ⋮---- -// Trade USDT linear perps - -================ -File: examples/Rest/rest-v5-all.ts -================ -import { RestClientV5 } from '../../src/index'; +/** 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; +} ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; -⋮---- -/** - * If you don't plan on making any private api calls, - * you can instance the REST client without any parameters: - * - * const client = new RestClientV5(); - */ - -================ -File: examples/Rest/rest-v5-custom-url.ts -================ -import { RestClientV5 } from '../../src/index'; +/** 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; +} ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; +/** 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; +} ⋮---- -/** - * The first parameter of the REST client allows you to pass any configuration parameters supported by the SDK. - * - * These include API keys, if you wish to use private endpoints, but also expose other features such as - * setting a custom base URL (e.g. for Turkish users). - * - * Refer to the API documentation for a complete list of domains: https://bybit-exchange.github.io/docs/v5/guide#authentication - */ +export interface PwmInvestmentPlanOrdersResultV5 { + list: PwmInvestmentPlanOrderV5[]; + nextPageCursor: string; +} ⋮---- -/** - * You can pass a completely custom base URL, - * e.g. if you're trying to use a domain that hasn't been added yet (please let us know) - */ -// baseUrl: 'https://api5.bybit.com', -// -// -/** - * - * There are also predefined API regions, which you can easily use with the "apiRegion" property: - * - */ -// -// -// default: routes to api.bybit.com -// apiRegion: 'default', -// -// -// bytick: routes to api.bytick.com -// apiRegion: 'bytick', -// -// -// NL: routes to api.bybit.nl (for Netherland users) -// apiRegion: 'NL', -// -// -// HK: routes to api.byhkbit.com (for Hong Kong users) -// apiRegion: 'HK', -// -// -// TK: routes to api.bybit-tr.com (for Turkey users) -// apiRegion: 'TK', - -================ -File: examples/Rest/rest-v5-next-cursor.ts -================ -import { RestClientV5, UniversalTransferRecordV5 } from '../../src/index'; +/** 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; +} ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; +export interface PwmSubscribableProductGroupV5 { + type: string; + cards: PwmSubscribableProductCardV5[]; +} ⋮---- -async function getAllUniversalTransfers() +export interface PwmSubscribableProductInfoResultV5 { + products: PwmSubscribableProductGroupV5[]; +} ⋮---- -limit: 50, // Maximum page size per request -cursor: nextCursor || undefined, // Only send cursor if we have one +/** POST /v5/earn/pwm/customize-plan/create */ +export interface CreatePwmCustomizeInvestmentPlanResultV5 { + planId: string; + planName: string; + status: string; + orderLinkId?: string; +} ⋮---- -// Optional: Add a small delay to avoid rate limits - -================ -File: examples/Rest/rest-v5-p2p.ts -================ -import fs from 'fs'; -import path from 'path'; +/** 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; +} ⋮---- -import { RestClientV5 } from '../../src'; +export interface PwmAllFundsResultV5 { + list: PwmAssetManagerFundV5[]; + nextPageCursor: string; +} ⋮---- -// ENDPOINT: /v5/p2p/oss/upload_file -// METHOD: POST -// PUBLIC: NO -// NOTE: Node.js only (Buffer required) +/** POST /v5/earn/pwm/asset-manager/settle-profit */ +export interface SettlePwmFundProfitResultV5 { + fundId: string; + status: string; + totalProfitShared: string; + instIncome: string; + coin: string; + createdTime: string; +} ⋮---- -async function uploadP2PChatFile() +/** 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; +} ⋮---- -// You must read the file yourself and pass the Buffer + filename +/** POST /v5/earn/pwm/asset-manager/create-investment-plan */ +export interface CreatePwmAssetManagerInvestmentPlanResultV5 { + planId: string; + planType: string; + accountUid: string; + status: string; + createdTime: string; +} ⋮---- -/** - * - * - * - * - * - * - */ +/** GET /v5/earn/pwm/asset-manager/get-investment-plan */ +export interface PwmAssetManagerInvestmentPlanDistributionV5 { + category: string; + coin: string; + productId: string; + currentAmount: string; +} ⋮---- -// Test basic P2P API connectivity +export interface PwmAssetManagerInvestmentPlanV5 { + planId: string; + planName: string; + planType: string; + subscriptionUid: string; + status: string; + source: string; + currentAssetUsd: string; + accumulateYieldUsd: string; + investmentDistribution: PwmAssetManagerInvestmentPlanDistributionV5[]; + createdTime: string; +} ⋮---- -// Example 1: Upload from file path +export interface PwmAssetManagerInvestmentPlansResultV5 { + list: PwmAssetManagerInvestmentPlanV5[]; + nextPageCursor: string; +} ⋮---- -fileName: path.basename(filePath), // Extract filename from path +/** POST /v5/earn/pwm/asset-manager/manage-investment-plan */ +export interface ManagePwmAssetManagerInvestmentPlanFundResultV5 { + fundId: string; + amount: string; +} ⋮---- -// Example 2: Upload with custom filename -// You control the filename sent to Bybit +export interface ManagePwmAssetManagerInvestmentPlanResultV5 { + planId: string; + status: string; + updatedTime: string; + updateFunds: ManagePwmAssetManagerInvestmentPlanFundResultV5[]; +} ⋮---- -fileName: 'custom-name.png', // Use any filename you want +/** 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; +} ⋮---- -// Example 3: Upload different file +export interface PwmAllFundOrdersResultV5 { + list: PwmAssetManagerFundOrderV5[]; + nextPageCursor: string; +} ⋮---- -// Supported file types (determined by filename extension): -// - Images: jpg, jpeg, png -// - Documents: pdf -// - Videos: mp4 - -================ -File: examples/Rest/rest-v5-private.ts -================ -import { RestClientV5 } from '../../src/index'; +/** 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; +} ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; +/** POST /v5/earn/pwm/asset-manager/create-sub-account */ +export interface CreatePwmFundSubAccountResultV5 { + fundId: string; + subAccountUid: string; + createdTime: string; + status: string; +} ⋮---- -/** Simple examples for private REST API calls with bybit's V5 REST APIs */ +/** POST /v5/earn/pwm/fund-transfer */ +export interface PwmFundTransferResultV5 { + transferId: string; + status: string; +} ⋮---- -// Trade USDT linear perps +/** GET /v5/earn/pwm/query-fund-transfer-result */ +export interface PwmFundTransferRecordV5 { + transferId: string; + status: string; + fromUserId: number; + toUserId: number; + amount: string; + coin: string; +} ================ -File: examples/Rest/rest-v5-proxies.ts +File: src/types/response/v5-earn-token.ts ================ -import { RestClientV5 } from '../../src/index'; +/** + * Earn token product (e.g. BYUSDT) — /v5/earn/token/* + */ ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; +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; +} ⋮---- -// 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, +export interface PlaceEarnTokenOrderResultV5 { + orderId: string; + orderLinkId: string; +} ⋮---- -/** - * Axios has a native way of supporting http/https proxies. It works for most proxy services but not all. - * If you have issues making any proxied requests this way, take a look at the rest-v5-proxies2.ts example using the https-proxy-agent. - */ +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; +} ⋮---- -protocol: 'http', // or 'https' +export interface EarnTokenPositionV5 { + totalAmount: string; + totalYield: string; + yesterdayYield: string; + aprE8: number; + bonusAprE8: number; + bonusMaxAmount: string; + hasQuota: boolean; +} ⋮---- -// const orders = await client.batchSubmitOrders('linear', [ -// { -// symbol: 'ETHUSDT', -// orderType: 'Limit', -// side: 'Buy', -// qty: '1', -// orderIv: '6', -// timeInForce: 'GTC', -// orderLinkId: 'option-test-001', -// mmp: false, -// reduceOnly: false, -// }, -// { -// symbol: 'ETHUSDT', -// orderType: 'Limit', -// side: 'Sell', -// qty: '2', -// price: '700', -// timeInForce: 'GTC', -// orderLinkId: 'option-test-001', -// mmp: false, -// reduceOnly: false, -// }, -// ]); +export interface EarnTokenDailyYieldRecordV5 { + yield: string; + bonusYield: string; + status: 'Success' | 'Processing'; + createdTime: string; +} ⋮---- -// console.log('orders: ', JSON.stringify(orders, null, 2)); +export interface EarnTokenHourlyYieldRecordV5 { + effectiveAmount: string; + yield: string; + rewardType: 0 | 1; + aprE8: string; + hourlyDate: string; + createdTime: string; +} +⋮---- +export interface EarnTokenHistoryAprPointV5 { + timestamp: string; + aprE8: string; +} ================ -File: examples/Rest/rest-v5-public.ts +File: src/types/response/v5-rfq.ts ================ -import { RestClientV5 } from '../../src/index'; +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 + }[]; +} ⋮---- -// or -// import { RestClientV5 } from 'bybit-api'; +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 ⋮---- -/** - * If you don't plan on making any private api calls, - * you can instance the REST client without any parameters - */ +strategyName: string; // Policy name ⋮---- -// const klineResult = await client.getKline({ -// category: 'linear', -// interval: '15', -// symbol: 'BTCUSDT', -// }); -// console.log('klineResult: ', klineResult); +strategyName: string; // Policy name ⋮---- -// const markPriceKlineResult = await client.getMarkPriceKline({ -// category: 'linear', -// interval: '15', -// symbol: 'BTCUSDT', -// }); -// console.log('markPriceKlineResult: ', markPriceKlineResult); +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 +} ⋮---- -// const indexPriceKline = await client.getIndexPriceKline({ -// category: 'linear', -// interval: '15', -// symbol: 'BTCUSDT', -// }); -// console.log('indexPriceKline: ', indexPriceKline); +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 ⋮---- -// const openInterest = await client.getOpenInterest({ -// category: 'linear', -// symbol: 'BTCUSDT', -// intervalTime: '5min', -// }); +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 +} ⋮---- -// console.log( -// JSON.stringify( -// tickers.result.list.map((ticker) => ticker.symbol), -// null, -// 2, -// ), -// ); +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 ⋮---- -// openInterest.result.list.forEach((row) => { -// console.log('int: ', { -// timestamp: row.timestamp, -// value: row.openInterest, -// }); -// }); -// console.log('openInterest: ', openInterest.result.list); - -================ -File: examples/Websocket/WS-API/ws-api-client.ts -================ -import { DefaultLogger, WebsocketAPIClient } from '../../../src'; +export interface CancelRFQResultV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Inquiry Custom ID +} ⋮---- -// or -// import { DefaultLogger, WebsocketAPIClient } from 'bybit-api'; -// const { DefaultLogger, WebsocketAPIClient } = require('bybit-api'); +rfqId: string; // Inquiry ID +rfqLinkId: string; // Inquiry Custom ID ⋮---- -// function attachEventHandlers( -// wsClient: TWSClient, -// ): void { -// wsClient.on('update', (data) => { -// console.log('raw message received ', JSON.stringify(data)); -// }); -// wsClient.on('open', (data) => { -// console.log('ws connected', data.wsKey); -// }); -// wsClient.on('reconnect', ({ wsKey }) => { -// console.log('ws automatically reconnecting.... ', wsKey); -// }); -// wsClient.on('reconnected', (data) => { -// console.log('ws has reconnected ', data?.wsKey); -// }); -// wsClient.on('authenticated', (data) => { -// console.log('ws has authenticated ', data?.wsKey); -// }); -// } +export interface CancelRFQItemV5 { + rfqId: string; // Inquiry ID + rfqLinkId: string; // Inquiry Custom ID + code: number; // Cancel success or failure, 0 means success + msg: string; // Cancellation failure reason +} ⋮---- -async function main() +rfqId: string; // Inquiry ID +rfqLinkId: string; // Inquiry Custom ID +code: number; // Cancel success or failure, 0 means success +msg: string; // Cancellation failure reason ⋮---- -// Optional +export interface CancelAllRFQResultV5 { + data: CancelRFQItemV5[]; // Array of cancellation results +} ⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: -// trace: (...params) => console.log('trace', ...params), +data: CancelRFQItemV5[]; // Array of cancellation results ⋮---- -// testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management +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 +} ⋮---- -// 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, +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 ⋮---- -// If you want your own event handlers instead of the default ones with logs, -// disable this setting and see the `attachEventHandlers` example below: -// attachEventListeners: false +export interface 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 +} ⋮---- -logger, // Optional: inject a custom logger +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 ⋮---- -// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled -// attachEventHandlers(wsClient.getWSClient()); +export interface CancelRFQQuoteResultV5 { + rfqId: string; // Inquiry ID + quoteId: string; // Quotation ID + quoteLinkId: string; // Quotation Custom ID +} ⋮---- -// Optional, if you see RECV Window errors, you can use this to manage time issues. -// ! However, make sure you sync your system clock first! -// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow -// wsClient.setTimeOffsetMs(-5000); +rfqId: string; // Inquiry ID +quoteId: string; // Quotation ID +quoteLinkId: string; // Quotation Custom ID ⋮---- -// Optional: prepare the WebSocket API connection in advance. -// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. -// await wsClient.getWSClient().connectWSAPI(); - -================ -File: examples/Websocket/WS-API/ws-api-raw-events.ts -================ -import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; +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 +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; +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 ⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: -// trace: (...params) => console.log('trace', ...params), +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 +} ⋮---- -// testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management -// demoTrading: false, // note: As of Jan 2025, demo trading does NOT support the WS API +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 ⋮---- -logger, // Optional: inject a custom logger +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 +} ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +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 ⋮---- -async function main() +| '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 ⋮---- -/** - * - * This SDK's WebSocket API integration is event-driven at its core. You can treat the sentWSAPIRquest(...) method as - * a fire-and-forget method, to submit commands (create/amend/cancel order) via a WebSocket Connection. - * - * Replies to commands will show in the `response` event from the WebsocketClient's EventEmitter. Exceptions, however, - * will show in the `error` event from the WebsocketClient's EventEmitter. - * - * - Fire-and-forget a command. - * - Handle command results in the `response` event handler asynchronously as desired. - * - Handle any exceptions in a catch block. - * - * This is a more "raw" workflow in how WebSockets behave. For a more convenient & REST-like approach, using the - * promise-driven interface is recommended. See the `ws-api-raw-promises.ts` and `ws-api-client.ts` examples for a - * demonstration you can compare. - * - * Note: even without using promises, you should still tie on a .catch handler to each sendWSAPIRequest call, to prevent - * any unnecessary "unhandled promise rejection" exceptions. - * - */ +export interface GetRFQRealtimeResultV5 { + list: RFQItemV5[]; // Array of RFQ items +} ⋮---- -// To make it easier to watch, wait a few seconds before sending the amend order +list: RFQItemV5[]; // Array of RFQ items ⋮---- -// Then wait a few more before sending the cancel order +export interface RFQHistory { + cursor: string; // Page turning mark + list: RFQItemV5[]; // Array of RFQ items +} ⋮---- -// Exceptions including rejected commands will show here (as well as the catch handler used below) +cursor: string; // Page turning mark +list: RFQItemV5[]; // Array of RFQ items ⋮---- -// Replies to commands will show here +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 +} ⋮---- -/** - * - * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send - * your first command. That connection will then be reused for every command you send, unless the connection drops - then - * it will automatically be replaced with a healthy connection. - * - * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection - * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands. This is optional. - * - * Repeated note: even without using promises, you should still tie on a .catch handler to each sendWSAPIRequest call, to prevent - * any unnecessary "unhandled promise rejection" exceptions. - * - */ +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 ⋮---- -// Optional, see above. Can be used to prepare a connection before sending commands +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 +} ⋮---- -// Fire and forget the create.order command -// Even without using promises, you should still "catch" exceptions (although no need to await anything you send) +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 ⋮---- -// Fire and forget the order.amend command -// For simplicity, the orderId is hardcoded here (and will probably not work) -⋮---- -// -⋮---- -// Fire and forget the order.cancel command -// For simplicity, the orderId is hardcoded here (and will probably not work) -⋮---- -// Start executing the example workflow - -================ -File: examples/Websocket/WS-API/ws-api-raw-promises.ts -================ -import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; -⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: -// trace: (...params) => console.log('trace', ...params), -⋮---- -// testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management -// demoTrading: false, // note: As of Jan 2025, demo trading does NOT support the WS API -⋮---- -logger, // Optional: inject a custom logger -⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ -⋮---- -async function main() -⋮---- -/** - * - * This SDK's WebSocket API integration can connect WS API responses to the request that caused them. Each call - * to the `sendWSAPIRequest(...)` method returns a promise. - * - * This promise will resolve when the matching response is detected, and reject if an exception for that request - * is detected. This allows using Bybit's Websocket API in the same way that a REST API normally works. - * - * Send a command and immediately await the result. Handle any exceptions in a catch block. - * - * TypeScript users can benefit from smart type flowing for increased type safety & convenience: - * - Request parameters are fully typed, depending on the operation in the second parameter to the call. E.g. - * the `order.create` operation will automatically require the params to match the `OrderParamsV5` interface. - * - * - Response parameters are fully typed, depending on the operation in the second parameter. E.g the `order.create` - * operation will automatically map the returned value to `WSAPIResponse`. - * - */ -⋮---- -// To make it easier to watch, wait a few seconds before sending the amend order -⋮---- -// Then wait a few more before sending the cancel order +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 +} ⋮---- -/** - * - * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send - * your first command. That connection will then be reused for every command you send, unless the connection drops - then - * it will automatically be replaced with a healthy connection. - * - * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection - * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands. This is optional. - * - */ +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 ⋮---- -// Optional, see above. Can be used to prepare a connection before sending commands +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 +} ⋮---- -/** - * Create a new order - */ +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 ⋮---- -// The type for `wsAPISubmitOrderResult` is automatically resolved to `WSAPIResponse` +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 +} ⋮---- -// Save the orderId for the next call +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 ⋮---- -// The type for `wsAPIAmendOrderResult` is automatically resolved to `WSAPIResponse` +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 +} ⋮---- -// Save the orderId for the next call +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 ⋮---- -// The type for `wsAPICancelOrderResult` is automatically resolved to `WSAPIResponse` +export interface AcceptNonLPQuoteResultV5 { + rfqId: string; // Inquiry ID +} ⋮---- -// Start executing the example workflow +rfqId: string; // Inquiry ID ================ -File: src/constants/enum.ts +File: src/types/response/v5-spreadtrading.ts ================ -/** Full take profit/stop loss mode (a single TP order and a single SL order can be placed, covering the entire position) */ -⋮---- -/** Partial take profit/stop loss mode (multiple TP and SL orders can be placed, covering portions of the position) */ -⋮---- -/** This could mean bad request, incorrect value types or even incorrect/missing values */ +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'; + }[]; +} ⋮---- -/** API key requires specific whitelisted IPs, and this IP was not in the list */ +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 +} ⋮---- -/** Account not unified margin, update required */ +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 ⋮---- -/** Seen when placing an order */ +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 +} ⋮---- -/** Seen if a conditional order is too large */ +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 ⋮---- -/** E.g. trying to change position margin while on cross */ +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; +} ⋮---- -/** E.g. USDC Options trading, trying to access a symbol that is no longer active */ +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) ⋮---- -/** E.g. USDC Options trading when the account hasn't been opened for USDC Options yet */ +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; +} ⋮---- -/** - * Position idx, used to identify positions in different position modes. - * Required if you are under One-Way Mode: - */ -export enum LinearPositionIdx { - OneWayMode = 0, - BuySide = 1, - SellSide = 2, +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 } - -================ -File: src/types/request/index.ts -================ - - -================ -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; +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 ExecuteAlphaTradeParamsV5 { - fromTokenCode: string; - fromTokenAmount: string; - toTokenCode: string; - slippage: string; - quoteData: string; - gas: string; - quoteMode: 0 | 1 | 2; - correctingCode: string; - tenant?: string; +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 GetAlphaPayTokenListParamsV5 { - chainCode: string; - tokenAddress: string; +/** GET /v5/spread/max-qty */ +export interface SpreadMaxQtyResultV5 { + /** Maximum order quantity (available balance for the spread order). */ + ab: string; } ⋮---- -export interface GetAlphaTradeOrderListParamsV5 { - limit: number; - pageIndex: number; - tradeType?: number; - tokenCode?: string; - orderStatus?: number[]; - days?: number; - direction?: 'prev' | 'next'; +/** Maximum order quantity (available balance for the spread order). */ + +================ +File: src/types/response/v5-strategy.ts +================ +import { + OrderSideV5, + PositionIdx, + PovModeV5, + StrategyCategoryV5, + StrategyPreferV5, + StrategyTypeV5, +} from '../shared-v5'; +⋮---- +export interface CreateStrategyOrderResultV5 { + strategyId: string; + /** null when creation succeeded */ + result: string | null; } ⋮---- -export interface GetAlphaBizTokenListParamsV5 { - tokenTag?: number; +/** null when creation succeeded */ +⋮---- +export interface StopStrategyResultV5 { + strategyId: string; } ⋮---- -export interface AlphaTokenAddressInfoV5 { - chainCode: string; - tokenAddress: 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; + 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; } ⋮---- -export interface GetAlphaBizTokenPriceListParamsV5 { - tokenAddressInfo: AlphaTokenAddressInfoV5[]; +/** 2: running, 3: terminated, 4: terminated unfilled, 5: paused, 6: untriggered */ +⋮---- +/** POV only */ +⋮---- +export interface StrategyListResultV5 { + list: StrategyListItemV5[]; + nextCursor: string; + prevCursor: string; } ⋮---- -export interface GetAlphaBizTokenDetailsParamsV5 { - chainCode: string; - tokenAddress: string; +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; } ⋮---- -export interface GetAlphaAssetDetailParamsV5 { - chainCode: string; - tokenAddress: string; +/** 2: created, 3: create failed, 4: partially filled, 5: fully filled, 6: rejected, 7: canceled */ +⋮---- +export interface StrategyOrderListResultV5 { + list: StrategyOrderListItemV5[]; + nextCursor: string; + prevCursor: string; } ================ -File: src/types/request/v5-broker.ts +File: src/types/shared.ts ================ -export interface GetExchangeBrokerEarningsParamsV5 { - bizType?: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; - begin?: string; - end?: string; - uid?: string; - limit?: number; - cursor?: string; -} +import { RestClientV5 } from '../rest-client-v5'; +import { SpotClientV3 } from '../spot-client-v3'; ⋮---- -export interface GetBrokerSubAccountDepositsV5 { - id?: string; - txID?: string; - subMemberId?: string; - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} +export type RESTClient = SpotClientV3 | RestClientV5; ⋮---- -export interface IssueVoucherParamsV5 { - accountId: string; - awardId: string; - specCode: string; - amount: string; - brokerId: string; -} +export type numberInString = string; ⋮---- -export interface GetBrokerIssuedVoucherParamsV5 { - accountId: string; - awardId: string; - specCode: string; - withUsedAmount?: boolean; -} +export type OrderSide = 'Buy' | 'Sell'; ⋮---- -/** Set Rate Limit - exchange broker only. API rate limit: 1 req per second. */ -export interface SetBrokerRateLimitParamsV5 { - list: { - uids: string; - bizType: string; - rate: number; - }[]; -} +export type KlineInterval = + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '12h' + | '1d' + | '1w' + | '1M'; ⋮---- -/** Get All Rate Limits - exchange broker only. API rate limit: 1 req per second. */ -export interface GetAllBrokerRateLimitsParamsV5 { - limit?: string; - cursor?: string; - uids?: string; -} - -================ -File: src/types/request/v5-card.ts -================ -/** - * Bybit Card — /v5/card/* - * Authenticated; API key permission per Bybit (often card-related). - */ +export type KlineIntervalV3 = + | '1' + | '3' + | '5' + | '15' + | '30' + | '60' + | '120' + | '240' + | '360' + | '720' + | 'D' + | 'W' + | 'M'; ⋮---- -export interface QueryCardAssetRecordsParamsV5 { - /** 0: Pending, 1: Cleared, 2: Declined */ - statusCode?: string; - /** Default 100, range [1, 500] */ - limit?: number; - /** Default 1, min 1 */ - page?: number; - /** Last 2/4 digits of card number */ - pan4?: string; - createBeginTime?: number; - createEndTime?: number; - /** Fuzzy search */ - merchName?: string; - /** Authorization / Clearing / Refund (see Bybit) */ - type?: string; - txnId?: string; - cardToken?: string; - orderNo?: 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; } ⋮---- -/** 0: Pending, 1: Cleared, 2: Declined */ +/** Remaining requests to this endpoint before the next reset */ ⋮---- -/** Default 100, range [1, 500] */ +/** Max requests for this endpoint per rollowing window (before next reset) */ ⋮---- -/** Default 1, min 1 */ +/** + * Timestamp when the rate limit resets if you have exceeded your current maxRequests. + * Otherwise, this is approximately your current timestamp. + */ ⋮---- -/** Last 2/4 digits of card number */ +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; +} ⋮---- -/** Fuzzy search */ +/** + * 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 + */ ⋮---- -/** Authorization / Clearing / Refund (see Bybit) */ +export type APIResponseV3WithTime = APIResponseV3< + TResult, + TExtInfo +> & { time: number }; ⋮---- -export interface QueryCardPointRecordsParamsV5 { - type?: string; - pageSize?: number; - pageNo?: number; - startTime?: number; - endTime?: number; - outOrderId?: string; - bizId?: string; - bizTxnId?: string; - /** 1: Earn, 2: Deduct */ - side?: 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; } ⋮---- -/** 1: Earn, 2: Deduct */ -⋮---- -export interface QueryCardMallItemListParamsV5 { - pageNo?: number; - pageSize?: number; - /** 1: Virtual, 2: Physical */ - itemType?: number; - /** 1: POINTS, 2: CURRENCY */ - itemBizType?: number; - /** 1: Priority, 2: Listing time, 3: Price */ - orderBy?: number; - asc?: boolean; - /** 0: Default, 1: VIP */ - source?: number; +/** + * Request Parameter Types + */ +export interface SymbolParam { + symbol: string; } ⋮---- -/** 1: Virtual, 2: Physical */ -⋮---- -/** 1: POINTS, 2: CURRENCY */ -⋮---- -/** 1: Priority, 2: Listing time, 3: Price */ +export interface SymbolLimitParam { + symbol: string; + limit?: TLimit; +} ⋮---- -/** 0: Default, 1: VIP */ +export interface SymbolPeriodLimitParam { + symbol: string; + period: string; + limit?: TLimit; +} ⋮---- -export interface QueryCardPointCashbackDetailParamsV5 { - bizTxnId: string; +export interface SymbolFromLimitParam { + symbol: string; + from?: number; + limit?: number; } - -================ -File: src/types/request/v5-earn-advance-discount.ts -================ -/** - * /v5/earn/advance/ — product-extra, place order, position, order (Discount Buy, Dual Assets, etc.) - */ -export type GetAdvanceEarnProductExtraInfoParamsV5 = - | { - category: 'DiscountBuy'; - productId?: string; - } - | { - category: 'DualAssets'; - /** Required for Dual Assets quote. */ - productId: string; - }; ⋮---- -/** Required for Dual Assets quote. */ +export interface SymbolIntervalFromLimitParam { + symbol: string; + interval: string; + from: number; + limit?: number; +} ⋮---- -export interface AdvanceEarnDiscountBuyExtraV5 { - initialPrice: string; - purchasePrice: string; - knockoutPrice: string; - knockoutCouponE8: string; - settleType: 'Base' | 'Quote'; - instUid: string; +export interface CoinParam { + coin: string; } ⋮---- -export interface AdvanceEarnDualAssetsExtraV5 { - orderDirection: 'BuyLow' | 'SellHigh'; - selectPrice: string; - /** Expected APY in e8 precision; API may return int. */ - apyE8: string | number; +export interface WalletFundRecordsReq { + start_date?: string; + end_date?: string; + currency?: string; + coin?: string; + wallet_fund_type?: string; + page?: number; + limit?: number; } ⋮---- -/** Expected APY in e8 precision; API may return int. */ +export interface WithdrawRecordsReq { + start_date?: string; + end_date?: string; + coin?: string; + status?: string; + page?: number; + limit?: number; +} ⋮---- -export interface AdvanceEarnInterestCardExtraV5 { - awardId: string | number; - specCode: string; +export interface AssetExchangeRecordsReq { + limit?: number; + from?: number; + direction?: string; } ⋮---- /** - * POST /v5/earn/advance/place-order — Discount Buy + * Response types */ -export interface SubmitAdvanceEarnPlaceOrderDiscountBuyV5 { - category: 'DiscountBuy'; - productId: string; - orderType: 'Stake'; - amount: string; - coin: string; - accountType: 'FUND' | 'UNIFIED'; - orderLinkId: string; - discountBuyExtra: AdvanceEarnDiscountBuyExtraV5; -} ⋮---- -/** - * POST /v5/earn/advance/place-order — Dual Assets - */ -export interface SubmitAdvanceEarnPlaceOrderDualAssetsV5 { - category: 'DualAssets'; - productId: string; - orderType: 'Stake'; - amount: string; - coin: string; - accountType: 'FUND' | 'UNIFIED'; - orderLinkId: string; - dualAssetsExtra: AdvanceEarnDualAssetsExtraV5; - interestCard?: AdvanceEarnInterestCardExtraV5; +export interface LeverageFilter { + min_leverage: numberInString; + max_leverage: numberInString; + leverage_step: numberInString; } -⋮---- -export type SubmitAdvanceEarnPlaceOrderParamsV5 = - | SubmitAdvanceEarnPlaceOrderDiscountBuyV5 - | SubmitAdvanceEarnPlaceOrderDualAssetsV5; -⋮---- -export interface GetAdvanceEarnPositionListParamsV5 { - category: 'DiscountBuy' | 'DualAssets' | string; - productId?: string; - coin?: string; - limit?: number; - cursor?: string; +export interface PriceFilter { + min_price: numberInString; + max_price: numberInString; + tick_size: numberInString; } ⋮---- -export interface GetAdvanceEarnOrderListParamsV5 { - category: 'DiscountBuy' | 'DualAssets' | string; - orderId?: string; - orderLinkId?: string; - productId?: string; - /** Dual Assets docs use string ms; other categories may use number. */ - startTime?: string | number; - endTime?: string | number; - limit?: number; - cursor?: string; +export interface LotSizeFilter { + max_trading_qty: number; + min_trading_qty: number; + qty_step: number; } ⋮---- -/** Dual Assets docs use string ms; other categories may use 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; +} ================ -File: src/types/request/v5-earn-fixed-term.ts +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'; +⋮---- /** - * /v5/earn/fixed-term/* + * Configurable options specific to only the REST-like WebsocketAPIClient */ -export interface GetFixedTermEarnProductParamsV5 { - coin?: string; -} -⋮---- -export interface SubmitFixedTermEarnOrderParamsV5 { - productId: string; - category: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; - coin: string; - amount: string; - accountType: 'FUND' | 'UNIFIED'; - orderLinkId: string; - autoInvest?: boolean; -} -⋮---- -export interface RedeemFixedTermEarnParamsV5 { - productId: string; - /** Early redemption: FundPool only */ - category: 'FundPool'; - positionId: string; -} -⋮---- -/** Early redemption: FundPool only */ -⋮---- -export interface GetFixedTermEarnPositionParamsV5 { - productId?: string; - category?: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; - coin?: string; -} -⋮---- -export interface GetFixedTermEarnOrderListParamsV5 { - orderType?: 'Stake' | 'Redeem' | 'Reinvest'; - productId?: string; - category?: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; - orderId?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +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 SetFixedTermEarnAutoInvestParamsV5 { - productId: string; - category: 'FixedTermSaving' | 'FundPool' | 'FundPoolPremium'; - positionId: string; - status: 'Enable' | 'Disable'; -} - -================ -File: src/types/request/v5-earn-liquidity-mining.ts -================ /** - * GET /v5/earn/liquidity-mining/product (public, 50 req/s per IP) - */ -export interface GetLiquidityMiningProductParamsV5 { - baseCoin?: string; - quoteCoin?: string; -} - -================ -File: src/types/request/v5-earn-token.ts -================ + * 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(....)`. + */ +⋮---- /** - * Earn token product (e.g. BYUSDT) — /v5/earn/token/* + * 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 GetEarnTokenProductParamsV5 { - /** Currently only BYUSDT */ - coin: string; -} +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -/** Currently only BYUSDT */ +public getWSClient(): WebsocketClient ⋮---- -export interface PlaceEarnTokenOrderParamsV5 { - coin: string; - orderLinkId: string; - orderType: 'Mint' | 'Redeem'; - amount: string; - /** Mint: FlexibleSaving; Redeem: UNIFIED */ - accountType: 'FlexibleSaving' | 'UNIFIED'; -} +public setTimeOffsetMs(newOffset: number): void ⋮---- -/** Mint: FlexibleSaving; Redeem: UNIFIED */ +/* + * Bybit WebSocket API Methods + * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline + */ ⋮---- -export interface GetEarnTokenOrderListParamsV5 { - coin: string; - orderLinkId?: string; - orderId?: string; - orderType?: 'Mint' | 'Redeem'; - /** seconds */ - startTime?: number; - /** seconds */ - endTime?: number; - cursor?: string; - limit?: number; -} +/** + * Submit a new order + * + * @param params + * @returns + */ +submitNewOrder( + params: OrderParamsV5, +): Promise> ⋮---- -/** seconds */ +/** + * Amend an order + * + * @param params + * @returns + */ +amendOrder( + params: AmendOrderParamsV5, +): Promise> ⋮---- -/** seconds */ +/** + * Cancel an order + * + * @param params + * @returns + */ +cancelOrder( + params: CancelOrderParamsV5, +): Promise> ⋮---- -export interface GetEarnTokenPositionParamsV5 { - coin: string; -} -⋮---- -export interface GetEarnTokenDailyYieldParamsV5 { - coin: string; - startTime?: number; - endTime?: number; - cursor?: string; - limit?: number; -} -⋮---- -export interface GetEarnTokenHourlyYieldParamsV5 { - coin: string; - startTime?: number; - endTime?: number; - cursor?: string; - limit?: number; -} -⋮---- -export interface GetEarnTokenHistoryAprParamsV5 { - coin: string; - /** 1 = 7d, 2 = 30d, 3 = 180d */ - range: 1 | 2 | 3; -} -⋮---- -/** 1 = 7d, 2 = 30d, 3 = 180d */ - -================ -File: src/types/request/v5-position.ts -================ -import { - CategoryV5, - ExecTypeV5, - OrderTriggerByV5, - OrderTypeV5, - PositionIdx, - TPSLModeV5, -} from '../shared-v5'; -⋮---- -export interface PositionInfoParamsV5 { - category: CategoryV5; - symbol?: string; - baseCoin?: string; - settleCoin?: string; - limit?: number; - cursor?: string; -} -⋮---- -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; -} +/** + * 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 SetTPSLModeParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - tpSlMode: TPSLModeV5; -} +/** + * 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, + }, + ); ⋮---- -export interface SwitchPositionModeParamsV5 { - category: 'linear' | 'inverse'; - symbol?: string; - coin?: string; - mode: 0 | 3; -} +/** + * 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, + }, + ); ⋮---- -export interface SetRiskLimitParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - riskId: number; - positionIdx?: PositionIdx; -} +/** + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * + */ ⋮---- -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; -} +private setupDefaultEventListeners() ⋮---- -export interface SetAutoAddMarginParamsV5 { - category: 'linear'; - symbol: string; - autoAddMargin: 0 | 1; - positionIdx?: PositionIdx; -} +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -export interface AddOrReduceMarginParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - margin: string; - positionIDex?: PositionIdx; -} +// Blind JSON.stringify can fail on circular references ⋮---- -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; -} +// JSON.stringify({ ...data, target: 'WebSocket' }), + +================ +File: webpack/webpack.config.js +================ +function generateConfig(name) ⋮---- -settleCoin?: string; // Settle coin, uppercase only. For linear, inverse, option +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -export interface GetClosedPnLParamsV5 { - category: CategoryV5; - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} +// 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 MovePositionParamsV5 { - fromUid: string; - toUid: string; - list: { - category: 'linear' | 'spot' | 'option' | 'inverse'; - symbol: string; - price: string; - side: 'Buy' | 'Sell'; - qty: string; - }[]; -} +// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. ⋮---- -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; -} +// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. ================ -File: src/types/request/v5-rfq.ts +File: docs/BYBIT_SDK_QUICKSTART_GUIDE.md ================ -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 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 -} -⋮---- -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 -} -⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Quotation ID -quoteSide: 'buy' | 'sell'; // The direction of the quote -⋮---- -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 +# Bybit API JavaScript Tutorial for Node.js and TypeScript -================ -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; -} +> [!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) -================ -File: src/types/request/v5-trade.ts -================ -import { - CategoryV5, - OrderFilterV5, - OrderSideV5, - OrderSMPTypeV5, - OrderStatusV5, - OrderTimeInForceV5, - OrderTriggerByV5, - OrderTypeV5, - PositionIdx, - StopOrderTypeV5, -} from '../shared-v5'; -⋮---- -export interface OrderParamsV5 { - category: CategoryV5; - symbol: string; - isLeverage?: 0 | 1; - side: OrderSideV5; - orderType: OrderTypeV5; - qty: string; - marketUnit?: 'baseCoin' | 'quoteCoin'; - slippageToleranceType?: string; - slippageTolerance?: string; - price?: string; - triggerDirection?: 1 | 2; - orderFilter?: OrderFilterV5; - triggerPrice?: string; - triggerBy?: OrderTriggerByV5; - orderIv?: string; - timeInForce?: OrderTimeInForceV5; - positionIdx?: PositionIdx; - orderLinkId?: string; - takeProfit?: string; - stopLoss?: string; - tpTriggerBy?: OrderTriggerByV5; - slTriggerBy?: OrderTriggerByV5; - reduceOnly?: boolean; - closeOnTrigger?: boolean; - smpType?: OrderSMPTypeV5; - mmp?: boolean; - tpslMode?: 'Full' | 'Partial'; - tpLimitPrice?: string; - slLimitPrice?: string; - tpOrderType?: OrderTypeV5; - slOrderType?: OrderTypeV5; - bboSideType?: 'Queue' | 'Counterparty'; - bboLevel?: '1' | '2' | '3' | '4' | '5'; -} -⋮---- -export interface AmendOrderParamsV5 { - category: CategoryV5; - symbol: string; - orderId?: string; - orderLinkId?: string; - orderIv?: string; - triggerPrice?: string; - qty?: string; - price?: string; - tpslMode?: 'Full' | 'Partial'; - takeProfit?: string; - stopLoss?: string; - tpTriggerBy?: OrderTriggerByV5; - slTriggerBy?: OrderTriggerByV5; - triggerBy?: OrderTriggerByV5; - tpLimitPrice?: string; - slLimitPrice?: string; -} -⋮---- -export interface CancelOrderParamsV5 { - category: CategoryV5; - symbol: string; - orderId?: string; - orderLinkId?: string; - orderFilter?: OrderFilterV5; -} -⋮---- -export interface GetAccountOrdersParamsV5 { - category: CategoryV5; - symbol?: string; - baseCoin?: string; - settleCoin?: string; - orderId?: string; - orderLinkId?: string; - openOnly?: 0 | 1 | 2; - orderFilter?: OrderFilterV5; - orderStatus?: OrderStatusV5; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetAccountHistoricOrdersParamsV5 { - category: CategoryV5; - symbol?: string; - baseCoin?: string; - settleCoin?: string; - orderId?: string; - orderLinkId?: string; - orderFilter?: OrderFilterV5; - orderStatus?: OrderStatusV5; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} -⋮---- -export interface CancelAllOrdersParamsV5 { - category: CategoryV5; - symbol?: string; - baseCoin?: string; - settleCoin?: string; - orderFilter?: OrderFilterV5; - stopOrderType?: StopOrderTypeV5; -} -⋮---- -export interface BatchOrderParamsV5 { - symbol: string; - side: OrderSideV5; - isLeverage?: 0 | 1; - orderType: OrderTypeV5; - qty: string; - price?: string; - triggerDirection?: 1 | 2; - triggerBy?: OrderTriggerByV5; - orderIv?: string; - timeInForce?: OrderTimeInForceV5; - positionIdx?: PositionIdx; - orderLinkId?: string; - takeProfit?: string; - stopLoss?: string; - tpTriggerBy?: OrderTriggerByV5; - slTriggerBy?: OrderTriggerByV5; - reduceOnly?: boolean; - closeOnTrigger?: boolean; - smpType?: OrderSMPTypeV5; - mmp?: boolean; - tpslMode?: 'Full' | 'Partial'; - tpLimitPrice?: string; - slLimitPrice?: string; - tpOrderType?: OrderTypeV5; - slOrderType?: OrderTypeV5; -} -⋮---- -export interface BatchAmendOrderParamsV5 { - symbol: string; - orderId?: string; - orderLinkId?: string; - orderIv?: string; - triggerPrice?: string; - qty?: string; - price?: string; - tpslMode?: 'Full' | 'Partial'; - takeProfit?: string; - stopLoss?: string; - tpTriggerBy?: OrderTriggerByV5; - slTriggerBy?: OrderTriggerByV5; - triggerBy?: OrderTriggerByV5; - tpLimitPrice?: string; - slLimitPrice?: string; -} -⋮---- -export interface BatchCancelOrderParamsV5 { - symbol: string; - orderId?: string; - orderLinkId?: string; -} +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. -================ -File: src/types/response/index.ts -================ +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** -================ -File: src/types/response/v5-alpha-trade.ts -================ -/** - * V5 private Alpha / on-chain (Web3) trade responses. - */ -⋮---- -export interface AlphaTradeQuoteModeEstimationV5 { - quoteMode: number; - estimatedGas: string; - estimatedGasUsd: string; - estimatedSlippage: 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 ExecuteAlphaTradeResultV5 { - orderNo: string; -} -⋮---- -export interface AlphaPayTokenV5 { - tokenCode: string; - symbol: string; - tokenDecimals: number; - tokenIconUrlDay: string; - tokenIconUrlNight: string; - limit: string; - supportChains: 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 AlphaTradeOrderListResultV5 { - total: number; - pageIndex: number; - orders: AlphaTradeOrderV5[]; -} -⋮---- -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 AlphaBizTokenPriceV5 { - chainCode: string; - tokenAddress: string; - price: string; - change24h: string; - vol24h: string; - marketCap: string; - liquidity: string; - holders: string; -} -⋮---- -export interface AlphaBizTokenPriceListResultV5 { - tokenPriceInfoList: AlphaBizTokenPriceV5[]; -} -⋮---- -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 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 AlphaAssetListResultV5 { - totalAssetUsd: string; - assetList: AlphaAssetV5[]; -} -⋮---- -export interface AlphaAssetDetailResultV5 { - assetList: AlphaAssetV5[]; -} +- 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) -================ -File: src/types/response/v5-broker.ts -================ -interface EarningDetailV5 { - userId: string; - bizType: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; - symbol: string; - coin: string; - earning: string; - markupEarning: string; - baseFeeEarning: string; - orderId: string; - execTime: string; -} -⋮---- -interface TotalEarningCategoryV5 { - coin: string; - earning: string; -} -⋮---- -export interface ExchangeBrokerEarningResultV5 { - totalEarningCat: { - spot: TotalEarningCategoryV5[]; - derivatives: TotalEarningCategoryV5[]; - options: TotalEarningCategoryV5[]; - convert: TotalEarningCategoryV5[]; - total: TotalEarningCategoryV5[]; - }; - details: EarningDetailV5[]; - nextPageCursor: string; -} -⋮---- -export interface ExchangeBrokerAccountInfoV5 { - subAcctQty: string; - maxSubAcctQty: string; - baseFeeRebateRate: { - spot: string; - derivatives: string; - }; - markupFeeRebateRate: { - spot: string; - derivatives: string; - convert: string; - }; - ts: 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 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 BrokerIssuedVoucherV5 { - accountId: string; - awardId: string; - specCode: string; - amount: string; - isClaimed: boolean; - startAt: string; - endAt: string; - effectiveAt: string; - ineffectiveAt: string; - usedAmount: string; -} -⋮---- -export interface BrokerRateLimitSetResultItemV5 { - uids: string; - bizType: string; - rate: number; - success: boolean; - msg: string; -} -⋮---- -export interface BrokerRateLimitCapItemV5 { - bizType: string; - totalRate: string; - ebCap: string; - uidCap: string; -} -⋮---- -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 CardAssetRecordsResultV5 { - pageSize: number; - pageNo: number; - totalCount: number; - data: CardAssetRecordV5[]; -} -⋮---- -export interface CardPointBalanceV5 { - accountId: string; - availablePoint: string | number; - pendingPoint: string | number; - status: string; - updateTime: string | number; - settlementPeriod: number; -} -⋮---- -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 CardPointRecordsResultV5 { - pageSize: number; - pageNo: number; - totalCount: number; - data: CardPointRecordV5[]; -} -⋮---- -export interface CardPointTierInfoV5 { - usedLimit: string; - limit: string; - unit: string; - tier: string; - autoCashback: boolean; -} -⋮---- -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 CardMallItemListResultV5 { - pageNo: number; - pageSize: number; - totalCount: number; - data: CardMallItemV5[]; -} -⋮---- -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; -} +## Why use the SDK -================ -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; -} -⋮---- -/** GET /v5/earn/advance/product-extra-info?category=DiscountBuy */ -export interface AdvanceEarnProductExtraInfoDiscountBuyV5 { - offers: AdvanceEarnDiscountBuyOfferV5[]; -} -⋮---- -export interface AdvanceEarnDualAssetQuoteLevelV5 { - selectPrice: string; - apyE8: string; - maxInvestmentAmount: string; - expiredAt: string; -} -⋮---- -export interface AdvanceEarnDualAssetQuoteProductV5 { - productId: string; - currentPrice: string; - buyLowPrice: AdvanceEarnDualAssetQuoteLevelV5[]; - sellHighPrice: AdvanceEarnDualAssetQuoteLevelV5[]; -} -⋮---- -/** GET /v5/earn/advance/product-extra-info?category=DualAssets&productId= */ -export interface AdvanceEarnProductExtraInfoDualAssetsV5 { - category: 'DualAssets'; - list: AdvanceEarnDualAssetQuoteProductV5[]; -} -⋮---- -export type AdvanceEarnProductExtraInfoV5 = - | AdvanceEarnProductExtraInfoDiscountBuyV5 - | AdvanceEarnProductExtraInfoDualAssetsV5; -⋮---- -export interface AdvanceEarnPlaceOrderResultV5 { - orderId: string; - orderLinkId: 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 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 AdvanceEarnPositionListV5 { - category: string; - list: (AdvanceEarnDiscountBuyPositionV5 | AdvanceEarnDualAssetsPositionV5)[]; - nextPageCursor: string; -} -⋮---- -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 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 AdvanceEarnOrderListV5 { - category: string; - list: (AdvanceEarnDiscountBuyOrderV5 | AdvanceEarnDualAssetsOrderV5)[]; - nextPageCursor: string; -} +The Bybit API is unified, but a real integration still has several moving parts: -================ -File: src/types/response/v5-earn-fixed-term.ts -================ -export interface FixedTermEarnTieredApyV5 { - min: string; - max: string; - apy: string; -} -⋮---- -export interface FixedTermEarnInterestCoinApyV5 { - coin: string; - apy: string; - expectUnitEarning: string; - currentPrice: 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 FixedTermEarnProductListV5 { - list: FixedTermEarnProductV5[]; -} -⋮---- -export interface FixedTermEarnPlaceOrderResultV5 { - orderId: string; - orderLinkId: string; -} -⋮---- -export interface RedeemFixedTermEarnResultV5 { - redeemAmount: string; - estEarnings: string; -} -⋮---- -export interface FixedTermEarnEarlyRedeemInfoV5 { - allowEarlyRedeem: boolean; - earlyRedeemEarning: string; - returnCoin: string; - redemptionLimitDuration: string; -} -⋮---- -export interface FixedTermEarnPositionInterestV5 { - coin: string; - apy: string; - expectReturnEarning: string; - price: 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 FixedTermEarnPositionListV5 { - list: FixedTermEarnPositionV5[]; -} -⋮---- -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 FixedTermEarnOrderListV5 { - list: FixedTermEarnOrderV5[]; - nextPageCursor: string; -} +- 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. -================ -File: src/types/response/v5-earn-liquidity-mining.ts -================ -export interface LiquidityMiningApyBreakdownV5 { - coin: string; - apy: 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[]; -} -⋮---- -export interface LiquidityMiningProductResultV5 { - products: LiquidityMiningProductV5[]; -} +The SDK gives you the main surfaces needed for those workflows: -================ -File: src/types/response/v5-earn-token.ts -================ -/** - * Earn token product (e.g. BYUSDT) — /v5/earn/token/* - */ -⋮---- -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 PlaceEarnTokenOrderResultV5 { - orderId: string; - orderLinkId: string; -} -⋮---- -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 EarnTokenPositionV5 { - totalAmount: string; - totalYield: string; - yesterdayYield: string; - aprE8: number; - bonusAprE8: number; - bonusMaxAmount: string; - hasQuota: boolean; -} -⋮---- -export interface EarnTokenDailyYieldRecordV5 { - yield: string; - bonusYield: string; - status: 'Success' | 'Processing'; - createdTime: string; -} -⋮---- -export interface EarnTokenHourlyYieldRecordV5 { - effectiveAmount: string; - yield: string; - rewardType: 0 | 1; - aprE8: string; - hourlyDate: string; - createdTime: string; -} -⋮---- -export interface EarnTokenHistoryAprPointV5 { - timestamp: string; - aprE8: string; -} +- `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. -================ -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 -} -⋮---- -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 -} -⋮---- -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 CancelRFQResultV5 { - rfqId: string; // Inquiry ID - rfqLinkId: string; // Inquiry Custom ID -} -⋮---- -rfqId: string; // Inquiry ID -rfqLinkId: string; // Inquiry Custom ID -⋮---- -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 -} -⋮---- -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 CancelAllRFQResultV5 { - data: CancelRFQItemV5[]; // Array of cancellation results -} -⋮---- -data: CancelRFQItemV5[]; // Array of cancellation results -⋮---- -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 +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, + }); } -⋮---- -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 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 -} -⋮---- -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 CancelRFQQuoteResultV5 { - rfqId: string; // Inquiry ID - quoteId: string; // Quotation ID - quoteLinkId: string; // Quotation Custom ID -} -⋮---- -rfqId: string; // Inquiry ID -quoteId: string; // Quotation ID -quoteLinkId: string; // Quotation Custom ID -⋮---- -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 -} -⋮---- -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 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 -} -⋮---- -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 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 -} -⋮---- -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 -⋮---- -export interface GetRFQRealtimeResultV5 { - list: RFQItemV5[]; // Array of RFQ items + +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); } -⋮---- -list: RFQItemV5[]; // Array of RFQ items -⋮---- -export interface RFQHistory { - cursor: string; // Page turning mark - list: RFQItemV5[]; // Array of RFQ items + +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); } -⋮---- -cursor: string; // Page turning mark -list: RFQItemV5[]; // Array of RFQ items -⋮---- -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 -} -⋮---- -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 - 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 -} -⋮---- -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 -} -⋮---- -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 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 -} -⋮---- -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 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 -} -⋮---- -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 -} -⋮---- -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 -} -⋮---- -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 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 -} -⋮---- -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 -} -⋮---- -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; -} -⋮---- -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 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 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 -} -⋮---- -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; -} -⋮---- -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). */ +main().catch(console.error); +``` -================ -File: src/types/shared.ts -================ -import { RestClientV5 } from '../rest-client-v5'; -import { SpotClientV3 } from '../spot-client-v3'; -⋮---- -export type RESTClient = SpotClientV3 | RestClientV5; -⋮---- -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. - */ - resetAtTimestamp: number; -} -⋮---- -/** 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; -} -⋮---- -/** - * 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 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; -} -⋮---- -/** - * Request Parameter Types - */ -export interface SymbolParam { - symbol: string; -} -⋮---- -export interface SymbolLimitParam { - symbol: string; - limit?: TLimit; -} -⋮---- -export interface SymbolPeriodLimitParam { - symbol: string; - period: string; - limit?: TLimit; -} -⋮---- -export interface SymbolFromLimitParam { - symbol: string; - from?: number; - limit?: number; -} -⋮---- -export interface SymbolIntervalFromLimitParam { - symbol: string; - interval: string; - from: number; - limit?: number; -} -⋮---- -export interface CoinParam { - coin: string; -} -⋮---- -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; -} +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. -================ -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; -} -⋮---- -/** - * 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(....)`. - */ -⋮---- -/** - * 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 -⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) -⋮---- -public getWSClient(): WebsocketClient -⋮---- -public setTimeOffsetMs(newOffset: number): void -⋮---- -/* - * Bybit WebSocket API Methods - * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline - */ -⋮---- -/** - * Submit a new order - * - * @param params - * @returns - */ -submitNewOrder( - params: OrderParamsV5, -): Promise> -⋮---- -/** - * Amend an order - * - * @param params - * @returns - */ -amendOrder( - params: AmendOrderParamsV5, -): Promise> -⋮---- -/** - * Cancel an order - * - * @param params - * @returns - */ -cancelOrder( - params: CancelOrderParamsV5, -): Promise> -⋮---- -/** - * 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, - }, - ); -⋮---- -/** - * 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' }), +See also: [WebSocket API client example](../examples/Websocket/WS-API/ws-api-client.ts) -================ -File: webpack/webpack.config.js -================ -function generateConfig(name) -⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. -⋮---- -// Node.js core modules not available in browsers -// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers -⋮---- -// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. -⋮---- -// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. +--- -================ -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, +## REST API -================ -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) +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. -================ -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 a public `RestClientV5` -================ -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) +```typescript +import { RestClientV5 } from 'bybit-api'; -================ -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; -} -⋮---- -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. - */ +const client = new RestClientV5(); +``` -================ -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 RepayInstitutionalLoanParamsV5 { - token: string; // Coin name - quantity: string; // The qty to be repaid -} -⋮---- -token: string; // Coin name -quantity: string; // The qty to be repaid +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) -================ -File: src/types/request/v5-earn.ts -================ -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; +--- + +## 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'; ⋮---- -export interface ModifyEarnPositionParamsV5 { - category: 'OnChain'; - productId: number; - positionId: number; - autoReinvest: 0 | 1; -} +import { RestClientV5 } from '../../src/index'; ⋮---- -export interface GetEarnAprHistoryParamsV5 { - category: 'FlexibleSaving' | 'OnChain'; - productId: string; - startTime?: number; - endTime?: number; -} +// or +// import { RestClientV5 } from 'bybit-api'; ⋮---- /** - * GET /v5/earn/advance/product — Advanced Earn: Dual Asset, Double Win, Smart Leverage, etc. - * Public, no auth. Rate limit: 50 req/s per IP. + * 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). */ -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` */ +// 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: src/types/request/v5-market.ts +File: examples/Websocket/Private/ws-private-v5.ts ================ -import { KlineIntervalV3 } from '../shared'; -import { - CategoryV5, - InstrumentStatusV5, - InstrumentSymbolTypeV5, - OptionTypeV5, -} from '../shared-v5'; +/* eslint-disable @typescript-eslint/no-empty-function */ +import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; ⋮---- -export interface GetKlineParamsV5 { - category: 'spot' | 'linear' | 'inverse'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - limit?: number; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; ⋮---- -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; -} +// Create & inject a custom logger to enable the trace logging level (empty function) ⋮---- -/** - * linear (default if omitted), inverse, or option. - */ +// trace: (...params) => console.log('trace', ...params), ⋮---- /** - * Futures: [1, 1000], default 200. Options: [1, 500], default 200. - */ + * 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. + */ ⋮---- -export interface GetIndexPriceKlineParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - limit?: number; -} +// testnet: false, +// demoTrading: false, // set testnet to false, if you plan on using demo trading ⋮---- -export interface GetPremiumIndexPriceKlineParamsV5 { - category: 'linear'; - symbol: string; - interval: KlineIntervalV3; - start?: number; - end?: number; - limit?: number; -} +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -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; -} +// wsClient.on('exception', (data) => { +// console.error('ws exception: ', data); +// }); ⋮---- -/** Filter by instrument `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ +/** + * 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. + */ ⋮---- -export interface GetOrderbookParamsV5 { - category: CategoryV5; - symbol: string; - limit?: number; -} +// wsClient.subscribeV5('execution.fast', 'linear'); +// wsClient.subscribeV5('execution.fast.linear', 'linear'); +// wsClient.subscribeV5('execution.fast.spot', 'spot'); +// wsClient.subscribeV5('execution.fast.option', 'option'); ⋮---- -export interface GetRPIOrderbookParamsV5 { - category?: 'spot' | 'linear' | 'inverse'; - symbol: string; - limit: number; // Required for RPI orderbook, [1, 50] -} +/** + * 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']); ⋮---- -limit: number; // Required for RPI orderbook, [1, 50] +// To unsubscribe from topics (after a 5 second delay, in this example): +// setTimeout(() => { +// console.log('unsubscribing'); +// wsClient.unsubscribeV5('execution', 'linear'); +// }, 5 * 1000); ⋮---- -export interface GetIndexPriceComponentsParamsV5 { - indexName: string; // Index name, like BTCUSDT -} +// 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'; ⋮---- -indexName: string; // Index name, like BTCUSDT +// or +// import { +// RestClientV5, +// WebsocketClient, +// isWsAllLiquidationEvent, +// } from 'bybit-api'; ⋮---- -export interface GetADLAlertParamsV5 { - symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only -} +function onAllLiquidationEvent(event: unknown) ⋮---- -symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only +/** + * + * 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() ⋮---- -export interface GetFeeGroupStructureParamsV5 { - productType: string; // Product type. contract only for now - groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 -} +// Make an array of topics ready for submission ⋮---- -productType: string; // Product type. contract only for now -groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 +// subscribe to all linear symbols ⋮---- -export interface GetTickersParamsV5 { - category: TCategory; - symbol?: string; - baseCoin?: string; - expDate?: string; -} +// subscribe to all inverse symbols + +================ +File: examples/Websocket/Public/ws-public-v5.ts +================ +import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; ⋮---- -export interface GetFundingRateHistoryParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - startTime?: number; - endTime?: number; - limit?: number; -} +// 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. + */ ⋮---- -export interface GetPublicTradingHistoryParamsV5 { - category: CategoryV5; - symbol: string; - baseCoin?: string; - optionType?: OptionTypeV5; - limit?: number; -} +// Linear v5 +// -> Just one topic per call +// wsClient.subscribeV5('orderbook.50.BTCUSDT', 'linear'); ⋮---- -export type OpenInterestIntervalV5 = - | '5min' - | '15min' - | '30min' - | '1h' - | '4h' - | '1d'; +// -> Or multiple topics in one call +// wsClient.subscribeV5( +// ['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], +// 'linear' +// ); ⋮---- -export interface GetOpenInterestParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - intervalTime: OpenInterestIntervalV5; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; -} +// Inverse v5 +// wsClient.subscribeV5('orderbook.50.BTCUSD', 'inverse'); ⋮---- -export interface GetHistoricalVolatilityParamsV5 { - category: 'option'; - baseCoin?: string; - period?: 7 | 14 | 21 | 30 | 60 | 90 | 180 | 270; - startTime?: number; - endTime?: number; -} +// Spot v5 +// wsClient.subscribeV5('orderbook.50.BTCUSDT', 'spot'); ⋮---- -export interface GetInsuranceParamsV5 { - coin?: string; -} +// Option v5 +// wsClient.subscribeV5('publicTrade.BTC', 'option'); ⋮---- -export interface GetRiskLimitParamsV5 { - category?: 'linear' | 'inverse'; - symbol?: string; - cursor?: string; -} +// Use the subscribeV5() call for most subscribe calls with v5 websockets ⋮---- -export interface GetOptionDeliveryPriceParamsV5 { - category: 'option'; - symbol?: string; - baseCoin?: string; - limit?: number; - cursor?: string; -} +// Alternatively, you can also use objects in the wsClient.subscribe() call +// wsClient.subscribe({ +// topic: 'orderook.50.BTCUSDT', +// category: 'spot', +// }); ⋮---- -export interface GetDeliveryPriceParamsV5 { - category: 'linear' | 'inverse' | 'option'; - symbol?: string; - baseCoin?: string; - settleCoin?: string; - limit?: number; - cursor?: string; -} +/** + * 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) + */ ⋮---- -export interface GetLongShortRatioParamsV5 { - category: 'linear' | 'inverse'; - symbol: string; - period: OpenInterestIntervalV5; - startTime?: string; - endTime?: string; - limit?: number; - cursor?: string; -} +// 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 @@ -9940,6 +9995,7 @@ export interface WalletBalanceV5Coin { marginCollateral: boolean; collateralSwitch: boolean; spotBorrow: string; + colRes?: string; } ⋮---- free: string; // spot only @@ -10074,1172 +10130,979 @@ export interface MMPStateV5 { 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-earn.ts -================ -export interface EarnProductV5 { - category: string; - estimateApr: string; - coin: string; - minStakeAmount: string; - maxStakeAmount: string; - precision: string; - productId: string; - status: 'Available' | 'NotAvailable'; -} -⋮---- -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 EarnPositionFreezeDetailV5 { - amount: string; - description: string; -} -⋮---- -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[]; -} -⋮---- -/** Redeemable amount */ -⋮---- -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; + repaymentQty: string; } ⋮---- -export interface EarnHourlyYieldHistoryV5 { - productId: 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; - id: string; - amount: string; - effectiveStakingAmount: string; - status: 'Pending' | 'Success' | 'Fail'; - hourlyDate: string; - createdAt: string; + totalDelta: string; + totalRPL: string; + totalUPL: string; + assetIM: string; + assetMM: string; + sendTime: number; } ⋮---- -export interface EarnAprHistoryPointV5 { - timestamp: string; - apr: string; +export interface OptionAssetInfoNestedResultV5 { + result: OptionAssetInfoRowV5[]; } ⋮---- -/** - * 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; +/** GET /v5/account/pay-info */ +export interface PayInfoCollateralItemV5 { + coin: string; + availableSize: string; + availableValue: string; + coinScale: number; + borrowSize: string; + spotHedgeAmount: string; + assetFrozen: string; } ⋮---- -export interface AdvanceEarnDualAssetProductInfoV5 { - category: string; - list: AdvanceEarnDualAssetProductV5[]; +export interface PayInfoBorrowBlockV5 { + coin?: string; + borrowSize: string; + borrowValue?: string; + assetFrozen: string; + availableBalance: 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 PayInfoResultV5 { + collateralInfo: { + collateralList: PayInfoCollateralItemV5[]; + }; + borrowInfo: PayInfoBorrowBlockV5; } ⋮---- -/** - * 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/account/trade-info-for-analysis */ +export interface TradeInfoAnalysisDailyV5 { + day: string; + sumBuyExecValue: string; + sumSellExecValue: string; + sumExecValue: string; } ⋮---- -/** - * Advanced Earn — Discount Buy (GET /v5/earn/advance/product?category=DiscountBuy). - */ -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 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 type AdvanceEarnAdvanceProductListItemV5 = - | AdvanceEarnDualAssetProductV5 - | AdvanceEarnDoubleWinProductV5 - | AdvanceEarnSmartLeverageProductV5 - | AdvanceEarnDiscountBuyProductV5; +export interface OrderResultV5 { + orderId: string; + orderLinkId: string; +} ⋮---- -export interface AdvanceEarnAdvanceProductInfoV5 { - category: string; - list: AdvanceEarnAdvanceProductListItemV5[]; +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; } ⋮---- -/** GET /v5/earn/hold-to-earn/product — Hold to Earn airdrop products */ -export type HoldToEarnAirdropProductStatusV5 = - | 'NotStarted' - | 'Online' - | 'Ended'; +parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) ⋮---- -export interface HoldToEarnAirdropProductYieldV5 { - coinName: string; - /** Yesterday's APR for display, e.g. "10%", "0%" */ - apy: string; +cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee +⋮---- +export interface BatchCreateOrderResultV5 { + category: CategoryV5; + symbol: string; + orderId: string; + orderLinkId: string; + createAt?: 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; +export interface BatchOrdersRetExtInfoV5 { + list: { + code: number; + msg: string; + }[]; } ⋮---- -/** Yesterday's avg APR across yield coins */ +export interface BatchAmendOrderResultV5 { + category: CategoryV5; + symbol: string; + orderId: string; + orderLinkId: string; +} ⋮---- -export interface HoldToEarnAirdropProductsResultV5 { - products: HoldToEarnAirdropProductV5[]; +export interface BatchCancelOrderResultV5 { + category: CategoryV5; + symbol: string; + orderId: string; + orderLinkId: 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 SpotBorrowCheckResultV5 { + symbol: string; + side: OrderSideV5; + maxTradeQty: string; + maxTradeAmount: string; + spotMaxTradeQty: string; + spotMaxTradeAmount: string; + borrowCoin: string; } ⋮---- -export interface HoldToEarnAirdropYieldHistoryResultV5 { - nextCursor: string; - airdropDailyPnls: HoldToEarnAirdropDailyPnlV5[]; +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: src/types/response/v5-position.ts +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, - ExecTypeV5, - OrderSideV5, - OrderTypeV5, - PositionIdx, - PositionSideV5, - PositionStatusV5, - StopOrderTypeV5, - TPSLModeV5, - TradeModeV5, + InstrumentSymbolTypeV5, + TransactionTypeV5, } from '../shared-v5'; ⋮---- -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; +export interface GetWalletBalanceParamsV5 { + accountType: AccountTypeV5; + coin?: string; } ⋮---- -breakEvenPrice?: string; // Break even price, only for linear & inverse -⋮---- -/** Position open timestamp (ms). Default `0` when not set. */ +export interface GetBorrowHistoryParamsV5 { + currency?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -export interface SetRiskLimitResultV5 { +export interface GetFeeRateParamsV5 { category: CategoryV5; - riskId: number; - riskLimitValue: string; + symbol?: string; + baseCoin?: string; } ⋮---- -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 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; } ⋮---- -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; +/** + * 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; } ⋮---- -feeCurrency: string; // Trading fee currency +export interface RepayLiabilityParamsV5 { + coin?: string; +} ⋮---- -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 SetCollateralCoinParamsV5 { + coin: string; + collateralSwitch: 'ON' | 'OFF'; } ⋮---- -export interface MovePositionResultV5 { - blockTradeId: string; - status: 'Processing' | 'Rejected'; - rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; +export interface GetClassicTransactionLogsParamsV5 { + currency?: string; + baseCoin?: string; + type?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: 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 SetLimitPriceActionParamsV5 { + category: CategoryV5; + modifyEnable: boolean; } ⋮---- -export interface ClosedOptionsPositionV5 { +/** + * 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; - side: 'Buy' | 'Sell'; - totalOpenFee: string; - deliveryFee: string; - totalCloseFee: string; - qty: string; - closeTime: number; - avgExitPrice: string; - deliveryPrice: string; - openTime: number; - avgEntryPrice: string; - totalPnl: 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/response/v5-trade.ts +File: src/types/request/v5-crypto-loan.ts ================ -import { - CategoryV5, - OrderCancelTypeV5, - OrderCreateTypeV5, - OrderRejectReasonV5, - OrderSideV5, - OrderStatusV5, - OrderTimeInForceV5, - OrderTriggerByV5, - OrderTypeV5, - PositionIdx, - StopOrderTypeV5, -} from '../shared-v5'; +export interface BorrowCryptoLoanParamsV5 { + loanCurrency: string; + loanAmount?: string; + loanTerm?: string; + collateralCurrency: string; + collateralAmount?: string; +} ⋮---- -export interface OrderResultV5 { - orderId: string; - orderLinkId: string; +export interface GetUnpaidLoanOrdersParamsV5 { + orderId?: string; + loanCurrency?: string; + collateralCurrency?: string; + loanTermType?: string; + loanTerm?: string; + limit?: string; + cursor?: 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 +export interface GetRepaymentHistoryParamsV5 { + orderId?: string; + repayId?: string; + loanCurrency?: string; + limit?: string; + cursor?: string; } ⋮---- -parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) +export interface GetCompletedLoanOrderHistoryParamsV5 { + orderId?: string; + loanCurrency?: string; + collateralCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee +export interface GetLoanLTVAdjustmentHistoryParamsV5 { + orderId?: string; + adjustId?: string; + collateralCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -export interface BatchCreateOrderResultV5 { - category: CategoryV5; - symbol: string; - orderId: string; - orderLinkId: string; - createAt?: 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; } ⋮---- -export interface BatchOrdersRetExtInfoV5 { - list: { - code: number; - msg: string; +// Flexible Loan Request Types +⋮---- +export interface BorrowFlexibleParamsV5 { + loanCurrency: string; + loanAmount: string; + collateralList?: { + currency: string; + amount: string; }[]; } ⋮---- -export interface BatchAmendOrderResultV5 { - category: CategoryV5; - symbol: string; - orderId: string; - orderLinkId: string; +export interface RepayFlexibleParamsV5 { + loanCurrency: string; + amount: string; } ⋮---- -export interface BatchCancelOrderResultV5 { - category: CategoryV5; - symbol: string; - orderId: string; - orderLinkId: string; +export interface RepayCollateralFlexibleParamsV5 { + loanCurrency: string; + collateralCoin: string; + amount: string; } ⋮---- -export interface SpotBorrowCheckResultV5 { - symbol: string; - side: OrderSideV5; - maxTradeQty: string; - maxTradeAmount: string; - spotMaxTradeQty: string; - spotMaxTradeAmount: string; - borrowCoin: string; +export interface GetOngoingFlexibleLoansParamsV5 { + loanCurrency?: 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 GetBorrowHistoryFlexibleParamsV5 { + orderId?: string; + loanCurrency?: string; + limit?: string; + cursor?: 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) - -================ -File: src/types/shared-v5.ts -================ -export type CategoryV5 = 'spot' | 'linear' | 'inverse' | 'option'; -export type ContractTypeV5 = - | 'InversePerpetual' - | 'LinearPerpetual' - | 'InverseFutures'; -export type CopyTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalOnly'; -⋮---- -export type InstrumentStatusV5 = - | 'PreLaunch' - | 'Trading' - | 'Settling' - | 'Delivering' - | 'Closed'; +export interface GetRepaymentHistoryFlexibleParamsV5 { + repayId?: string; + loanCurrency?: string; + limit?: string; + cursor?: 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'; +// Fixed Loan Request Types ⋮---- -export type MarginTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalSpotOnly'; +export interface GetSupplyOrderQuoteFixedParamsV5 { + orderCurrency: string; + term?: string; + orderBy: 'apy' | 'term' | 'quantity'; + sort?: number; + limit?: number; +} ⋮---- -/** 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 interface GetBorrowOrderQuoteFixedParamsV5 { + orderCurrency: string; + term?: string; + orderBy: 'apy' | 'term' | 'quantity'; + sort?: number; + limit?: number; +} ⋮---- -export type StrategyTypeV5 = 'twap' | 'chaseOrder' | 'iceberg' | 'pov'; +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; + }[]; +} ⋮---- -export type StrategyPreferV5 = - | 'limit' - | 'priceSpeedBalance' - | 'fastestExecution' - | 'quickExecution'; +autoRepay?: string; // Deprecated +repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan ⋮---- -/** POV strategy execution mode */ -export type PovModeV5 = - | 'TradedVolume' - | 'OppositeSideLiquidity' - | 'SameSideLiquidity'; +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'; +} ⋮---- -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'; +/** + * Source account for supply. 0: Funding Account; 1: Earn Flexible Account; 2: ALL. Default: 0 + */ ⋮---- -export type OrderSMPTypeV5 = - | 'None' - | 'CancelMaker' - | 'CancelTaker' - | 'CancelBoth'; +export interface CancelBorrowOrderFixedParamsV5 { + orderId: string; +} ⋮---- -export type OrderStatusV5 = - | 'Created' - | 'New' - | 'Rejected' - | 'PartiallyFilled' - | 'PartiallyFilledCanceled' - | 'Filled' - | 'Cancelled' - | 'Untriggered' - | 'Triggered' - | 'Deactivated' - | 'Active'; +export interface CancelSupplyOrderFixedParamsV5 { + orderId: string; + /** + * Account to receive the refund. 0: Funding Account; 1: EasyEarn. Default: 0 + */ + refundedAccount?: '0' | '1'; +} ⋮---- /** - * 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. + * Account to receive the refund. 0: Funding Account; 1: EasyEarn. Default: 0 */ - | '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. */ +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; +} ⋮---- -/** Represents an order created by an admin closing. */ +export interface GetSupplyOrderInfoFixedParamsV5 { + orderId?: string; + orderCurrency?: string; + state?: string; + term?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** Futures conditional order. */ +export interface RepayFixedParamsV5 { + loanId?: string; + loanCurrency?: string; +} ⋮---- -/** Futures take profit order. */ +export interface RepayCollateralFixedParamsV5 { + loanCurrency: string; + collateralCoin: string; + amount: string; +} ⋮---- -/** Futures partial take profit order. */ +export interface GetRepaymentHistoryFixedParamsV5 { + repayId?: string; + loanCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** Futures stop loss order. */ +export interface RenewBorrowOrderFixedParamsV5 { + loanId: string; + collateralList?: { + currency?: string; + amount?: string; + }[]; +} ⋮---- -/** Futures partial stop loss order. */ +export interface GetRenewOrderInfoFixedParamsV5 { + orderId?: string; + orderCurrency?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** Futures trailing stop order. */ +// Max Loan Amount Request Types ⋮---- -/** Laddered liquidation to reduce the required maintenance margin. */ +export interface GetMaxLoanAmountParamsV5 { + currency: string; // Coin to borrow + collateralList?: { + ccy: string; // Collateral coin + amount: string; // Collateral amount + }[]; +} ⋮---- -/** - * 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. - */ +currency: string; // Coin to borrow ⋮---- -/** Auto-Deleveraging(ADL) */ +ccy: string; // Collateral coin +amount: string; // Collateral amount ⋮---- -/** Order placed via Paradigm. */ +// Institutional Loan Request Types ⋮---- -/** Order created by move position. */ +export interface GetCoinDeltaAmountParamsV5 { + coin?: string; +} ⋮---- -/** The close order placed via web or app position area - web/app. */ +export interface RepayInstitutionalLoanParamsV5 { + token: string; // Coin name + quantity: string; // The qty to be repaid +} ⋮---- -/** Order created via grid bot - web/app. */ +token: string; // Coin name +quantity: string; // The qty to be repaid + +================ +File: src/types/request/v5-earn.ts +================ +export interface GetEarnCouponListParamsV5 { + category: 'FlexibleSaving' | 'DualAssets'; +} ⋮---- -/** Order closed via grid bot - web/app. */ +export interface SubmitStakeRedeemParamsV5 { + category: string; + orderType: 'Stake' | 'Redeem'; + accountType: 'FUND' | 'UNIFIED'; + amount: string; + coin: string; + productId: string; + orderLinkId: string; + toAccountType?: 'FUND' | 'UNIFIED'; +} ⋮---- -/** Order created by TWAP - web/app. */ +export interface GetEarnOrderHistoryParamsV5 { + category: string; + orderId?: string; + orderLinkId?: string; + productId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** Order created by TV webhook - web/app. */ +export interface GetEarnPositionParamsV5 { + category: string; + productId?: string; + coin?: string; +} ⋮---- -/** Order created by Mm rate close function - web/app. */ +export interface GetEarnYieldHistoryParamsV5 { + category: string; + productId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** Order created by Martingale bot - web/app. */ +export interface GetEarnHourlyYieldHistoryParamsV5 { + category: string; + productId?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** Order closed by Martingale bot - web/app. */ +export interface ModifyEarnPositionParamsV5 { + category: 'OnChain'; + productId: number; + positionId: number; + autoReinvest: 0 | 1; +} ⋮---- -/** Order created by Ice berg strategy - web/app. */ +export interface GetEarnAprHistoryParamsV5 { + category: 'FlexibleSaving' | 'OnChain'; + productId: string; + startTime?: number; + endTime?: number; +} ⋮---- -/** Order created by arbitrage - web/app. */ +/** + * 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; +} ⋮---- -/** Option dynamic delta hedge order - web/app */ +/** + * Product duration, e.g. 8h, 1d, 2d, 3d, 6d, 7d, 12d (depends on product). + */ ⋮---- -/** BBO Order - Best Bid/Offer order */ +/** 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; +} ⋮---- -export type OrderCancelTypeV5 = - | 'CancelByUser' - | 'CancelByReduceOnly' - | 'CancelByPrepareLiq' - | 'CancelAllBeforeLiq' - | 'CancelByPrepareAdl' - | 'CancelAllBeforeAdl' - | 'CancelByAdmin' - | 'CancelByTpSlTsClear' - | 'CancelByPzSideCh' - | 'UNKNOWN'; +/** Unix seconds. Cannot be earlier than now minus 3 months */ ⋮---- -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'; +/** Unix seconds. Requires timeStart ≤ timeEnd */ ⋮---- -export type StopOrderTypeV5 = - | 'TakeProfit' - | 'StopLoss' - | 'TrailingStop' - | 'Stop' - | 'PartialTakeProfit' - | 'PartialStopLoss' - | 'tpslOrder' - | 'OcoOrder' - | 'MmRateClose' - | 'BidirectionalTpslOrder'; +/** Page size [1, 49] */ ⋮---- -/** - * 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; +/** 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; +} ⋮---- -/** - * 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 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; +} ⋮---- -export type OptionTypeV5 = 'Call' | 'Put'; +/** + * linear (default if omitted), inverse, or option. + */ ⋮---- /** - * Trade mode. - * - * - 0 cross-margin, - * - 1 isolated margin - */ -export type TradeModeV5 = 0 | 1; + * Futures: [1, 1000], default 200. Options: [1, 500], default 200. + */ ⋮---- -export type TPSLModeV5 = 'Full' | 'Partial'; -export type AccountMarginModeV5 = - | 'ISOLATED_MARGIN' - | 'REGULAR_MARGIN' - | 'PORTFOLIO_MARGIN'; -export type UnifiedUpdateStatusV5 = 'FAIL' | 'PROCESS' | 'SUCCESS'; +export interface GetIndexPriceKlineParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + interval: KlineIntervalV3; + start?: number; + end?: number; + limit?: number; +} ⋮---- -export type AccountTypeV5 = - | 'CONTRACT' - | 'SPOT' - | 'INVESTMENT' - | 'OPTION' - | 'UNIFIED' - | 'FUND' - | 'EARN'; +export interface GetPremiumIndexPriceKlineParamsV5 { + category: 'linear'; + symbol: string; + interval: KlineIntervalV3; + start?: number; + end?: number; + limit?: number; +} ⋮---- -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'; +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; +} ⋮---- -export type PermissionTypeV5 = - | 'ContractTrade' - | 'Spot' - | 'Wallet' - | 'Options' - | 'Derivatives' - | 'Exchange' - | 'NFT'; +/** Filter by instrument `symbolType` (e.g. `commodity`, `stock`, `forex` for linear). */ ⋮---- -/** - * 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 GetOrderbookParamsV5 { + category: CategoryV5; + symbol: string; + limit?: number; +} ⋮---- -/** - * Leveraged token order type: '1': purchase, '2': redeem - */ -export type LTOrderTypeV5 = '1' | '2'; +export interface GetRPIOrderbookParamsV5 { + category?: 'spot' | 'linear' | 'inverse'; + symbol: string; + limit: number; // Required for RPI orderbook, [1, 50] +} ⋮---- -/** - * Leveraged token order status: '1': completed, '2': in progress, '3': failed - */ -export type LTOrderStatusV5 = '1' | '2' | '3'; +limit: number; // Required for RPI orderbook, [1, 50] ⋮---- -export type ExecTypeV5 = - | 'Trade' - | 'AdlTrade' - | 'Funding' - | 'BustTrade' - | 'Settle' - | 'BlockTrade' - | 'MovePosition' - | 'UNKNOWN'; +export interface GetIndexPriceComponentsParamsV5 { + indexName: string; // Index name, like BTCUSDT +} ⋮---- -/** - * Withdraw type. 0(default): on chain. 1: off chain. 2: all. - */ -export type WithdrawalTypeV5 = '0' | '1' | '2'; +indexName: string; // Index name, like BTCUSDT ⋮---- -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 interface GetADLAlertParamsV5 { + symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only } ⋮---- -/** @deprecated , always returns []*/ +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 +} ⋮---- -/** Bybit Pay (FaitPayOrder) */ +productType: string; // Product type. contract only for now +groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 ⋮---- -export interface CategoryCursorListV5< - T extends unknown[], - TCategory extends CategoryV5 = CategoryV5, -> { +export interface GetTickersParamsV5 { category: TCategory; - list: T; - nextPageCursor?: string; + symbol?: string; + baseCoin?: string; + expDate?: string; } ⋮---- -/** - * Next page cursor does not exist for spot! - */ -export interface CursorListV5 { - nextPageCursor: string; - list: T; +export interface GetFundingRateHistoryParamsV5 { + category: 'linear' | 'inverse'; + symbol: string; + startTime?: number; + endTime?: number; + limit?: 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 interface GetPublicTradingHistoryParamsV5 { + category: CategoryV5; + symbol: string; + baseCoin?: string; + optionType?: OptionTypeV5; + limit?: number; } ⋮---- -export interface CategoryListV5< - T extends unknown[], - TCategory extends CategoryV5, -> { - category: TCategory; - list: T; -} +export type OpenInterestIntervalV5 = + | '5min' + | '15min' + | '30min' + | '1h' + | '4h' + | '1d'; ⋮---- -export interface CategorySymbolListV5< - T extends unknown[], - TCategory extends CategoryV5, -> { - category: TCategory; +export interface GetOpenInterestParamsV5 { + category: 'linear' | 'inverse'; symbol: string; - list: T; + intervalTime: OpenInterestIntervalV5; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -export interface GetSystemStatusParamsV5 { - id?: string; - state?: string; +export interface GetHistoricalVolatilityParamsV5 { + category: 'option'; + baseCoin?: string; + period?: 7 | 14 | 21 | 30 | 60 | 90 | 180 | 270; + startTime?: number; + endTime?: number; } ⋮---- -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 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; } ================ @@ -11370,142 +11233,17 @@ export interface GetFixedRateBorrowContractInfoParamsV5 { 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/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; -} -⋮---- -/** - * 1: normal, 6: custodial - */ -⋮---- -/** - * 0: quick login disabled (default), 1: quick login enabled - */ -⋮---- -export interface CreateSubApiKeyParamsV5 { - subuid: number; - note?: string; - readOnly: 0 | 1; - ips?: string; - permissions: PermissionsV5; -} -⋮---- -export interface UpdateApiKeyParamsV5 { - apikey?: string; - readOnly?: 0 | 1; - permissions: PermissionsV5; -} -⋮---- -export interface UpdateSubApiKeyUpdateParamsV5 { - readOnly?: number; - ips?: string[]; - permissions: PermissionsV5; -} -⋮---- -export interface DeleteSubMemberParamsV5 { - subMemberId: string; -} -⋮---- -export interface GetSubAccountAllApiKeysParamsV5 { - subMemberId: string; - limit?: number; - cursor?: string; -} -⋮---- -export interface GetAffiliateUserListParamsV5 { - size?: number; - cursor?: string; - needDeposit?: boolean; - need30?: boolean; - need365?: boolean; - startDate?: string; - endDate?: string; -} -⋮---- -/** 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; -} -⋮---- -/** [0, 100]. Default: 0 */ -⋮---- -/** YYYY-MM-DD. Range with endDate max 3 months */ -⋮---- -/** YYYY-MM-DD. Must be provided with startDate or both omitted (T-1 default) */ -⋮---- -/** Exact sub-affiliate ID. 0 or omit for all */ -⋮---- -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'; -} -⋮---- -/** The master account UID of affiliate's client */ -⋮---- -/** Coin type for filtering, e.g. USDT */ -⋮---- -/** - * Business line filter. 1: Derivatives, 2: Spot, 3: ByFi, 4: USDC, 5: Options - */ -⋮---- -/** Get Friend Referrals - invitation relationship status. 0: alive; 1: invalid */ -export interface GetFriendReferralsParamsV5 { - status?: string; - size?: string; - cursor?: string; -} -⋮---- -/** 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 GetFixedRateBorrowOrderQuoteParamsV5 { + orderCurrency: string; + term?: string; + orderBy?: 'apy' | 'term' | 'quantity'; + sort?: 0 | 1; + limit?: number; +} +⋮---- +export interface RenewFixedRateBorrowParamsV5 { + loanId: string; + qty?: string; } ================ @@ -11603,3446 +11341,4601 @@ export interface LoanLTVAdjustmentHistoryV5 { amount: string; } ⋮---- -// New Crypto Loan Types +// 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 CollateralRatioV5 { + collateralRatio: string; + maxValue: string; + minValue: string; +} +⋮---- +export interface CollateralRatioConfigV5 { + collateralRatioList: CollateralRatioV5[]; + currencies: string; +} +⋮---- +export interface CurrencyLiquidationV5 { + currency: string; + liquidationOrder: number; +} +⋮---- +export interface CollateralDataV5 { + collateralRatioConfigList: CollateralRatioConfigV5[]; + currencyLiquidationList: CurrencyLiquidationV5[]; +} +⋮---- +// Additional New Crypto Loan Types +⋮---- +export interface AdjustCollateralAmountV5 { + adjustId: number; +} +⋮---- +export interface CollateralAdjustmentHistoryV5 { + adjustId: number; + adjustTime: number; + afterLTV: string; + amount: string; + collateralCurrency: string; + direction: number; + preLTV: string; + status: number; +} +⋮---- +export interface BorrowListV5 { + fixedTotalDebt: string; + fixedTotalDebtUSD: string; + flexibleHourlyInterestRate: string; + flexibleTotalDebt: string; + flexibleTotalDebtUSD: string; + loanCurrency: string; +} +⋮---- +export interface CollateralListV5 { + amount: string; + amountUSD: string; + currency: string; + ltv: string; +} +⋮---- +export interface SupplyListV5 { + amount: string; + amountUSD: string; + currency: string; +} +⋮---- +export interface CryptoLoanPositionV5 { + borrowList: BorrowListV5[]; + collateralList: CollateralListV5[]; + supplyList: SupplyListV5[]; + totalCollateral: string; + totalDebt: string; + totalSupply: string; + colRes?: string; +} +⋮---- +// Flexible Loan Types +⋮---- +export interface BorrowFlexibleV5 { + orderId: string; +} +⋮---- +export interface RepayFlexibleV5 { + repayId: string; +} +⋮---- +export interface OngoingFlexibleLoanV5 { + hourlyInterestRate: string; + loanCurrency: string; + totalDebt: string; + unpaidAmount: string; + unpaidInterest: string; +} +⋮---- +export interface BorrowHistoryFlexibleV5 { + borrowTime: number; + initialLoanAmount: string; + loanCurrency: string; + orderId: string; + status: number; +} +⋮---- +export interface RepaymentHistoryFlexibleV5 { + loanCurrency: string; + repayAmount: string; + repayId: string; + repayStatus: number; + repayTime: number; + repayType: number; +} +⋮---- +// Fixed Loan Types +⋮---- +export interface SupplyOrderQuoteFixedV5 { + orderCurrency: string; + term: number; + annualRate: string; + qty: string; +} +⋮---- +export interface BorrowOrderQuoteFixedV5 { + orderCurrency: string; + term: number; + annualRate: string; + qty: string; +} +⋮---- +export interface CreateBorrowOrderFixedV5 { + orderId: string; +} +⋮---- +export interface CreateSupplyOrderFixedV5 { + orderId: 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; +} +⋮---- +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 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 +} +⋮---- +repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +⋮---- +export interface SupplyOrderInfoFixedV5 { + annualRate: string; + orderId: number; + orderTime: string; + filledQty: string; + orderQty: string; + orderCurrency: string; + state: number; + term: number; +} +⋮---- +export interface RepayFixedV5 { + repayId: string; +} +⋮---- +export interface RepaymentHistoryFixedV5 { + details: { + loanCurrency: string; + loanId: string; + repayAmount: string; + }[]; + loanCurrency: string; + repayAmount: string; + repayId: string; + repayStatus: number; + repayTime: number; + repayType: number; +} +⋮---- +export interface RenewBorrowOrderFixedV5 { + orderId: string; +} +⋮---- +export interface RenewOrderInfoFixedV5 { + amount: string; + autoRepay: number; + borrowCurrency: string; + contractNo: string; + dueTime: string; + loanId: string; + orderId: number; + renewLoanNo: string; + time: string; +} +⋮---- +// Institutional 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 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; +} +⋮---- +/** `0`: Default, `1`: CTA, `2`: Hedge */ +⋮---- +export interface InstitutionalLendingCoinDeltaItemV5 { + coin: string; + coinDeltaSize: string; + coinDeltaAvailableAmount: string; + coinDeltaAmount: string; } ⋮---- -export interface CollateralRatioV5 { - collateralRatio: string; - maxValue: string; - minValue: string; +export interface InstitutionalLendingCoinDeltaAmountV5 { + riskUnitDeltaAmount: string; + riskUnitDeltaAvailableAmount: string; + list: InstitutionalLendingCoinDeltaItemV5[]; } ⋮---- -export interface CollateralRatioConfigV5 { - collateralRatioList: CollateralRatioV5[]; - currencies: string; +export interface UnpaidInfoV5 { + token: string; // Coin + unpaidQty: string; // Unpaid principle + unpaidInterest: string; // Unpaid interest } ⋮---- -export interface CurrencyLiquidationV5 { - currency: string; - liquidationOrder: number; +token: string; // Coin +unpaidQty: string; // Unpaid principle +unpaidInterest: string; // Unpaid interest +⋮---- +export interface BalanceInfoV5 { + token: string; // Margin coin + price: string; // Margin coin price + qty: string; // Margin coin quantity + convertedAmount: string; // Margin conversion amount } ⋮---- -export interface CollateralDataV5 { - collateralRatioConfigList: CollateralRatioConfigV5[]; - currencyLiquidationList: CurrencyLiquidationV5[]; +token: string; // Margin coin +price: string; // Margin coin price +qty: string; // Margin coin quantity +convertedAmount: string; // Margin conversion amount +⋮---- +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 } ⋮---- -// Additional New Crypto Loan Types +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 AdjustCollateralAmountV5 { - adjustId: number; +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 CollateralAdjustmentHistoryV5 { - adjustId: number; - adjustTime: number; - afterLTV: string; - amount: string; - collateralCurrency: string; - direction: number; - preLTV: string; - status: number; +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 RepayInstitutionalLoanResultV5 { + repayOrderStatus: string; // P: processing } ⋮---- -export interface BorrowListV5 { - fixedTotalDebt: string; - fixedTotalDebtUSD: string; - flexibleHourlyInterestRate: string; - flexibleTotalDebt: string; - flexibleTotalDebtUSD: string; - loanCurrency: string; +repayOrderStatus: string; // P: processing +⋮---- +// Max Loan Amount Response Types +⋮---- +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) } ⋮---- -export interface CollateralListV5 { - amount: string; - amountUSD: string; - currency: string; - ltv: string; +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-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 SupplyListV5 { +export interface EarnAwardCardV5 { + awardId: number; + specCode: string; + claimedAt: number; + usedAt: number; + expireAt: number; + status: 'InUse' | 'NotUse' | 'Expired' | 'AlreadyUsed' | string; amount: string; - amountUSD: string; - currency: string; + limitPnlPercentage: string; + baseCoin: string; + quoteCoin: string; + direction: 1 | 2; + category: 'FlexibleSaving' | 'DualAssets' | string; } ⋮---- -export interface CryptoLoanPositionV5 { - borrowList: BorrowListV5[]; - collateralList: CollateralListV5[]; - supplyList: SupplyListV5[]; - totalCollateral: string; - totalDebt: string; - totalSupply: string; +export interface EarnCouponListResultV5 { + interestCards: EarnInterestCardV5[]; + awardCards: EarnAwardCardV5[]; } ⋮---- -// Flexible Loan Types +export interface EarnProductV5 { + category: string; + estimateApr: string; + coin: string; + minStakeAmount: string; + maxStakeAmount: string; + precision: string; + productId: string; + status: 'Available' | 'NotAvailable'; +} ⋮---- -export interface BorrowFlexibleV5 { +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 RepayFlexibleV5 { - repayId: string; +export interface EarnPositionFreezeDetailV5 { + amount: string; + description: string; } ⋮---- -export interface OngoingFlexibleLoanV5 { - hourlyInterestRate: string; - loanCurrency: string; - totalDebt: string; - unpaidAmount: string; - unpaidInterest: string; +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[]; } ⋮---- -export interface BorrowHistoryFlexibleV5 { - borrowTime: number; - initialLoanAmount: string; - loanCurrency: string; +/** Redeemable amount */ +⋮---- +export interface EarnYieldHistoryV5 { + productId: string; + coin: string; + id: string; + amount: string; + yieldType: string; + distributionMode: string; + effectiveStakingAmount: string; orderId: string; - status: number; + status: 'Pending' | 'Success' | 'Fail'; + createdAt: string; } ⋮---- -export interface RepaymentHistoryFlexibleV5 { - loanCurrency: string; - repayAmount: string; - repayId: string; - repayStatus: number; - repayTime: number; - repayType: number; +export interface EarnHourlyYieldHistoryV5 { + productId: string; + coin: string; + id: string; + amount: string; + effectiveStakingAmount: string; + status: 'Pending' | 'Success' | 'Fail'; + hourlyDate: string; + createdAt: string; +} +⋮---- +export interface EarnAprHistoryPointV5 { + timestamp: string; + apr: string; +} +⋮---- +/** + * 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; } ⋮---- -// Fixed Loan Types -⋮---- -export interface SupplyOrderQuoteFixedV5 { - orderCurrency: string; - term: number; - annualRate: string; - qty: string; +export interface AdvanceEarnDualAssetProductInfoV5 { + category: string; + list: AdvanceEarnDualAssetProductV5[]; } ⋮---- -export interface BorrowOrderQuoteFixedV5 { - orderCurrency: string; - term: number; - annualRate: string; - qty: 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 CreateBorrowOrderFixedV5 { - orderId: 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; } ⋮---- -export interface CreateSupplyOrderFixedV5 { - orderId: string; +/** + * Advanced Earn — Discount Buy (GET /v5/earn/advance/product?category=DiscountBuy). + */ +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 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 type AdvanceEarnAdvanceProductListItemV5 = + | AdvanceEarnDualAssetProductV5 + | AdvanceEarnDoubleWinProductV5 + | AdvanceEarnSmartLeverageProductV5 + | AdvanceEarnDiscountBuyProductV5; ⋮---- -autoRepay: string; // Deprecated +export interface AdvanceEarnAdvanceProductInfoV5 { + category: string; + list: AdvanceEarnAdvanceProductListItemV5[]; +} ⋮---- -repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +/** GET /v5/earn/hold-to-earn/product — Hold to Earn airdrop products */ +export type HoldToEarnAirdropProductStatusV5 = + | 'NotStarted' + | 'Online' + | 'Ended'; ⋮---- -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 HoldToEarnAirdropProductYieldV5 { + coinName: string; + /** Yesterday's APR for display, e.g. "10%", "0%" */ + apy: string; } ⋮---- -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 +/** 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; } ⋮---- -repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment +/** Yesterday's avg APR across yield coins */ ⋮---- -export interface SupplyOrderInfoFixedV5 { - annualRate: string; - orderId: number; - orderTime: string; - filledQty: string; - orderQty: string; - orderCurrency: string; - state: number; - term: number; +export interface HoldToEarnAirdropProductsResultV5 { + products: HoldToEarnAirdropProductV5[]; } ⋮---- -export interface RepayFixedV5 { - repayId: 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 RepaymentHistoryFixedV5 { - details: { - loanCurrency: string; - loanId: string; - repayAmount: string; - }[]; - loanCurrency: string; - repayAmount: string; - repayId: string; - repayStatus: number; - repayTime: number; - repayType: number; +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; } ⋮---- -export interface RenewBorrowOrderFixedV5 { - orderId: string; +export interface FuturesLeverageResultV5 { + category: 'linear' | 'inverse'; + list: FuturesLeverageItemV5[]; } ⋮---- -export interface RenewOrderInfoFixedV5 { - amount: string; - autoRepay: number; - borrowCurrency: string; - contractNo: string; - dueTime: string; - loanId: string; - orderId: number; - renewLoanNo: string; - time: string; +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; } ⋮---- -// Institutional Loan Types -⋮---- -export interface UnpaidInfoV5 { - token: string; // Coin - unpaidQty: string; // Unpaid principle - unpaidInterest: string; // Unpaid interest -} +breakEvenPrice?: string; // Break even price, only for linear & inverse ⋮---- -token: string; // Coin -unpaidQty: string; // Unpaid principle -unpaidInterest: string; // Unpaid interest +/** Position open timestamp (ms). Default `0` when not set. */ ⋮---- -export interface BalanceInfoV5 { - token: string; // Margin coin - price: string; // Margin coin price - qty: string; // Margin coin quantity - convertedAmount: string; // Margin conversion amount +export interface SetRiskLimitResultV5 { + category: CategoryV5; + riskId: number; + riskLimitValue: string; } ⋮---- -token: string; // Margin coin -price: string; // Margin coin price -qty: string; // Margin coin quantity -convertedAmount: string; // Margin conversion amount -⋮---- -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 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; } ⋮---- -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 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; } ⋮---- -ltvInfo: LTVInfoV5[]; // LTV info array -liqStatus?: number; // Liquidation status: 0=Normal, 1=Under liquidation, 2=Manual repayment in progress, 3=Transfer in progress +feeCurrency: string; // Trading fee currency ⋮---- -export interface RepayInstitutionalLoanResultV5 { - repayOrderStatus: string; // P: processing +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; } ⋮---- -repayOrderStatus: string; // P: processing -⋮---- -// Max Loan Amount Response Types -⋮---- -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) +export interface MovePositionResultV5 { + blockTradeId: string; + status: 'Processing' | 'Rejected'; + rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; } ⋮---- -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 -================ -import { - CategoryCursorListV5, - CategoryV5, - ContractTypeV5, - CopyTradingV5, - InstrumentStatusV5, - InstrumentSymbolTypeV5, - MarginTradingV5, - OptionTypeV5, - OrderSideV5, -} from '../shared-v5'; -⋮---- -/** - * OHLCVT candle used by v5 APIs - * - * - list[0]: startTime string Start time of the candle (ms) - * - list[1]: openPrice string Open price - * - list[2]: highPrice string Highest price - * - list[3]: lowPrice string Lowest price - * - list[4]: closePrice string Close price. Is the last traded price when the candle is not closed - * - list[5]: volume string Trade volume. Unit of contract: pieces of contract. Unit of spot: quantity of coins - * - list[6]: turnover string Turnover. Unit of figure: quantity of quota coin - */ -export type OHLCVKlineV5 = [ - string, - string, - string, - string, - string, - string, - string, -]; -⋮---- -/** - * OHLC candle used by v5 APIs - * - * - list[0]: startTime string Start time of the candle (ms) - * - list[1]: openPrice string Open price - * - list[2]: highPrice string Highest price - * - list[3]: lowPrice string Lowest price - * - list[4]: closePrice string Close price. Is the last traded price when the candle is not closed - */ -export type OHLCKlineV5 = [string, string, string, string, string]; -⋮---- -export interface LinearInverseInstrumentInfoV5 { - /** The ID of the symbol name. */ - symbolId: number; - symbol: string; - contractType: ContractTypeV5; - status: InstrumentStatusV5; - baseCoin: string; - quoteCoin: string; - /** Region / product class for the pair (`stock`, `forex`, `commodity`, `xstocks`, etc.). */ - symbolType: InstrumentSymbolTypeV5; - launchTime: string; - deliveryTime?: string; - deliveryFeeRate?: string; - priceScale: string; - leverageFilter: { - minLeverage: string; - maxLeverage: string; - leverageStep: string; - }; - priceFilter: { - minPrice: string; - maxPrice: string; - tickSize: string; - }; - lotSizeFilter: { - maxOrderQty: string; - maxMktOrderQty: string; - minOrderQty: string; - qtyStep: string; - postOnlyMaxOrderQty?: string; - minNotionalValue?: string; - }; - unifiedMarginTrade: boolean; - fundingInterval: number; - settleCoin: string; - copyTrading: CopyTradingV5; - upperFundingRate: string; - lowerFundingRate: string; - riskParameters: { - priceLimitRatioX: string; - priceLimitRatioY: string; - }; - isPreListing: boolean; - preListingInfo: { - curAuctionPhase: string; - phases: { - phase: string; - startTime: string; - endTime: string; - }[]; - auctionFeeInfo: { - auctionFeeRate: string; - takerFeeRate: string; - makerFeeRate: string; - }; - } | null; - skipCallAuction?: boolean; // For USDT pre-market contract - displayName: 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'; } ⋮---- -/** The ID of the symbol name. */ +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-spot-leverage-token.ts +================ +import { + LeverageTokenStatusV5, + LTOrderStatusV5, + LTOrderTypeV5, +} from '../shared-v5'; ⋮---- -/** Region / product class for the pair (`stock`, `forex`, `commodity`, `xstocks`, etc.). */ +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; +} ⋮---- -skipCallAuction?: boolean; // For USDT pre-market contract +export interface LeveragedTokenMarketResultV5 { + ltCoin: string; + nav: string; + navTime: string; + circulation: string; + basket: string; + leverage: string; +} ⋮---- -export interface OptionInstrumentInfoV5 { - /** The ID of the symbol name. */ - symbolId: number; - symbol: string; - optionsType: OptionTypeV5; - status: InstrumentStatusV5; - baseCoin: string; - quoteCoin: string; - settleCoin: string; - symbolType: InstrumentSymbolTypeV5; - launchTime: string; - deliveryTime: string; - deliveryFeeRate: string; - priceFilter: { - minPrice: string; - maxPrice: string; - tickSize: string; - }; - lotSizeFilter: { - maxOrderQty: string; - minOrderQty: string; - qtyStep: string; - }; - displayName: 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; } ⋮---- -/** The ID of the symbol name. */ +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 SpotInstrumentInfoV5 { - /** The ID of the symbol name. */ - symbolId: number; - symbol: string; - baseCoin: string; - quoteCoin: string; - /** - * Xstock multiplier for `symbolType` = xstocks pairs. `stock_price = token_price / multiplier`, - * `stock_qty = token_qty * multiplier`. Default `"1"`. - */ - xstockMultiplier?: string; - symbolType: InstrumentSymbolTypeV5; - innovation: '0' | '1'; // Deprecated, always 0 - status: InstrumentStatusV5; - marginTrading: MarginTradingV5; - stTag: '0' | '1'; - lotSizeFilter: { - basePrecision: string; - quotePrecision: string; - minOrderQty: string; - maxOrderQty: string; - minOrderAmt: string; - maxOrderAmt: string; - maxLimitOrderQty: string; - maxMarketOrderQty: string; - postOnlyMaxLimitOrderSize: string; - }; - priceFilter: { - tickSize: string; - }; - riskParameters: { - priceLimitRatioX: string; - priceLimitRatioY: string; - }; - forbidUplWithdrawal: boolean; +export interface VIPMarginDataV5 { + vipCoinList: { + list: { + borrowable: boolean; + collateralRatio: string; + currency: string; + hourlyBorrowRate: string; + liquidationOrder: string; + marginCollateral: boolean; + maxBorrowingAmount: string; + }[]; + vipLevel: string; + }[]; } ⋮---- -/** The ID of the symbol name. */ +export interface SpotMarginCurrencyDataV5 { + currency: string; + flexibleManualBorrowable: boolean; + minFlexibleManualBorrowQty: string; + flexibleManualBorrowAccuracy: string; + fixedManualBorrowable: boolean; + minFixedManualBorrowQty: string; + fixedManualBorrowAccuracy: string; + fixedInterestRateAccuracy: string; + minFixedInterestRate: string; + maxFixedInterestRate: string; +} ⋮---- -/** - * Xstock multiplier for `symbolType` = xstocks pairs. `stock_price = token_price / multiplier`, - * `stock_qty = token_qty * multiplier`. Default `"1"`. - */ +export interface SpotMarginStateV5 { + spotLeverage: string; + spotMarginMode: '1' | '0'; + effectiveLeverage: string; +} ⋮---- -innovation: '0' | '1'; // Deprecated, always 0 +// Spot Margin Trade (UTA) response types +export interface ManualBorrowResultV5 { + coin: string; + amount: string; +} ⋮---- -type InstrumentInfoV5Mapping = { - linear: LinearInverseInstrumentInfoV5[]; - inverse: LinearInverseInstrumentInfoV5[]; - option: OptionInstrumentInfoV5[]; - spot: SpotInstrumentInfoV5[]; -}; +export interface MaxBorrowableAmountV5 { + currency: string; + maxLoan: string; +} ⋮---- -export type InstrumentInfoResponseV5 = - CategoryCursorListV5; +export interface PositionTierV5 { + tier: string; + borrowLimit: string; + positionMMR: string; + positionIMR: string; + maxLeverage: string; +} ⋮---- -// Account Instruments Info (includes RPI permissions) -export interface AccountSpotInstrumentInfoV5 extends SpotInstrumentInfoV5 { - isPublicRpi: boolean; - myRpiPermission: boolean; +export interface CurrencyPositionTiersV5 { + currency: string; + positionTiersRatioList: PositionTierV5[]; } ⋮---- -export interface AccountLinearInverseInstrumentInfoV5 - extends LinearInverseInstrumentInfoV5 { - isPublicRpi: boolean; - myRpiPermission: boolean; +export interface CoinStateV5 { + currency: string; + spotLeverage: string; } ⋮---- -type AccountInstrumentInfoV5Mapping = { - linear: AccountLinearInverseInstrumentInfoV5[]; - inverse: AccountLinearInverseInstrumentInfoV5[]; - spot: AccountSpotInstrumentInfoV5[]; -}; +export interface AvailableAmountToRepayV5 { + currency: string; + lossLessRepaymentAmount: string; +} ⋮---- -export type AccountInstrumentInfoResponseV5< - C extends 'spot' | 'linear' | 'inverse', -> = CategoryCursorListV5; +export interface ManualRepayWithoutConversionResultV5 { + /** + * Result status: + * - P: Processing + * - SU: Success + * - FA: Failed + */ + resultStatus: 'P' | 'SU' | 'FA'; +} ⋮---- /** - * [price, size] - */ -export type OrderbookLevelV5 = [string, string]; + * Result status: + * - P: Processing + * - SU: Success + * - FA: Failed + */ ⋮---- -export interface OrderbookResponseV5 { - s: string; - b: OrderbookLevelV5[]; - a: OrderbookLevelV5[]; - ts: number; - u: number; - seq: number; - cts: number; +export interface AutoRepayModeItemV5 { + currency: string; // Coin name, uppercase only + autoRepayMode: '0' | '1'; // 0: Off, 1: On } ⋮---- -/** - * RPI Orderbook level: [price, nonRpiSize, rpiSize] - */ -export type RPIOrderbookLevelV5 = [string, string, string]; +currency: string; // Coin name, uppercase only +autoRepayMode: '0' | '1'; // 0: Off, 1: On ⋮---- -export interface RPIOrderbookResponseV5 { - s: string; // Symbol name - b: RPIOrderbookLevelV5[]; // Bids. Sorted by price in descending order - a: RPIOrderbookLevelV5[]; // Asks. Sorted by price in ascending order - ts: number; // The timestamp (ms) that the system generates the data - u: number; // Update ID, is always in sequence corresponds to u in the 50-level WebSocket RPI orderbook stream - seq: number; // Cross sequence - cts: number; // The timestamp from the matching engine when this orderbook data is produced +export interface AutoRepayModeResultV5 { + data: AutoRepayModeItemV5[]; } ⋮---- -s: string; // Symbol name -b: RPIOrderbookLevelV5[]; // Bids. Sorted by price in descending order -a: RPIOrderbookLevelV5[]; // Asks. Sorted by price in ascending order -ts: number; // The timestamp (ms) that the system generates the data -u: number; // Update ID, is always in sequence corresponds to u in the 50-level WebSocket RPI orderbook stream -seq: number; // Cross sequence -cts: number; // The timestamp from the matching engine when this orderbook data is produced -⋮---- -export interface TickerLinearInverseV5 { - symbol: string; - lastPrice: string; - indexPrice: string; - markPrice: string; - prevPrice24h: string; - price24hPcnt: string; - highPrice24h: string; - lowPrice24h: string; - prevPrice1h: string; - openInterest: string; - openInterestValue: string; - turnover24h: string; - volume24h: string; - fundingRate: string; - nextFundingTime: string; - predictedDeliveryPrice: string; - basisRate: string; - basisRateYear: string; - fundingIntervalHour: string; - fundingCap: string; - deliveryFeeRate: string; - deliveryTime: string; - ask1Size: string; - bid1Price: string; - ask1Price: string; - bid1Size: string; - preOpenPrice: string; - preQty: string; - curPreListingPhase: string; - basis: string; +export interface SpotMarginLiabilityInfoV5 { + currency: string; + totalBorrowAmount: string; + fixedBorrowAmount: string; + flexibleBorrowAmount: string; + spotTotalBorrow: string; + derivativesBorrow: string; } ⋮---- -export interface TickerOptionV5 { - symbol: string; - bid1Price: string; - bid1Size: string; - bid1Iv: string; - ask1Price: string; - ask1Size: string; - ask1Iv: string; - lastPrice: string; - highPrice24h: string; - lowPrice24h: string; - markPrice: string; - indexPrice: string; - markIv: 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 FixedRateBorrowResultV5 { + orderId: string; } ⋮---- -export interface TickerSpotV5 { - symbol: string; - bid1Price: string; - bid1Size: string; - ask1Price: string; - ask1Size: string; - lastPrice: string; - prevPrice24h: string; - price24hPcnt: string; - highPrice24h: string; - lowPrice24h: string; - turnover24h: string; - volume24h: string; - usdIndexPrice: string; +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 FundingRateHistoryResponseV5 { - symbol: string; - fundingRate: string; - fundingRateTimestamp: string; +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'; } ⋮---- -export interface PublicTradeV5 { - execId: string; - symbol: string; - price: string; - size: string; - side: OrderSideV5; - time: string; - isBlockTrade: boolean; - isRPITrade: boolean; - mP?: string; - iP?: string; - mIv?: string; - iv?: string; - seq?: string; +export interface FixedRateBorrowQuoteV5 { + orderCurrency: string; + term: number; + annualRate: string; + qty: string; } + +================ +File: src/types/shared-v5.ts +================ +export type CategoryV5 = 'spot' | 'linear' | 'inverse' | 'option'; +export type ContractTypeV5 = + | 'InversePerpetual' + | 'LinearPerpetual' + | 'InverseFutures'; +export type CopyTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalOnly'; +⋮---- +export type InstrumentStatusV5 = + | 'PreLaunch' + | 'Trading' + | 'Settling' + | 'Delivering' + | 'Closed'; ⋮---- /** - * - * - openInterest string Open interest - * - timestamp string The timestamp (ms) + * 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 OpenInterestV5 = { - openInterest: string; - timestamp: string; -}; +export type InstrumentSymbolTypeV5 = + | '' + | 'stock' + | 'forex' + | 'commodity' + | 'xstocks'; ⋮---- -export interface OpenInterestResponseV5 { - category: 'linear' | 'inverse'; - symbol: string; - list: OpenInterestV5[]; - nextPageCursor?: string; -} +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'; ⋮---- -export interface HistoricalVolatilityV5 { - period: number; - value: string; - time: 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'; ⋮---- -export interface InsuranceDataV5 { - coin: string; - symbols: string; - balance: string; - value: string; -} +/** Represents an order created by a user. */ ⋮---- -export interface InsuranceResponseV5 { - updatedTime: string; - list: InsuranceDataV5[]; -} +/** Represents an order created by an admin closing. */ ⋮---- -export interface RiskLimitV5 { - id: number; - symbol: string; - riskLimitValue: string; - maintenanceMargin: number; - initialMargin: number; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - section: any; - isLowestRisk: 0 | 1; - maxLeverage: string; - mmDeduction: string; - nextPageCursor?: string; -} +/** Futures conditional order. */ ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +/** Futures take profit order. */ ⋮---- -/** @deprecated use DeliveryPriceV5 instead */ -export interface OptionDeliveryPriceV5 { - symbol: string; - deliveryPrice: string; - deliveryTime: string; -} +/** Futures partial take profit order. */ ⋮---- -export interface DeliveryPriceV5 { - symbol: string; - deliveryPrice: string; - deliveryTime: string; -} +/** Futures stop loss order. */ ⋮---- -export interface LongShortRatioV5 { - symbol: string; - buyRatio: string; - sellRatio: string; - timestamp: string; -} +/** Futures partial stop loss order. */ ⋮---- -export interface OrderPriceLimitV5 { - symbol: string; - buyLmt: string; - sellLmt: string; - ts: string; -} +/** Futures trailing stop order. */ ⋮---- -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 -} +/** Laddered liquidation to reduce the required maintenance margin. */ ⋮---- -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 +/** + * 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 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 -} +/** Auto-Deleveraging(ADL) */ ⋮---- -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 +/** Order placed via Paradigm. */ ⋮---- -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 -} +/** Order created by move position. */ ⋮---- -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 +/** The close order placed via web or app position area - web/app. */ ⋮---- -export interface ADLAlertResponseV5 { - updateTime: string; // Latest data update timestamp (ms) - list: ADLAlertItemV5[]; // List of ADL alert items -} +/** Order created via grid bot - web/app. */ ⋮---- -updateTime: string; // Latest data update timestamp (ms) -list: ADLAlertItemV5[]; // List of ADL alert items +/** Order closed via grid bot - web/app. */ ⋮---- -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 -} +/** Order created by TWAP - web/app. */ ⋮---- -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 +/** Order created by TV webhook - web/app. */ ⋮---- -export interface FeeGroupRatesV5 { - pro: FeeGroupLevelV5[]; // Pro-level fee structures - marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures -} +/** Order created by Mm rate close function - web/app. */ ⋮---- -pro: FeeGroupLevelV5[]; // Pro-level fee structures -marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures +/** Order created by Martingale bot - web/app. */ ⋮---- -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) -} +/** Order closed by Martingale bot - web/app. */ ⋮---- -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) +/** Order created by Ice berg strategy - web/app. */ ⋮---- -export interface FeeGroupStructureResponseV5 { - list: FeeGroupItemV5[]; // List of fee group objects -} +/** Order created by arbitrage - web/app. */ ⋮---- -list: FeeGroupItemV5[]; // List of fee group objects - -================ -File: src/types/response/v5-spot-leverage-token.ts -================ -import { - LeverageTokenStatusV5, - LTOrderStatusV5, - LTOrderTypeV5, -} from '../shared-v5'; +/** Option dynamic delta hedge order - web/app */ ⋮---- -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; -} +/** BBO Order - Best Bid/Offer order */ ⋮---- -export interface LeveragedTokenMarketResultV5 { - ltCoin: string; - nav: string; - navTime: string; - circulation: string; - basket: string; - leverage: string; -} +export type OrderCancelTypeV5 = + | 'CancelByUser' + | 'CancelByReduceOnly' + | 'CancelByPrepareLiq' + | 'CancelAllBeforeLiq' + | 'CancelByPrepareAdl' + | 'CancelAllBeforeAdl' + | 'CancelByAdmin' + | 'CancelByTpSlTsClear' + | 'CancelByPzSideCh' + | 'UNKNOWN'; ⋮---- -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 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 SpotLeveragedTokenOrderHistoryV5 { - ltCoin: string; - orderId: string; - ltOrderType: LTOrderTypeV5; - orderTime: number; - updateTime: number; - ltOrderStatus: LTOrderStatusV5; - fee: string; - amount: string; - value: string; - valueCoin: string; - serialNo: string; -} +export type StopOrderTypeV5 = + | 'TakeProfit' + | 'StopLoss' + | 'TrailingStop' + | 'Stop' + | 'PartialTakeProfit' + | 'PartialStopLoss' + | 'tpslOrder' + | 'OcoOrder' + | 'MmRateClose' + | 'BidirectionalTpslOrder'; ⋮---- -export interface VIPMarginDataV5 { - vipCoinList: { - list: { - borrowable: boolean; - collateralRatio: string; - currency: string; - hourlyBorrowRate: string; - liquidationOrder: string; - marginCollateral: boolean; - maxBorrowingAmount: string; - }[]; - vipLevel: 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 SpotMarginCurrencyDataV5 { - currency: string; - flexibleManualBorrowable: boolean; - minFlexibleManualBorrowQty: string; - flexibleManualBorrowAccuracy: string; - fixedManualBorrowable: boolean; - minFixedManualBorrowQty: string; - fixedManualBorrowAccuracy: string; - fixedInterestRateAccuracy: string; - minFixedInterestRate: string; - maxFixedInterestRate: 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 SpotMarginStateV5 { - spotLeverage: string; - spotMarginMode: '1' | '0'; - effectiveLeverage: string; -} +export type OptionTypeV5 = 'Call' | 'Put'; ⋮---- -// Spot Margin Trade (UTA) response types -export interface ManualBorrowResultV5 { - coin: string; - amount: string; -} +/** + * Trade mode. + * + * - 0 cross-margin, + * - 1 isolated margin + */ +export type TradeModeV5 = 0 | 1; ⋮---- -export interface MaxBorrowableAmountV5 { - currency: string; - maxLoan: string; -} +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'; ⋮---- -export interface PositionTierV5 { - tier: string; - borrowLimit: string; - positionMMR: string; - positionIMR: string; - maxLeverage: string; -} +export type PermissionTypeV5 = + | 'ContractTrade' + | 'Spot' + | 'Wallet' + | 'Options' + | 'Derivatives' + | 'Exchange' + | 'NFT'; ⋮---- -export interface CurrencyPositionTiersV5 { - currency: string; - positionTiersRatioList: PositionTierV5[]; -} +/** + * 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 CoinStateV5 { - currency: string; - spotLeverage: string; -} +/** + * Leveraged token order type: '1': purchase, '2': redeem + */ +export type LTOrderTypeV5 = '1' | '2'; ⋮---- -export interface AvailableAmountToRepayV5 { - currency: string; - lossLessRepaymentAmount: string; -} +/** + * Leveraged token order status: '1': completed, '2': in progress, '3': failed + */ +export type LTOrderStatusV5 = '1' | '2' | '3'; ⋮---- -export interface ManualRepayWithoutConversionResultV5 { - /** - * Result status: - * - P: Processing - * - SU: Success - * - FA: Failed - */ - resultStatus: 'P' | 'SU' | 'FA'; -} +export type ExecTypeV5 = + | 'Trade' + | 'AdlTrade' + | 'Funding' + | 'BustTrade' + | 'Settle' + | 'BlockTrade' + | 'MovePosition' + | 'UNKNOWN'; ⋮---- /** - * Result status: - * - P: Processing - * - SU: Success - * - FA: Failed - */ + * Withdraw type. 0(default): on chain. 1: off chain. 2: all. + */ +export type WithdrawalTypeV5 = '0' | '1' | '2'; ⋮---- -export interface AutoRepayModeItemV5 { - currency: string; // Coin name, uppercase only - autoRepayMode: '0' | '1'; // 0: Off, 1: On +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[]; } ⋮---- -currency: string; // Coin name, uppercase only -autoRepayMode: '0' | '1'; // 0: Off, 1: On +/** @deprecated , always returns []*/ ⋮---- -export interface AutoRepayModeResultV5 { - data: AutoRepayModeItemV5[]; -} +/** Bybit Pay (FaitPayOrder) */ ⋮---- -export interface SpotMarginLiabilityInfoV5 { - currency: string; - totalBorrowAmount: string; - fixedBorrowAmount: string; - flexibleBorrowAmount: string; - spotTotalBorrow: string; - derivativesBorrow: string; +export interface CategoryCursorListV5< + T extends unknown[], + TCategory extends CategoryV5 = CategoryV5, +> { + category: TCategory; + list: T; + nextPageCursor?: string; } ⋮---- -export interface FixedRateBorrowResultV5 { - orderId: string; +/** + * Next page cursor does not exist for spot! + */ +export interface CursorListV5 { + nextPageCursor: string; + list: T; } ⋮---- -export interface FixedRateBorrowOrderInfoV5 { - annualRate: string; - orderId: string; - orderTime: string; - filledQty: string; - orderQty: string; - orderCurrency: string; - state: number; - term: number; - repayType: string; - strategyType: 'PARTIAL' | 'FULL'; +/** + * 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 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'; +export interface CategoryListV5< + T extends unknown[], + TCategory extends CategoryV5, +> { + category: TCategory; + list: T; } ⋮---- -export interface FixedRateBorrowQuoteV5 { - orderCurrency: string; - term: number; - annualRate: string; - qty: string; +export interface CategorySymbolListV5< + T extends unknown[], + TCategory extends CategoryV5, +> { + category: TCategory; + symbol: string; + list: T; } - -================ -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 GetSystemStatusParamsV5 { + id?: string; + state?: string; } ⋮---- -export interface CreateSubApiKeyResultV5 { +export interface SystemStatusItemV5 { id: string; - note: string; - apiKey: string; - readOnly: number; - secret: string; - permissions: PermissionsV5; + title: string; + state: string; + begin: string; + end: string; + href: string; + serviceTypes: number[]; + product: number[]; + uidSuffix: number[]; + maintainType: string; + env: string; } + +================ +File: src/types/request/v5-asset.ts +================ +import { AccountTypeV5, CategoryV5 } from '../shared-v5'; ⋮---- -export interface SubMemberV5 { - uid: string; - username: string; - memberType: number; - status: number; - accountMode: number; - remark: string; +export interface GetCoinExchangeRecordParamsV5 { + fromCoin?: string; + toCoin?: string; + limit?: number; + cursor?: string; } -export type ApiKeyType = 1 | 2; ⋮---- -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 GetDeliveryRecordParamsV5 { + category: CategoryV5; + symbol?: string; + startTime?: number; + endTime?: number; + expDate?: string; + limit?: number; + cursor?: string; } ⋮---- -/** @deprecated */ +export interface GetSettlementRecordParamsV5 { + category: CategoryV5; + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -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 GetAssetInfoParamsV5 { + accountType: AccountTypeV5; + coin?: string; } ⋮---- -type: 1 | 2; // 1: personal, 2: connected to third-party app +export interface GetAllCoinsBalanceParamsV5 { + memberId?: string; + accountType: AccountTypeV5; + coin?: string; + withBonus?: number; +} ⋮---- -/** @deprecated */ +export interface GetAccountCoinBalanceParamsV5 { + memberId?: string; + toMemberId?: string; + accountType: AccountTypeV5; + coin: string; + toAccountType?: AccountTypeV5; + withBonus?: number; + withTransferSafeAmount?: 0 | 1; + withLtvTransferSafeAmount?: 0 | 1; +} ⋮---- -uta: 0 | 1; // 0: regular account, 1: unified trade account +export interface GetInternalTransferParamsV5 { + transferId?: string; + coin?: string; + status?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -export interface UpdateApiKeyResultV5 { - id: string; - note: string; - apiKey: string; - readOnly: 0 | 1; - secret: string; - permissions: PermissionsV5; - ips: string[]; +export interface UniversalTransferParamsV5 { + transferId: string; + coin: string; + amount: string; + fromMemberId: number; + toMemberId: number; + fromAccountType: AccountTypeV5; + toAccountType: AccountTypeV5; } ⋮---- -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 GetUniversalTransferRecordsParamsV5 { + transferId?: string; + coin?: string; + status?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; } ⋮---- -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; +export interface GetAllowedDepositCoinInfoParamsV5 { + coin?: string; + chain?: string; + limit?: number; + cursor?: string; } ⋮---- -/** tradfi trade volume in [startDate, endDate] when startDate/endDate in params */ +export interface GetDepositRecordParamsV5 { + id?: string; + txID?: string; + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** tradfi trade volume in last 30 days. 0 when startDate/endDate in params */ +export interface GetSubAccountDepositRecordParamsV5 { + id?: string; + txID?: string; + subMemberId: string; + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** tradfi trade volume in past year. 0 when startDate/endDate in params */ +export interface GetInternalDepositRecordParamsV5 { + txID?: string; + startTime?: number; + endTime?: number; + coin?: string; + cursor?: string; + limit?: number; +} ⋮---- -/** Commission between startDate and endDate when startDate/endDate in params. Coin -> amount */ +export interface GetWithdrawalRecordsParamsV5 { + withdrawID?: string; + txID?: string; + coin?: string; + withdrawType?: number; + startTime?: number; + endTime?: number; + limit?: number; + cursor?: string; +} ⋮---- -/** Commission in last 30 days. Coin -> amount */ +export interface GetWithdrawalAddressListParamsV5 { + coin?: string; + chain?: string; + addressType?: 0 | 1 | 2; + limit?: number; + cursor?: string; +} ⋮---- -/** Commission in past year. Coin -> amount */ +export interface SubmitDepositOriginatorInfoParamsV5 { + depositId: number; + subAccountId?: number; + /** Travel Rule questionnaire JSON string. See Questionnaire docs. */ + questionnaire: string; +} ⋮---- -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; +/** Travel Rule questionnaire JSON string. See Questionnaire docs. */ +⋮---- +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; + }; } ⋮---- -/** tradfi trade volume in last 30 days (USDT) */ +/** + * When forceChain is 0 or 1, required. When forceChain is 2 (Bybit UID withdraw), may be null/omitted. + */ ⋮---- -/** tradfi trade volume in past year (USDT) */ +/** + * 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. + */ ⋮---- -/** tradfi commissions in last 30 days. Coin -> amount */ +/** + * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. + */ ⋮---- -/** tradfi commissions in past year. Coin -> amount */ +/** + * Travel Rule questionnaire JSON string (max 16384 bytes). Takes precedence over `beneficiary` / `transactionPurpose` when both are set. + */ ⋮---- -/** Payment amount in the last 30 days */ +export interface ConvertCoinsParamsV5 { + coin?: string; + side?: number; + accountType: + | 'eb_convert_funding' + | 'eb_convert_uta' + | 'eb_convert_spot' + | 'eb_convert_contract' + | 'eb_convert_inverse'; +} ⋮---- -/** Pay first transaction amount */ +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; +} ⋮---- -/** Card first-time transaction amount */ +export interface GetConvertHistoryParamsV5 { + accountType?: string; + index?: number; + limit?: number; +} ⋮---- -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; +export interface GetSmallBalanceListParamsV5 { + accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet + fromCoin?: string; // Source currency } ⋮---- -/** Commission per currency (BTC, ETH, MNT, USDC, USDT) for the queried date range */ +accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet +fromCoin?: string; // Source currency ⋮---- -export interface AffiliateSubAffiliateListResultV5 { - list: AffiliateSubAffiliateListItemV5[]; - nextPageCursor: string; +export interface GetFiatTradingPairListParamsV5 { + side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) } ⋮---- -export interface FriendReferralRecordV5 { - id: string; - inviteeUid: string; - status: number; - createdAt: string; - updatedAt: 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; } - -================ -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'; +/** 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 MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; +/** 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 function isMessageEvent(msg: unknown): msg is MessageEventLike +/** GET /v5/asset/total-members-assets */ +export interface GetTotalMembersAssetsParamsV5 { + /** If omitted, defaults to BTC. Total is quoted in this coin. */ + coin?: string; +} ⋮---- -export interface WSPublicTopicEventV5 { - id?: string; - topic: TTopic; - type: TType; - /** Cross sequence */ - cs?: number; - /** Event timestamp */ - ts: number; - data: TData; +/** 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; /** - * matching engine timestamp (correlated with T from public trade channel) + * 1: normal, 6: custodial */ - cts: number; + memberType: 1 | 6; /** - * Internal reference, can be used to determine if this is spot/linear/inverse/etc + * 0: quick login disabled (default), 1: quick login enabled */ - wsKey: WsKey; + switch?: 0 | 1; + isUta?: boolean; + note?: string; } ⋮---- -/** Cross sequence */ -⋮---- -/** Event timestamp */ -⋮---- /** - * matching engine timestamp (correlated with T from public trade channel) + * 1: normal, 6: custodial */ ⋮---- /** - * Internal reference, can be used to determine if this is spot/linear/inverse/etc + * 0: quick login disabled (default), 1: quick login enabled */ ⋮---- -export interface WSPrivateTopicEventV5 { - id?: string; - topic: TTopic; - creationTime: number; - data: TData; - wsKey: WsKey; +export interface CreateSubApiKeyParamsV5 { + subuid: number; + note?: string; + readOnly: 0 | 1; + ips?: string; + permissions: PermissionsV5; } ⋮---- -export interface WSOrderbookV5 { - /** Symbol */ - s: string; - /** [price, qty][] */ - b: [string, string][]; - /** [price, qty][] */ - a: [string, string][]; - /** Update ID */ - u: number; - /** Cross sequence */ - seq: number; +export interface UpdateApiKeyParamsV5 { + apikey?: string; + readOnly?: 0 | 1; + permissions: PermissionsV5; +} +⋮---- +export interface UpdateSubApiKeyUpdateParamsV5 { + readOnly?: number; + ips?: string[]; + permissions: PermissionsV5; +} +⋮---- +export interface DeleteSubMemberParamsV5 { + subMemberId: string; +} +⋮---- +export interface GetSubAccountAllApiKeysParamsV5 { + subMemberId: string; + limit?: number; + cursor?: string; +} +⋮---- +export interface GetAffiliateUserListParamsV5 { + size?: number; + cursor?: string; + needDeposit?: boolean; + need30?: boolean; + need365?: boolean; + startDate?: string; + endDate?: string; +} +⋮---- +/** 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; } ⋮---- -/** Symbol */ +/** [0, 100]. Default: 0 */ +⋮---- +/** YYYY-MM-DD. Range with endDate max 3 months */ +⋮---- +/** YYYY-MM-DD. Must be provided with startDate or both omitted (T-1 default) */ +⋮---- +/** Exact sub-affiliate ID. 0 or omit for all */ ⋮---- -/** [price, qty][] */ +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'; +} ⋮---- -/** [price, qty][] */ +/** The master account UID of affiliate's client */ ⋮---- -/** Update ID */ +/** Coin type for filtering, e.g. USDT */ ⋮---- -/** Cross sequence */ +/** + * Business line filter. 1: Derivatives, 2: Spot, 3: ByFi, 4: USDC, 5: Options + */ ⋮---- -export type WSOrderbookEventV5 = WSPublicTopicEventV5< - string, - 'delta' | 'snapshot', - WSOrderbookV5 ->; +/** Get Friend Referrals - invitation relationship status. 0: alive; 1: invalid */ +export interface GetFriendReferralsParamsV5 { + status?: string; + size?: string; + cursor?: string; +} ⋮---- -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; +/** 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-market.ts +================ +import { + CategoryCursorListV5, + CategoryV5, + ContractTypeV5, + CopyTradingV5, + InstrumentStatusV5, + InstrumentSymbolTypeV5, + MarginTradingV5, + OptionTypeV5, + OrderSideV5, +} from '../shared-v5'; ⋮---- -export type WSTradeEventV5 = WSPublicTopicEventV5< +/** + * OHLCVT candle used by v5 APIs + * + * - list[0]: startTime string Start time of the candle (ms) + * - list[1]: openPrice string Open price + * - list[2]: highPrice string Highest price + * - list[3]: lowPrice string Lowest price + * - list[4]: closePrice string Close price. Is the last traded price when the candle is not closed + * - list[5]: volume string Trade volume. Unit of contract: pieces of contract. Unit of spot: quantity of coins + * - list[6]: turnover string Turnover. Unit of figure: quantity of quota coin + */ +export type OHLCVKlineV5 = [ string, - 'snapshot', - WSTradeV5[] ->; + string, + string, + string, + string, + string, + string, +]; ⋮---- /** - * WSTickerV5 is the data structure for the "linear" ticker channel - * */ -export interface WSTickerV5 { + * OHLC candle used by v5 APIs + * + * - list[0]: startTime string Start time of the candle (ms) + * - list[1]: openPrice string Open price + * - list[2]: highPrice string Highest price + * - list[3]: lowPrice string Lowest price + * - list[4]: closePrice string Close price. Is the last traded price when the candle is not closed + */ +export type OHLCKlineV5 = [string, string, string, string, string]; +⋮---- +export interface LinearInverseInstrumentInfoV5 { + /** The ID of the symbol name. */ + symbolId: number; symbol: string; - tickDirection: string; - price24hPcnt: string; - lastPrice: string; - prevPrice24h: string; - highPrice24h: string; - lowPrice24h: string; - prevPrice1h: string; - markPrice: string; - indexPrice: string; - openInterest: string; - openInterestValue: string; - turnover24h: string; - volume24h: string; - nextFundingTime: string; - fundingRate: string; - bid1Price: string; - bid1Size: string; - ask1Price: string; - ask1Size: string; + contractType: ContractTypeV5; + status: InstrumentStatusV5; + baseCoin: string; + quoteCoin: string; + /** Region / product class for the pair (`stock`, `forex`, `commodity`, `xstocks`, etc.). */ + symbolType: InstrumentSymbolTypeV5; + launchTime: string; deliveryTime?: string; - basisRate?: string; deliveryFeeRate?: string; - predictedDeliveryPrice?: string; - preOpenPrice?: string; - preQty?: string; - curPreListingPhase?: string; - fundingIntervalHour?: string; - fundingCap?: string; - basisRateYear?: string; + priceScale: string; + leverageFilter: { + minLeverage: string; + maxLeverage: string; + leverageStep: string; + }; + priceFilter: { + minPrice: string; + maxPrice: string; + tickSize: string; + }; + lotSizeFilter: { + maxOrderQty: string; + maxMktOrderQty: string; + minOrderQty: string; + qtyStep: string; + postOnlyMaxOrderQty?: string; + minNotionalValue?: string; + }; + unifiedMarginTrade: boolean; + fundingInterval: number; + settleCoin: string; + copyTrading: CopyTradingV5; + upperFundingRate: string; + lowerFundingRate: string; + riskParameters: { + priceLimitRatioX: string; + priceLimitRatioY: string; + }; + isPreListing: boolean; + preListingInfo: { + curAuctionPhase: string; + phases: { + phase: string; + startTime: string; + endTime: string; + }[]; + auctionFeeInfo: { + auctionFeeRate: string; + takerFeeRate: string; + makerFeeRate: string; + }; + } | null; + skipCallAuction?: boolean; // For USDT pre-market contract + displayName: string; } ⋮---- -export interface WSTickerOptionV5 { +/** The ID of the symbol name. */ +⋮---- +/** Region / product class for the pair (`stock`, `forex`, `commodity`, `xstocks`, etc.). */ +⋮---- +skipCallAuction?: boolean; // For USDT pre-market contract +⋮---- +export interface OptionInstrumentInfoV5 { + /** The ID of the symbol name. */ + symbolId: number; 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; + optionsType: OptionTypeV5; + status: InstrumentStatusV5; + baseCoin: string; + quoteCoin: string; + settleCoin: string; + symbolType: InstrumentSymbolTypeV5; + launchTime: string; + deliveryTime: string; + deliveryFeeRate: string; + priceFilter: { + minPrice: string; + maxPrice: string; + tickSize: string; + }; + lotSizeFilter: { + maxOrderQty: string; + minOrderQty: string; + qtyStep: string; + }; + displayName: string; +} +⋮---- +/** The ID of the symbol name. */ +⋮---- +export interface SpotInstrumentInfoV5 { + /** The ID of the symbol name. */ + symbolId: number; + symbol: string; + baseCoin: string; + quoteCoin: string; + /** + * Xstock multiplier for `symbolType` = xstocks pairs. `stock_price = token_price / multiplier`, + * `stock_qty = token_qty * multiplier`. Default `"1"`. + */ + xstockMultiplier?: string; + symbolType: InstrumentSymbolTypeV5; + innovation: '0' | '1'; // Deprecated, always 0 + status: InstrumentStatusV5; + marginTrading: MarginTradingV5; + stTag: '0' | '1'; + lotSizeFilter: { + basePrecision: string; + quotePrecision: string; + minOrderQty: string; + maxOrderQty: string; + minOrderAmt: string; + maxOrderAmt: string; + maxLimitOrderQty: string; + maxMarketOrderQty: string; + postOnlyMaxLimitOrderSize: string; + }; + priceFilter: { + tickSize: string; + }; + riskParameters: { + priceLimitRatioX: string; + priceLimitRatioY: string; + }; + forbidUplWithdrawal: boolean; } ⋮---- -export interface WSTickerSpotV5 { - symbol: string; - lastPrice: string; - highPrice24h: string; - lowPrice24h: string; - prevPrice24h: string; - volume24h: string; - turnover24h: string; - price24hPcnt: string; - usdIndexPrice: string; -} +/** The ID of the symbol name. */ ⋮---- -export type WSTickerEventV5 = WSPublicTopicEventV5< - string, - 'snapshot' | 'delta', - WSTickerV5 | WSTickerOptionV5 | WSTickerSpotV5 ->; +/** + * Xstock multiplier for `symbolType` = xstocks pairs. `stock_price = token_price / multiplier`, + * `stock_qty = token_qty * multiplier`. Default `"1"`. + */ ⋮---- -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; -} +innovation: '0' | '1'; // Deprecated, always 0 ⋮---- -export type WSKlineEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSKlineV5[] ->; +type InstrumentInfoV5Mapping = { + linear: LinearInverseInstrumentInfoV5[]; + inverse: LinearInverseInstrumentInfoV5[]; + option: OptionInstrumentInfoV5[]; + spot: SpotInstrumentInfoV5[]; +}; ⋮---- -export interface WSLiquidationV5 { - T: number; - s: string; - S: OrderSideV5; - v: string; - p: string; +export type InstrumentInfoResponseV5 = + CategoryCursorListV5; +⋮---- +// Account Instruments Info (includes RPI permissions) +export interface AccountSpotInstrumentInfoV5 extends SpotInstrumentInfoV5 { + isPublicRpi: boolean; + myRpiPermission: boolean; } ⋮---- -export type WSLiquidationEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSLiquidationV5[] ->; +export interface AccountLinearInverseInstrumentInfoV5 + extends LinearInverseInstrumentInfoV5 { + isPublicRpi: boolean; + myRpiPermission: boolean; +} ⋮---- -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; +type AccountInstrumentInfoV5Mapping = { + linear: AccountLinearInverseInstrumentInfoV5[]; + inverse: AccountLinearInverseInstrumentInfoV5[]; + spot: AccountSpotInstrumentInfoV5[]; +}; +⋮---- +export type AccountInstrumentInfoResponseV5< + C extends 'spot' | 'linear' | 'inverse', +> = CategoryCursorListV5; +⋮---- +/** + * [price, size] + */ +export type OrderbookLevelV5 = [string, string]; +⋮---- +export interface OrderbookResponseV5 { + s: string; + b: OrderbookLevelV5[]; + a: OrderbookLevelV5[]; + ts: number; + u: number; seq: number; + cts: number; } ⋮---- -breakEvenPrice?: string; // Break even price, only for linear & inverse +/** + * RPI Orderbook level: [price, nonRpiSize, rpiSize] + */ +export type RPIOrderbookLevelV5 = [string, string, string]; ⋮---- -/** Position open timestamp (ms). Default `0` when not set. */ +export interface RPIOrderbookResponseV5 { + s: string; // Symbol name + b: RPIOrderbookLevelV5[]; // Bids. Sorted by price in descending order + a: RPIOrderbookLevelV5[]; // Asks. Sorted by price in ascending order + ts: number; // The timestamp (ms) that the system generates the data + u: number; // Update ID, is always in sequence corresponds to u in the 50-level WebSocket RPI orderbook stream + seq: number; // Cross sequence + cts: number; // The timestamp from the matching engine when this orderbook data is produced +} ⋮---- -export type WSPositionEventV5 = WSPrivateTopicEventV5< - 'position', - WSPositionV5[] ->; +s: string; // Symbol name +b: RPIOrderbookLevelV5[]; // Bids. Sorted by price in descending order +a: RPIOrderbookLevelV5[]; // Asks. Sorted by price in ascending order +ts: number; // The timestamp (ms) that the system generates the data +u: number; // Update ID, is always in sequence corresponds to u in the 50-level WebSocket RPI orderbook stream +seq: number; // Cross sequence +cts: number; // The timestamp from the matching engine when this orderbook data is produced ⋮---- -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; +export interface TickerLinearInverseV5 { 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 + lastPrice: string; + indexPrice: string; + markPrice: string; + prevPrice24h: string; + price24hPcnt: string; + highPrice24h: string; + lowPrice24h: string; + prevPrice1h: string; + openInterest: string; + openInterestValue: string; + singleOpenInterest?: string; + singleOpenInterestValue?: string; + turnover24h: string; + volume24h: string; + fundingRate: string; + nextFundingTime: string; + predictedDeliveryPrice: string; + basisRate: string; + basisRateYear: string; + fundingIntervalHour: string; + fundingCap: string; + deliveryFeeRate: string; + deliveryTime: string; + ask1Size: string; + bid1Price: string; + ask1Price: string; + bid1Size: string; + preOpenPrice: string; + preQty: string; + curPreListingPhase: string; + basis: 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; +export interface TickerOptionV5 { 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; + bid1Price: string; + bid1Size: string; + bid1Iv: string; + ask1Price: string; + ask1Size: string; + ask1Iv: string; + lastPrice: string; + highPrice24h: string; + lowPrice24h: string; markPrice: string; indexPrice: string; + markIv: string; underlyingPrice: string; - blockTradeId: string; - closedSize: string; - extraFees: string; - seq: number; - marketUnit: string; + openInterest: string; + turnover24h: string; + volume24h: string; + totalVolume: string; + totalTurnover: string; + delta: string; + gamma: string; + vega: string; + theta: string; + predictedDeliveryPrice: string; + change24h: string; } ⋮---- -feeCurrency: string; // Trading fee currency -⋮---- -export type WSExecutionEventV5 = WSPrivateTopicEventV5< - 'execution', - WSExecutionV5[] ->; +export interface TickerSpotV5 { + symbol: string; + bid1Price: string; + bid1Size: string; + ask1Price: string; + ask1Size: string; + lastPrice: string; + prevPrice24h: string; + price24hPcnt: string; + highPrice24h: string; + lowPrice24h: string; + turnover24h: string; + volume24h: string; + usdIndexPrice: string; +} ⋮---- -export interface WSExecutionFastV5 { - category: CategoryV5; +export interface FundingRateHistoryResponseV5 { symbol: string; + fundingRate: string; + fundingRateTimestamp: string; +} +⋮---- +export interface PublicTradeV5 { execId: string; - execPrice: string; - execQty: string; - orderId: string; - isMaker: boolean; - orderLinkId: string; + symbol: string; + price: string; + size: string; side: OrderSideV5; - execTime: string; - seq: number; + time: string; + isBlockTrade: boolean; + isRPITrade: boolean; + mP?: string; + iP?: string; + mIv?: string; + iv?: string; + seq?: string; } ⋮---- -export type WSExecutionFastEventV5 = WSPrivateTopicEventV5< - 'execution.fast', - WSExecutionFastV5[] ->; +/** + * + * - openInterest string Open interest + * - timestamp string The timestamp (ms) + */ +export type OpenInterestV5 = { + openInterest: string; + singleOpenInterest?: string; + timestamp: string; +}; ⋮---- -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; +export interface OpenInterestResponseV5 { + category: 'linear' | 'inverse'; + symbol: string; + list: OpenInterestV5[]; + nextPageCursor?: 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 interface HistoricalVolatilityV5 { + period: number; + value: string; + time: string; } ⋮---- -export type WSWalletEventV5 = WSPrivateTopicEventV5<'wallet', WSWalletV5[]>; -⋮---- -export interface WSGreeksV5 { - baseCoin: string; - totalDelta: string; - totalGamma: string; - totalVega: string; - totalTheta: string; +export interface InsuranceDataV5 { + coin: string; + symbols: string; + balance: string; + value: 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; +export interface InsuranceResponseV5 { updatedTime: string; - feeCurrency: string; - createType: OrderCreateTypeV5; - closedPnl: string; - cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency -} -⋮---- -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; + list: InsuranceDataV5[]; } ⋮---- -feeCurrency: string; // Trading fee currency +export interface RiskLimitV5 { + id: number; + symbol: string; + riskLimitValue: string; + maintenanceMargin: number; + initialMargin: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + section: any; + isLowestRisk: 0 | 1; + maxLeverage: string; + mmDeduction: string; + nextPageCursor?: string; +} ⋮---- -export type WSSpreadExecutionEventV5 = WSPrivateTopicEventV5< - 'spread.execution', - WSSpreadExecutionV5[] ->; +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -export interface WSInsuranceV5 { - coin: string; - symbols: string; - balance: string; - updateTime: string; +/** @deprecated use DeliveryPriceV5 instead */ +export interface OptionDeliveryPriceV5 { + symbol: string; + deliveryPrice: string; + deliveryTime: string; } ⋮---- -export type WSInsuranceEventV5 = WSPublicTopicEventV5< - 'insurance.USDT' | 'insurance.USDC' | 'insurance.inverse', - 'snapshot' | 'delta', - WSInsuranceV5[] ->; +export interface DeliveryPriceV5 { + symbol: string; + deliveryPrice: string; + deliveryTime: string; +} ⋮---- -export interface WSPriceLimitV5 { +export interface LongShortRatioV5 { + symbol: string; + buyRatio: string; + sellRatio: string; + timestamp: string; +} +⋮---- +export interface OrderPriceLimitV5 { symbol: string; buyLmt: string; sellLmt: string; + ts: string; } ⋮---- -export type WSPriceLimitEventV5 = WSPublicTopicEventV5< - string, - 'snapshot', - WSPriceLimitV5 ->; +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 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 +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 } ⋮---- -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 +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 type WSADLAlertEventV5 = WSPublicTopicEventV5< - 'adlAlert.USDT' | 'adlAlert.USDC' | 'adlAlert.inverse', - 'snapshot', - WSADLAlertV5[] ->; +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 type WSSystemStatusEventV5 = WSPublicTopicEventV5< - 'system.status', - 'snapshot', - SystemStatusItemV5[] ->; +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 ⋮---- -/** - * RFQ WebSocket Events - */ +export interface ADLAlertResponseV5 { + updateTime: string; // Latest data update timestamp (ms) + list: ADLAlertItemV5[]; // List of ADL alert items +} ⋮---- -/** - * 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[] ->; +updateTime: string; // Latest data update timestamp (ms) +list: ADLAlertItemV5[]; // List of ADL alert items ⋮---- -/** - * 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[] ->; +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 +} ⋮---- -/** - * 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[] ->; +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 ⋮---- -/** - * 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: .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 +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/request/v5-asset.ts +File: src/types/response/v5-user.ts ================ -import { AccountTypeV5, CategoryV5 } from '../shared-v5'; +import { PermissionsV5 } from '../shared-v5'; +⋮---- +export interface CreateSubMemberResultV5 { + uid: string; + username: string; + memberType: number; + status: number; + remark: string; +} ⋮---- -export interface GetCoinExchangeRecordParamsV5 { - fromCoin?: string; - toCoin?: string; - limit?: number; - cursor?: string; +export interface CreateSubApiKeyResultV5 { + id: string; + note: string; + apiKey: string; + readOnly: number; + secret: string; + permissions: PermissionsV5; } ⋮---- -export interface GetDeliveryRecordParamsV5 { - category: CategoryV5; - symbol?: string; - startTime?: number; - endTime?: number; - expDate?: string; - limit?: number; - cursor?: string; +export interface SubMemberV5 { + uid: string; + username: string; + memberType: number; + status: number; + accountMode: number; + remark: string; } +export type ApiKeyType = 1 | 2; ⋮---- -export interface GetSettlementRecordParamsV5 { - category: CategoryV5; - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +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 GetAssetInfoParamsV5 { - accountType: AccountTypeV5; - coin?: 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 GetAllCoinsBalanceParamsV5 { - memberId?: string; - accountType: AccountTypeV5; - coin?: string; - withBonus?: number; +type: 1 | 2; // 1: personal, 2: connected to third-party app +⋮---- +/** @deprecated */ +⋮---- +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 GetAccountCoinBalanceParamsV5 { - memberId?: string; - toMemberId?: string; - accountType: AccountTypeV5; - coin: string; - toAccountType?: AccountTypeV5; - withBonus?: number; - withTransferSafeAmount?: 0 | 1; - withLtvTransferSafeAmount?: 0 | 1; +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 GetInternalTransferParamsV5 { - transferId?: string; - coin?: string; - status?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +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; } ⋮---- -export interface UniversalTransferParamsV5 { - transferId: string; - coin: string; - amount: string; - fromMemberId: number; - toMemberId: number; - fromAccountType: AccountTypeV5; - toAccountType: AccountTypeV5; +/** 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; } ⋮---- -export interface GetUniversalTransferRecordsParamsV5 { - transferId?: string; - coin?: string; - status?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: 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; } ⋮---- -export interface GetAllowedDepositCoinInfoParamsV5 { - coin?: string; - chain?: string; - limit?: number; - cursor?: string; -} +/** Commission per currency (BTC, ETH, MNT, USDC, USDT) for the queried date range */ ⋮---- -export interface GetDepositRecordParamsV5 { - id?: string; - txID?: string; - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface AffiliateSubAffiliateListResultV5 { + list: AffiliateSubAffiliateListItemV5[]; + nextPageCursor: string; } ⋮---- -export interface GetSubAccountDepositRecordParamsV5 { - id?: string; - txID?: string; - subMemberId: string; - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +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 interface GetInternalDepositRecordParamsV5 { - txID?: string; - startTime?: number; - endTime?: number; - coin?: string; - cursor?: string; - limit?: number; -} +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 GetWithdrawalRecordsParamsV5 { - withdrawID?: string; - txID?: string; - coin?: string; - withdrawType?: number; - startTime?: number; - endTime?: number; - limit?: number; - cursor?: string; +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; } ⋮---- -export interface GetWithdrawalAddressListParamsV5 { - coin?: string; - chain?: string; - addressType?: 0 | 1 | 2; - limit?: number; - cursor?: string; -} +export function isMessageEvent(msg: unknown): msg is MessageEventLike ⋮---- -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; +export interface WSPublicTopicEventV5 { + id?: string; + topic: TTopic; + type: TType; + /** Cross sequence */ + cs?: number; + /** Event timestamp */ + ts: number; + data: TData; /** - * 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. + * matching engine timestamp (correlated with T from public trade channel) */ - accountType: string; - feeType?: 0 | 1; - requestId?: string; + cts: number; /** - * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. + * Internal reference, can be used to determine if this is spot/linear/inverse/etc */ - transactionPurpose?: string; - beneficiary?: { - vaspEntityId?: string; - beneficiaryName?: string; - beneficiaryLegalType?: string; - beneficiaryWalletType?: string; - beneficiaryUnhostedWalletType?: string; - beneficiaryPoiNumber?: string; - beneficiaryPoiType?: string; - beneficiaryPoiIssuingCountry?: string; - beneficiaryPoiExpiredDate?: string; - }; + wsKey: WsKey; } ⋮---- -/** - * When forceChain is 0 or 1, required. When forceChain is 2 (Bybit UID withdraw), may be null/omitted. - */ +/** Cross sequence */ +⋮---- +/** Event timestamp */ ⋮---- /** - * 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. + * matching engine timestamp (correlated with T from public trade channel) */ ⋮---- /** - * Required for Bybit Turkey (TR) site users when creating a withdrawal. Omitted for other regions unless the API requires it. + * Internal reference, can be used to determine if this is spot/linear/inverse/etc */ ⋮---- -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 WSPrivateTopicEventV5 { + id?: string; + topic: TTopic; + creationTime: number; + data: TData; + wsKey: WsKey; } ⋮---- -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 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 GetConvertHistoryParamsV5 { - accountType?: string; - index?: number; - limit?: number; +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 GetSmallBalanceListParamsV5 { - accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet - fromCoin?: string; // Source currency +export interface WSTickerSpotV5 { + symbol: string; + lastPrice: string; + highPrice24h: string; + lowPrice24h: string; + prevPrice24h: string; + volume24h: string; + turnover24h: string; + price24hPcnt: string; + usdIndexPrice: string; } ⋮---- -accountType: 'eb_convert_uta'; // Wallet type, only supports Unified wallet -fromCoin?: string; // Source currency +export type WSTickerEventV5 = WSPublicTopicEventV5< + string, + 'snapshot' | 'delta', + WSTickerV5 | WSTickerOptionV5 | WSTickerSpotV5 +>; ⋮---- -export interface GetFiatTradingPairListParamsV5 { - side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) +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; } ⋮---- -side?: 0 | 1; // 0: buy (buy crypto, sell fiat), 1: sell (sell crypto, buy fiat) +export type WSKlineEventV5 = WSPublicTopicEventV5< + string, + 'snapshot', + WSKlineV5[] +>; ⋮---- -/** Funding Account Transaction History. Interval createTimeFrom-createTimeTo max 7 days. */ -export interface GetFundingAccountTransactionHistoryParamsV5 { - createTimeFrom?: string; - createTimeTo?: string; - limit?: string; - cursor?: string; +export interface WSLiquidationV5 { + T: number; + s: string; + S: OrderSideV5; + v: string; + p: 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 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; } ⋮---- -/** Fiat currency for valuation; defaults to USD if omitted. */ +breakEvenPrice?: string; // Break even price, only for linear & inverse ⋮---- -/** Account type filter; returns all if omitted. */ +/** Position open timestamp (ms). Default `0` when not set. */ ⋮---- -/** GET /v5/asset/portfolio-margin */ -export interface GetPortfolioMarginInfoParamsV5 { - baseCoin?: string; -} +export type WSPositionEventV5 = WSPrivateTopicEventV5< + 'position', + WSPositionV5[] +>; ⋮---- -/** GET /v5/asset/total-members-assets */ -export interface GetTotalMembersAssetsParamsV5 { - /** If omitted, defaults to BTC. Total is quoted in this coin. */ - coin?: 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; } ⋮---- -/** If omitted, defaults to BTC. Total is quoted in this coin. */ - -================ -File: src/types/response/v5-asset.ts -================ -import { AccountTypeV5, OrderSideV5, WithdrawalTypeV5 } from '../shared-v5'; +parentOrderLinkId?: string; // Linked parent order for attached TP/SL orders (futures & options) ⋮---- -export interface CoinExchangeRecordV5 { - fromCoin: string; - fromAmount: string; - toCoin: string; - toAmount: string; - exchangeRate: string; - createdTime: string; - exchangeTxId: string; +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; } ⋮---- -export interface DeliveryRecordV5 { - deliveryTime: number; - symbol: string; - side: OrderSideV5; - position: string; - deliveryPrice: string; - strike: string; - fee: string; - deliveryRpl: string; - entryPrice: string; -} +feeCurrency: string; // Trading fee currency ⋮---- -export interface SettlementRecordV5 { - symbol: string; - side: string; - size: number; - sessionAvgPrice: string; - markPrice: string; - realisedPnl: string; - createdTime: string; -} +export type WSExecutionEventV5 = WSPrivateTopicEventV5< + 'execution', + WSExecutionV5[] +>; ⋮---- -export interface AssetInfoAssetV5 { - coin: string; - frozen: string; - free: string; - withdraw: string; +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 interface AssetInfoV5 { - status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED'; - assets: AssetInfoAssetV5[]; -} +export type WSExecutionFastEventV5 = WSPrivateTopicEventV5< + 'execution.fast', + WSExecutionFastV5[] +>; ⋮---- -export interface CoinBalanceV5 { +export interface WSCoinV5 { coin: string; + equity: string; + usdValue: 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; - }; + 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 InternalTransferRecordV5 { - transferId: string; - coin: string; - amount: string; - fromAccountType: AccountTypeV5; - toAccountType: AccountTypeV5; - timestamp: string; - status: 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 interface UniversalTransferRecordV5 { - transferId: string; - coin: string; - amount: string; - fromMemberId: string; - toMemberId: string; - fromAccountType: AccountTypeV5; - toAccountType: AccountTypeV5; - timestamp: string; - status: string; -} +export type WSWalletEventV5 = WSPrivateTopicEventV5<'wallet', WSWalletV5[]>; ⋮---- -export interface AllowedDepositCoinInfoV5 { - coin: string; - chain: string; - coinShowName: string; - chainType: string; - blockConfirmNumber: number; - minDepositAmount: string; +export interface WSGreeksV5 { + baseCoin: string; + totalDelta: string; + totalGamma: string; + totalVega: string; + totalTheta: 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; -} +export type WSGreeksEventV5 = WSPrivateTopicEventV5<'greeks', WSGreeksV5[]>; ⋮---- -export interface InternalDepositRecordV5 { - id: string; - type: 1; - coin: string; - amount: string; - status: 1 | 2 | 3; - address: string; +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; - txID: string; + updatedTime: string; + feeCurrency: string; + createType: OrderCreateTypeV5; + closedPnl: string; + cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency } ⋮---- -export interface DepositAddressChainV5 { - chainType: string; - addressDeposit: string; - tagDeposit: string; - chain: string; - batchReleaseLimit: string; - contractAddress: string; -} +cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency ⋮---- -export interface DepositAddressResultV5 { - coin: string; - chains: DepositAddressChainV5[]; -} +export type WSSpreadOrderEventV5 = WSPrivateTopicEventV5< + 'spread.order', + WSSpreadOrderV5[] +>; ⋮---- -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; - }[]; +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; } ⋮---- -/** @deprecated Use `chains[].withdrawMax` instead */ +feeCurrency: string; // Trading fee currency ⋮---- -/** Max withdraw amount per transaction per chain. `-1` means no limit */ +export type WSSpreadExecutionEventV5 = WSPrivateTopicEventV5< + 'spread.execution', + WSSpreadExecutionV5[] +>; ⋮---- -export interface WithdrawalRecordV5 { - withdrawId: string; - txID: string; - withdrawType: WithdrawalTypeV5; +export interface WSInsuranceV5 { coin: string; - chain: string; - amount: string; - withdrawFee: string; - status: string; - toAddress: string; - tag: string; - createTime: string; + symbols: string; + balance: 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; -} +export type WSInsuranceEventV5 = WSPublicTopicEventV5< + 'insurance.USDT' | 'insurance.USDC' | 'insurance.inverse', + 'snapshot' | 'delta', + WSInsuranceV5[] +>; ⋮---- -/** - * 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 WSPriceLimitV5 { + symbol: string; + buyLmt: string; + sellLmt: string; } ⋮---- -export interface VaspEntityV5 { - vaspEntityId: string; - vaspName: string; -} +export type WSPriceLimitEventV5 = WSPublicTopicEventV5< + string, + 'snapshot', + WSPriceLimitV5 +>; ⋮---- -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 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 } ⋮---- -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[]; -} +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 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 type WSADLAlertEventV5 = WSPublicTopicEventV5< + 'adlAlert.USDT' | 'adlAlert.USDC' | 'adlAlert.inverse', + 'snapshot', + WSADLAlertV5[] +>; ⋮---- -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 type WSSystemStatusEventV5 = WSPublicTopicEventV5< + 'system.status', + 'snapshot', + SystemStatusItemV5[] +>; ⋮---- -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 -} +/** + * RFQ WebSocket Events + */ ⋮---- -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 +/** + * 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[] +>; ⋮---- -export interface SmallBalanceListV5 { - smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info - supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) -} +/** + * 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[] +>; ⋮---- -smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info -supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) +/** + * 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[] +>; ⋮---- -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 -} +/** + * 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/types/websockets/ws-general.ts +================ +import { AxiosRequestConfig } from 'axios'; +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; ⋮---- -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 +import { RestClientOptions, WS_KEY_MAP } from '../../util'; ⋮---- -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 -} +/** For spot markets, spotV3 is recommended */ +export type APIMarket = 'v5'; ⋮---- -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 +// Same as inverse futures +export type WsPublicInverseTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'klineV2'; ⋮---- -export interface FiatTradingPairListV5 { - fiats: FiatCoinInfoV5[]; // Fiat coin list - cryptos: CryptoCoinInfoV5[]; // Crypto coin list -} +export type WsPublicUSDTPerpTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'kline'; ⋮---- -fiats: FiatCoinInfoV5[]; // Fiat coin list -cryptos: CryptoCoinInfoV5[]; // Crypto coin list +export type WsPublicSpotV1Topic = + | 'trade' + | 'realtimes' + | 'kline' + | 'depth' + | 'mergedDepth' + | 'diffDepth'; ⋮---- -export interface FundingAccountTransactionRecordV5 { - memberId: string; - currency: string; - ioDirection: string; - txnAmt: string; - afterAmt: string; - createTime: string; - showBusiType: string; - showBusiTypeEn: string; - description: string; - descriptionEn: string; -} +export type WsPublicSpotV2Topic = + | 'depth' + | 'kline' + | 'trade' + | 'bookTicker' + | 'realtimes'; ⋮---- -/** When accountType=Alpha and category is farm, under `coinDetail` in sub-categories. */ -export interface AssetOverviewCoinExtMapV5 { - priceUpper?: string; - priceLower?: string; - equityUnit?: string; -} +export type WsPublicTopics = + | WsPublicInverseTopic + | WsPublicUSDTPerpTopic + | WsPublicSpotV1Topic + | WsPublicSpotV2Topic + | string; ⋮---- -export interface AssetOverviewCoinDetailV5 { - coin: string; - equity: string; - extMap?: AssetOverviewCoinExtMapV5; -} +// Same as inverse futures +export type WsPrivateInverseTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order'; ⋮---- -export interface AssetOverviewCategoryV5 { - category: string; - equity: string; - coinDetail: AssetOverviewCoinDetailV5[]; -} +export type WsPrivateUSDTPerpTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order' + | 'wallet'; ⋮---- -export interface AssetOverviewAccountItemV5 { - accountType: string; - totalEquity: string; - valuationCurrency: string; - snapshotTime: string; - coinDetail?: AssetOverviewCoinDetailV5[]; - categories?: AssetOverviewCategoryV5[]; -} +export type WsPrivateSpotTopic = + | 'outboundAccountInfo' + | 'executionReport' + | 'ticketInfo'; ⋮---- -export interface AssetOverviewResultV5 { - totalEquity: string; - list: AssetOverviewAccountItemV5[]; -} +export type WsPrivateTopic = + | WsPrivateInverseTopic + | WsPrivateUSDTPerpTopic + | WsPrivateSpotTopic + | string; ⋮---- -// --- GET /v5/asset/portfolio-margin (portfolio margin P&L ranges) --- +export type WsTopic = WsPublicTopics | WsPrivateTopic; ⋮---- -export interface PortfolioMarginWalletV5 { - equity: string; - cashBalance: string; - marginBalance: string; - availableBalance: string; - accountIM: string; - accountMM: string; - accountMMRate: string; - accountIMRate: string; -} +/** 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 PortfolioMarginPnlRangePointV5 { - priceScale: string; - pnls: string[]; +export interface WSClientConfigurableOptions { + /** Your API key */ + key?: string; + + /** Your API secret */ + secret?: string; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; + + /** How often to check if the connection is alive */ + pingInterval?: number; + + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; + + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; + + restOptions?: RestClientOptions; + requestOptions?: AxiosRequestConfig; + + wsOptions?: { + protocols?: string[]; + agent?: any; + } & Partial; + + wsUrl?: string; + + /** + * 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; + + /** + * 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; } ⋮---- -export interface PortfolioMarginContractBucketPnlV5 { - pnlRanges: PortfolioMarginPnlRangePointV5[]; -} +/** Your API key */ ⋮---- -export interface PortfolioMarginTotalPnlRangesV5 { - ALL?: PortfolioMarginContractBucketPnlV5; - PERPETUAL?: PortfolioMarginContractBucketPnlV5; - OPTION?: PortfolioMarginContractBucketPnlV5; -} +/** Your API secret */ ⋮---- -export interface PortfolioMarginPerpPositionPnlV5 { - symbolName: string; - position: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; - sessionAvgPrice: string; - markPrice: string; - orderSize: string; - contractType: number; - settleCoin: string; - symbolAlias?: string; -} +/** + * 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. + */ ⋮---- -export interface PortfolioMarginOptionPositionPnlV5 { - symbolName: string; - position: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; - sessionAvgPrice: string; - markPrice: string; - orderSize: string; - contractType: number; - settleCoin: string; -} +/** + * 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. + */ ⋮---- -export interface PortfolioMarginOptionExpiryPnlV5 { - expiryDateRepresentation: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; - optionPositionPnlRanges: PortfolioMarginOptionPositionPnlV5[]; -} +/** + * The API group this client should connect to. The V5 market is currently used by default. + * + * Only the "V5" "market" is supported here. + */ ⋮---- -export interface PortfolioMarginContingencyV5 { - optionContingency: string; - futureDeltaContingency: string; - optionVegaContingency: string; - contingencyComponents: string; - usdtUsdcContingency: string; - futureContingency: string; -} +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- -export interface PortfolioMarginAssetBlockV5 { - coin: string; - assetIM: string; - assetMM: string; -} +/** How often to check if the connection is alive */ ⋮---- -export interface PortfolioMarginSpotHedgeInfoV5 { - hedgeSpotSize: string; - walletBalance: string; - usdIndexPrice: string; - pnlRanges: PortfolioMarginPnlRangePointV5[]; -} +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -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[]; -} +/** Delay in milliseconds before respawning the connection */ ⋮---- -export interface PortfolioMarginInfoResultV5 { - wallet: PortfolioMarginWalletV5; - assetPnlRange: PortfolioMarginByBaseCoinV5[]; -} +/** + * 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. + */ ⋮---- -// --- GET /v5/asset/total-members-assets --- +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ ⋮---- -export interface TotalMembersAccountBreakdownItemV5 { - type: string; - origb: string; - quoteb: string; - stat: number; +/** + * 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; + + /** + * 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; + + /** + * Whether to use native WebSocket ping/pong frames for heartbeats + */ + useNativeHeartbeats: boolean; } ⋮---- -export interface TotalMembersMemberEntryV5 { - uid: number; - isM?: boolean; - type?: number; - stat: number; - origb: string; - quoteb?: string; - items: TotalMembersAccountBreakdownItemV5[]; -} +/** + * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + */ ⋮---- -export interface TotalMembersAssetsResultV5 { - total: string; - quoteTotal: string; - stat: number; - list: TotalMembersMemberEntryV5[]; -} +/** + * Whether to use native WebSocket ping/pong frames for heartbeats + */ +⋮---- +export type WsEventInternalSrc = 'event' | 'function' | 'frame'; ================ -File: src/types/websockets/ws-general.ts +File: src/websocket-client.ts ================ -import { AxiosRequestConfig } from 'axios'; -import type { ClientRequestArgs } from 'http'; +/* eslint-disable @typescript-eslint/no-unused-vars */ import WebSocket from 'isomorphic-ws'; ⋮---- -import { RestClientOptions, WS_KEY_MAP } from '../../util'; +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'; ⋮---- -/** For spot markets, spotV3 is recommended */ -export type APIMarket = 'v5'; +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; +} ⋮---- -// Same as inverse futures -export type WsPublicInverseTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'klineV2'; +/** If true, will skip auth requirement for WS API connection */ ⋮---- -export type WsPublicUSDTPerpTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'kline'; +export class WebsocketClient extends BaseWebsocketClient< ⋮---- -export type WsPublicSpotV1Topic = - | 'trade' - | 'realtimes' - | 'kline' - | 'depth' - | 'mergedDepth' - | 'diffDepth'; +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- -export type WsPublicSpotV2Topic = - | 'depth' - | 'kline' - | 'trade' - | 'bookTicker' - | 'realtimes'; +/** + * Request connection of all dependent (public & private) websockets, instead of waiting + * for automatic connection by SDK. + */ +public connectAll(): Promise[] ⋮---- -export type WsPublicTopics = - | WsPublicInverseTopic - | WsPublicUSDTPerpTopic - | WsPublicSpotV1Topic - | WsPublicSpotV2Topic - | string; +/** + * Ensures the WS API connection is active and ready. + * + * You do not need to call this, but if you call this before making any WS API requests, + * it can accelerate the first request (by preparing the connection in advance). + */ +public connectWSAPI(): Promise ⋮---- -// Same as inverse futures -export type WsPrivateInverseTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order'; +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -export type WsPrivateUSDTPerpTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order' - | 'wallet'; +public connectPublic(): Promise[] ⋮---- -export type WsPrivateSpotTopic = - | 'outboundAccountInfo' - | 'executionReport' - | 'ticketInfo'; +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[] ⋮---- -export type WsPrivateTopic = - | WsPrivateInverseTopic - | WsPrivateUSDTPerpTopic - | WsPrivateSpotTopic - | string; +// Sort into per-WsKey batches, in case there is a mix of topics here ⋮---- -export type WsTopic = WsPublicTopics | WsPrivateTopic; +// Prevent duplicate requests to the same topic ⋮---- -/** 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'; +// Batch sub topics per ws key ⋮---- -export interface WSClientConfigurableOptions { - /** Your API key */ - key?: string; - - /** Your API secret */ - secret?: string; - - /** - * Set to `true` to connect to Bybit's testnet environment. - * - * Notes: +// 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. * - * - 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. + * @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) */ - testnet?: boolean; - - /** - * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo +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. * - * Only the "V5" "market" is supported here. - */ - demoTrading?: boolean; - - /** - * The API group this client should connect to. The V5 market is currently used by default. + * Request subscription to one or more topics. Pass topics as either an array of strings, + * or array of objects (if the topic has parameters). * - * Only the "V5" "market" is supported here. - */ - market?: APIMarket; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; - - /** How often to check if the connection is alive */ - pingInterval?: number; - - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; - - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; - - restOptions?: RestClientOptions; - requestOptions?: AxiosRequestConfig; - - wsOptions?: { - protocols?: string[]; - agent?: any; - } & Partial; - - wsUrl?: string; - - /** - * Default: false. + * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. * - * 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; - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. * - * Look in the examples folder for a demonstration on using node's createHmac instead. + * Call `unsubscribe(topics)` to remove topics */ - customSignMessageFn?: (message: string, secret: string) => Promise; -} -⋮---- -/** Your API key */ +public subscribe( + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], + requestedWsKey?: WsKey, +) ⋮---- -/** Your API secret */ +// Batch sub topics per ws key ⋮---- /** - * Set to `true` to connect to Bybit's testnet environment. - * - * Notes: + * 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. * - * - 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. + * - 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 ⋮---- /** - * 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. + * + * + * WS API Methods - similar to the REST API, but via WebSockets + * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline + * + * + * */ ⋮---- /** - * The API group this client should connect to. The V5 market is currently used by default. + * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. * - * Only the "V5" "market" is supported here. + * 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 */ ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +// 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; ⋮---- -/** How often to check if the connection is alive */ +// 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; ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +sendWSAPIRequest( + wsKey: typeof WS_KEY_MAP.v5PrivateTrade, + operation: TWSOperation, + params: WsAPITopicRequestParamMap[TWSOperation], + requestFlags?: WSAPIRequestFlags, + ): Promise; ⋮---- -/** Delay in milliseconds before respawning the connection */ +sendWSAPIRequest( + wsKey: typeof WS_KEY_MAP.v5PrivateTrade, + operation: TWSOperation, + params: WsAPITopicRequestParamMap[TWSOperation], + requestFlags?: WSAPIRequestFlags, + ): Promise; ⋮---- -/** - * 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. - */ +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 ⋮---- -/** - * 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. - */ +// 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 ⋮---- /** - * 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; - - /** - * 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; - - /** - * Whether to use native WebSocket ping/pong frames for heartbeats + * + * + * Internal methods - not intended for public use + * + * */ - useNativeHeartbeats: boolean; -} ⋮---- /** - * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + * Note: implementing this method will wipe the WsStore state for this WsKey, once this method returns */ +protected isCustomReconnectionNeeded(): boolean +⋮---- +protected async triggerCustomReconnectionWorkflow(): Promise ⋮---- /** - * Whether to use native WebSocket ping/pong frames for heartbeats + * @returns The WS URL to connect to for this WS key */ +protected async getWsUrl(wsKey: WsKey): Promise ⋮---- -export type WsEventInternalSrc = 'event' | 'function' | 'frame'; - -================ -File: src/websocket-client.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import WebSocket from 'isomorphic-ws'; +// If auth is needed for this wsKey URL, this returns a suffix ⋮---- -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'; +/** + * Return params required to make authorized request + */ +private async getWsAuthURLSuffix(): Promise ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} +private async signMessage( + paramsStr: string, + secret: string, + method?: 'hex' | 'base64', + algorithm: SignAlgorithm = 'SHA-256', +): Promise ⋮---- -/** If true, will skip auth requirement for WS API connection */ +protected async getWsAuthRequestEvent( + wsKey: WsKey, +): Promise> ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +private async getWsAuthSignature( + wsKey: WsKey, +): Promise< ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +undefined, // Let the function automatically determine encoding based on key type ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting - * for automatic connection by SDK. - */ -public connectAll(): Promise[] +private async signWSAPIRequest( + requestEvent: WSAPIRequest, +): 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 +// Not needed for Bybit. Auth happens only on connection open, automatically. ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +protected sendPingEvent(wsKey: WsKey) ⋮---- -public connectPublic(): Promise[] +protected sendPongEvent(wsKey: WsKey) ⋮---- -public connectPrivate(): Promise +/** 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 ⋮---- /** - * 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) + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ -public subscribeV5( - wsTopics: WsTopic[] | WsTopic, - category: CategoryV5, - isPrivateTopic?: boolean, -): Promise[] +protected async getWsRequestEvents( + market: WsMarket, + operation: WsOperation, + requests: WsTopicRequest[], + // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars + _wsKey: WsKey, +): Promise>[]> ⋮---- -// Sort into per-WsKey batches, in case there is a mix of topics here +// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars ⋮---- -// Prevent duplicate requests to the same topic +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- -// Batch sub topics per ws key +protected getPrivateWSKeys(): WsKey[] ⋮---- -// Return promise to resolve midflight WS request (only works if already connected before request) +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** - * 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) + * Determines if a topic is for a private channel, using a hardcoded list of strings */ -public unsubscribeV5( - wsTopics: WsTopic[] | WsTopic, - category: CategoryV5, - isPrivateTopic?: boolean, -): Promise[] +protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- -// Sort into per-WsKey batches, in case there is a mix of topics here +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPing(msg: any): boolean ⋮---- -// Batch sub topics per ws key +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPong(msg: any): boolean ⋮---- -// Return promise to resolve midflight WS request (only works if already connected before request) +// public ws connections +⋮---- +// private ws connections ⋮---- /** - * 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 + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ -public subscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - requestedWsKey?: WsKey, -) +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; +} ⋮---- -// Batch sub topics per ws key +export interface AssetInfoAssetV5 { + coin: string; + frozen: string; + free: string; + withdraw: string; +} ⋮---- -/** - * 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, -) +export interface AssetInfoV5 { + status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED'; + assets: AssetInfoAssetV5[]; +} ⋮---- -// Batch sub topics per ws key +export interface CoinBalanceV5 { + coin: string; + walletBalance: string; + transferBalance: string; + bonus?: string; +} ⋮---- -/** - * - * - * - * WS API Methods - similar to the REST API, but via WebSockets - * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline - * - * - * - */ +export interface AllCoinsBalanceV5 { + accountType: AccountTypeV5; + memberId?: string; + balance: CoinBalanceV5[]; +} ⋮---- -/** - * 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 - */ +export interface AccountCoinBalanceV5 { + accountType: AccountTypeV5; + bizType: number; + accountId: string; + memberId: string; + balance: { + coin: string; + walletBalance: string; + transferBalance: string; + bonus: string; + transferSafeAmount: string; + ltvTransferSafeAmount: string; + }; +} ⋮---- -// 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; +export interface InternalTransferRecordV5 { + transferId: string; + coin: string; + amount: string; + fromAccountType: AccountTypeV5; + toAccountType: AccountTypeV5; + timestamp: string; + status: string; +} ⋮---- -// 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; +export interface UniversalTransferRecordV5 { + transferId: string; + coin: string; + amount: string; + fromMemberId: string; + toMemberId: string; + fromAccountType: AccountTypeV5; + toAccountType: AccountTypeV5; + timestamp: string; + status: string; +} ⋮---- -sendWSAPIRequest( - wsKey: typeof WS_KEY_MAP.v5PrivateTrade, - operation: TWSOperation, - params: WsAPITopicRequestParamMap[TWSOperation], - requestFlags?: WSAPIRequestFlags, - ): Promise; +export interface AllowedDepositCoinInfoV5 { + coin: string; + chain: string; + coinShowName: string; + chainType: string; + blockConfirmNumber: number; + minDepositAmount: string; +} ⋮---- -sendWSAPIRequest( - wsKey: typeof WS_KEY_MAP.v5PrivateTrade, - operation: TWSOperation, - params: WsAPITopicRequestParamMap[TWSOperation], - requestFlags?: WSAPIRequestFlags, - ): Promise; +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; +} ⋮---- -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 +export interface SubmitDepositOriginatorInfoResultV5 { + travelRuleStatus: number; +} ⋮---- -// Some commands don't require authentication. +export interface InternalDepositRecordV5 { + id: string; + type: 1; + coin: string; + amount: string; + status: 1 | 2 | 3; + address: string; + createdTime: string; + txID: string; +} ⋮---- -// Sign, if needed +export interface DepositAddressChainV5 { + chainType: string; + addressDeposit: string; + tagDeposit: string; + chain: string; + batchReleaseLimit: string; + contractAddress: string; +} ⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +export interface DepositAddressResultV5 { + coin: string; + chains: DepositAddressChainV5[]; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +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; + }[]; +} ⋮---- -// Enrich returned promise with request context for easier debugging +/** @deprecated Use `chains[].withdrawMax` instead */ ⋮---- -// throw e; +/** Max withdraw amount per transaction per chain. `-1` means no limit */ ⋮---- -// Send event +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; +} ⋮---- -// Return deferred promise, so caller can await this call +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; +} ⋮---- /** - * - * - * Internal methods - not intended for public use - * - * - */ + * 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; + }; +} ⋮---- -/** - * Note: implementing this method will wipe the WsStore state for this WsKey, once this method returns - */ -protected isCustomReconnectionNeeded(): boolean +export interface VaspEntityV5 { + vaspEntityId: string; + vaspName: string; +} ⋮---- -protected async triggerCustomReconnectionWorkflow(): Promise +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; +} ⋮---- -/** - * @returns The WS URL to connect to for this WS key - */ -protected async getWsUrl(wsKey: WsKey): Promise +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[]; +} ⋮---- -// If auth is needed for this wsKey URL, this returns a suffix +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; +} ⋮---- -/** - * Return params required to make authorized request - */ -private async getWsAuthURLSuffix(): Promise +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; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method?: 'hex' | 'base64', - algorithm: SignAlgorithm = 'SHA-256', -): Promise +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 +} ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, -): Promise> +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 ⋮---- -private async getWsAuthSignature( - wsKey: WsKey, -): Promise< +export interface SmallBalanceListV5 { + smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info + supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) +} ⋮---- -undefined, // Let the function automatically determine encoding based on key type +smallAssetCoins: SmallBalanceCoinV5[]; // Small balance info +supportToCoins: string[]; // Supported target coins (e.g., ["MNT","USDT","USDC"]) ⋮---- -private async signWSAPIRequest( - requestEvent: WSAPIRequest, -): Promise> +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 +} ⋮---- -// Not needed for Bybit. Auth happens only on connection open, automatically. +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 ⋮---- -protected sendPingEvent(wsKey: WsKey) +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 +} ⋮---- -protected sendPongEvent(wsKey: WsKey) +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 ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface FiatTradingPairListV5 { + fiats: FiatCoinInfoV5[]; // Fiat coin list + cryptos: CryptoCoinInfoV5[]; // Crypto coin list +} ⋮---- -protected authPrivateConnectionsOnConnect(_wsKey: WsKey): boolean +fiats: FiatCoinInfoV5[]; // Fiat coin list +cryptos: CryptoCoinInfoV5[]; // Crypto coin list ⋮---- -/** - * @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 FundingAccountTransactionRecordV5 { + memberId: string; + currency: string; + ioDirection: string; + txnAmt: string; + afterAmt: string; + createTime: string; + showBusiType: string; + showBusiTypeEn: string; + description: string; + descriptionEn: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars +/** When accountType=Alpha and category is farm, under `coinDetail` in sub-categories. */ +export interface AssetOverviewCoinExtMapV5 { + priceUpper?: string; + priceLower?: string; + equityUnit?: string; +} ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +export interface AssetOverviewCoinDetailV5 { + coin: string; + equity: string; + extMap?: AssetOverviewCoinExtMapV5; +} ⋮---- -protected getPrivateWSKeys(): WsKey[] +export interface AssetOverviewCategoryV5 { + category: string; + equity: string; + coinDetail: AssetOverviewCoinDetailV5[]; +} ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +export interface AssetOverviewAccountItemV5 { + accountType: string; + totalEquity: string; + valuationCurrency: string; + snapshotTime: string; + coinDetail?: AssetOverviewCoinDetailV5[]; + categories?: AssetOverviewCategoryV5[]; +} ⋮---- -/** - * Determines if a topic is for a private channel, using a hardcoded list of strings - */ -protected isPrivateTopicRequest(request: WsTopicRequest): boolean +export interface AssetOverviewResultV5 { + totalEquity: string; + list: AssetOverviewAccountItemV5[]; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPing(msg: any): boolean +// --- GET /v5/asset/portfolio-margin (portfolio margin P&L ranges) --- ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPong(msg: any): boolean +export interface PortfolioMarginWalletV5 { + equity: string; + cashBalance: string; + marginBalance: string; + availableBalance: string; + accountIM: string; + accountMM: string; + accountMMRate: string; + accountIMRate: string; +} ⋮---- -// public ws connections +export interface PortfolioMarginPnlRangePointV5 { + priceScale: string; + pnls: string[]; +} ⋮---- -// private ws connections +export interface PortfolioMarginContractBucketPnlV5 { + pnlRanges: PortfolioMarginPnlRangePointV5[]; +} ⋮---- -/** - * 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 PortfolioMarginTotalPnlRangesV5 { + ALL?: PortfolioMarginContractBucketPnlV5; + PERPETUAL?: PortfolioMarginContractBucketPnlV5; + OPTION?: PortfolioMarginContractBucketPnlV5; +} ⋮---- -// this.logger.trace('resolveEmittableEvents', { -// ...WS_LOGGER_CATEGORY, -// wsKey, -// parsed: JSON.stringify(parsed), -// }); +export interface PortfolioMarginPerpPositionPnlV5 { + symbolName: string; + position: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; + sessionAvgPrice: string; + markPrice: string; + orderSize: string; + contractType: number; + settleCoin: string; + symbolAlias?: string; +} ⋮---- -// Only applies to the V5 WS topics +export interface PortfolioMarginOptionPositionPnlV5 { + symbolName: string; + position: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; + sessionAvgPrice: string; + markPrice: string; + orderSize: string; + contractType: number; + settleCoin: string; +} ⋮---- -// WS API response +export interface PortfolioMarginOptionExpiryPnlV5 { + expiryDateRepresentation: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; + optionPositionPnlRanges: PortfolioMarginOptionPositionPnlV5[]; +} ⋮---- -// eslint-disable-next-line max-len +export interface PortfolioMarginContingencyV5 { + optionContingency: string; + futureDeltaContingency: string; + optionVegaContingency: string; + contingencyComponents: string; + usdtUsdcContingency: string; + futureContingency: string; +} ⋮---- -// WS API Exception +export interface PortfolioMarginAssetBlockV5 { + coin: string; + assetIM: string; + assetMM: string; +} ⋮---- -// WS API Success +export interface PortfolioMarginSpotHedgeInfoV5 { + hedgeSpotSize: string; + walletBalance: string; + usdIndexPrice: string; + pnlRanges: PortfolioMarginPnlRangePointV5[]; +} ⋮---- -// Messages for a subscribed topic all include the "topic" property +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[]; +} ⋮---- -// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property +export interface PortfolioMarginInfoResultV5 { + wallet: PortfolioMarginWalletV5; + assetPnlRange: PortfolioMarginByBaseCoinV5[]; +} ⋮---- -// Failed request +// --- GET /v5/asset/total-members-assets --- ⋮---- -// These are r equest/reply pattern events (e.g. after subscribing to topics or authenticating) +export interface TotalMembersAccountBreakdownItemV5 { + type: string; + origb: string; + quoteb: string; + stat: number; +} ⋮---- -// Request/reply pattern for authentication success +export interface TotalMembersMemberEntryV5 { + uid: number; + isM?: boolean; + type?: number; + stat: number; + origb: string; + quoteb?: string; + items: TotalMembersAccountBreakdownItemV5[]; +} ⋮---- -// In case of catastrophic failure, fallback to noisy emit update +export interface TotalMembersAssetsResultV5 { + total: string; + quoteTotal: string; + stat: number; + list: TotalMembersMemberEntryV5[]; +} ================ File: README.md @@ -15056,6 +15949,7 @@ File: README.md [![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)

@@ -15810,7 +16704,28 @@ import { AlphaBizTokenDetailsV5, AlphaBizTokenPriceListResultV5, AlphaBizTokenV5, + AlphaLPOrderListResultV5, + AlphaLPPayTokenListResultV5, + AlphaLPPayTokenPriceResultV5, + AlphaLPPoolInfoV5, + AlphaLPPoolListResultV5, + AlphaLPPositionListResultV5, AlphaPayTokenV5, + AlphaPredictionEngineStatusV5, + AlphaPredictionEventDetailV5, + AlphaPredictionOrderBookV5, + AlphaPredictionOrderEstimateV5, + AlphaPredictionOrderListResultV5, + AlphaPredictionPayTokenV5, + AlphaPredictionPortfolioSummaryV5, + AlphaPredictionPositionHistoryResultV5, + AlphaPredictionPositionListResultV5, + AlphaPredictionPriceHistoryV5, + AlphaPredictionSideMarketListResultV5, + AlphaPredictionSportsGroupStageDetailV5, + AlphaPredictionSportsMatchListResultV5, + AlphaPredictionSportsTimelineStagesV5, + AlphaPredictionTokenPriceV5, AlphaTradeOrderListResultV5, AlphaTradeQuoteResultV5, AmendOrderParamsV5, @@ -15916,6 +16831,7 @@ import { DepositAddressChainV5, DepositRecordV5, EarnAprHistoryPointV5, + EarnCouponListResultV5, EarnHourlyYieldHistoryV5, EarnOrderHistoryV5, EarnPositionV5, @@ -15930,6 +16846,13 @@ import { ExchangeBrokerAccountInfoV5, ExchangeBrokerEarningResultV5, ExchangeBrokerSubAccountDepositRecordV5, + ExecuteAlphaLPRedeemParamsV5, + ExecuteAlphaLPRedeemResultV5, + ExecuteAlphaLPStakeParamsV5, + ExecuteAlphaLPStakeResultV5, + ExecuteAlphaPredictionBuyParamsV5, + ExecuteAlphaPredictionOrderResultV5, + ExecuteAlphaPredictionSellParamsV5, ExecuteAlphaTradeParamsV5, ExecuteAlphaTradeResultV5, ExecuteRFQQuoteParamsV5, @@ -15950,6 +16873,7 @@ import { FriendReferralRecordV5, FundingAccountTransactionRecordV5, FundingRateHistoryResponseV5, + FuturesLeverageResultV5, GetAccountCoinBalanceParamsV5, GetAccountHistoricOrdersParamsV5, GetAccountInstrumentsInfoParamsV5, @@ -15969,7 +16893,25 @@ import { GetAlphaBizTokenDetailsParamsV5, GetAlphaBizTokenListParamsV5, GetAlphaBizTokenPriceListParamsV5, + GetAlphaLPOrderListParamsV5, + GetAlphaLPPayTokenListParamsV5, + GetAlphaLPPayTokenPriceParamsV5, + GetAlphaLPPoolInfoParamsV5, + GetAlphaLPPoolListParamsV5, GetAlphaPayTokenListParamsV5, + GetAlphaPredictionEventDetailParamsV5, + GetAlphaPredictionOrderBookParamsV5, + GetAlphaPredictionOrderEstimateParamsV5, + GetAlphaPredictionOrderListParamsV5, + GetAlphaPredictionPortfolioSummaryParamsV5, + GetAlphaPredictionPositionHistoryParamsV5, + GetAlphaPredictionPositionListParamsV5, + GetAlphaPredictionPriceHistoryParamsV5, + GetAlphaPredictionSideMarketListParamsV5, + GetAlphaPredictionSportsGroupStageDetailParamsV5, + GetAlphaPredictionSportsMatchListParamsV5, + GetAlphaPredictionSportsTimelineStagesParamsV5, + GetAlphaPredictionTokenPriceParamsV5, GetAlphaTradeOrderListParamsV5, GetAlphaTradeQuoteParamsV5, GetAssetInfoParamsV5, @@ -15987,6 +16929,7 @@ import { GetClassicTransactionLogsParamsV5, GetClosedOptionsPositionsParamsV5, GetClosedPnLParamsV5, + GetCoinDeltaAmountParamsV5, GetCoinExchangeRecordParamsV5, GetCoinStateParamsV5, GetCollateralAdjustmentHistoryParamsV5, @@ -15997,6 +16940,7 @@ import { GetDeliveryRecordParamsV5, GetDepositRecordParamsV5, GetEarnAprHistoryParamsV5, + GetEarnCouponListParamsV5, GetEarnHourlyYieldHistoryParamsV5, GetEarnOrderHistoryParamsV5, GetEarnPositionParamsV5, @@ -16021,6 +16965,7 @@ import { GetFriendReferralsParamsV5, GetFundingAccountTransactionHistoryParamsV5, GetFundingRateHistoryParamsV5, + GetFuturesLeverageParamsV5, GetHistoricalVolatilityParamsV5, GetHoldToEarnAirdropYieldHistoryParamsV5, GetIndexPriceComponentsParamsV5, @@ -16082,6 +17027,9 @@ import { GetRFQTradeListParamsV5, GetRiskLimitParamsV5, GetRPIOrderbookParamsV5, + GetRWANavChartParamsV5, + GetRWAOrderListParamsV5, + GetRWAProductListParamsV5, GetSettlementRecordParamsV5, GetSmallBalanceListParamsV5, GetSpotMarginCurrencyDataParamsV5, @@ -16113,6 +17061,8 @@ import { HoldToEarnAirdropProductsResultV5, HoldToEarnAirdropYieldHistoryResultV5, IndexPriceComponentsResponseV5, + InstitutionalLendingCoinDeltaAmountV5, + InstitutionalLendingProductInfoV5, InstitutionalLoanLTVV5, InstrumentInfoResponseV5, InsuranceResponseV5, @@ -16168,6 +17118,8 @@ import { PayInfoResultV5, PlaceEarnTokenOrderParamsV5, PlaceEarnTokenOrderResultV5, + PlaceRWAOrderParamsV5, + PlaceRWAOrderResultV5, PortfolioMarginInfoResultV5, PositionInfoParamsV5, PositionV5, @@ -16222,6 +17174,10 @@ import { RFQTradeV5, RiskLimitV5, RPIOrderbookResponseV5, + RWANavChartResultV5, + RWAOrderListResultV5, + RWAPositionListResultV5, + RWAProductListResultV5, SendP2POrderMessageParamsV5, SetAutoAddMarginParamsV5, SetAutoRepayModeParamsV5, @@ -16259,6 +17215,8 @@ import { StrategyOrderListResultV5, SubMemberV5, SubmitAdvanceEarnPlaceOrderParamsV5, + SubmitDepositOriginatorInfoParamsV5, + SubmitDepositOriginatorInfoResultV5, SubmitFixedTermEarnOrderParamsV5, SubmitSpreadOrderParamsV5, SubmitStakeRedeemParamsV5, @@ -17033,6 +17991,16 @@ getPositionInfo( params: PositionInfoParamsV5, ): Promise>> ⋮---- +/** + * Get Futures Leverage + * Query isolated leverage settings without requiring an open position. + * + * Returns an error under Portfolio Margin mode. + */ +getFuturesLeverage( + params: GetFuturesLeverageParamsV5, +): Promise> +⋮---- /** * Set the leverage * @@ -17924,6 +18892,14 @@ getExchangeEntities(): Promise< > { return this.getPrivate('/v5/asset/withdraw/vasp/list'); ⋮---- +/** + * Submit Deposit Originator Info + * Submit Travel Rule originator questionnaire when deposit `travel_rule_status` is pending (1). + */ +submitDepositOriginatorInfo( + params: SubmitDepositOriginatorInfoParamsV5, +): Promise> +⋮---- /** * Withdraw from Funding, Unified, and/or Earn (and combos such as FUND,UTA,EARN per API). * @@ -18343,6 +19319,221 @@ getAlphaAssetDetail( params: GetAlphaAssetDetailParamsV5, ): Promise> ⋮---- +/** + * + ****** Alpha / Web3 prediction market APIs + * + */ +⋮---- +/** + * Get Engine Status + * Query prediction market matching engine availability before placing buy/sell orders. + */ +getAlphaPredictionEngineStatus(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/alpha/prediction/engine-status'); +⋮---- +/** + * Get Payment Token List + * Available payment tokens for prediction market trading (Phase 1: USDC). + */ +getAlphaPredictionPayTokenList(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/alpha/prediction/pay-token-list'); +⋮---- +/** + * Get Event Detail + * Event metadata, outcome markets, and current prices. Obtain tokenId before trading. + */ +getAlphaPredictionEventDetail( + params: GetAlphaPredictionEventDetailParamsV5, +): Promise> +⋮---- +/** + * Get Order Estimate + * Preview buy/sell outcome before execution. Show estimate to user and confirm before Buy/Sell. + */ +getAlphaPredictionOrderEstimate( + params: GetAlphaPredictionOrderEstimateParamsV5, +): Promise> +⋮---- +/** + * Execute Buy + * Buy prediction outcome tokens with USDC. HTTP 200 is acknowledgment only — poll order list. + */ +executeAlphaPredictionBuy( + params: ExecuteAlphaPredictionBuyParamsV5, +): Promise> +⋮---- +/** + * Execute Sell + * Sell prediction outcome token shares for USDC. HTTP 200 is acknowledgment only — poll order list. + */ +executeAlphaPredictionSell( + params: ExecuteAlphaPredictionSellParamsV5, +): Promise> +⋮---- +/** + * Get Order List + * Prediction market order history for the authenticated user. + */ +getAlphaPredictionOrderList( + params: GetAlphaPredictionOrderListParamsV5, +): Promise> +⋮---- +/** + * Get Order Book + * Full bid/ask depth snapshot for up to 20 outcome tokens. + */ +getAlphaPredictionOrderBook( + params: GetAlphaPredictionOrderBookParamsV5, +): Promise> +⋮---- +/** + * Get Token Price + * Best bid/ask and last price for up to 20 outcome tokens. + */ +getAlphaPredictionTokenPrice( + params: GetAlphaPredictionTokenPriceParamsV5, +): Promise> +⋮---- +/** + * Get Price History + * OHLC candlestick history for an outcome token. + */ +getAlphaPredictionPriceHistory( + params: GetAlphaPredictionPriceHistoryParamsV5, +): Promise> +⋮---- +/** + * Get Position List + * Active prediction market positions. Confirm before placing sell orders. + */ +getAlphaPredictionPositionList( + params?: GetAlphaPredictionPositionListParamsV5, +): Promise> +⋮---- +/** + * Get Position History + * Closed prediction market positions including settlement results. + */ +getAlphaPredictionPositionHistory( + params?: GetAlphaPredictionPositionHistoryParamsV5, +): Promise> +⋮---- +/** + * Get Portfolio Summary + * Overall prediction market portfolio P&L and win rate. + */ +getAlphaPredictionPortfolioSummary( + params?: GetAlphaPredictionPortfolioSummaryParamsV5, +): Promise> +⋮---- +/** + * Get Side Market List + * Outcome markets for an event with prices, liquidity, and status. + */ +getAlphaPredictionSideMarketList( + params: GetAlphaPredictionSideMarketListParamsV5, +): Promise> +⋮---- +/** + * Get Sports Match List + * Sports matches available in prediction markets (Phase 1: FIFA 2026). + */ +getAlphaPredictionSportsMatchList( + params: GetAlphaPredictionSportsMatchListParamsV5, +): Promise> +⋮---- +/** + * Get Sports Timeline Stages + * Tournament stage timeline with status and match counts. + */ +getAlphaPredictionSportsTimelineStages( + params: GetAlphaPredictionSportsTimelineStagesParamsV5, +): Promise> +⋮---- +/** + * Get Sports Group Stage Detail + * Group stage standings and match schedule for a sports prediction event. + */ +getAlphaPredictionSportsGroupStageDetail( + params: GetAlphaPredictionSportsGroupStageDetailParamsV5, +): Promise> +⋮---- +/** + * + ****** Alpha / Web3 LP APIs + * + */ +⋮---- +/** + * Get LP Pool List + * Available liquidity pools, optionally filtered by token symbol. + */ +getAlphaLPPoolList( + params?: GetAlphaLPPoolListParamsV5, +): Promise> +⋮---- +/** + * Get LP Pool Info + * Detailed pool data including APY, reserves, and price range. + */ +getAlphaLPPoolInfo( + params: GetAlphaLPPoolInfoParamsV5, +): Promise> +⋮---- +/** + * Execute LP Stake + * Stake tokens into a liquidity pool. HTTP 200 is ACK only — poll order list for status. + */ +executeAlphaLPStake( + params: ExecuteAlphaLPStakeParamsV5, +): Promise> +⋮---- +/** + * Execute LP Redeem + * Redeem liquidity from a pool position. HTTP 200 is ACK only — poll order list for status. + */ +executeAlphaLPRedeem( + params: ExecuteAlphaLPRedeemParamsV5, +): Promise> +⋮---- +/** + * Get LP Order List + * LP stake/redeem order history. + */ +getAlphaLPOrderList( + params?: GetAlphaLPOrderListParamsV5, +): Promise> +⋮---- +/** + * Get LP Pay Token List + * Supported payment tokens and available balances for LP staking. + */ +getAlphaLPPayTokenList( + params?: GetAlphaLPPayTokenListParamsV5, +): Promise> +⋮---- +/** + * Get LP Pay Token Price + * Batch USD prices for up to 50 payment token codes. + */ +getAlphaLPPayTokenPrice( + params: GetAlphaLPPayTokenPriceParamsV5, +): Promise> +⋮---- +/** + * Get LP Position List + * User LP positions with valuation, rewards, and APY. + */ +getAlphaLPPositionList(): Promise< + APIResponseV3WithTime + > { +return this.postPrivate('/v5/alpha/lp/position-list', +⋮---- /** * ****** Spot Margin Trade APIs (UTA) @@ -19281,9 +20472,20 @@ getRenewOrderInfoFixed(params?: GetRenewOrderInfoFixedParamsV5): Promise< /** * Get Product Info */ -getInstitutionalLendingProductInfo( - productId?: string, -): Promise + > { +return this.get('/v5/ins-loan/product-infos', +⋮---- +/** + * Get Coin Delta Amount + * Coin delta amount details for institutional loan hedge product (unified account only). + */ +getInstitutionalLendingCoinDeltaAmount( + params?: GetCoinDeltaAmountParamsV5, +): Promise> ⋮---- /** * Get Margin Coin Info @@ -19519,6 +20721,53 @@ getEarnProduct(params: { category: string; coin?: string }): Promise< > { return this.get('/v5/earn/product', params); ⋮---- +/** + * Get Coupon List + * Interest-rate coupons and Dual Assets reward cards for FlexibleSaving or DualAssets. + */ +getEarnCouponList( + params: GetEarnCouponListParamsV5, +): Promise> +⋮---- +/** + * Get RWA Product List + * Real World Assets earn products. Auth optional; `userQuota` populated when authenticated. + */ +getRWAProductList( + params?: GetRWAProductListParamsV5, +): Promise> +⋮---- +/** + * Place RWA Order + * Stake or redeem RWA product. Async — use getRWAOrderList to track status. + */ +placeRWAOrder( + params: PlaceRWAOrderParamsV5, +): Promise> +⋮---- +/** + * Get RWA Position List + */ +getRWAPositionList(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/earn/rwa/position'); +⋮---- +/** + * Get RWA Order List + */ +getRWAOrderList( + params?: GetRWAOrderListParamsV5, +): Promise> +⋮---- +/** + * Get RWA NAV Chart + * NAV history for an RWA product (public; max 180-day span). + */ +getRWANavChart( + params: GetRWANavChartParamsV5, +): Promise> +⋮---- /** * Get Hold to Earn airdrop products (ByFi). * @@ -20487,7 +21736,7 @@ File: package.json ================ { "name": "bybit-api", - "version": "4.6.2", + "version": "4.6.6", "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", @@ -20526,13 +21775,11 @@ File: package.json "eslint-plugin-require-extensions": "^0.1.3", "eslint-plugin-simple-import-sort": "^12.1.1", "jest": "^29.7.0", - "ts-jest": "^29.1.2", - "ts-node": "^10.9.2", - "typescript": "^5.7.3" - }, - "optionalDependencies": { "source-map-loader": "^2.0.0", + "ts-jest": "^29.1.2", "ts-loader": "^8.0.11", + "ts-node": "^10.9.2", + "typescript": "^5.7.3", "webpack": "^5.4.0", "webpack-bundle-analyzer": "^4.10.2", "webpack-cli": "^4.2.0" diff --git a/package-lock.json b/package-lock.json index 7a466092..18c65eda 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bybit-api", - "version": "4.6.4", + "version": "4.6.5", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "bybit-api", - "version": "4.6.4", + "version": "4.6.5", "license": "MIT", "dependencies": { "axios": "^1.13.2", diff --git a/package.json b/package.json index fce6ac8d..1d38c4fd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bybit-api", - "version": "4.6.4", + "version": "4.6.6", "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 f852e43d..75960f0f 100644 --- a/src/rest-client-v5.ts +++ b/src/rest-client-v5.ts @@ -30,7 +30,28 @@ import { AlphaBizTokenDetailsV5, AlphaBizTokenPriceListResultV5, AlphaBizTokenV5, + AlphaLPOrderListResultV5, + AlphaLPPayTokenListResultV5, + AlphaLPPayTokenPriceResultV5, + AlphaLPPoolInfoV5, + AlphaLPPoolListResultV5, + AlphaLPPositionListResultV5, AlphaPayTokenV5, + AlphaPredictionEngineStatusV5, + AlphaPredictionEventDetailV5, + AlphaPredictionOrderBookV5, + AlphaPredictionOrderEstimateV5, + AlphaPredictionOrderListResultV5, + AlphaPredictionPayTokenV5, + AlphaPredictionPortfolioSummaryV5, + AlphaPredictionPositionHistoryResultV5, + AlphaPredictionPositionListResultV5, + AlphaPredictionPriceHistoryV5, + AlphaPredictionSideMarketListResultV5, + AlphaPredictionSportsGroupStageDetailV5, + AlphaPredictionSportsMatchListResultV5, + AlphaPredictionSportsTimelineStagesV5, + AlphaPredictionTokenPriceV5, AlphaTradeOrderListResultV5, AlphaTradeQuoteResultV5, AmendOrderParamsV5, @@ -136,6 +157,7 @@ import { DepositAddressChainV5, DepositRecordV5, EarnAprHistoryPointV5, + EarnCouponListResultV5, EarnHourlyYieldHistoryV5, EarnOrderHistoryV5, EarnPositionV5, @@ -150,6 +172,13 @@ import { ExchangeBrokerAccountInfoV5, ExchangeBrokerEarningResultV5, ExchangeBrokerSubAccountDepositRecordV5, + ExecuteAlphaLPRedeemParamsV5, + ExecuteAlphaLPRedeemResultV5, + ExecuteAlphaLPStakeParamsV5, + ExecuteAlphaLPStakeResultV5, + ExecuteAlphaPredictionBuyParamsV5, + ExecuteAlphaPredictionOrderResultV5, + ExecuteAlphaPredictionSellParamsV5, ExecuteAlphaTradeParamsV5, ExecuteAlphaTradeResultV5, ExecuteRFQQuoteParamsV5, @@ -170,6 +199,7 @@ import { FriendReferralRecordV5, FundingAccountTransactionRecordV5, FundingRateHistoryResponseV5, + FuturesLeverageResultV5, GetAccountCoinBalanceParamsV5, GetAccountHistoricOrdersParamsV5, GetAccountInstrumentsInfoParamsV5, @@ -189,7 +219,25 @@ import { GetAlphaBizTokenDetailsParamsV5, GetAlphaBizTokenListParamsV5, GetAlphaBizTokenPriceListParamsV5, + GetAlphaLPOrderListParamsV5, + GetAlphaLPPayTokenListParamsV5, + GetAlphaLPPayTokenPriceParamsV5, + GetAlphaLPPoolInfoParamsV5, + GetAlphaLPPoolListParamsV5, GetAlphaPayTokenListParamsV5, + GetAlphaPredictionEventDetailParamsV5, + GetAlphaPredictionOrderBookParamsV5, + GetAlphaPredictionOrderEstimateParamsV5, + GetAlphaPredictionOrderListParamsV5, + GetAlphaPredictionPortfolioSummaryParamsV5, + GetAlphaPredictionPositionHistoryParamsV5, + GetAlphaPredictionPositionListParamsV5, + GetAlphaPredictionPriceHistoryParamsV5, + GetAlphaPredictionSideMarketListParamsV5, + GetAlphaPredictionSportsGroupStageDetailParamsV5, + GetAlphaPredictionSportsMatchListParamsV5, + GetAlphaPredictionSportsTimelineStagesParamsV5, + GetAlphaPredictionTokenPriceParamsV5, GetAlphaTradeOrderListParamsV5, GetAlphaTradeQuoteParamsV5, GetAssetInfoParamsV5, @@ -207,6 +255,7 @@ import { GetClassicTransactionLogsParamsV5, GetClosedOptionsPositionsParamsV5, GetClosedPnLParamsV5, + GetCoinDeltaAmountParamsV5, GetCoinExchangeRecordParamsV5, GetCoinStateParamsV5, GetCollateralAdjustmentHistoryParamsV5, @@ -217,6 +266,7 @@ import { GetDeliveryRecordParamsV5, GetDepositRecordParamsV5, GetEarnAprHistoryParamsV5, + GetEarnCouponListParamsV5, GetEarnHourlyYieldHistoryParamsV5, GetEarnOrderHistoryParamsV5, GetEarnPositionParamsV5, @@ -241,6 +291,7 @@ import { GetFriendReferralsParamsV5, GetFundingAccountTransactionHistoryParamsV5, GetFundingRateHistoryParamsV5, + GetFuturesLeverageParamsV5, GetHistoricalVolatilityParamsV5, GetHoldToEarnAirdropYieldHistoryParamsV5, GetIndexPriceComponentsParamsV5, @@ -302,6 +353,9 @@ import { GetRFQTradeListParamsV5, GetRiskLimitParamsV5, GetRPIOrderbookParamsV5, + GetRWANavChartParamsV5, + GetRWAOrderListParamsV5, + GetRWAProductListParamsV5, GetSettlementRecordParamsV5, GetSmallBalanceListParamsV5, GetSpotMarginCurrencyDataParamsV5, @@ -333,6 +387,8 @@ import { HoldToEarnAirdropProductsResultV5, HoldToEarnAirdropYieldHistoryResultV5, IndexPriceComponentsResponseV5, + InstitutionalLendingCoinDeltaAmountV5, + InstitutionalLendingProductInfoV5, InstitutionalLoanLTVV5, InstrumentInfoResponseV5, InsuranceResponseV5, @@ -388,6 +444,8 @@ import { PayInfoResultV5, PlaceEarnTokenOrderParamsV5, PlaceEarnTokenOrderResultV5, + PlaceRWAOrderParamsV5, + PlaceRWAOrderResultV5, PortfolioMarginInfoResultV5, PositionInfoParamsV5, PositionV5, @@ -442,6 +500,10 @@ import { RFQTradeV5, RiskLimitV5, RPIOrderbookResponseV5, + RWANavChartResultV5, + RWAOrderListResultV5, + RWAPositionListResultV5, + RWAProductListResultV5, SendP2POrderMessageParamsV5, SetAutoAddMarginParamsV5, SetAutoRepayModeParamsV5, @@ -479,6 +541,8 @@ import { StrategyOrderListResultV5, SubMemberV5, SubmitAdvanceEarnPlaceOrderParamsV5, + SubmitDepositOriginatorInfoParamsV5, + SubmitDepositOriginatorInfoResultV5, SubmitFixedTermEarnOrderParamsV5, SubmitSpreadOrderParamsV5, SubmitStakeRedeemParamsV5, @@ -1400,6 +1464,18 @@ export class RestClientV5 extends BaseRestClient { return this.getPrivate('/v5/position/list', params); } + /** + * Get Futures Leverage + * Query isolated leverage settings without requiring an open position. + * + * Returns an error under Portfolio Margin mode. + */ + getFuturesLeverage( + params: GetFuturesLeverageParamsV5, + ): Promise> { + return this.getPrivate('/v5/position/symbol-info', params); + } + /** * Set the leverage * @@ -2449,6 +2525,16 @@ export class RestClientV5 extends BaseRestClient { return this.getPrivate('/v5/asset/withdraw/vasp/list'); } + /** + * Submit Deposit Originator Info + * Submit Travel Rule originator questionnaire when deposit `travel_rule_status` is pending (1). + */ + submitDepositOriginatorInfo( + params: SubmitDepositOriginatorInfoParamsV5, + ): Promise> { + return this.postPrivate('/v5/asset/travel-rule/deposit/submit', params); + } + /** * Withdraw from Funding, Unified, and/or Earn (and combos such as FUND,UTA,EARN per API). * @@ -2932,6 +3018,274 @@ export class RestClientV5 extends BaseRestClient { return this.postPrivate('/v5/alpha/trade/asset-detail', params); } + /** + * + ****** Alpha / Web3 prediction market APIs + * + */ + + /** + * Get Engine Status + * Query prediction market matching engine availability before placing buy/sell orders. + */ + getAlphaPredictionEngineStatus(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/alpha/prediction/engine-status'); + } + + /** + * Get Payment Token List + * Available payment tokens for prediction market trading (Phase 1: USDC). + */ + getAlphaPredictionPayTokenList(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/alpha/prediction/pay-token-list'); + } + + /** + * Get Event Detail + * Event metadata, outcome markets, and current prices. Obtain tokenId before trading. + */ + getAlphaPredictionEventDetail( + params: GetAlphaPredictionEventDetailParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/event-detail', params); + } + + /** + * Get Order Estimate + * Preview buy/sell outcome before execution. Show estimate to user and confirm before Buy/Sell. + */ + getAlphaPredictionOrderEstimate( + params: GetAlphaPredictionOrderEstimateParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/order-estimate', params); + } + + /** + * Execute Buy + * Buy prediction outcome tokens with USDC. HTTP 200 is acknowledgment only — poll order list. + */ + executeAlphaPredictionBuy( + params: ExecuteAlphaPredictionBuyParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/buy', params); + } + + /** + * Execute Sell + * Sell prediction outcome token shares for USDC. HTTP 200 is acknowledgment only — poll order list. + */ + executeAlphaPredictionSell( + params: ExecuteAlphaPredictionSellParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/sell', params); + } + + /** + * Get Order List + * Prediction market order history for the authenticated user. + */ + getAlphaPredictionOrderList( + params: GetAlphaPredictionOrderListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/order-list', params); + } + + /** + * Get Order Book + * Full bid/ask depth snapshot for up to 20 outcome tokens. + */ + getAlphaPredictionOrderBook( + params: GetAlphaPredictionOrderBookParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/order-book', params); + } + + /** + * Get Token Price + * Best bid/ask and last price for up to 20 outcome tokens. + */ + getAlphaPredictionTokenPrice( + params: GetAlphaPredictionTokenPriceParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/token-price', params); + } + + /** + * Get Price History + * OHLC candlestick history for an outcome token. + */ + getAlphaPredictionPriceHistory( + params: GetAlphaPredictionPriceHistoryParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/price-history', params); + } + + /** + * Get Position List + * Active prediction market positions. Confirm before placing sell orders. + */ + getAlphaPredictionPositionList( + params?: GetAlphaPredictionPositionListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/position-list', params); + } + + /** + * Get Position History + * Closed prediction market positions including settlement results. + */ + getAlphaPredictionPositionHistory( + params?: GetAlphaPredictionPositionHistoryParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/position-history', params); + } + + /** + * Get Portfolio Summary + * Overall prediction market portfolio P&L and win rate. + */ + getAlphaPredictionPortfolioSummary( + params?: GetAlphaPredictionPortfolioSummaryParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/portfolio-summary', params); + } + + /** + * Get Side Market List + * Outcome markets for an event with prices, liquidity, and status. + */ + getAlphaPredictionSideMarketList( + params: GetAlphaPredictionSideMarketListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/side-market-list', params); + } + + /** + * Get Sports Match List + * Sports matches available in prediction markets (Phase 1: FIFA 2026). + */ + getAlphaPredictionSportsMatchList( + params: GetAlphaPredictionSportsMatchListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/prediction/sports/match-list', params); + } + + /** + * Get Sports Timeline Stages + * Tournament stage timeline with status and match counts. + */ + getAlphaPredictionSportsTimelineStages( + params: GetAlphaPredictionSportsTimelineStagesParamsV5, + ): Promise> { + return this.getPrivate( + '/v5/alpha/prediction/sports/timeline-stages', + params, + ); + } + + /** + * Get Sports Group Stage Detail + * Group stage standings and match schedule for a sports prediction event. + */ + getAlphaPredictionSportsGroupStageDetail( + params: GetAlphaPredictionSportsGroupStageDetailParamsV5, + ): Promise> { + return this.postPrivate( + '/v5/alpha/prediction/sports/group-stage-detail', + params, + ); + } + + /** + * + ****** Alpha / Web3 LP APIs + * + */ + + /** + * Get LP Pool List + * Available liquidity pools, optionally filtered by token symbol. + */ + getAlphaLPPoolList( + params?: GetAlphaLPPoolListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/pool-list', params); + } + + /** + * Get LP Pool Info + * Detailed pool data including APY, reserves, and price range. + */ + getAlphaLPPoolInfo( + params: GetAlphaLPPoolInfoParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/pool-info', params); + } + + /** + * Execute LP Stake + * Stake tokens into a liquidity pool. HTTP 200 is ACK only — poll order list for status. + */ + executeAlphaLPStake( + params: ExecuteAlphaLPStakeParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/stake', params); + } + + /** + * Execute LP Redeem + * Redeem liquidity from a pool position. HTTP 200 is ACK only — poll order list for status. + */ + executeAlphaLPRedeem( + params: ExecuteAlphaLPRedeemParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/redeem', params); + } + + /** + * Get LP Order List + * LP stake/redeem order history. + */ + getAlphaLPOrderList( + params?: GetAlphaLPOrderListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/order-list', params); + } + + /** + * Get LP Pay Token List + * Supported payment tokens and available balances for LP staking. + */ + getAlphaLPPayTokenList( + params?: GetAlphaLPPayTokenListParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/pay-token-list', params); + } + + /** + * Get LP Pay Token Price + * Batch USD prices for up to 50 payment token codes. + */ + getAlphaLPPayTokenPrice( + params: GetAlphaLPPayTokenPriceParamsV5, + ): Promise> { + return this.postPrivate('/v5/alpha/lp/pay-token-price', params); + } + + /** + * Get LP Position List + * User LP positions with valuation, rewards, and APY. + */ + getAlphaLPPositionList(): Promise< + APIResponseV3WithTime + > { + return this.postPrivate('/v5/alpha/lp/position-list', {}); + } + /** * ****** Spot Margin Trade APIs (UTA) @@ -3996,12 +4350,24 @@ export class RestClientV5 extends BaseRestClient { /** * Get Product Info */ - getInstitutionalLendingProductInfo( - productId?: string, - ): Promise> { + getInstitutionalLendingProductInfo(productId?: string): Promise< + APIResponseV3WithTime<{ + marginProductInfo: InstitutionalLendingProductInfoV5[]; + }> + > { return this.get('/v5/ins-loan/product-infos', { productId }); } + /** + * Get Coin Delta Amount + * Coin delta amount details for institutional loan hedge product (unified account only). + */ + getInstitutionalLendingCoinDeltaAmount( + params?: GetCoinDeltaAmountParamsV5, + ): Promise> { + return this.getPrivate('/v5/ins-loan/coin-delta-amount', params); + } + /** * Get Margin Coin Info * @deprecated @@ -4263,6 +4629,64 @@ export class RestClientV5 extends BaseRestClient { return this.get('/v5/earn/product', params); } + /** + * Get Coupon List + * Interest-rate coupons and Dual Assets reward cards for FlexibleSaving or DualAssets. + */ + getEarnCouponList( + params: GetEarnCouponListParamsV5, + ): Promise> { + return this.getPrivate('/v5/earn/coupons', params); + } + + /** + * Get RWA Product List + * Real World Assets earn products. Auth optional; `userQuota` populated when authenticated. + */ + getRWAProductList( + params?: GetRWAProductListParamsV5, + ): Promise> { + return this.get('/v5/earn/rwa/product', params); + } + + /** + * Place RWA Order + * Stake or redeem RWA product. Async — use getRWAOrderList to track status. + */ + placeRWAOrder( + params: PlaceRWAOrderParamsV5, + ): Promise> { + return this.postPrivate('/v5/earn/rwa/place-order', params); + } + + /** + * Get RWA Position List + */ + getRWAPositionList(): Promise< + APIResponseV3WithTime + > { + return this.getPrivate('/v5/earn/rwa/position'); + } + + /** + * Get RWA Order List + */ + getRWAOrderList( + params?: GetRWAOrderListParamsV5, + ): Promise> { + return this.getPrivate('/v5/earn/rwa/order', params); + } + + /** + * Get RWA NAV Chart + * NAV history for an RWA product (public; max 180-day span). + */ + getRWANavChart( + params: GetRWANavChartParamsV5, + ): Promise> { + return this.get('/v5/earn/rwa/nav-chart', params); + } + /** * Get Hold to Earn airdrop products (ByFi). * diff --git a/src/types/request/index.ts b/src/types/request/index.ts index 9344b321..0a3c0313 100644 --- a/src/types/request/index.ts +++ b/src/types/request/index.ts @@ -8,6 +8,8 @@ export * from './usdc-options'; export * from './usdc-perp'; export * from './usdc-shared'; export * from './v5-account'; +export * from './v5-alpha-lp'; +export * from './v5-alpha-prediction'; export * from './v5-alpha-trade'; export * from './v5-asset'; export * from './v5-broker'; @@ -24,6 +26,7 @@ export * from './v5-p2p-trading'; export * from './v5-position'; export * from './v5-pre-upgrade'; export * from './v5-rfq'; +export * from './v5-rwa'; export * from './v5-spot-leverage-token'; export * from './v5-spreadtrading'; export * from './v5-strategy'; diff --git a/src/types/request/v5-account.ts b/src/types/request/v5-account.ts index 67ec0280..8abf6e6a 100644 --- a/src/types/request/v5-account.ts +++ b/src/types/request/v5-account.ts @@ -46,6 +46,7 @@ export interface MMPModifyParamsV5 { frozenPeriod: string; qtyLimit: string; deltaLimit: string; + vegaLimit?: string; } export interface RepayLiabilityParamsV5 { diff --git a/src/types/request/v5-alpha-lp.ts b/src/types/request/v5-alpha-lp.ts new file mode 100644 index 00000000..96099f3f --- /dev/null +++ b/src/types/request/v5-alpha-lp.ts @@ -0,0 +1,49 @@ +/** + * 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; +} diff --git a/src/types/request/v5-alpha-prediction.ts b/src/types/request/v5-alpha-prediction.ts new file mode 100644 index 00000000..d0adc620 --- /dev/null +++ b/src/types/request/v5-alpha-prediction.ts @@ -0,0 +1,106 @@ +/** + * 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; +} diff --git a/src/types/request/v5-asset.ts b/src/types/request/v5-asset.ts index dde70e84..c020dd41 100644 --- a/src/types/request/v5-asset.ts +++ b/src/types/request/v5-asset.ts @@ -135,6 +135,13 @@ export interface GetWithdrawalAddressListParamsV5 { cursor?: string; } +export interface SubmitDepositOriginatorInfoParamsV5 { + depositId: number; + subAccountId?: number; + /** Travel Rule questionnaire JSON string. See Questionnaire docs. */ + questionnaire: string; +} + export interface WithdrawParamsV5 { coin: string; /** @@ -157,6 +164,10 @@ export interface WithdrawParamsV5 { * 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; diff --git a/src/types/request/v5-crypto-loan.ts b/src/types/request/v5-crypto-loan.ts index 0f487c32..f1e4d635 100644 --- a/src/types/request/v5-crypto-loan.ts +++ b/src/types/request/v5-crypto-loan.ts @@ -243,6 +243,10 @@ export interface GetMaxLoanAmountParamsV5 { // Institutional Loan Request Types +export interface GetCoinDeltaAmountParamsV5 { + coin?: string; +} + export interface RepayInstitutionalLoanParamsV5 { token: string; // Coin name quantity: string; // The qty to be repaid diff --git a/src/types/request/v5-earn.ts b/src/types/request/v5-earn.ts index 999993f6..94e9777c 100644 --- a/src/types/request/v5-earn.ts +++ b/src/types/request/v5-earn.ts @@ -1,3 +1,7 @@ +export interface GetEarnCouponListParamsV5 { + category: 'FlexibleSaving' | 'DualAssets'; +} + export interface SubmitStakeRedeemParamsV5 { category: string; orderType: 'Stake' | 'Redeem'; diff --git a/src/types/request/v5-position.ts b/src/types/request/v5-position.ts index b0b8fa04..f24ede2c 100644 --- a/src/types/request/v5-position.ts +++ b/src/types/request/v5-position.ts @@ -7,6 +7,11 @@ import { TPSLModeV5, } from '../shared-v5'; +export interface GetFuturesLeverageParamsV5 { + category: 'linear' | 'inverse'; + symbol?: string; +} + export interface PositionInfoParamsV5 { category: CategoryV5; symbol?: string; diff --git a/src/types/request/v5-rwa.ts b/src/types/request/v5-rwa.ts new file mode 100644 index 00000000..35a08b06 --- /dev/null +++ b/src/types/request/v5-rwa.ts @@ -0,0 +1,34 @@ +/** + * 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; +} diff --git a/src/types/request/v5-trade.ts b/src/types/request/v5-trade.ts index dd7af75f..fb942cea 100644 --- a/src/types/request/v5-trade.ts +++ b/src/types/request/v5-trade.ts @@ -45,6 +45,7 @@ export interface OrderParamsV5 { slOrderType?: OrderTypeV5; bboSideType?: 'Queue' | 'Counterparty'; bboLevel?: '1' | '2' | '3' | '4' | '5'; + rpiTakerAccess?: boolean; } export interface AmendOrderParamsV5 { diff --git a/src/types/response/index.ts b/src/types/response/index.ts index 3d7508c4..05049f7a 100644 --- a/src/types/response/index.ts +++ b/src/types/response/index.ts @@ -5,6 +5,8 @@ export * from './spot'; export * from './unified-margin'; export * from './usdt-perp'; export * from './v5-account'; +export * from './v5-alpha-lp'; +export * from './v5-alpha-prediction'; export * from './v5-alpha-trade'; export * from './v5-asset'; export * from './v5-broker'; @@ -21,6 +23,7 @@ export * from './v5-p2p-trading'; export * from './v5-position'; export * from './v5-preupgrade'; export * from './v5-rfq'; +export * from './v5-rwa'; export * from './v5-spot-leverage-token'; export * from './v5-spreadtrading'; export * from './v5-strategy'; diff --git a/src/types/response/v5-account.ts b/src/types/response/v5-account.ts index 9d8e348c..b5f33743 100644 --- a/src/types/response/v5-account.ts +++ b/src/types/response/v5-account.ts @@ -26,6 +26,7 @@ export interface WalletBalanceV5Coin { marginCollateral: boolean; collateralSwitch: boolean; spotBorrow: string; + colRes?: string; } export interface WalletBalanceV5 { @@ -149,6 +150,7 @@ export interface MMPStateV5 { frozenPeriod: string; qtyLimit: string; deltaLimit: string; + vegaLimit?: string; mmpFrozenUntil: string; mmpFrozen: boolean; } diff --git a/src/types/response/v5-alpha-lp.ts b/src/types/response/v5-alpha-lp.ts new file mode 100644 index 00000000..8ec13e80 --- /dev/null +++ b/src/types/response/v5-alpha-lp.ts @@ -0,0 +1,134 @@ +/** + * V5 private Alpha LP responses. + */ + +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 AlphaLPPoolListResultV5 { + pools: AlphaLPPoolV5[]; +} + +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 ExecuteAlphaLPRedeemResultV5 { + orderNo: string; +} + +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 AlphaLPPayTokenListResultV5 { + tokens: AlphaLPPayTokenV5[]; +} + +export interface AlphaLPPayTokenPriceV5 { + tokenCode: string; + tokenSymbol: string; + priceUsd: string; + chainCode: string; + updateTime: number; +} + +export interface AlphaLPPayTokenPriceResultV5 { + prices: AlphaLPPayTokenPriceV5[]; +} + +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 AlphaLPPositionListResultV5 { + positions: AlphaLPPositionV5[]; +} diff --git a/src/types/response/v5-alpha-prediction.ts b/src/types/response/v5-alpha-prediction.ts new file mode 100644 index 00000000..19f11b61 --- /dev/null +++ b/src/types/response/v5-alpha-prediction.ts @@ -0,0 +1,255 @@ +/** + * V5 private Alpha prediction market responses. + */ + +export interface AlphaPredictionEngineStatusV5 { + available: boolean; +} + +export interface AlphaPredictionPayTokenV5 { + tokenCode: string; + symbol: string; + tokenDecimals: number; + tokenIconUrlDay: string; + tokenIconUrlNight: string; + supportChains: string[]; +} + +export interface AlphaPredictionMarketV5 { + tokenId: string; + outcome: string; + price: string; + side: number; + volume: string; + liquidity: 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 AlphaPredictionOrderEstimateFeeDetailV5 { + serverFee: string; + polymarketFee: string; +} + +export interface AlphaPredictionOrderEstimateV5 { + avgPrice: string; + estimatedCost: string; + estimatedReceive: string; + toWin?: string; + feeAmount: string; + feeDetail: AlphaPredictionOrderEstimateFeeDetailV5; + slippage: string; +} + +export interface ExecuteAlphaPredictionOrderResultV5 { + orderNo: 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 AlphaPredictionOrderListResultV5 { + orders: AlphaPredictionOrderV5[]; + total: number; + pageIndex: number; +} + +export interface AlphaPredictionOrderBookLevelV5 { + price: string; + size: string; +} + +export interface AlphaPredictionOrderBookV5 { + tokenId: string; + bids: AlphaPredictionOrderBookLevelV5[]; + asks: AlphaPredictionOrderBookLevelV5[]; +} + +export interface AlphaPredictionTokenPriceV5 { + tokenId: string; + bestBid: string; + bestAsk: string; + lastPrice: string; + volume24h: string; + updateTime: number; +} + +export interface AlphaPredictionPriceHistoryCandleV5 { + openTime: number; + open: string; + high: string; + low: string; + close: string; + volume: string; +} + +export interface AlphaPredictionPriceHistoryV5 { + tokenId: string; + interval: string; + list: AlphaPredictionPriceHistoryCandleV5[]; +} + +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 AlphaPredictionPositionListResultV5 { + positions: AlphaPredictionPositionV5[]; + total: number; + totalAssetUsd: 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 AlphaPredictionPositionHistoryResultV5 { + positions: AlphaPredictionPositionHistoryV5[]; + total: number; +} + +export interface AlphaPredictionPortfolioSummaryV5 { + positionValue: string; + positionValueUsd: string; + biggestWin: string; + winRate: string; + winCount: number; + lossCount: number; +} + +export interface AlphaPredictionSideMarketTokenV5 { + tokenId: string; + outcome: string; + price: string; + liquidity: string; +} + +export interface AlphaPredictionSideMarketV5 { + marketId: string; + eventId: string; + marketType: number; + question: string; + tokens: AlphaPredictionSideMarketTokenV5[]; + volume24h: string; + endDate: number; + status: number; +} + +export interface AlphaPredictionSideMarketListResultV5 { + list: AlphaPredictionSideMarketV5[]; + total: number; + pageIndex: number; + pageSize: number; +} + +export interface AlphaPredictionSportsMatchV5 { + matchId: string; + eventType: number; + stageCode: string; + homeTeam: string; + awayTeam: string; + matchTime: number; + status: number; + eventId: string; +} + +export interface AlphaPredictionSportsMatchListResultV5 { + list: AlphaPredictionSportsMatchV5[]; + total: number; + pageIndex: number; + pageSize: number; +} + +export interface AlphaPredictionSportsTimelineStageV5 { + stageCode: string; + stageName: string; + status: number; + matchCount: number; + startTime: number; + endTime: number; +} + +export interface AlphaPredictionSportsTimelineStagesV5 { + eventType: number; + stages: AlphaPredictionSportsTimelineStageV5[]; +} + +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 AlphaPredictionSportsGroupMatchV5 { + matchId: string; + homeTeam: string; + awayTeam: string; + matchTime: number; + status: number; + homeScore: number; + awayScore: number; + eventId: string; +} + +export interface AlphaPredictionSportsGroupV5 { + groupName: string; + standings: AlphaPredictionSportsGroupStandingV5[]; + matches: AlphaPredictionSportsGroupMatchV5[]; +} + +export interface AlphaPredictionSportsGroupStageDetailV5 { + groups: AlphaPredictionSportsGroupV5[]; +} diff --git a/src/types/response/v5-asset.ts b/src/types/response/v5-asset.ts index 16264c67..13736ae8 100644 --- a/src/types/response/v5-asset.ts +++ b/src/types/response/v5-asset.ts @@ -122,6 +122,10 @@ export interface DepositRecordV5 { fromAddress: string; } +export interface SubmitDepositOriginatorInfoResultV5 { + travelRuleStatus: number; +} + export interface InternalDepositRecordV5 { id: string; type: 1; diff --git a/src/types/response/v5-crypto-loan.ts b/src/types/response/v5-crypto-loan.ts index f7518985..a5296689 100644 --- a/src/types/response/v5-crypto-loan.ts +++ b/src/types/response/v5-crypto-loan.ts @@ -178,6 +178,7 @@ export interface CryptoLoanPositionV5 { totalCollateral: string; totalDebt: string; totalSupply: string; + colRes?: string; } // Flexible Loan Types @@ -329,6 +330,53 @@ export interface RenewOrderInfoFixedV5 { // Institutional Loan Types +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 InstitutionalLendingCoinDeltaItemV5 { + coin: string; + coinDeltaSize: string; + coinDeltaAvailableAmount: string; + coinDeltaAmount: string; +} + +export interface InstitutionalLendingCoinDeltaAmountV5 { + riskUnitDeltaAmount: string; + riskUnitDeltaAvailableAmount: string; + list: InstitutionalLendingCoinDeltaItemV5[]; +} + export interface UnpaidInfoV5 { token: string; // Coin unpaidQty: string; // Unpaid principle diff --git a/src/types/response/v5-earn.ts b/src/types/response/v5-earn.ts index 06e433ec..fb14af64 100644 --- a/src/types/response/v5-earn.ts +++ b/src/types/response/v5-earn.ts @@ -1,3 +1,40 @@ +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; + limitPnlPercentage: string; + baseCoin: string; + quoteCoin: string; + direction: 1 | 2; + category: 'FlexibleSaving' | 'DualAssets' | string; +} + +export interface EarnCouponListResultV5 { + interestCards: EarnInterestCardV5[]; + awardCards: EarnAwardCardV5[]; +} + export interface EarnProductV5 { category: string; estimateApr: string; diff --git a/src/types/response/v5-market.ts b/src/types/response/v5-market.ts index f8bab5f7..a021566c 100644 --- a/src/types/response/v5-market.ts +++ b/src/types/response/v5-market.ts @@ -239,6 +239,8 @@ export interface TickerLinearInverseV5 { prevPrice1h: string; openInterest: string; openInterestValue: string; + singleOpenInterest?: string; + singleOpenInterestValue?: string; turnover24h: string; volume24h: string; fundingRate: string; @@ -333,6 +335,7 @@ export interface PublicTradeV5 { */ export type OpenInterestV5 = { openInterest: string; + singleOpenInterest?: string; timestamp: string; }; diff --git a/src/types/response/v5-position.ts b/src/types/response/v5-position.ts index 78adddb5..a25ee29e 100644 --- a/src/types/response/v5-position.ts +++ b/src/types/response/v5-position.ts @@ -11,6 +11,18 @@ import { TradeModeV5, } from '../shared-v5'; +export interface FuturesLeverageItemV5 { + symbol: string; + leverage: string; + side: OrderSideV5 | ''; + positionIdx: PositionIdx; +} + +export interface FuturesLeverageResultV5 { + category: 'linear' | 'inverse'; + list: FuturesLeverageItemV5[]; +} + export interface PositionV5 { positionIdx: PositionIdx; riskId: number; diff --git a/src/types/response/v5-rwa.ts b/src/types/response/v5-rwa.ts new file mode 100644 index 00000000..f5913917 --- /dev/null +++ b/src/types/response/v5-rwa.ts @@ -0,0 +1,82 @@ +/** + * V5 RWA (Real World Assets) earn responses. + */ + +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; +} + +export interface RWAProductListResultV5 { + list: RWAProductV5[]; +} + +export interface PlaceRWAOrderResultV5 { + orderId: string; + orderLinkId: string; +} + +export interface RWAPositionV5 { + productId: number; + coin: string; + assetSymbol: string; + effectiveShare: string; + processingStakeAmount: string; + processingRedeemShare: string; + bonusEarned: string; + nav: string; + holdAmount: string; + duration: number; +} + +export interface RWAPositionListResultV5 { + list: RWAPositionV5[]; +} + +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; +} + +export interface RWAOrderListResultV5 { + list: RWAOrderV5[]; + nextPageCursor: string; +} + +export interface RWANavChartPointV5 { + date: string; + nav: string; +} + +export interface RWANavChartResultV5 { + productId: number; + list: RWANavChartPointV5[]; +} diff --git a/src/types/response/v5-trade.ts b/src/types/response/v5-trade.ts index 337d0775..a111c40e 100644 --- a/src/types/response/v5-trade.ts +++ b/src/types/response/v5-trade.ts @@ -72,6 +72,11 @@ export interface AccountOrderV5 { 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 BatchCreateOrderResultV5 { diff --git a/src/types/websockets/ws-events.ts b/src/types/websockets/ws-events.ts index d270e4fc..ca7ac430 100644 --- a/src/types/websockets/ws-events.ts +++ b/src/types/websockets/ws-events.ts @@ -128,6 +128,8 @@ export interface WSTickerV5 { indexPrice: string; openInterest: string; openInterestValue: string; + singleOpenInterest?: string; + singleOpenInterestValue?: string; turnover24h: string; volume24h: string; nextFundingTime: string; @@ -329,6 +331,8 @@ export interface WSAccountOrderV5 { createdTime: string; updatedTime: string; cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency + rpiTakerAccess?: boolean; + rpiMatchedQty?: string; } export type WSAccountOrderEventV5 = WSPrivateTopicEventV5< @@ -389,6 +393,7 @@ export interface WSExecutionFastV5 { side: OrderSideV5; execTime: string; seq: number; + liquidity?: string; } export type WSExecutionFastEventV5 = WSPrivateTopicEventV5< @@ -417,6 +422,7 @@ export interface WSCoinV5 { collateralSwitch: boolean; marginCollateral: boolean; spotBorrow: string; + colRes?: string; } export interface WSWalletV5 {