From c559e968c3f57e3aa89946297ed14f3a90b1dff7 Mon Sep 17 00:00:00 2001 From: JJ-Cro Date: Fri, 3 Jul 2026 19:50:15 +0200 Subject: [PATCH] feat(v3.5.11): update CoinMClient and MainClient to support new algo order endpoints, enhance documentation, and add new examples for loan and travel rule functionalities --- docs/endpointFunctionList.md | 1188 +- .../apidoc/CoinMClient/cancelAlgoOrder.js | 22 + .../apidoc/CoinMClient/getOpenAlgoOrders.js | 22 + .../apidoc/CoinMClient/submitNewAlgoOrder.js | 22 + .../MainClient/borrowVipLoanFixedRate.js | 22 + .../getInstitutionalLoanMaxBorrowable.js | 22 + .../MainClient/getTravelRuleCountryList.js | 22 + .../MainClient/getTravelRuleRegionList.js | 22 + .../MainClient/getVipLoanFixedRateMarket.js | 22 + llms.txt | 35363 ++++++++-------- package-lock.json | 4 +- package.json | 2 +- src/coinm-client.ts | 32 + src/main-client.ts | 38 + src/types/spot.ts | 84 +- src/types/websockets/ws-events-raw.ts | 3 +- src/util/beautifier-maps.ts | 1 + 17 files changed, 18677 insertions(+), 18214 deletions(-) create mode 100644 examples/apidoc/CoinMClient/cancelAlgoOrder.js create mode 100644 examples/apidoc/CoinMClient/getOpenAlgoOrders.js create mode 100644 examples/apidoc/CoinMClient/submitNewAlgoOrder.js create mode 100644 examples/apidoc/MainClient/borrowVipLoanFixedRate.js create mode 100644 examples/apidoc/MainClient/getInstitutionalLoanMaxBorrowable.js create mode 100644 examples/apidoc/MainClient/getTravelRuleCountryList.js create mode 100644 examples/apidoc/MainClient/getTravelRuleRegionList.js create mode 100644 examples/apidoc/MainClient/getVipLoanFixedRateMarket.js diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index b9076f5b..ca842290 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -52,523 +52,528 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [testConnectivity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L775) | | GET | `api/v3/ping` | -| [getExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L779) | | GET | `api/v3/exchangeInfo` | -| [getOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L799) | | GET | `api/v3/depth` | -| [getRecentTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L803) | | GET | `api/v3/trades` | -| [getHistoricalTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L807) | | GET | `api/v3/historicalTrades` | -| [getHistoricalBlockTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L811) | | GET | `api/v3/historicalBlockTrades` | -| [getAggregateTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L817) | | GET | `api/v3/aggTrades` | -| [getKlines()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L823) | | GET | `api/v3/klines` | -| [getUIKlines()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L827) | | GET | `api/v3/uiKlines` | -| [getAvgPrice()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L831) | | GET | `api/v3/avgPrice` | -| [getExecutionRules()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L835) | | GET | `api/v3/executionRules?symbols=` | -| [getReferencePrice()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L850) | | GET | `api/v3/referencePrice` | -| [getReferencePriceCalculation()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L856) | | GET | `api/v3/referencePrice/calculation` | -| [get24hrChangeStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L863) | | GET | `api/v3/ticker/24hr?symbols=` | -| [getTradingDayTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L893) | | GET | `api/v3/ticker/tradingDay?symbols=` | -| [getSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L908) | | GET | `api/v3/ticker/price?symbols=` | -| [getSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L925) | | GET | `api/v3/ticker/bookTicker?symbols=` | -| [getRollingWindowTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L942) | | GET | `api/v3/ticker?symbols=` | -| [submitNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L964) | :closed_lock_with_key: | POST | `api/v3/order` | -| [testNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L972) | :closed_lock_with_key: | POST | `api/v3/order/test` | -| [getOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L980) | :closed_lock_with_key: | GET | `api/v3/order` | -| [cancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L984) | :closed_lock_with_key: | DELETE | `api/v3/order` | -| [cancelAllSymbolOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L988) | :closed_lock_with_key: | DELETE | `api/v3/openOrders` | -| [replaceOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L994) | :closed_lock_with_key: | POST | `api/v3/order/cancelReplace` | -| [amendOrderKeepPriority()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1008) | :closed_lock_with_key: | PUT | `fapi/v1/order/amend/keepPriority` | -| [getOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1015) | :closed_lock_with_key: | GET | `api/v3/openOrders` | -| [getAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1019) | :closed_lock_with_key: | GET | `api/v3/allOrders` | -| [submitNewOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1026) | :closed_lock_with_key: | POST | `api/v3/order/oco` | -| [submitNewOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1033) | :closed_lock_with_key: | POST | `api/v3/orderList/oco` | -| [submitNewOrderListOTO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1042) | :closed_lock_with_key: | POST | `api/v3/orderList/oto` | -| [submitNewOrderListOTOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1051) | :closed_lock_with_key: | POST | `api/v3/orderList/otoco` | -| [submitNewOrderListOPO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1061) | :closed_lock_with_key: | POST | `api/v3/orderList/opo` | -| [submitNewOrderListOPOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1070) | :closed_lock_with_key: | POST | `api/v3/orderList/opoco` | -| [cancelOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1080) | :closed_lock_with_key: | DELETE | `api/v3/orderList` | -| [getOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1085) | :closed_lock_with_key: | GET | `api/v3/orderList` | -| [getAllOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1089) | :closed_lock_with_key: | GET | `api/v3/allOrderList` | -| [getAllOpenOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1096) | :closed_lock_with_key: | GET | `api/v3/openOrderList` | -| [submitNewSOROrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1103) | :closed_lock_with_key: | POST | `api/v3/sor/order` | -| [testNewSOROrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1114) | :closed_lock_with_key: | POST | `api/v3/sor/order/test` | -| [getAccountInformation()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1130) | :closed_lock_with_key: | GET | `api/v3/account` | -| [getAccountTradeList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1136) | :closed_lock_with_key: | GET | `api/v3/myTrades` | -| [getOrderRateLimit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1142) | :closed_lock_with_key: | GET | `api/v3/rateLimit/order` | -| [getPreventedMatches()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1146) | :closed_lock_with_key: | GET | `api/v3/myPreventedMatches` | -| [getAllocations()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1152) | :closed_lock_with_key: | GET | `api/v3/myAllocations` | -| [getCommissionRates()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1156) | :closed_lock_with_key: | GET | `api/v3/account/commission` | -| [getCrossMarginCollateralRatio()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1166) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginCollateralRatio` | -| [getAllCrossMarginPairs()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1175) | | GET | `sapi/v1/margin/allPairs` | -| [getIsolatedMarginAllSymbols()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1179) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/allPairs` | -| [getAllMarginAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1185) | | GET | `sapi/v1/margin/allAssets` | -| [getMarginDelistSchedule()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1189) | :closed_lock_with_key: | GET | `sapi/v1/margin/delist-schedule` | -| [getIsolatedMarginTierData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1193) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginTier` | -| [queryMarginPriceIndex()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1199) | | GET | `sapi/v1/margin/priceIndex` | -| [getMarginAvailableInventory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1205) | :closed_lock_with_key: | GET | `sapi/v1/margin/available-inventory` | -| [getLeverageBracket()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1211) | :closed_lock_with_key: | GET | `sapi/v1/margin/leverageBracket` | -| [getNextHourlyInterestRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1221) | :closed_lock_with_key: | GET | `sapi/v1/margin/next-hourly-interest-rate` | -| [getMarginInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1227) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestHistory` | -| [submitMarginAccountBorrowRepay()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1234) | :closed_lock_with_key: | POST | `sapi/v1/margin/borrow-repay` | -| [getMarginAccountBorrowRepayRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1240) | :closed_lock_with_key: | GET | `sapi/v1/margin/borrow-repay` | -| [getMarginInterestRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1246) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestRateHistory` | -| [queryMaxBorrow()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1252) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxBorrowable` | -| [getMarginForceLiquidationRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1264) | :closed_lock_with_key: | GET | `sapi/v1/margin/forceLiquidationRec` | -| [getSmallLiabilityExchangeCoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1273) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability` | -| [getSmallLiabilityExchangeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1277) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability-history` | -| [marginAccountCancelOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1289) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/openOrders` | -| [marginAccountCancelOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1295) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/orderList` | -| [marginAccountCancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1300) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/order` | -| [marginAccountNewOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1306) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oco` | -| [marginAccountNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1313) | :closed_lock_with_key: | POST | `sapi/v1/margin/order` | -| [getMarginOrderCountUsage()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1321) | :closed_lock_with_key: | GET | `sapi/v1/margin/rateLimit/order` | -| [queryMarginAccountAllOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1327) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrderList` | -| [queryMarginAccountAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1333) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrders` | -| [queryMarginAccountOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1339) | :closed_lock_with_key: | GET | `sapi/v1/margin/orderList` | -| [queryMarginAccountOpenOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1343) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrderList` | -| [queryMarginAccountOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1350) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrders` | -| [queryMarginAccountOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1354) | :closed_lock_with_key: | GET | `sapi/v1/margin/order` | -| [queryMarginAccountTradeList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1358) | :closed_lock_with_key: | GET | `sapi/v1/margin/myTrades` | -| [submitSmallLiabilityExchange()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1364) | :closed_lock_with_key: | POST | `sapi/v1/margin/exchange-small-liability` | -| [submitManualLiquidation()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1371) | :closed_lock_with_key: | POST | `sapi/v1/margin/manual-liquidation` | -| [submitMarginOTOOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1380) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oto` | -| [submitMarginOTOCOOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1392) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/otoco` | -| [createMarginSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1405) | :closed_lock_with_key: | POST | `sapi/v1/margin/apiKey` | -| [deleteMarginSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1411) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/apiKey` | -| [updateMarginIPForSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1419) | :closed_lock_with_key: | PUT | `sapi/v1/margin/apiKey/ip` | -| [getMarginSpecialLowLatencyKeys()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1430) | :closed_lock_with_key: | GET | `sapi/v1/margin/api-key-list` | -| [getMarginSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1439) | :closed_lock_with_key: | GET | `sapi/v1/margin/apiKey` | -| [getMarginLiquidationLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1449) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan` | -| [repayMarginLiquidationLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1456) | :closed_lock_with_key: | POST | `sapi/v1/margin/liquidation-loan/repay` | -| [getMarginLiquidationLoanRepayHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1465) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan/repay-history` | -| [exitMarginSpecialKeyMode()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1477) | :closed_lock_with_key: | POST | `sapi/v1/margin/exit-special-key-mode` | -| [getCrossMarginTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1487) | :closed_lock_with_key: | GET | `sapi/v1/margin/transfer` | -| [queryMaxTransferOutAmount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1493) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxTransferable` | -| [updateCrossMarginMaxLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1505) | :closed_lock_with_key: | POST | `sapi/v1/margin/max-leverage` | -| [disableIsolatedMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1511) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/isolated/account` | -| [enableIsolatedMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1518) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/account` | -| [getBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1525) | :closed_lock_with_key: | GET | `sapi/v1/bnbBurn` | -| [getMarginSummary()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1529) | :closed_lock_with_key: | GET | `sapi/v1/margin/tradeCoeff` | -| [queryCrossMarginAccountDetails()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1533) | :closed_lock_with_key: | GET | `sapi/v1/margin/account` | -| [getCrossMarginFeeData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1537) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginData` | -| [getIsolatedMarginAccountLimit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1543) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/accountLimit` | -| [getIsolatedMarginAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1550) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/account` | -| [getIsolatedMarginFeeData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1556) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginData` | -| [toggleBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1562) | :closed_lock_with_key: | POST | `sapi/v1/bnbBurn` | -| [getMarginCapitalFlow()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1570) | :closed_lock_with_key: | GET | `sapi/v1/margin/capital-flow` | -| [queryLoanRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1579) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan` | -| [queryRepayRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1588) | :closed_lock_with_key: | GET | `sapi/v1/margin/repay` | -| [isolatedMarginAccountTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1597) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/transfer` | -| [getBalances()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1609) | :closed_lock_with_key: | GET | `sapi/v1/capital/config/getall` | -| [withdraw()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1613) | :closed_lock_with_key: | POST | `sapi/v1/capital/withdraw/apply` | -| [getWithdrawHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1617) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/history` | -| [getWithdrawAddresses()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1623) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/address/list` | -| [getWithdrawQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1627) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/quota` | -| [getDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1634) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/hisrec` | -| [getDepositAddress()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1638) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address` | -| [getDepositAddresses()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1644) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address/list` | -| [submitDepositCredit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1650) | :closed_lock_with_key: | POST | `sapi/v1/capital/deposit/credit-apply` | -| [getAutoConvertStablecoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1659) | :closed_lock_with_key: | GET | `sapi/v1/capital/contract/convertible-coins` | -| [setConvertibleCoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1666) | :closed_lock_with_key: | POST | `sapi/v1/capital/contract/convertible-coins` | -| [getAssetDetail()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1679) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDetail` | -| [getWalletBalances()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1685) | :closed_lock_with_key: | GET | `sapi/v1/asset/wallet/balance` | -| [getUserAsset()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1691) | :closed_lock_with_key: | POST | `sapi/v3/asset/getUserAsset` | -| [submitUniversalTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1695) | :closed_lock_with_key: | POST | `sapi/v1/asset/transfer` | -| [getUniversalTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1701) | :closed_lock_with_key: | GET | `sapi/v1/asset/transfer` | -| [getDust()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1707) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-btc` | -| [convertDustToBnb()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1711) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust` | -| [convertDustAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1718) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/convert` | -| [queryDustConvertibleAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1725) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/query-convertible-assets` | -| [getDustLog()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1734) | :closed_lock_with_key: | GET | `sapi/v1/asset/dribblet` | -| [getAssetDividendRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1738) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDividend` | -| [getTradeFee()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1742) | :closed_lock_with_key: | GET | `sapi/v1/asset/tradeFee` | -| [getFundingAsset()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1746) | :closed_lock_with_key: | POST | `sapi/v1/asset/get-funding-asset` | -| [getCloudMiningHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1750) | :closed_lock_with_key: | GET | `sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage` | -| [getDelegationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1760) | :closed_lock_with_key: | GET | `sapi/v1/asset/custody/transfer-history` | -| [submitNewFutureAccountTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1790) | :closed_lock_with_key: | POST | `sapi/v1/futures/transfer` | -| [getFutureAccountTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1800) | :closed_lock_with_key: | GET | `sapi/v1/futures/transfer` | -| [getCrossCollateralBorrowHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1809) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/borrow/history` | -| [getCrossCollateralRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1816) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/repay/history` | -| [getCrossCollateralWalletV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1823) | :closed_lock_with_key: | GET | `sapi/v2/futures/loan/wallet` | -| [getAdjustCrossCollateralLTVHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1830) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/adjustCollateral/history` | -| [getCrossCollateralLiquidationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1842) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/liquidationHistory` | -| [getCrossCollateralInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1851) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/interestHistory` | -| [getAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1863) | :closed_lock_with_key: | GET | `sapi/v1/account/info` | -| [getDailyAccountSnapshot()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1867) | :closed_lock_with_key: | GET | `sapi/v1/accountSnapshot` | -| [disableFastWithdrawSwitch()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1873) | :closed_lock_with_key: | POST | `sapi/v1/account/disableFastWithdrawSwitch` | -| [enableFastWithdrawSwitch()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1877) | :closed_lock_with_key: | POST | `sapi/v1/account/enableFastWithdrawSwitch` | -| [getAccountStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1881) | :closed_lock_with_key: | GET | `sapi/v1/account/status` | -| [getApiTradingStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1885) | :closed_lock_with_key: | GET | `sapi/v1/account/apiTradingStatus` | -| [getApiKeyPermissions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1889) | :closed_lock_with_key: | GET | `sapi/v1/account/apiRestrictions` | -| [withdrawTravelRule()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1905) | :closed_lock_with_key: | POST | `sapi/v1/localentity/withdraw/apply` | -| [getTravelRuleWithdrawHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1916) | :closed_lock_with_key: | GET | `sapi/v1/localentity/withdraw/history` | -| [getTravelRuleWithdrawHistoryV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1925) | :closed_lock_with_key: | GET | `sapi/v2/localentity/withdraw/history` | -| [submitTravelRuleDepositQuestionnaire()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1937) | :closed_lock_with_key: | PUT | `sapi/v1/localentity/deposit/provide-info` | -| [getTravelRuleDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1946) | :closed_lock_with_key: | GET | `sapi/v1/localentity/deposit/history` | -| [getOnboardedVASPList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1957) | :closed_lock_with_key: | GET | `sapi/v1/localentity/vasp` | -| [getSystemStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1967) | | GET | `sapi/v1/system/status` | -| [getDelistSchedule()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1971) | :closed_lock_with_key: | GET | `sapi/v1/spot/delist-schedule` | -| [createVirtualSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1981) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/virtualSubAccount` | -| [getSubAccountList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1987) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/list` | -| [subAccountEnableFutures()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1993) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/enable` | -| [subAccountEnableMargin()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2001) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/enable` | -| [enableOptionsForSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2005) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/eoptions/enable` | -| [subAccountEnableLeverageToken()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2015) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/blvt/enable` | -| [getSubAccountStatusOnMarginOrFutures()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2021) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/status` | -| [getSubAccountFuturesPositionRisk()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2027) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/positionRisk` | -| [getSubAccountFuturesPositionRiskV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2035) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/positionRisk` | -| [getSubAccountTransactionStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2041) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transaction-statistics` | -| [getSubAccountIPRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2056) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/subAccountApi/ipRestriction` | -| [subAccountDeleteIPList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2065) | :closed_lock_with_key: | DELETE | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | -| [subAccountAddIPRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2074) | :closed_lock_with_key: | POST | `sapi/v2/sub-account/subAccountApi/ipRestriction` | -| [subAccountAddIPList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2087) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | -| [subAccountEnableOrDisableIPRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2100) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction` | -| [subAccountFuturesTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2115) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/transfer` | -| [getSubAccountFuturesAccountDetail()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2121) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/account` | -| [getSubAccountDetailOnFuturesAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2127) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/account` | -| [getSubAccountDetailOnMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2133) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/account` | -| [getSubAccountDepositAddress()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2139) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subAddress` | -| [getSubAccountDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2145) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subHisrec` | -| [getSubAccountFuturesAccountSummary()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2151) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/accountSummary` | -| [getSubAccountSummaryOnFuturesAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2155) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/accountSummary` | -| [getSubAccountsSummaryOfMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2164) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/accountSummary` | -| [subAccountMarginTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2168) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/transfer` | -| [getSubAccountAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2174) | :closed_lock_with_key: | GET | `sapi/v3/sub-account/assets` | -| [getSubAccountAssetsMaster()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2180) | :closed_lock_with_key: | GET | `sapi/v4/sub-account/assets` | -| [getSubAccountFuturesAssetTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2186) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/internalTransfer` | -| [getSubAccountSpotAssetTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2195) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/sub/transfer/history` | -| [getSubAccountSpotAssetsSummary()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2201) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/spotSummary` | -| [getSubAccountUniversalTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2207) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/universalTransfer` | -| [subAccountFuturesAssetTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2213) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/internalTransfer` | -| [subAccountTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2222) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transfer/subUserHistory` | -| [subAccountTransferToMaster()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2231) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToMaster` | -| [subAccountTransferToSameMaster()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2237) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToSub` | -| [subAccountUniversalTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2243) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/universalTransfer` | -| [subAccountMovePosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2249) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/move-position` | -| [getSubAccountFuturesPositionMoveHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2258) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/move-position` | -| [depositAssetsIntoManagedSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2273) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/deposit` | -| [getManagedSubAccountDepositAddress()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2279) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/deposit/address` | -| [withdrawAssetsFromManagedSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2288) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/withdraw` | -| [getManagedSubAccountTransfersParent()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2294) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForTradeParent` | -| [getManagedSubAccountTransferLog()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2306) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/query-trans-log` | -| [getManagedSubAccountTransfersInvestor()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2318) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForInvestor` | -| [getManagedSubAccounts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2330) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/info` | -| [getManagedSubAccountSnapshot()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2337) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/accountSnapshot` | -| [getManagedSubAccountAssetDetails()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2346) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/asset` | -| [getManagedSubAccountMarginAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2352) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/marginAsset` | -| [getManagedSubAccountFuturesAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2359) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/fetch-future-asset` | -| [getAutoInvestAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2375) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/all/asset` | -| [getAutoInvestSourceAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2382) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/source-asset/list` | -| [getAutoInvestTargetAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2391) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/list` | -| [getAutoInvestTargetAssetsROI()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2400) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/roi/list` | -| [getAutoInvestIndex()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2409) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/info` | -| [getAutoInvestPlans()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2415) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/list` | -| [submitAutoInvestOneTimeTransaction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2433) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/one-off` | -| [updateAutoInvestPlanStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2449) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit-status` | -| [updateAutoInvestmentPlan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2458) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit` | -| [submitAutoInvestRedemption()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2475) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/redeem` | -| [getAutoInvestSubscriptionTransactions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2483) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/history/list` | -| [getOneTimeTransactionStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2489) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/one-off/status` | -| [submitAutoInvestmentPlan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2498) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/add` | -| [getAutoInvestRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2513) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/redeem/history` | -| [getAutoInvestPlan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2522) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/id` | -| [getAutoInvestUserIndex()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2526) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/user-summary` | -| [getAutoInvestRebalanceHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2535) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/rebalance/history` | -| [getConvertPairs()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2550) | :closed_lock_with_key: | GET | `sapi/v1/convert/exchangeInfo` | -| [getConvertAssetInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2554) | :closed_lock_with_key: | GET | `sapi/v1/convert/assetInfo` | -| [convertQuoteRequest()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2564) | :closed_lock_with_key: | POST | `sapi/v1/convert/getQuote` | -| [acceptQuoteRequest()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2568) | :closed_lock_with_key: | POST | `sapi/v1/convert/acceptQuote` | -| [getConvertTradeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2572) | :closed_lock_with_key: | GET | `sapi/v1/convert/tradeFlow` | -| [getOrderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2576) | :closed_lock_with_key: | GET | `sapi/v1/convert/orderStatus` | -| [submitConvertLimitOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2580) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/placeOrder` | -| [cancelConvertLimitOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2584) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/cancelOrder` | -| [getConvertLimitOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2588) | :closed_lock_with_key: | GET | `sapi/v1/convert/limit/queryOpenOrders` | -| [getEthStakingAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2603) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/account` | -| [getEthStakingAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2607) | :closed_lock_with_key: | GET | `sapi/v2/eth-staking/account` | -| [getEthStakingQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2611) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/quota` | -| [subscribeEthStakingV1()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2624) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/stake` | -| [subscribeEthStakingV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2630) | :closed_lock_with_key: | POST | `sapi/v2/eth-staking/eth/stake` | -| [redeemEth()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2636) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/redeem` | -| [wrapBeth()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2640) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/wbeth/wrap` | -| [getEthStakingHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2650) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/stakingHistory` | -| [getEthRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2660) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/redemptionHistory` | -| [getBethRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2670) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rewardsHistory` | -| [getWbethRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2680) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/wbethRewardsHistory` | -| [getEthRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2689) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rateHistory` | -| [getBethWrapHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2699) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/wrapHistory` | -| [getBethUnwrapHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2709) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/unwrapHistory` | -| [getBfusdAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2725) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/account` | -| [getBfusdQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2729) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/quota` | -| [subscribeBfusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2733) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/subscribe` | -| [redeemBfusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2739) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/redeem` | -| [getBfusdSubscriptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2743) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/subscriptionHistory` | -| [getBfusdRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2749) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/redemptionHistory` | -| [getBfusdRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2755) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rewardsHistory` | -| [getBfusdRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2761) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rateHistory` | -| [getRwusdAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2773) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/account` | -| [getRwusdQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2777) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/quota` | -| [subscribeRwusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2781) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/subscribe` | -| [redeemRwusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2787) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/redeem` | -| [getRwusdSubscriptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2791) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/subscriptionHistory` | -| [getRwusdRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2797) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/redemptionHistory` | -| [getRwusdRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2803) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rewardsHistory` | -| [getRwusdRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2809) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rateHistory` | -| [getStakingProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2818) | :closed_lock_with_key: | GET | `sapi/v1/staking/productList` | -| [getStakingProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2829) | :closed_lock_with_key: | GET | `sapi/v1/staking/position` | -| [getStakingHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2841) | :closed_lock_with_key: | GET | `sapi/v1/staking/stakingRecord` | -| [getPersonalLeftQuotaOfStakingProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2848) | :closed_lock_with_key: | GET | `sapi/v1/staking/personalLeftQuota` | -| [getSolStakingAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2861) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/account` | -| [getSolStakingQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2865) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/quota` | -| [subscribeSolStaking()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2875) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/stake` | -| [redeemSol()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2881) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/redeem` | -| [claimSolBoostRewards()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2885) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/claim` | -| [getSolStakingHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2897) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/stakingHistory` | -| [getSolRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2907) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/redemptionHistory` | -| [getBnsolRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2917) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/bnsolRewardsHistory` | -| [getBnsolRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2928) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/rateHistory` | -| [getSolBoostRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2938) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/boostRewardsHistory` | -| [getSolUnclaimedRewards()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2948) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/unclaimedRewards` | -| [getOnchainYieldsLockedProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2963) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/list` | -| [getOnchainYieldsLockedPersonalLeftQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2969) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/personalLeftQuota` | -| [getOnchainYieldsLockedPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2978) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/position` | -| [getOnchainYieldsAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2984) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/account` | -| [getOnchainYieldsLockedSubscriptionPreview()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2994) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/subscriptionPreview` | -| [subscribeOnchainYieldsLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3003) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/subscribe` | -| [setOnchainYieldsLockedAutoSubscribe()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3009) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setAutoSubscribe` | -| [setOnchainYieldsLockedRedeemOption()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3018) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setRedeemOption` | -| [redeemOnchainYieldsLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3027) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/redeem` | -| [getOnchainYieldsLockedSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3039) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/subscriptionRecord` | -| [getOnchainYieldsLockedRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3048) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/rewardsRecord` | -| [getOnchainYieldsLockedRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3057) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/redemptionRecord` | -| [getSoftStakingProductList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3072) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/list` | -| [setSoftStaking()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3078) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/set` | -| [getSoftStakingRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3084) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/history/rewardsRecord` | -| [getFuturesLeadTraderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3099) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/userStatus` | -| [getFuturesLeadTradingSymbolWhitelist()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3103) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/leadSymbol` | -| [getMiningAlgos()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3115) | | GET | `sapi/v1/mining/pub/algoList` | -| [getMiningCoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3119) | | GET | `sapi/v1/mining/pub/coinList` | -| [getHashrateResales()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3123) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/config/details/list` | -| [getMiners()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3132) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/list` | -| [getMinerDetails()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3136) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/detail` | -| [getExtraBonuses()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3142) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/other` | -| [getMiningEarnings()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3148) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/list` | -| [cancelHashrateResaleConfig()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3154) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config/cancel` | -| [getHashrateResale()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3163) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/profit/details` | -| [getMiningAccountEarnings()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3172) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/uid` | -| [getMiningStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3178) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/status` | -| [submitHashrateResale()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3184) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config` | -| [getMiningAccounts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3188) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/list` | -| [submitVpNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3200) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderVp` | -| [submitTwapNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3207) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderTwap` | -| [cancelAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3214) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/futures/order` | -| [getAlgoSubOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3220) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/subOrders` | -| [getAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3226) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/openOrders` | -| [getAlgoHistoricalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3233) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/historicalOrders` | -| [submitSpotAlgoTwapOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3246) | :closed_lock_with_key: | POST | `sapi/v1/algo/spot/newOrderTwap` | -| [cancelSpotAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3253) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/spot/order` | -| [getSpotAlgoSubOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3259) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/subOrders` | -| [getSpotAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3265) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/openOrders` | -| [getSpotAlgoHistoricalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3272) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/historicalOrders` | -| [getCryptoLoanFlexibleCollateralAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3287) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/collateral/data` | -| [getCryptoLoanFlexibleAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3296) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/loanable/data` | -| [borrowCryptoLoanFlexible()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3309) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/borrow` | -| [repayCryptoLoanFlexible()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3315) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay` | -| [repayCryptoLoanFlexibleWithCollateral()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3321) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay/collateral` | -| [adjustCryptoLoanFlexibleLTV()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3327) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/adjust/ltv` | -| [getCryptoLoanFlexibleLTVAdjustmentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3339) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ltv/adjustment/history` | -| [getFlexibleLoanCollateralRepayRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3351) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/rate` | -| [getLoanFlexibleBorrowHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3362) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/borrow/history` | -| [getCryptoLoanFlexibleOngoingOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3371) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ongoing/orders` | -| [getFlexibleLoanLiquidationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3380) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/liquidation/history` | -| [getLoanFlexibleRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3389) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/history` | -| [getCryptoLoanLoanableAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3407) | :closed_lock_with_key: | GET | `sapi/v1/loan/loanable/data` | -| [getCryptoLoanCollateralRepayRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3414) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/collateral/rate` | -| [getCryptoLoanCollateralAssetsData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3423) | :closed_lock_with_key: | GET | `sapi/v1/loan/collateral/data` | -| [getCryptoLoansIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3432) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | -| [borrowCryptoLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3447) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | -| [repayCryptoLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3456) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | -| [adjustCryptoLoanLTV()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3465) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | -| [customizeCryptoLoanMarginCall()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3474) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | -| [getCryptoLoanOngoingOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3490) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | -| [getCryptoLoanBorrowHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3497) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | -| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3504) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | -| [getCryptoLoanRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3513) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | -| [getSimpleEarnAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3525) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | -| [getFlexibleSavingProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3529) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | -| [getSimpleEarnLockedProductList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3536) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | -| [getFlexibleProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3545) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | -| [getLockedProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3554) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | -| [getFlexiblePersonalLeftQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3563) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | -| [getLockedPersonalLeftQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3572) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | -| [purchaseFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3587) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | -| [subscribeSimpleEarnLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3593) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | -| [redeemFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3599) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | -| [redeemLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3605) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | -| [setFlexibleAutoSubscribe()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3611) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | -| [setLockedAutoSubscribe()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3620) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | -| [getFlexibleSubscriptionPreview()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3629) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | -| [getLockedSubscriptionPreview()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3638) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | -| [setLockedProductRedeemOption()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3647) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | -| [getFlexibleSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3665) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | -| [getLockedSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3677) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | -| [getFlexibleRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3689) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | -| [getLockedRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3701) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | -| [getFlexibleRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3711) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | -| [getLockedRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3721) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | -| [getCollateralRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3731) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | -| [getRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3741) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | -| [getVipBorrowInterestRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3757) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | -| [getVipLoanInterestRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3763) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | -| [getVipLoanableAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3772) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | -| [getVipCollateralAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3779) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | -| [getVipLoanOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3792) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | -| [getVipLoanRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3799) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | -| [checkVipCollateralAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3808) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | -| [getVipApplicationStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3815) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | -| [renewVipLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3828) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | -| [repayVipLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3832) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | -| [borrowVipLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3836) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | -| [getDualInvestmentProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3846) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | -| [subscribeDualInvestmentProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3861) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | -| [getDualInvestmentPositions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3867) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | -| [getDualInvestmentAccounts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3876) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | -| [getVipLoanAccruedInterest()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3880) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | -| [updateAutoCompoundStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3887) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | -| [createGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3902) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | -| [createDualTokenGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3906) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | -| [redeemGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3910) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | -| [verifyGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3914) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | -| [getTokenLimit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3918) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | -| [getRsaPublicKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3922) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | -| [getNftTransactionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3932) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | -| [getNftDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3939) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | -| [getNftWithdrawHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3946) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | -| [getNftAsset()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3953) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | -| [getC2CTradeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3966) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | -| [getFiatOrderHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3981) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | -| [getFiatPaymentsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3987) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | -| [fiatWithdraw()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3993) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | -| [fiatDeposit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3997) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | -| [getFiatOrderDetail()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4001) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | -| [getSpotRebateHistoryRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4013) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | -| [getPortfolioMarginIndexPrice()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4026) | | GET | `sapi/v1/portfolio/asset-index-price` | -| [getPortfolioMarginAssetLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4032) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | -| [getPortfolioMarginProCollateralRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4038) | | GET | `sapi/v1/portfolio/collateralRate` | -| [getPortfolioMarginProTieredCollateralRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4044) | | GET | `sapi/v2/portfolio/collateralRate` | -| [getPortfolioMarginProAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4055) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | -| [setPortfolioMarginMarginCallLevel()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4059) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | -| [getPortfolioMarginMarginCallLevel()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4065) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | -| [deletePortfolioMarginMarginCallLevel()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4069) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | -| [bnbTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4073) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | -| [submitPortfolioMarginProFullTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4079) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | -| [submitPortfolioMarginProSpecificTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4085) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | -| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4091) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | -| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4099) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | -| [repayFuturesNegativeBalance()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4103) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | -| [updateAutoRepayFuturesStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4109) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | -| [getAutoRepayFuturesStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4115) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | -| [getPortfolioMarginProInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4121) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | -| [getPortfolioMarginProSpanAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4127) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | -| [getPortfolioMarginProAccountBalance()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4131) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | -| [mintPortfolioMarginBFUSD()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4141) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | -| [redeemPortfolioMarginBFUSD()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4151) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | -| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4159) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | -| [transferLDUSDTPortfolioMargin()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4174) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | -| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4187) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | -| [getFuturesTickLevelOrderbookDataLink()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4204) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | -| [getBlvtInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4218) | | GET | `sapi/v1/blvt/tokenInfo` | -| [subscribeBlvt()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4222) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | -| [getBlvtSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4226) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | -| [redeemBlvt()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4232) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | -| [getBlvtRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4236) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | -| [getBlvtUserLimitInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4242) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | -| [getPayTransactions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4253) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | -| [getInstLoanRiskUnit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4263) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | -| [closeInstLoanRiskUnit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4269) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | -| [addInstLoanCollateralAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4273) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | -| [getActiveInstLoanRiskUnits()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4279) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | -| [getClosedInstLoanRiskUnits()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4283) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | -| [getInstLoanForceLiquidationRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4295) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | -| [transferInstLoanRiskUnit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4309) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | -| [borrowInstitutionalLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4321) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | -| [getInstLoanInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4327) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | -| [repayInstitutionalLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4336) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | -| [getInstLoanBorrowRepayRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4342) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | -| [getMarginInterestRebateBalance()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4348) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | -| [getMarginInterestRebateBalanceRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4352) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | -| [getAlphaTokenList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4367) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | -| [getAlphaExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4374) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | -| [getAlphaAggTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4381) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | -| [getAlphaKlines()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4389) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | -| [getAlphaTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4397) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | -| [getAlphaFullDepth()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4405) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | -| [createBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4421) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [getBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4427) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | -| [enableMarginBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4433) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | -| [createApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4439) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | -| [changePermissionApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4445) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | -| [changeComissionBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4451) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | -| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4457) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | -| [updateIpRestrictionForSubAccountApiKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4466) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | -| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4480) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | -| [deleteApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4496) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | -| [getSubAccountBrokerIpRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4502) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | -| [getApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4518) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | -| [getBrokerInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4524) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | -| [updateSubAccountBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4528) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | -| [updateSubAccountMarginInterestBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4538) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | -| [getSubAccountBNBBurnStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4551) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | -| [deleteBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4567) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | -| [transferBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4577) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | -| [getBrokerSubAccountHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4583) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | -| [submitBrokerSubFuturesTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4589) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | -| [getSubAccountFuturesTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4604) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | -| [getBrokerSubDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4616) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | -| [getBrokerSubAccountSpotAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4622) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | -| [getSubAccountMarginAssetInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4631) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | -| [querySubAccountFuturesAssetInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4640) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | -| [universalTransferBroker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4649) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | -| [getUniversalTransferBroker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4656) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | -| [updateBrokerSubAccountCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4668) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | -| [updateBrokerSubAccountFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4674) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | -| [getBrokerSubAccountFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4683) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | -| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4692) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | -| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4701) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | -| [getBrokerSpotCommissionRebate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4710) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | -| [getBrokerFuturesCommissionRebate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4716) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | -| [getBrokerIfNewSpotUser()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4753) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | -| [getBrokerSubAccountDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4764) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | -| [enableFuturesBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4783) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [enableMarginApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4793) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | -| [getSpotUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4834) | | POST | `api/v3/userDataStream` | -| [keepAliveSpotUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4838) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | -| [closeSpotUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4842) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | -| [getMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4849) | | POST | `sapi/v1/userDataStream` | -| [keepAliveMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4853) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [closeMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4857) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [getIsolatedMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4862) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4870) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [closeIsolatedMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4879) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [getMarginRiskUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4891) | | POST | `sapi/v1/margin/listen-key` | -| [keepAliveMarginRiskUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4895) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginRiskUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4899) | | DELETE | `sapi/v1/margin/listen-key` | -| [getMarginListenToken()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4907) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | -| [getBSwapLiquidity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4929) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | -| [addBSwapLiquidity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4936) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | -| [removeBSwapLiquidity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4945) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | -| [getBSwapOperations()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4954) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | -| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4969) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | -| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4978) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | -| [purchaseFixedAndActivityProject()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4992) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | -| [getFixedAndActivityProjects()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5002) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | -| [getFixedAndActivityProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5011) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | -| [getLendingAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5020) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | -| [getPurchaseRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5027) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | -| [getRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5034) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | -| [getInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5041) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | -| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5048) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | -| [enableConvertSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5065) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | -| [convertBUSD()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5073) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | -| [getConvertBUSDHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5080) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | +| [testConnectivity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L784) | | GET | `api/v3/ping` | +| [getExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L788) | | GET | `api/v3/exchangeInfo` | +| [getOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L808) | | GET | `api/v3/depth` | +| [getRecentTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L812) | | GET | `api/v3/trades` | +| [getHistoricalTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L816) | | GET | `api/v3/historicalTrades` | +| [getHistoricalBlockTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L820) | | GET | `api/v3/historicalBlockTrades` | +| [getAggregateTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L826) | | GET | `api/v3/aggTrades` | +| [getKlines()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L832) | | GET | `api/v3/klines` | +| [getUIKlines()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L836) | | GET | `api/v3/uiKlines` | +| [getAvgPrice()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L840) | | GET | `api/v3/avgPrice` | +| [getExecutionRules()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L844) | | GET | `api/v3/executionRules?symbols=` | +| [getReferencePrice()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L859) | | GET | `api/v3/referencePrice` | +| [getReferencePriceCalculation()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L865) | | GET | `api/v3/referencePrice/calculation` | +| [get24hrChangeStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L872) | | GET | `api/v3/ticker/24hr?symbols=` | +| [getTradingDayTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L902) | | GET | `api/v3/ticker/tradingDay?symbols=` | +| [getSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L917) | | GET | `api/v3/ticker/price?symbols=` | +| [getSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L934) | | GET | `api/v3/ticker/bookTicker?symbols=` | +| [getRollingWindowTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L951) | | GET | `api/v3/ticker?symbols=` | +| [submitNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L973) | :closed_lock_with_key: | POST | `api/v3/order` | +| [testNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L981) | :closed_lock_with_key: | POST | `api/v3/order/test` | +| [getOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L989) | :closed_lock_with_key: | GET | `api/v3/order` | +| [cancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L993) | :closed_lock_with_key: | DELETE | `api/v3/order` | +| [cancelAllSymbolOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L997) | :closed_lock_with_key: | DELETE | `api/v3/openOrders` | +| [replaceOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1003) | :closed_lock_with_key: | POST | `api/v3/order/cancelReplace` | +| [amendOrderKeepPriority()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1017) | :closed_lock_with_key: | PUT | `fapi/v1/order/amend/keepPriority` | +| [getOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1024) | :closed_lock_with_key: | GET | `api/v3/openOrders` | +| [getAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1028) | :closed_lock_with_key: | GET | `api/v3/allOrders` | +| [submitNewOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1035) | :closed_lock_with_key: | POST | `api/v3/order/oco` | +| [submitNewOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1042) | :closed_lock_with_key: | POST | `api/v3/orderList/oco` | +| [submitNewOrderListOTO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1051) | :closed_lock_with_key: | POST | `api/v3/orderList/oto` | +| [submitNewOrderListOTOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1060) | :closed_lock_with_key: | POST | `api/v3/orderList/otoco` | +| [submitNewOrderListOPO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1070) | :closed_lock_with_key: | POST | `api/v3/orderList/opo` | +| [submitNewOrderListOPOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1079) | :closed_lock_with_key: | POST | `api/v3/orderList/opoco` | +| [cancelOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1089) | :closed_lock_with_key: | DELETE | `api/v3/orderList` | +| [getOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1094) | :closed_lock_with_key: | GET | `api/v3/orderList` | +| [getAllOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1098) | :closed_lock_with_key: | GET | `api/v3/allOrderList` | +| [getAllOpenOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1105) | :closed_lock_with_key: | GET | `api/v3/openOrderList` | +| [submitNewSOROrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1112) | :closed_lock_with_key: | POST | `api/v3/sor/order` | +| [testNewSOROrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1123) | :closed_lock_with_key: | POST | `api/v3/sor/order/test` | +| [getAccountInformation()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1139) | :closed_lock_with_key: | GET | `api/v3/account` | +| [getAccountTradeList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1145) | :closed_lock_with_key: | GET | `api/v3/myTrades` | +| [getOrderRateLimit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1151) | :closed_lock_with_key: | GET | `api/v3/rateLimit/order` | +| [getPreventedMatches()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1155) | :closed_lock_with_key: | GET | `api/v3/myPreventedMatches` | +| [getAllocations()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1161) | :closed_lock_with_key: | GET | `api/v3/myAllocations` | +| [getCommissionRates()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1165) | :closed_lock_with_key: | GET | `api/v3/account/commission` | +| [getCrossMarginCollateralRatio()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1175) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginCollateralRatio` | +| [getAllCrossMarginPairs()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1184) | | GET | `sapi/v1/margin/allPairs` | +| [getIsolatedMarginAllSymbols()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1188) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/allPairs` | +| [getAllMarginAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1194) | | GET | `sapi/v1/margin/allAssets` | +| [getMarginDelistSchedule()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1198) | :closed_lock_with_key: | GET | `sapi/v1/margin/delist-schedule` | +| [getIsolatedMarginTierData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1202) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginTier` | +| [queryMarginPriceIndex()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1208) | | GET | `sapi/v1/margin/priceIndex` | +| [getMarginAvailableInventory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1214) | :closed_lock_with_key: | GET | `sapi/v1/margin/available-inventory` | +| [getLeverageBracket()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1220) | :closed_lock_with_key: | GET | `sapi/v1/margin/leverageBracket` | +| [getNextHourlyInterestRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1230) | :closed_lock_with_key: | GET | `sapi/v1/margin/next-hourly-interest-rate` | +| [getMarginInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1236) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestHistory` | +| [submitMarginAccountBorrowRepay()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1243) | :closed_lock_with_key: | POST | `sapi/v1/margin/borrow-repay` | +| [getMarginAccountBorrowRepayRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1249) | :closed_lock_with_key: | GET | `sapi/v1/margin/borrow-repay` | +| [getMarginInterestRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1255) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestRateHistory` | +| [queryMaxBorrow()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1261) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxBorrowable` | +| [getMarginForceLiquidationRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1273) | :closed_lock_with_key: | GET | `sapi/v1/margin/forceLiquidationRec` | +| [getSmallLiabilityExchangeCoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1282) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability` | +| [getSmallLiabilityExchangeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1286) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability-history` | +| [marginAccountCancelOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1298) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/openOrders` | +| [marginAccountCancelOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1304) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/orderList` | +| [marginAccountCancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1309) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/order` | +| [marginAccountNewOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1315) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oco` | +| [marginAccountNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1322) | :closed_lock_with_key: | POST | `sapi/v1/margin/order` | +| [getMarginOrderCountUsage()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1330) | :closed_lock_with_key: | GET | `sapi/v1/margin/rateLimit/order` | +| [queryMarginAccountAllOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1336) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrderList` | +| [queryMarginAccountAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1342) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrders` | +| [queryMarginAccountOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1348) | :closed_lock_with_key: | GET | `sapi/v1/margin/orderList` | +| [queryMarginAccountOpenOCO()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1352) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrderList` | +| [queryMarginAccountOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1359) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrders` | +| [queryMarginAccountOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1363) | :closed_lock_with_key: | GET | `sapi/v1/margin/order` | +| [queryMarginAccountTradeList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1367) | :closed_lock_with_key: | GET | `sapi/v1/margin/myTrades` | +| [submitSmallLiabilityExchange()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1373) | :closed_lock_with_key: | POST | `sapi/v1/margin/exchange-small-liability` | +| [submitManualLiquidation()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1380) | :closed_lock_with_key: | POST | `sapi/v1/margin/manual-liquidation` | +| [submitMarginOTOOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1389) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oto` | +| [submitMarginOTOCOOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1401) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/otoco` | +| [createMarginSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1414) | :closed_lock_with_key: | POST | `sapi/v1/margin/apiKey` | +| [deleteMarginSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1420) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/apiKey` | +| [updateMarginIPForSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1428) | :closed_lock_with_key: | PUT | `sapi/v1/margin/apiKey/ip` | +| [getMarginSpecialLowLatencyKeys()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1439) | :closed_lock_with_key: | GET | `sapi/v1/margin/api-key-list` | +| [getMarginSpecialLowLatencyKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1448) | :closed_lock_with_key: | GET | `sapi/v1/margin/apiKey` | +| [getMarginLiquidationLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1458) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan` | +| [repayMarginLiquidationLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1465) | :closed_lock_with_key: | POST | `sapi/v1/margin/liquidation-loan/repay` | +| [getMarginLiquidationLoanRepayHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1474) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan/repay-history` | +| [exitMarginSpecialKeyMode()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1486) | :closed_lock_with_key: | POST | `sapi/v1/margin/exit-special-key-mode` | +| [getCrossMarginTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1496) | :closed_lock_with_key: | GET | `sapi/v1/margin/transfer` | +| [queryMaxTransferOutAmount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1502) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxTransferable` | +| [updateCrossMarginMaxLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1514) | :closed_lock_with_key: | POST | `sapi/v1/margin/max-leverage` | +| [disableIsolatedMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1520) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/isolated/account` | +| [enableIsolatedMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1527) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/account` | +| [getBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1534) | :closed_lock_with_key: | GET | `sapi/v1/bnbBurn` | +| [getMarginSummary()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1538) | :closed_lock_with_key: | GET | `sapi/v1/margin/tradeCoeff` | +| [queryCrossMarginAccountDetails()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1542) | :closed_lock_with_key: | GET | `sapi/v1/margin/account` | +| [getCrossMarginFeeData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1546) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginData` | +| [getIsolatedMarginAccountLimit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1552) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/accountLimit` | +| [getIsolatedMarginAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1559) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/account` | +| [getIsolatedMarginFeeData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1565) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginData` | +| [toggleBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1571) | :closed_lock_with_key: | POST | `sapi/v1/bnbBurn` | +| [getMarginCapitalFlow()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1579) | :closed_lock_with_key: | GET | `sapi/v1/margin/capital-flow` | +| [queryLoanRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1588) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan` | +| [queryRepayRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1597) | :closed_lock_with_key: | GET | `sapi/v1/margin/repay` | +| [isolatedMarginAccountTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1606) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/transfer` | +| [getBalances()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1618) | :closed_lock_with_key: | GET | `sapi/v1/capital/config/getall` | +| [withdraw()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1622) | :closed_lock_with_key: | POST | `sapi/v1/capital/withdraw/apply` | +| [getWithdrawHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1626) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/history` | +| [getWithdrawAddresses()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1632) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/address/list` | +| [getWithdrawQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1636) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/quota` | +| [getDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1643) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/hisrec` | +| [getDepositAddress()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1647) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address` | +| [getDepositAddresses()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1653) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address/list` | +| [submitDepositCredit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1659) | :closed_lock_with_key: | POST | `sapi/v1/capital/deposit/credit-apply` | +| [getAutoConvertStablecoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1668) | :closed_lock_with_key: | GET | `sapi/v1/capital/contract/convertible-coins` | +| [setConvertibleCoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1675) | :closed_lock_with_key: | POST | `sapi/v1/capital/contract/convertible-coins` | +| [getAssetDetail()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1688) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDetail` | +| [getWalletBalances()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1694) | :closed_lock_with_key: | GET | `sapi/v1/asset/wallet/balance` | +| [getUserAsset()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1700) | :closed_lock_with_key: | POST | `sapi/v3/asset/getUserAsset` | +| [submitUniversalTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1704) | :closed_lock_with_key: | POST | `sapi/v1/asset/transfer` | +| [getUniversalTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1710) | :closed_lock_with_key: | GET | `sapi/v1/asset/transfer` | +| [getDust()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1716) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-btc` | +| [convertDustToBnb()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1720) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust` | +| [convertDustAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1727) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/convert` | +| [queryDustConvertibleAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1734) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/query-convertible-assets` | +| [getDustLog()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1743) | :closed_lock_with_key: | GET | `sapi/v1/asset/dribblet` | +| [getAssetDividendRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1747) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDividend` | +| [getTradeFee()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1751) | :closed_lock_with_key: | GET | `sapi/v1/asset/tradeFee` | +| [getFundingAsset()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1755) | :closed_lock_with_key: | POST | `sapi/v1/asset/get-funding-asset` | +| [getCloudMiningHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1759) | :closed_lock_with_key: | GET | `sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage` | +| [getDelegationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1769) | :closed_lock_with_key: | GET | `sapi/v1/asset/custody/transfer-history` | +| [submitNewFutureAccountTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1799) | :closed_lock_with_key: | POST | `sapi/v1/futures/transfer` | +| [getFutureAccountTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1809) | :closed_lock_with_key: | GET | `sapi/v1/futures/transfer` | +| [getCrossCollateralBorrowHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1818) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/borrow/history` | +| [getCrossCollateralRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1825) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/repay/history` | +| [getCrossCollateralWalletV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1832) | :closed_lock_with_key: | GET | `sapi/v2/futures/loan/wallet` | +| [getAdjustCrossCollateralLTVHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1839) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/adjustCollateral/history` | +| [getCrossCollateralLiquidationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1851) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/liquidationHistory` | +| [getCrossCollateralInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1860) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/interestHistory` | +| [getAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1872) | :closed_lock_with_key: | GET | `sapi/v1/account/info` | +| [getDailyAccountSnapshot()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1876) | :closed_lock_with_key: | GET | `sapi/v1/accountSnapshot` | +| [disableFastWithdrawSwitch()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1882) | :closed_lock_with_key: | POST | `sapi/v1/account/disableFastWithdrawSwitch` | +| [enableFastWithdrawSwitch()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1886) | :closed_lock_with_key: | POST | `sapi/v1/account/enableFastWithdrawSwitch` | +| [getAccountStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1890) | :closed_lock_with_key: | GET | `sapi/v1/account/status` | +| [getApiTradingStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1894) | :closed_lock_with_key: | GET | `sapi/v1/account/apiTradingStatus` | +| [getApiKeyPermissions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1898) | :closed_lock_with_key: | GET | `sapi/v1/account/apiRestrictions` | +| [withdrawTravelRule()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1914) | :closed_lock_with_key: | POST | `sapi/v1/localentity/withdraw/apply` | +| [getTravelRuleWithdrawHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1925) | :closed_lock_with_key: | GET | `sapi/v1/localentity/withdraw/history` | +| [getTravelRuleWithdrawHistoryV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1934) | :closed_lock_with_key: | GET | `sapi/v2/localentity/withdraw/history` | +| [submitTravelRuleDepositQuestionnaire()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1946) | :closed_lock_with_key: | PUT | `sapi/v1/localentity/deposit/provide-info` | +| [getTravelRuleDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1955) | :closed_lock_with_key: | GET | `sapi/v1/localentity/deposit/history` | +| [getOnboardedVASPList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1966) | :closed_lock_with_key: | GET | `sapi/v1/localentity/vasp` | +| [getTravelRuleCountryList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1970) | :closed_lock_with_key: | GET | `sapi/v1/localentity/country/list` | +| [getTravelRuleRegionList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1974) | :closed_lock_with_key: | GET | `sapi/v1/localentity/region/list` | +| [getSystemStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1986) | | GET | `sapi/v1/system/status` | +| [getDelistSchedule()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L1990) | :closed_lock_with_key: | GET | `sapi/v1/spot/delist-schedule` | +| [createVirtualSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2000) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/virtualSubAccount` | +| [getSubAccountList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2006) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/list` | +| [subAccountEnableFutures()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2012) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/enable` | +| [subAccountEnableMargin()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2020) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/enable` | +| [enableOptionsForSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2024) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/eoptions/enable` | +| [subAccountEnableLeverageToken()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2034) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/blvt/enable` | +| [getSubAccountStatusOnMarginOrFutures()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2040) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/status` | +| [getSubAccountFuturesPositionRisk()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2046) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/positionRisk` | +| [getSubAccountFuturesPositionRiskV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2054) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/positionRisk` | +| [getSubAccountTransactionStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2060) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transaction-statistics` | +| [getSubAccountIPRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2075) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/subAccountApi/ipRestriction` | +| [subAccountDeleteIPList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2084) | :closed_lock_with_key: | DELETE | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | +| [subAccountAddIPRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2093) | :closed_lock_with_key: | POST | `sapi/v2/sub-account/subAccountApi/ipRestriction` | +| [subAccountAddIPList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2106) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | +| [subAccountEnableOrDisableIPRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2119) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction` | +| [subAccountFuturesTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2134) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/transfer` | +| [getSubAccountFuturesAccountDetail()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2140) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/account` | +| [getSubAccountDetailOnFuturesAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2146) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/account` | +| [getSubAccountDetailOnMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2152) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/account` | +| [getSubAccountDepositAddress()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2158) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subAddress` | +| [getSubAccountDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2164) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subHisrec` | +| [getSubAccountFuturesAccountSummary()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2170) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/accountSummary` | +| [getSubAccountSummaryOnFuturesAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2174) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/accountSummary` | +| [getSubAccountsSummaryOfMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2183) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/accountSummary` | +| [subAccountMarginTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2187) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/transfer` | +| [getSubAccountAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2193) | :closed_lock_with_key: | GET | `sapi/v3/sub-account/assets` | +| [getSubAccountAssetsMaster()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2199) | :closed_lock_with_key: | GET | `sapi/v4/sub-account/assets` | +| [getSubAccountFuturesAssetTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2205) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/internalTransfer` | +| [getSubAccountSpotAssetTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2214) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/sub/transfer/history` | +| [getSubAccountSpotAssetsSummary()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2220) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/spotSummary` | +| [getSubAccountUniversalTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2226) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/universalTransfer` | +| [subAccountFuturesAssetTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2232) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/internalTransfer` | +| [subAccountTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2241) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transfer/subUserHistory` | +| [subAccountTransferToMaster()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2250) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToMaster` | +| [subAccountTransferToSameMaster()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2256) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToSub` | +| [subAccountUniversalTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2262) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/universalTransfer` | +| [subAccountMovePosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2268) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/move-position` | +| [getSubAccountFuturesPositionMoveHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2277) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/move-position` | +| [depositAssetsIntoManagedSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2292) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/deposit` | +| [getManagedSubAccountDepositAddress()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2298) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/deposit/address` | +| [withdrawAssetsFromManagedSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2307) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/withdraw` | +| [getManagedSubAccountTransfersParent()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2313) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForTradeParent` | +| [getManagedSubAccountTransferLog()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2325) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/query-trans-log` | +| [getManagedSubAccountTransfersInvestor()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2337) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForInvestor` | +| [getManagedSubAccounts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2349) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/info` | +| [getManagedSubAccountSnapshot()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2356) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/accountSnapshot` | +| [getManagedSubAccountAssetDetails()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2365) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/asset` | +| [getManagedSubAccountMarginAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2371) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/marginAsset` | +| [getManagedSubAccountFuturesAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2378) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/fetch-future-asset` | +| [getAutoInvestAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2394) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/all/asset` | +| [getAutoInvestSourceAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2401) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/source-asset/list` | +| [getAutoInvestTargetAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2410) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/list` | +| [getAutoInvestTargetAssetsROI()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2419) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/roi/list` | +| [getAutoInvestIndex()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2428) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/info` | +| [getAutoInvestPlans()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2434) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/list` | +| [submitAutoInvestOneTimeTransaction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2452) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/one-off` | +| [updateAutoInvestPlanStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2468) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit-status` | +| [updateAutoInvestmentPlan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2477) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit` | +| [submitAutoInvestRedemption()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2494) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/redeem` | +| [getAutoInvestSubscriptionTransactions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2502) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/history/list` | +| [getOneTimeTransactionStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2508) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/one-off/status` | +| [submitAutoInvestmentPlan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2517) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/add` | +| [getAutoInvestRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2532) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/redeem/history` | +| [getAutoInvestPlan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2541) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/id` | +| [getAutoInvestUserIndex()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2545) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/user-summary` | +| [getAutoInvestRebalanceHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2554) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/rebalance/history` | +| [getConvertPairs()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2569) | :closed_lock_with_key: | GET | `sapi/v1/convert/exchangeInfo` | +| [getConvertAssetInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2573) | :closed_lock_with_key: | GET | `sapi/v1/convert/assetInfo` | +| [convertQuoteRequest()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2583) | :closed_lock_with_key: | POST | `sapi/v1/convert/getQuote` | +| [acceptQuoteRequest()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2587) | :closed_lock_with_key: | POST | `sapi/v1/convert/acceptQuote` | +| [getConvertTradeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2591) | :closed_lock_with_key: | GET | `sapi/v1/convert/tradeFlow` | +| [getOrderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2595) | :closed_lock_with_key: | GET | `sapi/v1/convert/orderStatus` | +| [submitConvertLimitOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2599) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/placeOrder` | +| [cancelConvertLimitOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2603) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/cancelOrder` | +| [getConvertLimitOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2607) | :closed_lock_with_key: | GET | `sapi/v1/convert/limit/queryOpenOrders` | +| [getEthStakingAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2622) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/account` | +| [getEthStakingAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2626) | :closed_lock_with_key: | GET | `sapi/v2/eth-staking/account` | +| [getEthStakingQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2630) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/quota` | +| [subscribeEthStakingV1()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2643) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/stake` | +| [subscribeEthStakingV2()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2649) | :closed_lock_with_key: | POST | `sapi/v2/eth-staking/eth/stake` | +| [redeemEth()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2655) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/redeem` | +| [wrapBeth()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2659) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/wbeth/wrap` | +| [getEthStakingHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2669) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/stakingHistory` | +| [getEthRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2679) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/redemptionHistory` | +| [getBethRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2689) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rewardsHistory` | +| [getWbethRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2699) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/wbethRewardsHistory` | +| [getEthRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2708) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rateHistory` | +| [getBethWrapHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2718) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/wrapHistory` | +| [getBethUnwrapHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2728) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/unwrapHistory` | +| [getBfusdAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2744) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/account` | +| [getBfusdQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2748) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/quota` | +| [subscribeBfusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2752) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/subscribe` | +| [redeemBfusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2758) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/redeem` | +| [getBfusdSubscriptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2762) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/subscriptionHistory` | +| [getBfusdRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2768) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/redemptionHistory` | +| [getBfusdRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2774) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rewardsHistory` | +| [getBfusdRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2780) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rateHistory` | +| [getRwusdAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2792) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/account` | +| [getRwusdQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2796) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/quota` | +| [subscribeRwusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2800) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/subscribe` | +| [redeemRwusd()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2806) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/redeem` | +| [getRwusdSubscriptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2810) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/subscriptionHistory` | +| [getRwusdRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2816) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/redemptionHistory` | +| [getRwusdRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2822) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rewardsHistory` | +| [getRwusdRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2828) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rateHistory` | +| [getStakingProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2837) | :closed_lock_with_key: | GET | `sapi/v1/staking/productList` | +| [getStakingProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2848) | :closed_lock_with_key: | GET | `sapi/v1/staking/position` | +| [getStakingHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2860) | :closed_lock_with_key: | GET | `sapi/v1/staking/stakingRecord` | +| [getPersonalLeftQuotaOfStakingProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2867) | :closed_lock_with_key: | GET | `sapi/v1/staking/personalLeftQuota` | +| [getSolStakingAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2880) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/account` | +| [getSolStakingQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2884) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/quota` | +| [subscribeSolStaking()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2894) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/stake` | +| [redeemSol()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2900) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/redeem` | +| [claimSolBoostRewards()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2904) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/claim` | +| [getSolStakingHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2916) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/stakingHistory` | +| [getSolRedemptionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2926) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/redemptionHistory` | +| [getBnsolRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2936) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/bnsolRewardsHistory` | +| [getBnsolRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2947) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/rateHistory` | +| [getSolBoostRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2957) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/boostRewardsHistory` | +| [getSolUnclaimedRewards()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2967) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/unclaimedRewards` | +| [getOnchainYieldsLockedProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2982) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/list` | +| [getOnchainYieldsLockedPersonalLeftQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2988) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/personalLeftQuota` | +| [getOnchainYieldsLockedPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L2997) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/position` | +| [getOnchainYieldsAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3003) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/account` | +| [getOnchainYieldsLockedSubscriptionPreview()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3013) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/subscriptionPreview` | +| [subscribeOnchainYieldsLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3022) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/subscribe` | +| [setOnchainYieldsLockedAutoSubscribe()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3028) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setAutoSubscribe` | +| [setOnchainYieldsLockedRedeemOption()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3037) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setRedeemOption` | +| [redeemOnchainYieldsLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3046) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/redeem` | +| [getOnchainYieldsLockedSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3058) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/subscriptionRecord` | +| [getOnchainYieldsLockedRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3067) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/rewardsRecord` | +| [getOnchainYieldsLockedRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3076) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/redemptionRecord` | +| [getSoftStakingProductList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3091) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/list` | +| [setSoftStaking()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3097) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/set` | +| [getSoftStakingRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3103) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/history/rewardsRecord` | +| [getFuturesLeadTraderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3118) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/userStatus` | +| [getFuturesLeadTradingSymbolWhitelist()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3122) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/leadSymbol` | +| [getMiningAlgos()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3134) | | GET | `sapi/v1/mining/pub/algoList` | +| [getMiningCoins()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3138) | | GET | `sapi/v1/mining/pub/coinList` | +| [getHashrateResales()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3142) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/config/details/list` | +| [getMiners()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3151) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/list` | +| [getMinerDetails()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3155) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/detail` | +| [getExtraBonuses()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3161) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/other` | +| [getMiningEarnings()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3167) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/list` | +| [cancelHashrateResaleConfig()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3173) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config/cancel` | +| [getHashrateResale()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3182) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/profit/details` | +| [getMiningAccountEarnings()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3191) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/uid` | +| [getMiningStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3197) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/status` | +| [submitHashrateResale()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3203) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config` | +| [getMiningAccounts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3207) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/list` | +| [submitVpNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3219) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderVp` | +| [submitTwapNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3226) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderTwap` | +| [cancelAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3233) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/futures/order` | +| [getAlgoSubOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3239) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/subOrders` | +| [getAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3245) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/openOrders` | +| [getAlgoHistoricalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3252) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/historicalOrders` | +| [submitSpotAlgoTwapOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3265) | :closed_lock_with_key: | POST | `sapi/v1/algo/spot/newOrderTwap` | +| [cancelSpotAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3272) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/spot/order` | +| [getSpotAlgoSubOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3278) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/subOrders` | +| [getSpotAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3284) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/openOrders` | +| [getSpotAlgoHistoricalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3291) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/historicalOrders` | +| [getCryptoLoanFlexibleCollateralAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3306) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/collateral/data` | +| [getCryptoLoanFlexibleAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3315) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/loanable/data` | +| [borrowCryptoLoanFlexible()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3328) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/borrow` | +| [repayCryptoLoanFlexible()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3334) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay` | +| [repayCryptoLoanFlexibleWithCollateral()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3340) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay/collateral` | +| [adjustCryptoLoanFlexibleLTV()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3346) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/adjust/ltv` | +| [getCryptoLoanFlexibleLTVAdjustmentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3358) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ltv/adjustment/history` | +| [getFlexibleLoanCollateralRepayRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3370) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/rate` | +| [getLoanFlexibleBorrowHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3381) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/borrow/history` | +| [getCryptoLoanFlexibleOngoingOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3390) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ongoing/orders` | +| [getFlexibleLoanLiquidationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3399) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/liquidation/history` | +| [getLoanFlexibleRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3408) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/history` | +| [getCryptoLoanLoanableAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3426) | :closed_lock_with_key: | GET | `sapi/v1/loan/loanable/data` | +| [getCryptoLoanCollateralRepayRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3433) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/collateral/rate` | +| [getCryptoLoanCollateralAssetsData()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3442) | :closed_lock_with_key: | GET | `sapi/v1/loan/collateral/data` | +| [getCryptoLoansIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3451) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | +| [borrowCryptoLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3466) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | +| [repayCryptoLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3475) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | +| [adjustCryptoLoanLTV()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3484) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | +| [customizeCryptoLoanMarginCall()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3493) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | +| [getCryptoLoanOngoingOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3509) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | +| [getCryptoLoanBorrowHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3516) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | +| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3523) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | +| [getCryptoLoanRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3532) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | +| [getSimpleEarnAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3544) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | +| [getFlexibleSavingProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3548) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | +| [getSimpleEarnLockedProductList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3555) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | +| [getFlexibleProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3564) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | +| [getLockedProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3573) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | +| [getFlexiblePersonalLeftQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3582) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | +| [getLockedPersonalLeftQuota()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3591) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | +| [purchaseFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3606) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | +| [subscribeSimpleEarnLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3612) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | +| [redeemFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3618) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | +| [redeemLockedProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3624) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | +| [setFlexibleAutoSubscribe()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3630) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | +| [setLockedAutoSubscribe()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3639) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | +| [getFlexibleSubscriptionPreview()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3648) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | +| [getLockedSubscriptionPreview()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3657) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | +| [setLockedProductRedeemOption()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3666) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | +| [getFlexibleSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3684) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | +| [getLockedSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3696) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | +| [getFlexibleRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3708) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | +| [getLockedRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3720) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | +| [getFlexibleRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3730) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | +| [getLockedRewardsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3740) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | +| [getCollateralRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3750) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | +| [getRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3760) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | +| [getVipBorrowInterestRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3776) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | +| [getVipLoanInterestRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3782) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | +| [getVipLoanableAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3791) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | +| [getVipCollateralAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3798) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | +| [getVipLoanOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3811) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | +| [getVipLoanRepaymentHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3818) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | +| [checkVipCollateralAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3827) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | +| [getVipApplicationStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3834) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | +| [renewVipLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3847) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | +| [repayVipLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3851) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | +| [borrowVipLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3855) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | +| [getVipLoanFixedRateMarket()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3859) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/fixed/market` | +| [borrowVipLoanFixedRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3866) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/fixed/borrow` | +| [getDualInvestmentProducts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3878) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | +| [subscribeDualInvestmentProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3893) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | +| [getDualInvestmentPositions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3899) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | +| [getDualInvestmentAccounts()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3908) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | +| [getVipLoanAccruedInterest()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3912) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | +| [updateAutoCompoundStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3919) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | +| [createGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3934) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | +| [createDualTokenGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3938) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | +| [redeemGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3942) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | +| [verifyGiftCard()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3946) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | +| [getTokenLimit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3950) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | +| [getRsaPublicKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3954) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | +| [getNftTransactionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3964) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | +| [getNftDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3971) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | +| [getNftWithdrawHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3978) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | +| [getNftAsset()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3985) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | +| [getC2CTradeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L3998) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | +| [getFiatOrderHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4013) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | +| [getFiatPaymentsHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4019) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | +| [fiatWithdraw()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4025) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | +| [fiatDeposit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4029) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | +| [getFiatOrderDetail()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4033) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | +| [getSpotRebateHistoryRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4045) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | +| [getPortfolioMarginIndexPrice()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4058) | | GET | `sapi/v1/portfolio/asset-index-price` | +| [getPortfolioMarginAssetLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4064) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | +| [getPortfolioMarginProCollateralRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4070) | | GET | `sapi/v1/portfolio/collateralRate` | +| [getPortfolioMarginProTieredCollateralRate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4076) | | GET | `sapi/v2/portfolio/collateralRate` | +| [getPortfolioMarginProAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4087) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | +| [setPortfolioMarginMarginCallLevel()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4091) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | +| [getPortfolioMarginMarginCallLevel()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4097) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | +| [deletePortfolioMarginMarginCallLevel()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4101) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | +| [bnbTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4105) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | +| [submitPortfolioMarginProFullTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4111) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | +| [submitPortfolioMarginProSpecificTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4117) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | +| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4123) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | +| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4131) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | +| [repayFuturesNegativeBalance()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4135) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | +| [updateAutoRepayFuturesStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4141) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | +| [getAutoRepayFuturesStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4147) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | +| [getPortfolioMarginProInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4153) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | +| [getPortfolioMarginProSpanAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4159) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | +| [getPortfolioMarginProAccountBalance()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4163) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | +| [mintPortfolioMarginBFUSD()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4173) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | +| [redeemPortfolioMarginBFUSD()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4183) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | +| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4191) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | +| [transferLDUSDTPortfolioMargin()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4206) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | +| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4219) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | +| [getFuturesTickLevelOrderbookDataLink()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4236) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | +| [getBlvtInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4250) | | GET | `sapi/v1/blvt/tokenInfo` | +| [subscribeBlvt()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4254) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | +| [getBlvtSubscriptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4258) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | +| [redeemBlvt()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4264) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | +| [getBlvtRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4268) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | +| [getBlvtUserLimitInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4274) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | +| [getPayTransactions()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4285) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | +| [getInstLoanRiskUnit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4295) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | +| [closeInstLoanRiskUnit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4301) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | +| [addInstLoanCollateralAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4305) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | +| [getActiveInstLoanRiskUnits()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4311) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | +| [getClosedInstLoanRiskUnits()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4315) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | +| [getInstLoanForceLiquidationRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4327) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | +| [transferInstLoanRiskUnit()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4341) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | +| [getInstitutionalLoanMaxBorrowable()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4353) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/max-borrowable` | +| [borrowInstitutionalLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4359) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | +| [getInstLoanInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4365) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | +| [repayInstitutionalLoan()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4374) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | +| [getInstLoanBorrowRepayRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4380) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | +| [getMarginInterestRebateBalance()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4386) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | +| [getMarginInterestRebateBalanceRecords()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4390) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | +| [getAlphaTokenList()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4405) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | +| [getAlphaExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4412) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | +| [getAlphaAggTrades()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4419) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | +| [getAlphaKlines()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4427) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | +| [getAlphaTicker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4435) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | +| [getAlphaFullDepth()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4443) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | +| [createBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4459) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [getBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4465) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | +| [enableMarginBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4471) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | +| [createApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4477) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | +| [changePermissionApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4483) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [changeComissionBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4489) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4495) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | +| [updateIpRestrictionForSubAccountApiKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4504) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | +| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4518) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | +| [deleteApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4534) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | +| [getSubAccountBrokerIpRestriction()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4540) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | +| [getApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4556) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | +| [getBrokerInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4562) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | +| [updateSubAccountBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4566) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | +| [updateSubAccountMarginInterestBNBBurn()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4576) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | +| [getSubAccountBNBBurnStatus()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4589) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | +| [deleteBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4605) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | +| [transferBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4615) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | +| [getBrokerSubAccountHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4621) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | +| [submitBrokerSubFuturesTransfer()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4627) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | +| [getSubAccountFuturesTransferHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4642) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | +| [getBrokerSubDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4654) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | +| [getBrokerSubAccountSpotAssets()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4660) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | +| [getSubAccountMarginAssetInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4669) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | +| [querySubAccountFuturesAssetInfo()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4678) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | +| [universalTransferBroker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4687) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | +| [getUniversalTransferBroker()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4694) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | +| [updateBrokerSubAccountCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4706) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | +| [updateBrokerSubAccountFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4712) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | +| [getBrokerSubAccountFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4721) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | +| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4730) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4739) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSpotCommissionRebate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4748) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | +| [getBrokerFuturesCommissionRebate()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4754) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | +| [getBrokerIfNewSpotUser()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4791) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | +| [getBrokerSubAccountDepositHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4802) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | +| [enableFuturesBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4821) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [enableMarginApiKeyBrokerSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4831) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | +| [getSpotUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4872) | | POST | `api/v3/userDataStream` | +| [keepAliveSpotUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4876) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | +| [closeSpotUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4880) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | +| [getMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4887) | | POST | `sapi/v1/userDataStream` | +| [keepAliveMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4891) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [closeMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4895) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [getIsolatedMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4900) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4908) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [closeIsolatedMarginUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4917) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [getMarginRiskUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4929) | | POST | `sapi/v1/margin/listen-key` | +| [keepAliveMarginRiskUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4933) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginRiskUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4937) | | DELETE | `sapi/v1/margin/listen-key` | +| [getMarginListenToken()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4945) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | +| [getBSwapLiquidity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4967) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | +| [addBSwapLiquidity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4974) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | +| [removeBSwapLiquidity()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4983) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | +| [getBSwapOperations()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L4992) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | +| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5007) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | +| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5016) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | +| [purchaseFixedAndActivityProject()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5030) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | +| [getFixedAndActivityProjects()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5040) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | +| [getFixedAndActivityProductPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5049) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | +| [getLendingAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5058) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | +| [getPurchaseRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5065) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | +| [getRedemptionRecord()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5072) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | +| [getInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5079) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | +| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5086) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | +| [enableConvertSubAccount()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5103) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | +| [convertBUSD()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5111) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | +| [getConvertBUSDHistory()](https://github.com/tiagosiebler/binance/blob/master/src/main-client.ts#L5118) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | # usdm-client.ts @@ -686,79 +691,82 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [testConnectivity()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L122) | | GET | `dapi/v1/ping` | -| [getExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L126) | | GET | `dapi/v1/exchangeInfo` | -| [getOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L130) | | GET | `dapi/v1/depth` | -| [getRecentTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L134) | | GET | `dapi/v1/trades` | -| [getHistoricalTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L138) | | GET | `dapi/v1/historicalTrades` | -| [getAggregateTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L144) | | GET | `dapi/v1/aggTrades` | -| [getMarkPrice()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L153) | | GET | `dapi/v1/premiumIndex` | -| [getFundingRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L157) | | GET | `dapi/v1/fundingRate` | -| [getFundingRate()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L163) | | GET | `dapi/v1/fundingInfo` | -| [getKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L167) | | GET | `dapi/v1/klines` | -| [getContinuousContractKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L171) | | GET | `dapi/v1/continuousKlines` | -| [getIndexPriceKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L177) | | GET | `dapi/v1/indexPriceKlines` | -| [getMarkPriceKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L181) | | GET | `dapi/v1/markPriceKlines` | -| [getPremiumIndexKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L185) | | GET | `dapi/v1/premiumIndexKlines` | -| [get24hrChangeStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L189) | | GET | `dapi/v1/ticker/24hr` | -| [getSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L196) | | GET | `dapi/v1/ticker/price` | -| [getSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L203) | | GET | `dapi/v1/ticker/bookTicker` | -| [getOpenInterest()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L212) | | GET | `dapi/v1/openInterest` | -| [getOpenInterestStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L216) | | GET | `futures/data/openInterestHist` | -| [getTopTradersLongShortAccountRatio()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L220) | | GET | `futures/data/topLongShortAccountRatio` | -| [getTopTradersLongShortPositionRatio()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L226) | | GET | `futures/data/topLongShortPositionRatio` | -| [getGlobalLongShortAccountRatio()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L232) | | GET | `futures/data/globalLongShortAccountRatio` | -| [getTakerBuySellVolume()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L238) | | GET | `futures/data/takerBuySellVol` | -| [getCompositeSymbolIndex()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L244) | | GET | `futures/data/basis` | -| [getIndexPriceConstituents()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L252) | | GET | `dapi/v1/constituents` | -| [getQuarterlyContractSettlementPrices()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L262) | | GET | `futures/data/delivery-price` | -| [submitNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L274) | :closed_lock_with_key: | POST | `dapi/v1/order` | -| [submitMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L284) | :closed_lock_with_key: | POST | `dapi/v1/batchOrders` | -| [modifyOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L301) | :closed_lock_with_key: | PUT | `dapi/v1/order` | -| [modifyMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L310) | :closed_lock_with_key: | PUT | `dapi/v1/batchOrders` | -| [getOrderModifyHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L323) | :closed_lock_with_key: | GET | `dapi/v1/orderAmendment` | -| [cancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L329) | :closed_lock_with_key: | DELETE | `dapi/v1/order` | -| [cancelMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L333) | :closed_lock_with_key: | DELETE | `dapi/v1/batchOrders` | -| [cancelAllOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L353) | :closed_lock_with_key: | DELETE | `dapi/v1/allOpenOrders` | -| [setCancelOrdersOnTimeout()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L360) | :closed_lock_with_key: | POST | `dapi/v1/countdownCancelAll` | -| [getOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L366) | :closed_lock_with_key: | GET | `dapi/v1/order` | -| [getAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L370) | :closed_lock_with_key: | GET | `dapi/v1/allOrders` | -| [getAllOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L374) | :closed_lock_with_key: | GET | `dapi/v1/openOrders` | -| [getCurrentOpenOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L378) | :closed_lock_with_key: | GET | `dapi/v1/openOrder` | -| [getForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L382) | :closed_lock_with_key: | GET | `dapi/v1/forceOrders` | -| [getAccountTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L386) | :closed_lock_with_key: | GET | `dapi/v1/userTrades` | -| [getPositions()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L392) | :closed_lock_with_key: | GET | `dapi/v1/positionRisk` | -| [setPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L399) | :closed_lock_with_key: | POST | `dapi/v1/positionSide/dual` | -| [setMarginType()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L403) | :closed_lock_with_key: | POST | `dapi/v1/marginType` | -| [setLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L407) | :closed_lock_with_key: | POST | `dapi/v1/leverage` | -| [getADLQuantileEstimation()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L411) | :closed_lock_with_key: | GET | `dapi/v1/adlQuantile` | -| [setIsolatedPositionMargin()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L415) | :closed_lock_with_key: | POST | `dapi/v1/positionMargin` | -| [getPositionMarginChangeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L421) | :closed_lock_with_key: | GET | `dapi/v1/positionMargin/history` | -| [getBalance()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L432) | :closed_lock_with_key: | GET | `dapi/v1/balance` | -| [getAccountCommissionRate()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L436) | :closed_lock_with_key: | GET | `dapi/v1/commissionRate` | -| [getAccountInformation()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L442) | :closed_lock_with_key: | GET | `dapi/v1/account` | -| [getNotionalAndLeverageBrackets()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L449) | :closed_lock_with_key: | GET | `dapi/v2/leverageBracket` | -| [getCurrentPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L458) | :closed_lock_with_key: | GET | `dapi/v1/positionSide/dual` | -| [getIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L462) | :closed_lock_with_key: | GET | `dapi/v1/income` | -| [getDownloadIdForFuturesTransactionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L466) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn` | -| [getFuturesTransactionHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L476) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn/id` | -| [getDownloadIdForFuturesOrderHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L482) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn` | -| [getFuturesOrderHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L492) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn/id` | -| [getDownloadIdForFuturesTradeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L498) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn` | -| [getFuturesTradeHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L508) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn/id` | -| [getClassicPortfolioMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L520) | :closed_lock_with_key: | GET | `dapi/v1/pmAccountInfo` | -| [getClassicPortfolioMarginNotionalLimits()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L529) | :closed_lock_with_key: | GET | `dapi/v1/pmExchangeInfo` | -| [getBrokerIfNewFuturesUser()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L548) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/ifNewUser` | -| [setBrokerCustomIdForClient()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L561) | :closed_lock_with_key: | POST | `dapi/v1/apiReferral/customization` | -| [getBrokerClientCustomIds()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L574) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/customization` | -| [getBrokerUserCustomId()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L591) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/userCustomization` | -| [getBrokerRebateDataOverview()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L600) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/overview` | -| [getBrokerUserTradeVolume()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L609) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/tradeVol` | -| [getBrokerRebateVolume()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L626) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/rebateVol` | -| [getBrokerTradeDetail()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L643) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/traderSummary` | -| [getFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L663) | | POST | `dapi/v1/listenKey` | -| [keepAliveFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L667) | | PUT | `dapi/v1/listenKey` | -| [closeFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L671) | | DELETE | `dapi/v1/listenKey` | +| [testConnectivity()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L127) | | GET | `dapi/v1/ping` | +| [getExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L131) | | GET | `dapi/v1/exchangeInfo` | +| [getOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L135) | | GET | `dapi/v1/depth` | +| [getRecentTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L139) | | GET | `dapi/v1/trades` | +| [getHistoricalTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L143) | | GET | `dapi/v1/historicalTrades` | +| [getAggregateTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L149) | | GET | `dapi/v1/aggTrades` | +| [getMarkPrice()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L158) | | GET | `dapi/v1/premiumIndex` | +| [getFundingRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L162) | | GET | `dapi/v1/fundingRate` | +| [getFundingRate()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L168) | | GET | `dapi/v1/fundingInfo` | +| [getKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L172) | | GET | `dapi/v1/klines` | +| [getContinuousContractKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L176) | | GET | `dapi/v1/continuousKlines` | +| [getIndexPriceKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L182) | | GET | `dapi/v1/indexPriceKlines` | +| [getMarkPriceKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L186) | | GET | `dapi/v1/markPriceKlines` | +| [getPremiumIndexKlines()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L190) | | GET | `dapi/v1/premiumIndexKlines` | +| [get24hrChangeStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L194) | | GET | `dapi/v1/ticker/24hr` | +| [getSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L201) | | GET | `dapi/v1/ticker/price` | +| [getSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L208) | | GET | `dapi/v1/ticker/bookTicker` | +| [getOpenInterest()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L217) | | GET | `dapi/v1/openInterest` | +| [getOpenInterestStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L221) | | GET | `futures/data/openInterestHist` | +| [getTopTradersLongShortAccountRatio()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L225) | | GET | `futures/data/topLongShortAccountRatio` | +| [getTopTradersLongShortPositionRatio()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L231) | | GET | `futures/data/topLongShortPositionRatio` | +| [getGlobalLongShortAccountRatio()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L237) | | GET | `futures/data/globalLongShortAccountRatio` | +| [getTakerBuySellVolume()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L243) | | GET | `futures/data/takerBuySellVol` | +| [getCompositeSymbolIndex()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L249) | | GET | `futures/data/basis` | +| [getIndexPriceConstituents()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L257) | | GET | `dapi/v1/constituents` | +| [getQuarterlyContractSettlementPrices()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L267) | | GET | `futures/data/delivery-price` | +| [submitNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L279) | :closed_lock_with_key: | POST | `dapi/v1/order` | +| [submitMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L289) | :closed_lock_with_key: | POST | `dapi/v1/batchOrders` | +| [modifyOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L306) | :closed_lock_with_key: | PUT | `dapi/v1/order` | +| [modifyMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L315) | :closed_lock_with_key: | PUT | `dapi/v1/batchOrders` | +| [getOrderModifyHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L328) | :closed_lock_with_key: | GET | `dapi/v1/orderAmendment` | +| [cancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L334) | :closed_lock_with_key: | DELETE | `dapi/v1/order` | +| [cancelMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L338) | :closed_lock_with_key: | DELETE | `dapi/v1/batchOrders` | +| [cancelAllOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L358) | :closed_lock_with_key: | DELETE | `dapi/v1/allOpenOrders` | +| [setCancelOrdersOnTimeout()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L365) | :closed_lock_with_key: | POST | `dapi/v1/countdownCancelAll` | +| [getOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L371) | :closed_lock_with_key: | GET | `dapi/v1/order` | +| [getAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L375) | :closed_lock_with_key: | GET | `dapi/v1/allOrders` | +| [getAllOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L379) | :closed_lock_with_key: | GET | `dapi/v1/openOrders` | +| [getCurrentOpenOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L383) | :closed_lock_with_key: | GET | `dapi/v1/openOrder` | +| [submitNewAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L394) | :closed_lock_with_key: | POST | `dapi/v1/algoOrder` | +| [cancelAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L401) | :closed_lock_with_key: | DELETE | `dapi/v1/algoOrder` | +| [getOpenAlgoOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L407) | :closed_lock_with_key: | GET | `dapi/v1/openAlgoOrders` | +| [getForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L413) | :closed_lock_with_key: | GET | `dapi/v1/forceOrders` | +| [getAccountTrades()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L417) | :closed_lock_with_key: | GET | `dapi/v1/userTrades` | +| [getPositions()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L423) | :closed_lock_with_key: | GET | `dapi/v1/positionRisk` | +| [setPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L430) | :closed_lock_with_key: | POST | `dapi/v1/positionSide/dual` | +| [setMarginType()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L434) | :closed_lock_with_key: | POST | `dapi/v1/marginType` | +| [setLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L438) | :closed_lock_with_key: | POST | `dapi/v1/leverage` | +| [getADLQuantileEstimation()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L442) | :closed_lock_with_key: | GET | `dapi/v1/adlQuantile` | +| [setIsolatedPositionMargin()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L446) | :closed_lock_with_key: | POST | `dapi/v1/positionMargin` | +| [getPositionMarginChangeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L452) | :closed_lock_with_key: | GET | `dapi/v1/positionMargin/history` | +| [getBalance()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L463) | :closed_lock_with_key: | GET | `dapi/v1/balance` | +| [getAccountCommissionRate()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L467) | :closed_lock_with_key: | GET | `dapi/v1/commissionRate` | +| [getAccountInformation()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L473) | :closed_lock_with_key: | GET | `dapi/v1/account` | +| [getNotionalAndLeverageBrackets()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L480) | :closed_lock_with_key: | GET | `dapi/v2/leverageBracket` | +| [getCurrentPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L489) | :closed_lock_with_key: | GET | `dapi/v1/positionSide/dual` | +| [getIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L493) | :closed_lock_with_key: | GET | `dapi/v1/income` | +| [getDownloadIdForFuturesTransactionHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L497) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn` | +| [getFuturesTransactionHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L507) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn/id` | +| [getDownloadIdForFuturesOrderHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L513) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn` | +| [getFuturesOrderHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L523) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn/id` | +| [getDownloadIdForFuturesTradeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L529) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn` | +| [getFuturesTradeHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L539) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn/id` | +| [getClassicPortfolioMarginAccount()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L551) | :closed_lock_with_key: | GET | `dapi/v1/pmAccountInfo` | +| [getClassicPortfolioMarginNotionalLimits()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L560) | :closed_lock_with_key: | GET | `dapi/v1/pmExchangeInfo` | +| [getBrokerIfNewFuturesUser()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L579) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/ifNewUser` | +| [setBrokerCustomIdForClient()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L592) | :closed_lock_with_key: | POST | `dapi/v1/apiReferral/customization` | +| [getBrokerClientCustomIds()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L605) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/customization` | +| [getBrokerUserCustomId()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L622) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/userCustomization` | +| [getBrokerRebateDataOverview()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L631) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/overview` | +| [getBrokerUserTradeVolume()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L640) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/tradeVol` | +| [getBrokerRebateVolume()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L657) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/rebateVol` | +| [getBrokerTradeDetail()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L674) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/traderSummary` | +| [getFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L694) | | POST | `dapi/v1/listenKey` | +| [keepAliveFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L698) | | PUT | `dapi/v1/listenKey` | +| [closeFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/coinm-client.ts#L702) | | DELETE | `dapi/v1/listenKey` | # portfolio-client.ts diff --git a/examples/apidoc/CoinMClient/cancelAlgoOrder.js b/examples/apidoc/CoinMClient/cancelAlgoOrder.js new file mode 100644 index 00000000..da48c37d --- /dev/null +++ b/examples/apidoc/CoinMClient/cancelAlgoOrder.js @@ -0,0 +1,22 @@ +import { CoinMClient } from 'binance'; +// or, if require is preferred: +// const { CoinMClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: dapi/v1/algoOrder +// METHOD: DELETE +// PUBLIC: NO + +const client = new CoinMClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.cancelAlgoOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/CoinMClient/getOpenAlgoOrders.js b/examples/apidoc/CoinMClient/getOpenAlgoOrders.js new file mode 100644 index 00000000..fa247705 --- /dev/null +++ b/examples/apidoc/CoinMClient/getOpenAlgoOrders.js @@ -0,0 +1,22 @@ +import { CoinMClient } from 'binance'; +// or, if require is preferred: +// const { CoinMClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: dapi/v1/openAlgoOrders +// METHOD: GET +// PUBLIC: NO + +const client = new CoinMClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getOpenAlgoOrders(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/CoinMClient/submitNewAlgoOrder.js b/examples/apidoc/CoinMClient/submitNewAlgoOrder.js new file mode 100644 index 00000000..855fc156 --- /dev/null +++ b/examples/apidoc/CoinMClient/submitNewAlgoOrder.js @@ -0,0 +1,22 @@ +import { CoinMClient } from 'binance'; +// or, if require is preferred: +// const { CoinMClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: dapi/v1/algoOrder +// METHOD: POST +// PUBLIC: NO + +const client = new CoinMClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.submitNewAlgoOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/borrowVipLoanFixedRate.js b/examples/apidoc/MainClient/borrowVipLoanFixedRate.js new file mode 100644 index 00000000..2cc1a330 --- /dev/null +++ b/examples/apidoc/MainClient/borrowVipLoanFixedRate.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/loan/vip/fixed/borrow +// METHOD: POST +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.borrowVipLoanFixedRate(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getInstitutionalLoanMaxBorrowable.js b/examples/apidoc/MainClient/getInstitutionalLoanMaxBorrowable.js new file mode 100644 index 00000000..60eb6ada --- /dev/null +++ b/examples/apidoc/MainClient/getInstitutionalLoanMaxBorrowable.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/margin/loan-group/max-borrowable +// METHOD: GET +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getInstitutionalLoanMaxBorrowable(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getTravelRuleCountryList.js b/examples/apidoc/MainClient/getTravelRuleCountryList.js new file mode 100644 index 00000000..47f885cb --- /dev/null +++ b/examples/apidoc/MainClient/getTravelRuleCountryList.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/localentity/country/list +// METHOD: GET +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getTravelRuleCountryList(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getTravelRuleRegionList.js b/examples/apidoc/MainClient/getTravelRuleRegionList.js new file mode 100644 index 00000000..e9d9a9c4 --- /dev/null +++ b/examples/apidoc/MainClient/getTravelRuleRegionList.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/localentity/region/list +// METHOD: GET +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getTravelRuleRegionList(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getVipLoanFixedRateMarket.js b/examples/apidoc/MainClient/getVipLoanFixedRateMarket.js new file mode 100644 index 00000000..5e9bac36 --- /dev/null +++ b/examples/apidoc/MainClient/getVipLoanFixedRateMarket.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/loan/vip/fixed/market +// METHOD: GET +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getVipLoanFixedRateMarket(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index 2ed60934..3fc68806 100644 --- a/llms.txt +++ b/llms.txt @@ -790,2148 +790,1652 @@ import { MainClient } from '../../../src/index'; // ); ================ -File: src/types/coin.ts +File: examples/WebSockets/Demo/ws-demo-spot.ts ================ -import { FuturesContractType, PositionSide } from './futures'; -import { numberInString, OrderSide } from './shared'; -⋮---- -export interface PositionRisk { - symbol: string; - positionAmt: numberInString; - entryPrice: numberInString; - markPrice: numberInString; - unRealizedProfit: numberInString; - liquidationPrice: numberInString; - leverage: numberInString; - maxQty: numberInString; - marginType: string; - isolatedMargin: numberInString; - isAutoAddMargin: boolean; - positionSide: PositionSide; - updateTime: number; -} -⋮---- -export interface CoinMOpenInterest { - symbol: string; - pair: string; - openInterest: numberInString; - contractType: FuturesContractType; - time: number; -} -export type SymbolOrPair = - | { pair: string; symbol?: never } - | { pair?: never; symbol: string }; +import { WebsocketClient } from '../../../src'; ⋮---- -export interface CoinMSymbolOrderBookTicker { - symbol: string; - pair: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; -} +// or +// import { WebsocketClient } from 'binance'; ⋮---- -export interface CoinMPaginatedRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +async function start() ⋮---- -export interface CoinMAccountTradeParamsWithPair extends CoinMPaginatedRequest { - pair: string; - symbol?: never; - fromId?: never; -} +/** + * Demo trading uses real market data with simulated trading. + * Perfect for testing strategies without risk. + * + * For more information: + * https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d + */ ⋮---- -export interface CoinMAccountTradeParamsWithSymbol - extends CoinMPaginatedRequest { - symbol: string; - pair?: never; -} +// Subscribe to spot market streams on demo trading + +================ +File: examples/WebSockets/Demo/ws-demo-usdm.ts +================ +import { WebsocketClient } from '../../../src'; ⋮---- -export interface CoinMAccountTradeParamsWithFromId - extends CoinMPaginatedRequest { - fromId: number; - startTime?: never; - endTime?: never; -} +// or +// import { WebsocketClient } from 'binance'; ⋮---- -export type CoinMAccountTradeParams = - | CoinMAccountTradeParamsWithSymbol - | CoinMAccountTradeParamsWithPair - | CoinMAccountTradeParamsWithFromId; +async function start() ⋮---- -export interface CoinMPositionTrade { - symbol: string; - id: number; - orderId: number; - pair: string; - side: OrderSide; - price: numberInString; - qty: numberInString; - realizedPnl: numberInString; - marginAsset: string; - baseQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - positionSide: PositionSide; - buyer: boolean; - maker: boolean; -} +/** + * Demo trading uses real market data with simulated trading. + * Perfect for testing strategies without risk. + */ ⋮---- -export interface FundingRate { - symbol: string; - adjustedFundingRateCap: string; - adjustedFundingRateFloor: string; - fundingIntervalHours: number; - disclaimer: boolean; -} +// Subscribe to USDM futures market streams on demo trading + +================ +File: examples/WebSockets/Misc/ws-close.ts +================ +import { DefaultLogger, WebsocketClient } from '../../../src/index'; ⋮---- -export interface GetClassicPortfolioMarginNotionalLimitParams { - symbol?: string; - pair?: string; -} +// or +// import { DefaultLogger, WebsocketClient } from 'binance'; ⋮---- -export interface ClassicPortfolioMarginNotionalLimit { - symbol: string; - pair: string; - notionalLimit: string; -} +// unsubscribe from user data stream (for usd futures) ⋮---- -export interface ClassicPortfolioMarginAccount { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; -} +// unsubscribe from individual topics on a connection, one at a time: +// wsClient.unsubscribe('!miniTicker@arr', 'main'); ⋮---- -export interface FuturesTransactionHistoryDownloadLink { - downloadId: string; - status: string; - url: string; - notified: boolean; - expirationTimestamp: number; - isExpired: boolean | null; -} +// arrays also supported: ================ -File: webpack/webpack.config.js +File: examples/WebSockets/Misc/ws-custom-parser.ts ================ -function generateConfig(name) +// Optional, for 3rd scenario below: +// Import 3rd party library for parsing big number types in JSON +// import JSONbig from 'json-bigint'; ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +import { WebsocketClient } from '../../../src'; ⋮---- -// 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 +// Demonstrates using a custom JSON parser for incoming WS messages to preserve big integers ⋮---- -// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. +/** + * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: + * https://github.com/tiagosiebler/binance/issues/208 + * + * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: + */ ⋮---- -// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. +// Default behaviour, if you don't include this: +// customParseJSONFn: (rawEvent) => { +// return JSON.parse(rawEvent); +// }, +// Or, pre-process the raw event using RegEx, before using the same workflow: ⋮---- -// new webpack.DefinePlugin({ -// 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) -// }), +// Or, use a 3rd party library such as json-bigint: +// customParseJSONFn: (rawEvent) => { +// return JSONbig({ storeAsString: true }).parse(rawEvent); +// }, +⋮---- +// Subscribe to a couple of topics +// Note: '!ticker@arr' has been deprecated (2025-11-14). Using '!miniTicker@arr' instead. ================ -File: .jshintrc +File: examples/WebSockets/Misc/ws-unsubscribe.ts ================ -{ - "esversion": 8, - "asi": true, - "laxbreak": true, - "predef": [ "-Promise" ] -} +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { WebsocketClient } from '../../../src/index'; +⋮---- +// or, with the npm package +/* +import { + WebsocketClient, + DefaultLogger, + isWsFormatted24hrTicker, + isWsFormattedKline, +} from 'binance'; +*/ +⋮---- +/** + * + * A simple demonstration on how to unsubscribe from one or more topics. + * + */ +⋮---- +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled +⋮---- +/** + * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. + * + * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. + */ +⋮---- +// Aggregate Trade Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#aggregate-trade-streams +⋮---- +// Kline/Candlestick Streams for UTC +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc +⋮---- +// Individual Symbol Mini Ticker Stream +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream +⋮---- +// Individual Symbol Ticker Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-ticker-streams +⋮---- +// Individual Symbol Rolling Window Statistics Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-rolling-window-statistics-streams +⋮---- +// Average Price +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price +⋮---- +/** + * Subscribe to each available type of spot market topic, the new way + */ +⋮---- +// 5 seconds later, unsubscribe from almost all topics except avg price ================ -File: .npmignore +File: examples/WebSockets/Private(userdata)/ws-userdata-README.MD ================ -.gitignore -coverage/ -test/ -util/ -.vscode/ -.eslintrc.js -.travis.yml -.mocharc.json -.prettierrc +# User Data Streams - Binance -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" -} - -================ -File: CHANGELOG.md -================ -# Binance API - -## 2.0.14 -- Update values thrown by exception parser. - -## 2.0.13 -- Expose time sync offset getter/setter in base client. `getTimeOffset()/setTimeOffest(value)`. -- Add handler to signMessage method, falling back to browser equivalent if method is not a function (react/preact/#141). - -## 2.0.12 -- Increase default timeout for websocket pong heartbeats to 7500ms. - -## 2.0.11 -- Fix APIs that use the DELETE method. - -## 2.0.9-10 -- Fix typo in websocket types. -- Fix missing type properties for ws messages. - -## 2.0.8 -- Emit `reconnected` events for reconnected user data stream. - -## 2.0.6 -- Fix symbol & margin asset types for futures user data updated position event. +The user data streams are the WebSocket method for asynchronously receiving events when any changes happen on your account. Including but not limited to: +- order events (filled/cancelled/updated/etc) +- position events +- balance events (deposit/withdraw/etc) +- misc events (leverage changed, position mode changed, etc) -## 2.0.5 -- Refine types for user data websocket events (futures) +## Mechanisms -## 2.0.4 -- Disable 'silly' logger category by default to reduce ping/pong noise. -- Expand ws support to other API categories. -- Expand beautifier support for other WS messages. +There are currently two key mechanisms for subscribing to user data events -## 2.0.3 -- Expand main-client APIs. -- Expand usdm-client APIs. +### Mechanisms - Listen Key -## 2.0.2 -- Fix getAccountInformation main endpoint. -- Fix a few missing APIs. -- Refactor SpotClient->MainClient. SpotClient will be deprecated in future (MainClient is the same, just a different name). -- Fix build errors from incorrect module imports. +The older and original mechanism involves a listen key. This is requested via the REST API and then used when opening a connection to the user data stream. -## 2.0.0 +The listen key can expire and needs a regular "ping" (a REST API call) to keep it alive. -- Introduction for typescript with strong types on most request parameters & responses. - - NPM package includes transpiled framework & type declarations. - - Supports both typescript and vanilla node.js projects. - - REST requests and responses include detailed types, though some may still be missing. - - Raw and beautified WS events include detailed types, though some may still be missing. -- Introduction for webpack. - - To generate a browser bundle clone & build the library then run webpack using `npm run pack`. -- Introduction for integration tests via jest on all REST clients. - - Tests are executed automatically to avoid unintended breaking changes on release. - - Real API calls are made to validate integration. -- Complete networking overhaul using [axios](https://github.com/axios/axios). - - Small & modern framework. Significant reduction in dependencies via deprecation of `request`. - - Support for proxies and [other axios-supported functionality](https://github.com/axios/axios#request-config). - - Support for backend (node) and frontend (browser) requests. -- Complete overhaul in websockets client. - - Websocket events are still (optionally) beautified consistently with how the previous library worked. - - New event-driven architecture. - - Support for USDM Futures. More to come in a future release. - - Automatic connection monitoring, with automatic reconnect if the connection goes stale. - - Automatic userData connection monitoring, with automatic refresh and respawn if previous listen key expires or the connection closes unexpectedly. -- Complete overhaul in REST client. - - Revamped spot client (see [spot-client](./src/spot-client.ts)). - - Introduction of [usdm-client](./src/usdm-client.ts) for USDM Futures. -- Passive tracking & storage of API limit states (IP request weight & order weight). - - Parsed automatically via response headers when any request is made, if header is detected. - - See `getRateLimitStates()` to query the last seen weights on any of the REST clients. -- Smarter time-sync to handle common recvWindow latency issues (optional, default on). +With the "binance" Node.js & JavaScript SDK, you can easily subscribe to the user data stream via the listen key workflow, through just one function call. -### 2.0.0-beta.4 +The SDK will automatically: +- fetch a listen key +- perform regular keep alive requests on the listen key +- handle listen key expiry/refresh +- handle reconnects, if a connection is temporarily lost -- Breaking change: refactor most options to camel case (instead of underscore separation). -- Add optional beautifier support for REST responses (parses known numbers stored as strings into numbers). +All you have to do is ask for the user data stream and process incoming events - the SDK will handle the rest! -### 2.0.0-beta.5-8 +For a working example, refer to the [ws-userdata-listenkey](./ws-userdata-listenkey.ts) example. -- Breaking change: refactor spot getAllCoinsInformation to getBalances(). -- Fix POST request format to www-form-urlencoded. +**Deprecation warning: As of April 2025, the listen key workflow is also deprecated for Spot markets (no known ETA for removal).** Refer to the changelog for details: https://developers.binance.com/docs/binance-spot-api-docs/CHANGELOG#2025-04-07 - - - +### Mechanisms - WS API User Data Stream -================ -File: index.js -================ +The newer mechanism for the user data stream is via an active WebSocket API connection. This is a simpler mechanism in that it does not require a listen key. You can easily use this new mechanism via the WebsocketClient (or WebsocketAPIClient) within this SDK. +For a working example, refer to the [ws-userdata-wsapi](./ws-userdata-wsapi.ts) example. ================ -File: jest.config.ts +File: examples/WebSockets/Public/ws-public-spot-orderbook.ts ================ -/** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable no-unused-vars */ +import { + DefaultLogger, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WsMessagePartialBookDepthEventFormatted, +} from '../../../src/index'; ⋮---- -import type { Config } from 'jest'; +// or, with the npm package +/* +import { + WebsocketClient, + DefaultLogger, + isWsFormattedTrade, +} from 'binance'; +*/ ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +// trace: () => {}, ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +/** + * Simple example for receiving depth snapshots from spot orderbooks + */ ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +// Request subscription to the following symbol events: ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +// const symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT']; ⋮---- -// Indicates whether the coverage information should be collected while executing the test +// Loop through symbols ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +// The old way, convenient but unnecessary: +// wsClient.subscribePartialBookDepths(symbol, levels, 1000, 'spot'); ⋮---- -// The directory where Jest should output its coverage files +// Manually build a topic matching the structure expected by binance: +// btcusdt@depth20@1000ms ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +// Request subscribe for these topics in the main product group (spot markets are under "main") + +================ +File: examples/WebSockets/Public/ws-public-spot-trades.ts +================ +import { + DefaultLogger, + isWsFormattedTrade, + WebsocketClient, +} from '../../../src/index'; ⋮---- -// Indicates which provider should be used to instrument code for coverage +// or, with the npm package +/* +import { + WebsocketClient, + DefaultLogger, + isWsFormattedTrade, +} from 'binance'; +*/ ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +// trace: () => {}, ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +// Request subscription to the following symbol trade events: ⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, +// Loop through symbols + +================ +File: examples/WebSockets/Public/ws-public-usdm-funding.ts +================ +import { + DefaultLogger, + isWsFormattedMarkPriceUpdateArray, + WebsocketClient, +} from '../../../src/index'; ⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, +// or, with the npm package +/* +import { + WebsocketClient, + DefaultLogger, + isWsFormattedMarkPriceUpdateArray, +} from 'binance'; +*/ ⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, +// trace: () => {}, ⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], +// api_key: key, +// api_secret: secret, ⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, +// value is in decimal, multiply by 100 to get percent value ⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, +// log table sorted alphabetically by symbol ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) + +================ +File: examples/WebSockets/Public/ws-public.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, +} from '../../../src'; ⋮---- -// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. -// maxWorkers: "50%", +// or, with the npm package +/* +import { + WebsocketClient, + DefaultLogger, + isWsFormatted24hrTicker, + isWsFormattedKline, +} from 'binance'; +*/ ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +// Without typescript: +// const logger = { ⋮---- -// An array of file extensions your modules use -// moduleFileExtensions: [ -// "js", -// "mjs", -// "cjs", -// "jsx", -// "ts", -// "tsx", -// "json", -// "node" -// ], +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; +// } ⋮---- -// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module -// moduleNameMapper: {}, +// Optional: when enabled, the SDK will try to format incoming data into more readable objects. +// Beautified data is emitted via the "formattedMessage" event ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -// Activates notifications for test results -// notify: false, +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// console.log('raw message received ', JSON.stringify(data)); ⋮---- -// A preset that is used as a base for Jest's configuration -// preset: undefined, +// Formatted data that has gone through the beautifier ⋮---- -// Run tests from one or more projects -// projects: undefined, +/** + * Optional: we've included type-guards for many formatted websocket topics. + * + * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). + */ +// if (isWsAggTradeFormatted(data)) { +// console.log('log agg trade: ', data); +// return; +// } ⋮---- -// Use this configuration option to add custom reporters to Jest -// reporters: undefined, +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -// Automatically reset mock state before every test -// resetMocks: false, +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -// Reset the module registry before running each individual test -// resetModules: false, +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -// A path to a custom resolver -// resolver: undefined, +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -// Automatically restore mock state and implementation before every test -// restoreMocks: false, +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -// The root directory that Jest should scan for tests and modules within -// rootDir: undefined, +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -// A list of paths to directories that Jest should use to search for files in -// roots: [ -// "" -// ], +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -// Allows you to use a custom runner instead of Jest's default test runner -// runner: "jest-runner", +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -// The paths to modules that run some code to configure or set up the testing environment before each test -// setupFiles: [], +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -// A list of paths to modules that run some code to configure or set up the testing framework before each test -// setupFilesAfterEnv: [], +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- -// The number of seconds after which a test is considered as slow and reported as such in the results. -// slowTestThreshold: 5, +/** + * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. + * + * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. + */ ⋮---- -// A list of paths to snapshot serializer modules Jest should use for snapshot testing -// snapshotSerializers: [], +// // E.g. one at a time, routed to the coinm futures websockets: +// wsClient.subscribe('btcusd@indexPrice', 'coinm'); +// wsClient.subscribe('btcusd@miniTicker', 'coinm'); ⋮---- -// The test environment that will be used for testing -// testEnvironment: "jest-environment-node", +// // Or send many topics at once to a stream, e.g. the usdm futures stream: +// wsClient.subscribe( +// [ +// 'btcusdt@aggTrade', +// 'btcusdt@markPrice', +// '!ticker@arr', +// '!miniTicker@arr', +// ], +// 'usdm', +// ); ⋮---- -// Options that will be passed to the testEnvironment -// testEnvironmentOptions: {}, +/** + * Subscribe to each available type of spot market topic, the new way + */ ⋮---- -// Adds a location field to test results -// testLocationInResults: false, +// Aggregate Trade Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#aggregate-trade-streams ⋮---- -// The glob patterns Jest uses to detect test files +// Trade Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#trade-streams ⋮---- -// "**/__tests__/**/*.[jt]s?(x)", +// Kline/Candlestick Streams for UTC +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc ⋮---- -// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped -// testPathIgnorePatterns: [ -// "/node_modules/" -// ], +// Kline/Candlestick Streams with timezone offset +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-with-timezone-offset ⋮---- -// The regexp pattern or array of patterns that Jest uses to detect test files -// testRegex: [], +// Individual Symbol Mini Ticker Stream +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream ⋮---- -// This option allows the use of a custom results processor -// testResultsProcessor: undefined, +// All Market Mini Tickers Stream +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream ⋮---- -// This option allows use of a custom test runner -// testRunner: "jest-circus/runner", +// Individual Symbol Ticker Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-ticker-streams ⋮---- -// A map from regular expressions to paths to transformers -// transform: undefined, +// All Market Tickers Stream - DEPRECATED (2025-11-14) +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-tickers-stream +// '!ticker@arr', // DEPRECATED: Use '@ticker' or '!miniTicker@arr' instead +// Recommended alternative: '!miniTicker@arr' for all market mini tickers (already subscribed above) +// Individual Symbol Rolling Window Statistics Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-rolling-window-statistics-streams ⋮---- -// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation -// transformIgnorePatterns: [ -// "/node_modules/", -// "\\.pnp\\.[^\\/]+$" -// ], +// All Market Rolling Window Statistics Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams ⋮---- -// Prevents import esm module error from v1 axios release, issue #5026 +// Individual Symbol Book Ticker Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams ⋮---- -// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them -// unmockedModulePathPatterns: undefined, +// Average Price +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price ⋮---- -// Indicates whether each individual test should be reported during the run -// verbose: undefined, -verbose: true, // report individual test +// Partial Book Depth Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams ⋮---- -// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode -// watchPathIgnorePatterns: [], +// Diff. Depth Stream +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream ⋮---- -// Whether to use watchman for file crawling -// watchman: true, - -================ -File: jsconfig.json -================ -{ - "compilerOptions": { - "target": "ES6", - "module": "commonjs" - }, - "exclude": [ - "node_modules", - "**/node_modules/*", - "coverage", - "doc" - ] -} - -================ -File: LICENSE.md -================ -Copyright 2025 Tiago Siebler - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -================ -File: tsconfig.build.json -================ -{ - "extends": "./tsconfig.json", - "exclude": [ - "node_modules", - "test", - "dist", - "**/*spec.ts", - "**/*test.ts", - "jest.config.ts" - ] -} - -================ -File: tsconfig.json -================ -{ - "compileOnSave": true, - "compilerOptions": { - "allowJs": true, - "target": "es6", - "module": "commonjs", - "moduleResolution": "node", - "declaration": true, - "removeComments": false, - "noEmitOnError": true, - "noImplicitAny": false, - "strictNullChecks": true, - "skipLibCheck": true, - "sourceMap": true, - "esModuleInterop": true, - "lib": ["es2017", "dom"], - "baseUrl": ".", - "outDir": "lib" - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"] -} - -================ -File: tsconfig.linting.json -================ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "outDir": "dist/cjs", - "target": "esnext", - "rootDir": "../", - "allowJs": true - }, - "include": [ - "src/**/*.*", - "test/**/*.*", - "examples/**/*.*", - ".eslintrc.cjs", - "jest.config.ts", - "webpack/webpack.config.ts" - ] -} - -================ -File: examples/auth/rest-private-ed25519.md -================ -# Ed25519 Authentication with Binance APIs in Node.js - -## Creating Ed25519 Keys - -Officially, binance recommends downloading and running a key generator from their repo. Guidance for this can be found on the [binance website](https://www.binance.com/en/support/faq/detail/6b9a63f1e3384cf48a2eedb82767a69a) when trying to add a new Ed25519 API key, or in their GitHub repository: https://github.com/binance/asymmetric-key-generator - -## Using the Ed25519 public key to get an API key from Binance - -Once created, keep your **private key** completely secret! The **public** key needs to be provided to binance when creating new API credentials with the "Self-generated" option. - -Your public key should look something like this: - -```pem ------BEGIN PUBLIC KEY----- -lkn123bx123x+7lkmlkn123bx123xAMDO/lkm123x= ------END PUBLIC KEY----- -``` - -Submit this in the "Upload public key" form, shown when creating a new API key on binance and choosing the "self-generated" option. - -Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. - -After using the public key to create a new API key, you will be given an API Key such as the following: - -``` -mlk2mx3l12m3lxk1m3lxk1m3l1k2mx3l12km3xl1km23x1l2k3mx1l2km3x -``` - -This is the first piece, used as the "apiKey" in the [rest-private-ed25519.ts](./rest-private-ed25519.ts) example. - -## Using the Ed25519 private key for Ed25519 authentication with binance APIs in Node.js - -Your private key, if generated with the above steps, should look something like this (but with much more text): - -```pem ------BEGIN PRIVATE KEY----- -lx1k2m3xl12lkm2l1kmx312312l3mx1lk23m ------END PRIVATE KEY----- -``` - -This is your secret, you should **never** share this with anyone, not even binance! Treat this like a password. - -As part of this authentication process, your private key is used to generate a signature. This SDK handles this process automatically for you. Ed25519 authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. - -From here, simply use the key provided by binance as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. - -Based on the above example, the following would prepare the main REST client using the above credentials: - -```typescript -const ed25519PrivateKey = ` ------BEGIN PRIVATE KEY----- -lkmlkm123lkms1s12s+lkmlkm123lkms1s12s ------END PRIVATE KEY----- -`; - -const ed25519APIKey = 'lkmlkm123lkms1s12slkmlkm123lkms1s12slkmlkm123lkms1s12s'; - -const restClient = new MainClient({ - api_key: ed25519APIKey, - api_secret: ed25519PrivateKey, - beautifyResponses: true, -}); - -const wsApiClient = new WebsocketAPIClient({ - api_key: ed25519APIKey, - api_secret: ed25519PrivateKey, -}); -``` - -The rest is automatic - just continue using the SDK as you would normally. It will automatically handle signing requests using Ed25519 for you. - -For a complete example, refer to the [rest-private-ed25519.ts](./rest-private-ed25519.ts) file on GitHub. - -================ -File: examples/WebSockets/Demo/ws-demo-spot.ts -================ -import { WebsocketClient } from '../../../src'; +// Look at the `WS_KEY_URL_MAP` for a list of values here: +// https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts +// "main" connects to wss://stream.binance.com:9443/stream +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams ⋮---- -// or -// import { WebsocketClient } from 'binance'; +// Aggregate Trade Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams ⋮---- -async function start() +// Mark Price Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream +⋮---- +// Mark Price Stream for All market +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market +⋮---- +// Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams +// 'btcusdt@kline_1m', +// Continuous Contract Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams +// 'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER +// Individual Symbol Mini Ticker Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream +// 'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE +// All Market Mini Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream +// '!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD +// Individual Symbol Ticker Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams +//'btcusdt@ticker', +// All Market Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream +// '!ticker@arr', // DOESNT EXIST AS TYPE GUARD +// Individual Symbol Book Ticker Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Book-Ticker-Streams +//'btcusdt@bookTicker', // DOESNT EXIST AS TYPE GUARD +// All Book Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream +// '!bookTicker', // DOESNT EXIST AS TYPE GUARD +// Liquidation Order Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams +// 'btcusdt@forceOrder', +// Liquidation Order Stream for All market +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams +//'!forceOrder@arr', +// Partial Book Depth Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams +//'btcusdt@depth5', +// 'btcusdt@depth10@100ms' +// Diff. Book Depth Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams +// 'btcusdt@depth', +// 'btcusdt@depth@100ms', +// 'btcusdt@depth@500ms', +// 'btcusdt@depth@1000ms' +// Composite Index Symbol Information Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams +// 'btcusdt@compositeIndex' // DOESNT EXIST AS TYPE GUARD +// Contract Info Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream +// '!contractInfo' // DOESNT EXIST AS TYPE GUARD +// Multi-Assets Mode Asset Index Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index +// '!assetIndex@arr' // DOESNT EXIST AS TYPE GUARD +// 'btcusdt@assetIndex' ⋮---- /** - * Demo trading uses real market data with simulated trading. - * Perfect for testing strategies without risk. + * Subscribe to each available options market data websocket topic, the new way: * - * For more information: - * https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d + * https://developers.binance.com/docs/derivatives/options-trading/websocket-market-streams/New-Symbol-Info + * https://eapi.binance.com/eapi/v1/exchangeInfo */ ⋮---- -// Subscribe to spot market streams on demo trading - -================ -File: examples/WebSockets/Demo/ws-demo-usdm.ts -================ -import { WebsocketClient } from '../../../src'; -⋮---- -// or -// import { WebsocketClient } from 'binance'; +const optionsExpiration = '260128'; // YYMMDD ⋮---- -async function start() +// You can send raw commands, such as asking for list of active subscriptions after 5 seconds. Use with caution: +// setTimeout(() => { +// wsClient.tryWsSend( +// 'eoptions', +// JSON.stringify({ +// method: 'LIST_SUBSCRIPTIONS', +// id: Date.now(), +// }), +// ); +// }, 1000 * 5); ⋮---- -/** - * Demo trading uses real market data with simulated trading. - * Perfect for testing strategies without risk. - */ +// /** +// * +// * For those that used the Node.js Binance SDK before the v3 release, you can +// * still subscribe to available market topics the "old" way, for convenience +// * when migrating from the old WebsocketClient to the new multiplex client): +// * +// */ ⋮---- -// Subscribe to USDM futures market streams on demo trading +// wsClient.subscribeAggregateTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(symbol, 'spot'); +// wsClient.subscribeTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(coinMSymbol, 'coinm'); +// wsClient.subscribeCoinIndexPrice(coinMSymbol2); +// wsClient.subscribeAllBookTickers('usdm'); +// wsClient.subscribeSpotKline(symbol, '1m'); +// wsClient.subscribeMarkPrice(symbol, 'usdm'); +// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMarketMarkPrice('usdm'); +// wsClient.subscribeAllMarketMarkPrice('coinm'); +// wsClient.subscribeKlines(symbol, '1m', 'usdm'); +// wsClient.subscribeContinuousContractKlines( +// symbol, +// 'perpetual', +// '1m', +// 'usdm', +// ); +// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); +// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMini24hrTickers('spot'); +// wsClient.subscribeAllMini24hrTickers('usdm'); +// wsClient.subscribeAllMini24hrTickers('coinm'); +// wsClient.subscribeAll24hrTickers('spot'); +// wsClient.subscribeAll24hrTickers('usdm'); +// wsClient.subscribeAll24hrTickers('coinm'); +// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); +// wsClient.subscribeAllLiquidationOrders('usdm'); +// wsClient.subscribeAllLiquidationOrders('coinm'); +// wsClient.subscribeSpotSymbol24hrTicker(symbol); +// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); +// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); +// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); +// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); +// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); +// wsClient.subscribeContractInfoStream('usdm'); +// wsClient.subscribeContractInfoStream('coinm'); ================ -File: examples/WebSockets/Misc/ws-close.ts +File: src/types/coin.ts ================ -import { DefaultLogger, WebsocketClient } from '../../../src/index'; +import { FuturesContractType, PositionSide } from './futures'; +import { numberInString, OrderSide } from './shared'; ⋮---- -// or -// import { DefaultLogger, WebsocketClient } from 'binance'; -⋮---- -// unsubscribe from user data stream (for usd futures) -⋮---- -// unsubscribe from individual topics on a connection, one at a time: -// wsClient.unsubscribe('!miniTicker@arr', 'main'); -⋮---- -// arrays also supported: - -================ -File: examples/WebSockets/Misc/ws-custom-parser.ts -================ -// Optional, for 3rd scenario below: -// Import 3rd party library for parsing big number types in JSON -// import JSONbig from 'json-bigint'; +export interface PositionRisk { + symbol: string; + positionAmt: numberInString; + entryPrice: numberInString; + markPrice: numberInString; + unRealizedProfit: numberInString; + liquidationPrice: numberInString; + leverage: numberInString; + maxQty: numberInString; + marginType: string; + isolatedMargin: numberInString; + isAutoAddMargin: boolean; + positionSide: PositionSide; + updateTime: number; +} ⋮---- -import { WebsocketClient } from '../../../src'; +export interface CoinMOpenInterest { + symbol: string; + pair: string; + openInterest: numberInString; + contractType: FuturesContractType; + time: number; +} +export type SymbolOrPair = + | { pair: string; symbol?: never } + | { pair?: never; symbol: string }; ⋮---- -// Demonstrates using a custom JSON parser for incoming WS messages to preserve big integers +export interface CoinMSymbolOrderBookTicker { + symbol: string; + pair: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; +} ⋮---- -/** - * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: - * https://github.com/tiagosiebler/binance/issues/208 - * - * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: - */ +export interface CoinMPaginatedRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// Default behaviour, if you don't include this: -// customParseJSONFn: (rawEvent) => { -// return JSON.parse(rawEvent); -// }, -// Or, pre-process the raw event using RegEx, before using the same workflow: +export interface CoinMAccountTradeParamsWithPair extends CoinMPaginatedRequest { + pair: string; + symbol?: never; + fromId?: never; +} ⋮---- -// Or, use a 3rd party library such as json-bigint: -// customParseJSONFn: (rawEvent) => { -// return JSONbig({ storeAsString: true }).parse(rawEvent); -// }, +export interface CoinMAccountTradeParamsWithSymbol + extends CoinMPaginatedRequest { + symbol: string; + pair?: never; +} ⋮---- -// Subscribe to a couple of topics -// Note: '!ticker@arr' has been deprecated (2025-11-14). Using '!miniTicker@arr' instead. - -================ -File: examples/WebSockets/Misc/ws-unsubscribe.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { WebsocketClient } from '../../../src/index'; +export interface CoinMAccountTradeParamsWithFromId + extends CoinMPaginatedRequest { + fromId: number; + startTime?: never; + endTime?: never; +} ⋮---- -// or, with the npm package -/* -import { - WebsocketClient, - DefaultLogger, - isWsFormatted24hrTicker, - isWsFormattedKline, -} from 'binance'; -*/ +export type CoinMAccountTradeParams = + | CoinMAccountTradeParamsWithSymbol + | CoinMAccountTradeParamsWithPair + | CoinMAccountTradeParamsWithFromId; ⋮---- -/** - * - * A simple demonstration on how to unsubscribe from one or more topics. - * - */ +export interface CoinMPositionTrade { + symbol: string; + id: number; + orderId: number; + pair: string; + side: OrderSide; + price: numberInString; + qty: numberInString; + realizedPnl: numberInString; + marginAsset: string; + baseQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + positionSide: PositionSide; + buyer: boolean; + maker: boolean; +} ⋮---- -// Raw unprocessed incoming data, e.g. if you have the beautifier disabled +export interface FundingRate { + symbol: string; + adjustedFundingRateCap: string; + adjustedFundingRateFloor: string; + fundingIntervalHours: number; + disclaimer: boolean; +} ⋮---- -/** - * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. - * - * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. - */ +export interface GetClassicPortfolioMarginNotionalLimitParams { + symbol?: string; + pair?: string; +} ⋮---- -// Aggregate Trade Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#aggregate-trade-streams +export interface ClassicPortfolioMarginNotionalLimit { + symbol: string; + pair: string; + notionalLimit: string; +} ⋮---- -// Kline/Candlestick Streams for UTC -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc +export interface ClassicPortfolioMarginAccount { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; +} ⋮---- -// Individual Symbol Mini Ticker Stream -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream +export interface FuturesTransactionHistoryDownloadLink { + downloadId: string; + status: string; + url: string; + notified: boolean; + expirationTimestamp: number; + isExpired: boolean | null; +} + +================ +File: webpack/webpack.config.js +================ +function generateConfig(name) ⋮---- -// Individual Symbol Ticker Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-ticker-streams +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -// Individual Symbol Rolling Window Statistics Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-rolling-window-statistics-streams +// 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 ⋮---- -// Average Price -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price +// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. ⋮---- -/** - * Subscribe to each available type of spot market topic, the new way - */ +// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. ⋮---- -// 5 seconds later, unsubscribe from almost all topics except avg price +// new webpack.DefinePlugin({ +// 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) +// }), ================ -File: examples/WebSockets/Private(userdata)/ws-userdata-README.MD +File: .jshintrc ================ -# User Data Streams - Binance +{ + "esversion": 8, + "asi": true, + "laxbreak": true, + "predef": [ "-Promise" ] +} -The user data streams are the WebSocket method for asynchronously receiving events when any changes happen on your account. Including but not limited to: -- order events (filled/cancelled/updated/etc) -- position events -- balance events (deposit/withdraw/etc) -- misc events (leverage changed, position mode changed, etc) +================ +File: .npmignore +================ +.gitignore +coverage/ +test/ +util/ +.vscode/ +.eslintrc.js +.travis.yml +.mocharc.json +.prettierrc -## Mechanisms +================ +File: .prettierrc +================ +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" +} -There are currently two key mechanisms for subscribing to user data events +================ +File: CHANGELOG.md +================ +# Binance API -### Mechanisms - Listen Key +## 2.0.14 +- Update values thrown by exception parser. -The older and original mechanism involves a listen key. This is requested via the REST API and then used when opening a connection to the user data stream. +## 2.0.13 +- Expose time sync offset getter/setter in base client. `getTimeOffset()/setTimeOffest(value)`. +- Add handler to signMessage method, falling back to browser equivalent if method is not a function (react/preact/#141). -The listen key can expire and needs a regular "ping" (a REST API call) to keep it alive. +## 2.0.12 +- Increase default timeout for websocket pong heartbeats to 7500ms. -With the "binance" Node.js & JavaScript SDK, you can easily subscribe to the user data stream via the listen key workflow, through just one function call. +## 2.0.11 +- Fix APIs that use the DELETE method. -The SDK will automatically: -- fetch a listen key -- perform regular keep alive requests on the listen key -- handle listen key expiry/refresh -- handle reconnects, if a connection is temporarily lost +## 2.0.9-10 +- Fix typo in websocket types. +- Fix missing type properties for ws messages. -All you have to do is ask for the user data stream and process incoming events - the SDK will handle the rest! +## 2.0.8 +- Emit `reconnected` events for reconnected user data stream. -For a working example, refer to the [ws-userdata-listenkey](./ws-userdata-listenkey.ts) example. +## 2.0.6 +- Fix symbol & margin asset types for futures user data updated position event. -**Deprecation warning: As of April 2025, the listen key workflow is also deprecated for Spot markets (no known ETA for removal).** Refer to the changelog for details: https://developers.binance.com/docs/binance-spot-api-docs/CHANGELOG#2025-04-07 +## 2.0.5 +- Refine types for user data websocket events (futures) -### Mechanisms - WS API User Data Stream +## 2.0.4 +- Disable 'silly' logger category by default to reduce ping/pong noise. +- Expand ws support to other API categories. +- Expand beautifier support for other WS messages. -The newer mechanism for the user data stream is via an active WebSocket API connection. This is a simpler mechanism in that it does not require a listen key. You can easily use this new mechanism via the WebsocketClient (or WebsocketAPIClient) within this SDK. +## 2.0.3 +- Expand main-client APIs. +- Expand usdm-client APIs. -For a working example, refer to the [ws-userdata-wsapi](./ws-userdata-wsapi.ts) example. +## 2.0.2 +- Fix getAccountInformation main endpoint. +- Fix a few missing APIs. +- Refactor SpotClient->MainClient. SpotClient will be deprecated in future (MainClient is the same, just a different name). +- Fix build errors from incorrect module imports. + +## 2.0.0 + +- Introduction for typescript with strong types on most request parameters & responses. + - NPM package includes transpiled framework & type declarations. + - Supports both typescript and vanilla node.js projects. + - REST requests and responses include detailed types, though some may still be missing. + - Raw and beautified WS events include detailed types, though some may still be missing. +- Introduction for webpack. + - To generate a browser bundle clone & build the library then run webpack using `npm run pack`. +- Introduction for integration tests via jest on all REST clients. + - Tests are executed automatically to avoid unintended breaking changes on release. + - Real API calls are made to validate integration. +- Complete networking overhaul using [axios](https://github.com/axios/axios). + - Small & modern framework. Significant reduction in dependencies via deprecation of `request`. + - Support for proxies and [other axios-supported functionality](https://github.com/axios/axios#request-config). + - Support for backend (node) and frontend (browser) requests. +- Complete overhaul in websockets client. + - Websocket events are still (optionally) beautified consistently with how the previous library worked. + - New event-driven architecture. + - Support for USDM Futures. More to come in a future release. + - Automatic connection monitoring, with automatic reconnect if the connection goes stale. + - Automatic userData connection monitoring, with automatic refresh and respawn if previous listen key expires or the connection closes unexpectedly. +- Complete overhaul in REST client. + - Revamped spot client (see [spot-client](./src/spot-client.ts)). + - Introduction of [usdm-client](./src/usdm-client.ts) for USDM Futures. +- Passive tracking & storage of API limit states (IP request weight & order weight). + - Parsed automatically via response headers when any request is made, if header is detected. + - See `getRateLimitStates()` to query the last seen weights on any of the REST clients. +- Smarter time-sync to handle common recvWindow latency issues (optional, default on). + +### 2.0.0-beta.4 + +- Breaking change: refactor most options to camel case (instead of underscore separation). +- Add optional beautifier support for REST responses (parses known numbers stored as strings into numbers). + +### 2.0.0-beta.5-8 + +- Breaking change: refactor spot getAllCoinsInformation to getBalances(). +- Fix POST request format to www-form-urlencoded. + + + + ================ -File: examples/WebSockets/Private(userdata)/ws-userdata-wsapi-margin.ts +File: index.js +================ + + +================ +File: jest.config.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -// or -// import { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } from 'binance'; -// or -// const { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } = require('binance'); -⋮---- -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotBalanceUpdate, - isWsFormattedSpotOutboundAccountPosition, - isWsFormattedSpotUserDataEvent, - isWsFormattedUserDataEvent, - WebsocketAPIClient, - WebsocketClient, - WS_KEY_MAP, -} from '../../../src'; -⋮---- /** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration */ ⋮---- -// returned by binance, generated using the publicKey (above) -// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; -// Your Ed25519 private key is passed as the "secret" -// const secret = privateKey; -⋮---- -function attachEventHandlers( - wsClient: TWSClient, -): void +import type { Config } from 'jest'; ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- -// Raw events received from binance, as is: +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, ⋮---- -// console.log('raw message received ', JSON.stringify(data)); +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- -// Formatted events from the built-in beautifier, with fully readable property names and parsed floats: +// Automatically clear mock calls, instances, contexts and results before every test ⋮---- -// We've included type guards for many events, especially on the user data stream, to help easily -// identify events using simple `if` checks. -// -// Use `if` checks to narrow down specific events from the user data stream +// Indicates whether the coverage information should be collected while executing the test ⋮---- -//// More general handlers, if you prefer: +// An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- -// Any user data event in spot: +// The directory where Jest should output its coverage files ⋮---- -// Any user data event in futures: +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// Any user data event on any market (spot + futures) +// Indicates which provider should be used to instrument code for coverage ⋮---- -// Formatted user data events also have a dedicated event handler, but that's optional and no different to the above -// wsClient.on('formattedUserDataMessage', (data) => { -// if (isWsFormattedSpotOutboundAccountPosition(data)) { -// return; -// // console.log( -// // 'formattedUserDataMessage->isWsFormattedSpotOutboundAccountPosition: ', -// // data, -// // ); -// } -// if (isWsFormattedSpotBalanceUpdate(data)) { -// return console.log( -// 'formattedUserDataMessage->isWsFormattedSpotBalanceUpdate: ', -// data, -// ); -// } -// console.log('formattedUserDataMessage: ', data); -// }); +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], ⋮---- -// console.log('ws response: ', JSON.stringify(data)); +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, ⋮---- -async function main() +// A path to a custom dependency extractor +// dependencyExtractor: undefined, ⋮---- -// Optional, hook and customise logging behavior +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, ⋮---- -// Enforce testnet ws connections, regardless of supplied wsKey: -// testnet: true, +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, ⋮---- -// Note: unless you set this to false, the SDK will automatically call -// the `subscribeUserDataStream()` method again if reconnected (if you called it before): -// resubscribeUserDataStreamAfterReconnect: true, +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], ⋮---- -// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, ⋮---- -logger, // Optional: inject a custom logger, especially to see trace events +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, ⋮---- -// Attach your own event handlers to process incoming events -// You may want to disable the default ones to avoid unnecessary logs (via attachEventListeners:false, above) +// A set of global variables that need to be available in all test environments +// globals: {}, ⋮---- -// 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); +// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. +// maxWorkers: "50%", ⋮---- -// Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will -// automatically call this method again if reconnected, +// An array of directory names to be searched recursively up from the requiring module's location +// moduleDirectories: [ +// "node_modules" +// ], ⋮---- -// The `marginUserData` wsKey will connect to the cross margin Websocket API on Binance. +// An array of file extensions your modules use +// moduleFileExtensions: [ +// "js", +// "mjs", +// "cjs", +// "jsx", +// "ts", +// "tsx", +// "json", +// "node" +// ], ⋮---- -// Start executing the example workflow - -================ -File: examples/WebSockets/Public/ws-public-spot-orderbook.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* eslint-disable no-unused-vars */ -import { - DefaultLogger, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WsMessagePartialBookDepthEventFormatted, -} from '../../../src/index'; +// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module +// moduleNameMapper: {}, ⋮---- -// or, with the npm package -/* -import { - WebsocketClient, - DefaultLogger, - isWsFormattedTrade, -} from 'binance'; -*/ +// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader +// modulePathIgnorePatterns: [], ⋮---- -// trace: () => {}, +// Activates notifications for test results +// notify: false, ⋮---- -/** - * Simple example for receiving depth snapshots from spot orderbooks - */ +// An enum that specifies notification mode. Requires { notify: true } +// notifyMode: "failure-change", ⋮---- -// Request subscription to the following symbol events: +// A preset that is used as a base for Jest's configuration +// preset: undefined, ⋮---- -// const symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT']; +// Run tests from one or more projects +// projects: undefined, ⋮---- -// Loop through symbols -⋮---- -// The old way, convenient but unnecessary: -// wsClient.subscribePartialBookDepths(symbol, levels, 1000, 'spot'); -⋮---- -// Manually build a topic matching the structure expected by binance: -// btcusdt@depth20@1000ms -⋮---- -// Request subscribe for these topics in the main product group (spot markets are under "main") - -================ -File: examples/WebSockets/Public/ws-public-spot-trades.ts -================ -import { - DefaultLogger, - isWsFormattedTrade, - WebsocketClient, -} from '../../../src/index'; -⋮---- -// or, with the npm package -/* -import { - WebsocketClient, - DefaultLogger, - isWsFormattedTrade, -} from 'binance'; -*/ -⋮---- -// trace: () => {}, -⋮---- -// Request subscription to the following symbol trade events: -⋮---- -// Loop through symbols - -================ -File: examples/WebSockets/Public/ws-public-usdm-funding.ts -================ -import { - DefaultLogger, - isWsFormattedMarkPriceUpdateArray, - WebsocketClient, -} from '../../../src/index'; -⋮---- -// or, with the npm package -/* -import { - WebsocketClient, - DefaultLogger, - isWsFormattedMarkPriceUpdateArray, -} from 'binance'; -*/ -⋮---- -// trace: () => {}, -⋮---- -// api_key: key, -// api_secret: secret, -⋮---- -// value is in decimal, multiply by 100 to get percent value -⋮---- -// log table sorted alphabetically by symbol -⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) - -================ -File: examples/WebSockets/Public/ws-public.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, -} from '../../../src'; -⋮---- -// or, with the npm package -/* -import { - WebsocketClient, - DefaultLogger, - isWsFormatted24hrTicker, - isWsFormattedKline, -} from 'binance'; -*/ -⋮---- -// Without typescript: -// const logger = { -⋮---- -// A simple way to suppress heartbeats but receive all other traces -// if (params[0].includes('ping') || params[0].includes('pong')) { -// return; -// } -⋮---- -// Optional: when enabled, the SDK will try to format incoming data into more readable objects. -// Beautified data is emitted via the "formattedMessage" event -⋮---- -logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation -⋮---- -// Raw unprocessed incoming data, e.g. if you have the beautifier disabled -⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); -// console.log('raw message received ', JSON.stringify(data)); -⋮---- -// Formatted data that has gone through the beautifier -⋮---- -/** - * Optional: we've included type-guards for many formatted websocket topics. - * - * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). - */ -// if (isWsAggTradeFormatted(data)) { -// console.log('log agg trade: ', data); -// return; -// } -⋮---- -// // For one symbol -// if (isWsFormattedMarkPriceUpdateEvent(data)) { -// console.log('log mark price: ', data); -// return; -// } +// Use this configuration option to add custom reporters to Jest +// reporters: undefined, ⋮---- -// // for many symbols -// if (isWsFormattedMarkPriceUpdateArray(data)) { -// console.log('log mark prices: ', data); -// return; -// } +// Automatically reset mock state before every test +// resetMocks: false, ⋮---- -// if (isWsFormattedKline(data)) { -// console.log('log kline: ', data); -// return; -// } +// Reset the module registry before running each individual test +// resetModules: false, ⋮---- -// if (isWsFormattedTrade(data)) { -// return console.log('log trade: ', data); -// } +// A path to a custom resolver +// resolver: undefined, ⋮---- -// if (isWsFormattedForceOrder(data)) { -// return console.log('log force order: ', data); -// } +// Automatically restore mock state and implementation before every test +// restoreMocks: false, ⋮---- -// if (isWsFormatted24hrTickerArray(data)) { -// return console.log('log 24hr ticker array: ', data); -// } +// The root directory that Jest should scan for tests and modules within +// rootDir: undefined, ⋮---- -// if (isWsFormattedRollingWindowTickerArray(data)) { -// return console.log('log rolling window ticker array: ', data); -// } +// A list of paths to directories that Jest should use to search for files in +// roots: [ +// "" +// ], ⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } +// Allows you to use a custom runner instead of Jest's default test runner +// runner: "jest-runner", ⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +// The paths to modules that run some code to configure or set up the testing environment before each test +// setupFiles: [], ⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. +// A list of paths to modules that run some code to configure or set up the testing framework before each test +// setupFilesAfterEnv: [], ⋮---- -/** - * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. - * - * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. - */ +// The number of seconds after which a test is considered as slow and reported as such in the results. +// slowTestThreshold: 5, ⋮---- -// // E.g. one at a time, routed to the coinm futures websockets: -// wsClient.subscribe('btcusd@indexPrice', 'coinm'); -// wsClient.subscribe('btcusd@miniTicker', 'coinm'); +// A list of paths to snapshot serializer modules Jest should use for snapshot testing +// snapshotSerializers: [], ⋮---- -// // Or send many topics at once to a stream, e.g. the usdm futures stream: -// wsClient.subscribe( -// [ -// 'btcusdt@aggTrade', -// 'btcusdt@markPrice', -// '!ticker@arr', -// '!miniTicker@arr', -// ], -// 'usdm', -// ); +// The test environment that will be used for testing +// testEnvironment: "jest-environment-node", ⋮---- -/** - * Subscribe to each available type of spot market topic, the new way - */ +// Options that will be passed to the testEnvironment +// testEnvironmentOptions: {}, ⋮---- -// Aggregate Trade Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#aggregate-trade-streams +// Adds a location field to test results +// testLocationInResults: false, ⋮---- -// Trade Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#trade-streams +// The glob patterns Jest uses to detect test files ⋮---- -// Kline/Candlestick Streams for UTC -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc +// "**/__tests__/**/*.[jt]s?(x)", ⋮---- -// Kline/Candlestick Streams with timezone offset -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-with-timezone-offset +// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped +// testPathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// Individual Symbol Mini Ticker Stream -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream +// The regexp pattern or array of patterns that Jest uses to detect test files +// testRegex: [], ⋮---- -// All Market Mini Tickers Stream -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream +// This option allows the use of a custom results processor +// testResultsProcessor: undefined, ⋮---- -// Individual Symbol Ticker Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-ticker-streams +// This option allows use of a custom test runner +// testRunner: "jest-circus/runner", ⋮---- -// All Market Tickers Stream - DEPRECATED (2025-11-14) -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-tickers-stream -// '!ticker@arr', // DEPRECATED: Use '@ticker' or '!miniTicker@arr' instead -// Recommended alternative: '!miniTicker@arr' for all market mini tickers (already subscribed above) -// Individual Symbol Rolling Window Statistics Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-rolling-window-statistics-streams +// A map from regular expressions to paths to transformers +// transform: undefined, ⋮---- -// All Market Rolling Window Statistics Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams +// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation +// transformIgnorePatterns: [ +// "/node_modules/", +// "\\.pnp\\.[^\\/]+$" +// ], ⋮---- -// Individual Symbol Book Ticker Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams +// Prevents import esm module error from v1 axios release, issue #5026 ⋮---- -// Average Price -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price +// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them +// unmockedModulePathPatterns: undefined, ⋮---- -// Partial Book Depth Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams +// Indicates whether each individual test should be reported during the run +// verbose: undefined, +verbose: true, // report individual test ⋮---- -// Diff. Depth Stream -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream +// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode +// watchPathIgnorePatterns: [], ⋮---- -// Look at the `WS_KEY_URL_MAP` for a list of values here: -// https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts -// "main" connects to wss://stream.binance.com:9443/stream -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams -⋮---- -// Aggregate Trade Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams -⋮---- -// Mark Price Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream -⋮---- -// Mark Price Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market -⋮---- -// Kline/Candlestick Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams -// 'btcusdt@kline_1m', -// Continuous Contract Kline/Candlestick Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams -// 'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER -// Individual Symbol Mini Ticker Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream -// 'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE -// All Market Mini Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream -// '!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD -// Individual Symbol Ticker Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams -//'btcusdt@ticker', -// All Market Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream -// '!ticker@arr', // DOESNT EXIST AS TYPE GUARD -// Individual Symbol Book Ticker Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Book-Ticker-Streams -//'btcusdt@bookTicker', // DOESNT EXIST AS TYPE GUARD -// All Book Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream -// '!bookTicker', // DOESNT EXIST AS TYPE GUARD -// Liquidation Order Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams -// 'btcusdt@forceOrder', -// Liquidation Order Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams -//'!forceOrder@arr', -// Partial Book Depth Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams -//'btcusdt@depth5', -// 'btcusdt@depth10@100ms' -// Diff. Book Depth Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams -// 'btcusdt@depth', -// 'btcusdt@depth@100ms', -// 'btcusdt@depth@500ms', -// 'btcusdt@depth@1000ms' -// Composite Index Symbol Information Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams -// 'btcusdt@compositeIndex' // DOESNT EXIST AS TYPE GUARD -// Contract Info Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream -// '!contractInfo' // DOESNT EXIST AS TYPE GUARD -// Multi-Assets Mode Asset Index Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index -// '!assetIndex@arr' // DOESNT EXIST AS TYPE GUARD -// 'btcusdt@assetIndex' -⋮---- -/** - * Subscribe to each available options market data websocket topic, the new way: - * - * https://developers.binance.com/docs/derivatives/options-trading/websocket-market-streams/New-Symbol-Info - * https://eapi.binance.com/eapi/v1/exchangeInfo - */ -⋮---- -const optionsExpiration = '260128'; // YYMMDD -⋮---- -// You can send raw commands, such as asking for list of active subscriptions after 5 seconds. Use with caution: -// setTimeout(() => { -// wsClient.tryWsSend( -// 'eoptions', -// JSON.stringify({ -// method: 'LIST_SUBSCRIPTIONS', -// id: Date.now(), -// }), -// ); -// }, 1000 * 5); -⋮---- -// /** -// * -// * For those that used the Node.js Binance SDK before the v3 release, you can -// * still subscribe to available market topics the "old" way, for convenience -// * when migrating from the old WebsocketClient to the new multiplex client): -// * -// */ -⋮---- -// wsClient.subscribeAggregateTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(symbol, 'spot'); -// wsClient.subscribeTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(coinMSymbol, 'coinm'); -// wsClient.subscribeCoinIndexPrice(coinMSymbol2); -// wsClient.subscribeAllBookTickers('usdm'); -// wsClient.subscribeSpotKline(symbol, '1m'); -// wsClient.subscribeMarkPrice(symbol, 'usdm'); -// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMarketMarkPrice('usdm'); -// wsClient.subscribeAllMarketMarkPrice('coinm'); -// wsClient.subscribeKlines(symbol, '1m', 'usdm'); -// wsClient.subscribeContinuousContractKlines( -// symbol, -// 'perpetual', -// '1m', -// 'usdm', -// ); -// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); -// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMini24hrTickers('spot'); -// wsClient.subscribeAllMini24hrTickers('usdm'); -// wsClient.subscribeAllMini24hrTickers('coinm'); -// wsClient.subscribeAll24hrTickers('spot'); -// wsClient.subscribeAll24hrTickers('usdm'); -// wsClient.subscribeAll24hrTickers('coinm'); -// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); -// wsClient.subscribeAllLiquidationOrders('usdm'); -// wsClient.subscribeAllLiquidationOrders('coinm'); -// wsClient.subscribeSpotSymbol24hrTicker(symbol); -// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); -// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); -// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); -// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); -// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); -// wsClient.subscribeContractInfoStream('usdm'); -// wsClient.subscribeContractInfoStream('coinm'); +// Whether to use watchman for file crawling +// watchman: true, ================ -File: src/types/websockets/ws-api-responses.ts +File: jsconfig.json ================ -import type { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures.js'; -import { - numberInString, - OrderSide, - OrderTimeInForce, - SelfTradePreventionMode, -} from '../shared'; -import { OrderResponse } from '../spot'; -⋮---- -/** - * Error response type - */ -export interface ErrorResponse { - code: number; - msg: string; -} -⋮---- -export interface WSAPISessionStatus { - apiKey: string; - authorizedSince: number; - connectedSince: number; - returnRateLimits: boolean; - serverTime: number; - userDataStream: boolean; +{ + "compilerOptions": { + "target": "ES6", + "module": "commonjs" + }, + "exclude": [ + "node_modules", + "**/node_modules/*", + "coverage", + "doc" + ] } -⋮---- -/** - * General response types - */ -export interface WSAPIServerTime { - serverTime: number; + +================ +File: LICENSE.md +================ +Copyright 2025 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================ +File: tsconfig.build.json +================ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules", + "test", + "dist", + "**/*spec.ts", + "**/*test.ts", + "jest.config.ts" + ] } -⋮---- -/** - * Market data response types - */ -export interface WSAPIOrderBook { - lastUpdateId: number; - // [price, quantity] - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; + +================ +File: tsconfig.json +================ +{ + "compileOnSave": true, + "compilerOptions": { + "allowJs": true, + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "declaration": true, + "removeComments": false, + "noEmitOnError": true, + "noImplicitAny": false, + "strictNullChecks": true, + "skipLibCheck": true, + "sourceMap": true, + "esModuleInterop": true, + "lib": ["es2017", "dom"], + "baseUrl": ".", + "outDir": "lib" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"] } -⋮---- -// [price, quantity] -⋮---- -export interface WSAPITrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; + +================ +File: tsconfig.linting.json +================ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext", + "rootDir": "../", + "allowJs": true + }, + "include": [ + "src/**/*.*", + "test/**/*.*", + "examples/**/*.*", + ".eslintrc.cjs", + "jest.config.ts", + "webpack/webpack.config.ts" + ] } + +================ +File: examples/auth/rest-private-ed25519.md +================ +# Ed25519 Authentication with Binance APIs in Node.js + +## Creating Ed25519 Keys + +Officially, binance recommends downloading and running a key generator from their repo. Guidance for this can be found on the [binance website](https://www.binance.com/en/support/faq/detail/6b9a63f1e3384cf48a2eedb82767a69a) when trying to add a new Ed25519 API key, or in their GitHub repository: https://github.com/binance/asymmetric-key-generator + +## Using the Ed25519 public key to get an API key from Binance + +Once created, keep your **private key** completely secret! The **public** key needs to be provided to binance when creating new API credentials with the "Self-generated" option. + +Your public key should look something like this: + +```pem +-----BEGIN PUBLIC KEY----- +lkn123bx123x+7lkmlkn123bx123xAMDO/lkm123x= +-----END PUBLIC KEY----- +``` + +Submit this in the "Upload public key" form, shown when creating a new API key on binance and choosing the "self-generated" option. + +Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. + +After using the public key to create a new API key, you will be given an API Key such as the following: + +``` +mlk2mx3l12m3lxk1m3lxk1m3l1k2mx3l12km3xl1km23x1l2k3mx1l2km3x +``` + +This is the first piece, used as the "apiKey" in the [rest-private-ed25519.ts](./rest-private-ed25519.ts) example. + +## Using the Ed25519 private key for Ed25519 authentication with binance APIs in Node.js + +Your private key, if generated with the above steps, should look something like this (but with much more text): + +```pem +-----BEGIN PRIVATE KEY----- +lx1k2m3xl12lkm2l1kmx312312l3mx1lk23m +-----END PRIVATE KEY----- +``` + +This is your secret, you should **never** share this with anyone, not even binance! Treat this like a password. + +As part of this authentication process, your private key is used to generate a signature. This SDK handles this process automatically for you. Ed25519 authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. + +From here, simply use the key provided by binance as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. + +Based on the above example, the following would prepare the main REST client using the above credentials: + +```typescript +const ed25519PrivateKey = ` +-----BEGIN PRIVATE KEY----- +lkmlkm123lkms1s12s+lkmlkm123lkms1s12s +-----END PRIVATE KEY----- +`; + +const ed25519APIKey = 'lkmlkm123lkms1s12slkmlkm123lkms1s12slkmlkm123lkms1s12s'; + +const restClient = new MainClient({ + api_key: ed25519APIKey, + api_secret: ed25519PrivateKey, + beautifyResponses: true, +}); + +const wsApiClient = new WebsocketAPIClient({ + api_key: ed25519APIKey, + api_secret: ed25519PrivateKey, +}); +``` + +The rest is automatic - just continue using the SDK as you would normally. It will automatically handle signing requests using Ed25519 for you. + +For a complete example, refer to the [rest-private-ed25519.ts](./rest-private-ed25519.ts) file on GitHub. + +================ +File: examples/WebSockets/Misc/ws-proxy-socks.ts +================ +/** + * Minimal example for using a socks proxy with the ws client, extracted from https://github.com/tiagosiebler/binance/pull/319 + */ +import { WebsocketClient } from '../../../src/index'; ⋮---- -export interface WSAPIAggregateTrade { - a: number; // Aggregate trade ID - p: numberInString; // Price - q: numberInString; // Quantity - f: number; // First trade ID - l: number; // Last trade ID - T: number; // Timestamp - m: boolean; // Was the buyer the maker? - M: boolean; // Was the trade the best price match? -} +// or +// import { WebsocketClient } from 'binance'; ⋮---- -a: number; // Aggregate trade ID -p: numberInString; // Price -q: numberInString; // Quantity -f: number; // First trade ID -l: number; // Last trade ID -T: number; // Timestamp -m: boolean; // Was the buyer the maker? -M: boolean; // Was the trade the best price match? +import { SocksProxyAgent } from 'socks-proxy-agent'; +// const { SocksProxyAgent } = require('socks-proxy-agent'); + +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-connection-safety.ts +================ +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotUserDataEvent, + isWsFormattedSpotUserDataExecutionReport, + isWsFormattedUserDataEvent, + WebsocketClient, + WsUserDataEvents, +} from '../../../src/index'; ⋮---- -export type WSAPIKline = [ - number, // Kline open time - numberInString, // Open price - numberInString, // High price - numberInString, // Low price - numberInString, // Close price - numberInString, // Volume - number, // Kline close time - numberInString, // Quote asset volume - number, // Number of trades - numberInString, // Taker buy base asset volume - numberInString, // Taker buy quote asset volume - numberInString, // Unused field -]; +// or +// import { DefaultLogger, WebsocketClient } from 'binance'; ⋮---- -number, // Kline open time -numberInString, // Open price -numberInString, // High price -numberInString, // Low price -numberInString, // Close price -numberInString, // Volume -number, // Kline close time -numberInString, // Quote asset volume -number, // Number of trades -numberInString, // Taker buy base asset volume -numberInString, // Taker buy quote asset volume -numberInString, // Unused field +/** + * This extended example for using the user data stream demonstrates one way to handle failures in the first connection attempt of the user data stream. + * In most cases this is overkill! + */ ⋮---- -export interface WSAPIAvgPrice { - mins: number; // Average price interval (in minutes) - price: numberInString; // Average price - closeTime: number; // Last trade time -} +// optionally block some silly logs from showing in the logger ⋮---- -mins: number; // Average price interval (in minutes) -price: numberInString; // Average price -closeTime: number; // Last trade time +// Optional, hook and customise logging behavior ⋮---- -export interface WSAPIFullTicker { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - prevClosePrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First trade ID - lastId: number; // Last trade ID - count: number; // Number of trades -} +// wsClient.on('message', (data) => { +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// }); ⋮---- -firstId: number; // First trade ID -lastId: number; // Last trade ID -count: number; // Number of trades +function onUserDataEvent(data: WsUserDataEvents) ⋮---- -export interface WSAPIMiniTicker { - symbol: string; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - lastPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First trade ID - lastId: number; // Last trade ID - count: number; // Number of trades -} +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { ⋮---- -firstId: number; // First trade ID -lastId: number; // Last trade ID -count: number; // Number of trades +// or use a type guard, if one exists (PRs welcome) ⋮---- -export interface WSAPIPriceTicker { - symbol: string; - price: numberInString; -} +// The wsKey can be parsed to determine the type of message (what websocket it came from) +// if (!Array.isArray(data) && data.wsKey.includes('userData')) { +// return onUserDataEvent(data); +// } ⋮---- -export interface WSAPIBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; -} +// or use a type guard if available ⋮---- -/** - * Futures market data response types - */ -export interface WSAPIFuturesOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - // [price, quantity] - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -E: number; // Message output time -T: number; // Transaction time -// [price, quantity] +// Note: manually re-subscribing like this may only be needed if the FIRST user data connection attempt failed +// Capture exceptions using the error event, and handle this. ⋮---- -export interface WSAPIFuturesPriceTicker { - symbol: string; - price: numberInString; - time: number; // Transaction time -} +// wsClient.subscribeMarginUserDataStream(); +// wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); + +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-listenKey-testnet.ts +================ +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotUserDataEvent, + isWsFormattedSpotUserDataExecutionReport, + isWsFormattedUserDataEvent, + WebsocketClient, + WsUserDataEvents, +} from '../../../src/index'; ⋮---- -time: number; // Transaction time +// or +// import { DefaultLogger, WebsocketClient } from 'binance'; ⋮---- -export interface WSAPIFuturesBookTicker { - lastUpdateId: number; - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; // Transaction time -} +// console.log('using api credentials: ', { key, secret }); ⋮---- -time: number; // Transaction time +// Optional, hook and customise logging behavior ⋮---- -/** - * Account response types - */ -export interface WSAPIAccountInformation { - makerCommission: number; - takerCommission: number; - buyerCommission: number; - sellerCommission: number; - canTrade: boolean; - canWithdraw: boolean; - canDeposit: boolean; - commissionRates: { - maker: numberInString; - taker: numberInString; - buyer: numberInString; - seller: numberInString; - }; - brokered: boolean; - requireSelfTradePrevention: boolean; - preventSor: boolean; - updateTime: number; - accountType: string; - balances: { - asset: string; - free: numberInString; - locked: numberInString; - }[]; - permissions: string[]; - uid: number; -} +// If you prefer, you can receive raw unprocessed data without the "beautifier": +// wsClient.on('message', (data) => { +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// }); ⋮---- -export interface WSAPIAccountCommission { - symbol: string; - standardCommission: { - maker: numberInString; - taker: numberInString; - buyer: numberInString; - seller: numberInString; - }; - taxCommission: { - maker: numberInString; - taker: numberInString; - buyer: numberInString; - seller: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - discount: numberInString; - }; -} +function onUserDataEvent(data: WsUserDataEvents) ⋮---- -export interface WSAPIRateLimit { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { ⋮---- -export interface WSAPIOrder { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice: numberInString; - icebergQty: numberInString; - time: number; - updateTime: number; - isWorking: boolean; - workingTime: number; - origQuoteOrderQty: numberInString; - selfTradePreventionMode: string; - preventedMatchId?: number; - preventedQuantity?: numberInString; - /** Present only for expired orders. */ - expiryReason?: string; -} +// or use a type guard, if one exists (PRs welcome) ⋮---- -/** Present only for expired orders. */ +// Beautified/formatted events from binance: ⋮---- -export interface WSAPIBlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} +// The wsKey can be parsed to determine the type of message (what websocket it came from) +// if (!Array.isArray(data) && data.wsKey.includes('userData')) { +// return onUserDataEvent(data); +// } ⋮---- -export interface WSAPIOrderList { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; -} +// or use a type guard if available ⋮---- -export interface WSAPITrade { - symbol: string; - id: number; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isBestMatch: boolean; -} +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -export interface WSAPIPreventedMatch { - symbol: string; - preventedMatchId: number; - takerOrderId: number; - makerSymbol: string; - makerOrderId: number; - tradeGroupId: number; - selfTradePreventionMode: string; - price: numberInString; - makerPreventedQuantity: numberInString; - transactTime: number; -} +// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: +// - fetch balances +// - fetch positions +// - fetch orders ⋮---- -export interface WSAPIAllocation { - symbol: string; - allocationId: number; - allocationType: string; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isAllocator: boolean; -} +// wsClient.subscribeMarginUserDataStream(); +// wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); +// wsClient.subscribeUsdFuturesUserDataStream(); +⋮---- +// setTimeout(() => { +// console.log('killing all connections'); +// wsClient.closeAll(); +// }, 1000 * 15); + +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-wsapi-margin.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +// or +// import { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } from 'binance'; +// or +// const { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } = require('binance'); +⋮---- +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotBalanceUpdate, + isWsFormattedSpotOutboundAccountPosition, + isWsFormattedSpotUserDataEvent, + isWsFormattedUserDataEvent, + WebsocketAPIClient, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- /** - * Trading response types + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. */ -export interface WSAPIOrderTestResponse { - // Empty response object - [key: string]: never; -} -⋮---- -// Empty response object ⋮---- -export interface WSAPIOrderTestWithCommission { - standardCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - discount: numberInString; - }; -} +// returned by binance, generated using the publicKey (above) +// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; +// Your Ed25519 private key is passed as the "secret" +// const secret = privateKey; ⋮---- -export interface WSAPIOrderCancel { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: numberInString; - trailingDelta?: number; - trailingTime?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode: string; -} +function attachEventHandlers( + wsClient: TWSClient, +): void ⋮---- -export interface WSAPIOrderCancelReplaceResponse { - cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: WSAPIOrderCancel | ErrorResponse; - newOrderResponse: OrderResponse | ErrorResponse | null; -} +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -export interface WSAPIOrderListCancelResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: WSAPIOrderCancel[]; -} +// Raw events received from binance, as is: ⋮---- -/** - * Order list response types - */ -export interface WSAPIOrderListPlaceResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: OrderResponse[]; -} +// console.log('raw message received ', JSON.stringify(data)); ⋮---- -export interface WSAPIOrderListStatusResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - /** Present only for expired orders. */ - expiryReason?: string; - }[]; -} +// Formatted events from the built-in beautifier, with fully readable property names and parsed floats: ⋮---- -/** Present only for expired orders. */ +// We've included type guards for many events, especially on the user data stream, to help easily +// identify events using simple `if` checks. +// +// Use `if` checks to narrow down specific events from the user data stream ⋮---- -/** - * SOR response types - */ -export interface WSAPISOROrderPlaceResponse { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; - fills: { - matchType: string; - price: string; - qty: string; - commission: string; - commissionAsset: string; - tradeId: number; - allocId: number; - }[]; - workingFloor: string; - selfTradePreventionMode: string; - usedSor: boolean; -} +//// More general handlers, if you prefer: ⋮---- -/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ +// Any user data event in spot: ⋮---- -export interface WSAPISOROrderTestResponse { - // Empty response object - [key: string]: never; -} +// Any user data event in futures: ⋮---- -// Empty response object +// Any user data event on any market (spot + futures) ⋮---- -export interface WSAPISOROrderTestResponseWithCommission { - standardCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - discount: numberInString; - }; -} +// Formatted user data events also have a dedicated event handler, but that's optional and no different to the above +// wsClient.on('formattedUserDataMessage', (data) => { +// if (isWsFormattedSpotOutboundAccountPosition(data)) { +// return; +// // console.log( +// // 'formattedUserDataMessage->isWsFormattedSpotOutboundAccountPosition: ', +// // data, +// // ); +// } +// if (isWsFormattedSpotBalanceUpdate(data)) { +// return console.log( +// 'formattedUserDataMessage->isWsFormattedSpotBalanceUpdate: ', +// data, +// ); +// } +// console.log('formattedUserDataMessage: ', data); +// }); ⋮---- -/** - * Futures trading response types - */ -export interface WSAPIFuturesOrder { - orderId: number; - symbol: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumQty: string; - cumQuote: string; - timeInForce: string; - type: string; - reduceOnly: boolean; - closePosition: boolean; - side: string; - positionSide: string; - stopPrice: string; - workingType: string; - priceProtect: boolean; - origType: string; - priceMatch: string; - selfTradePreventionMode: string; - goodTillDate: number; - updateTime: number; - time?: number; - activatePrice?: string; - priceRate?: string; -} +// console.log('ws response: ', JSON.stringify(data)); ⋮---- -export interface WSAPIFuturesPosition { - entryPrice: string; - breakEvenPrice: string; - marginType: string; - isAutoAddMargin: string; - isolatedMargin: string; - leverage: string; - liquidationPrice: string; - markPrice: string; - maxNotionalValue: string; - positionAmt: string; - notional: string; - isolatedWallet: string; - symbol: string; - unRealizedProfit: string; - positionSide: string; - updateTime: number; -} +async function main() ⋮---- -export interface WSAPIFuturesPositionV2 { - symbol: string; - positionSide: string; - positionAmt: string; - entryPrice: string; - breakEvenPrice: string; - markPrice: string; - unrealizedProfit: string; - liquidationPrice: string; - isolatedMargin: string; - notional: string; - marginAsset: string; - isolatedWallet: string; - initialMargin: string; - maintMargin: string; - positionInitialMargin: string; - openOrderInitialMargin: string; - adl: number; - bidNotional: string; - askNotional: string; - updateTime: number; -} -⋮---- -export interface WSAPIFuturesAlgoOrder { - algoId: number; - clientAlgoId: string; - algoType: FuturesAlgoOrderType; - orderType: FuturesAlgoConditionalOrderTypes; - symbol: string; - side: OrderSide; - positionSide: PositionSide; - timeInForce: OrderTimeInForce; - quantity: numberInString; - algoStatus: FuturesAlgoOrderStatus; - triggerPrice: numberInString; - price: numberInString; - icebergQuantity: numberInString | null; - selfTradePreventionMode: SelfTradePreventionMode; - workingType: WorkingType; - priceMatch: PriceMatchMode; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - createTime: number; - updateTime: number; - triggerTime: number; - goodTillDate: number; -} -⋮---- -export interface WSAPIFuturesAlgoOrderCancelResponse extends ErrorResponse { - algoId: number; - clientAlgoId: string; -} -⋮---- -/** - * Futures account response types - */ -export interface WSAPIFuturesAccountBalanceItem { - accountAlias: string; - asset: string; - balance: string; - crossWalletBalance: string; - crossUnPnl: string; - availableBalance: string; - maxWithdrawAmount: string; - marginAvailable: boolean; - updateTime: number; -} -⋮---- -export interface WSAPIFuturesAccountAsset { - asset: string; - walletBalance: string; - unrealizedProfit: string; - marginBalance: string; - maintMargin: string; - initialMargin: string; - positionInitialMargin: string; - openOrderInitialMargin: string; - crossWalletBalance: string; - crossUnPnl: string; - availableBalance: string; - maxWithdrawAmount: string; - marginAvailable?: boolean; - updateTime: number; -} +// Optional, hook and customise logging behavior ⋮---- -export interface WSAPIFuturesAccountPosition { - symbol: string; - initialMargin?: string; - maintMargin?: string; - unrealizedProfit: string; - positionInitialMargin?: string; - openOrderInitialMargin?: string; - leverage?: string; - isolated?: boolean; - entryPrice?: string; - breakEvenPrice?: string; - maxNotional?: string; - bidNotional?: string; - askNotional?: string; - positionSide: string; - positionAmt: string; - updateTime: number; -} +// Enforce testnet ws connections, regardless of supplied wsKey: +// testnet: true, ⋮---- -export interface WSAPIFuturesAccountStatus { - feeTier?: number; - canTrade?: boolean; - canDeposit?: boolean; - canWithdraw?: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId?: number; - totalInitialMargin: string; - totalMaintMargin: string; - totalWalletBalance: string; - totalUnrealizedProfit: string; - totalMarginBalance: string; - totalPositionInitialMargin: string; - totalOpenOrderInitialMargin: string; - totalCrossWalletBalance: string; - totalCrossUnPnl: string; - availableBalance: string; - maxWithdrawAmount: string; - assets: WSAPIFuturesAccountAsset[]; - positions: WSAPIFuturesAccountPosition[]; -} +// Note: unless you set this to false, the SDK will automatically call +// the `subscribeUserDataStream()` method again if reconnected (if you called it before): +// resubscribeUserDataStreamAfterReconnect: true, ⋮---- -/** - * Spot Order response types based on newOrderRespType parameter - */ -export interface WSAPISpotOrderACK { - symbol: string; - orderId: number; - orderListId: number; // always -1 for singular orders - clientOrderId: string; - transactTime: number; -} +// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: ⋮---- -orderListId: number; // always -1 for singular orders +logger, // Optional: inject a custom logger, especially to see trace events ⋮---- -export interface WSAPISpotOrderRESULT extends WSAPISpotOrderACK { - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; -} +// Attach your own event handlers to process incoming events +// You may want to disable the default ones to avoid unnecessary logs (via attachEventListeners:false, above) ⋮---- -/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ +// 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); ⋮---- -export interface WSAPISpotOrderFill { - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; - tradeId: number; -} +// Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will +// automatically call this method again if reconnected, ⋮---- -export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { - fills: WSAPISpotOrderFill[]; -} +// The `marginUserData` wsKey will connect to the cross margin Websocket API on Binance. ⋮---- -export type WSAPISpotOrderResponse = - | WSAPISpotOrderACK - | WSAPISpotOrderRESULT - | WSAPISpotOrderFULL; +// Start executing the example workflow ================ -File: src/types/portfolio-margin.ts +File: examples/WebSockets/WS-API/ws-api-client.ts ================ -// Enums -export type PMStrategyType = - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; +/* eslint-disable @typescript-eslint/no-unused-vars */ +// or +// import { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } from 'binance'; +// or +// const { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } = require('binance'); ⋮---- -export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +import { DefaultLogger, WebsocketAPIClient } from '../../../src'; ⋮---- -export type PMPriceMatch = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; +/** + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. + */ ⋮---- -export type PMSelfTradePreventionMode = - | 'NONE' - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH'; +// returned by binance, generated using the publicKey (above) +// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; +// Your Ed25519 private key is passed as the "secret" +// const secret = privateKey; ⋮---- -export type PMMarginOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +// function attachEventHandlers( +// wsClient: TWSClient, +// ): void { +// /** +// * General event handlers for monitoring the WebsocketClient +// */ +// wsClient.on('message', (data) => { +// // console.log('raw message received ', JSON.stringify(data)); +// }); +// wsClient.on('response', (data) => { +// // console.log('ws response: ', JSON.stringify(data)); +// }); +// wsClient.on('open', (data) => { +// console.log('ws connected', data.wsKey); +// }); +// wsClient.on('reconnecting', ({ 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); +// }); +// wsClient.on('exception', (data) => { +// console.error('ws exception: ', JSON.stringify(data)); +// }); +// } ⋮---- -export type PMMarginSideEffectType = - | 'NO_SIDE_EFFECT' - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'AUTO_BORROW_REPAY'; +async function main() ⋮---- -export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +// trace: (...params) => console.log(new Date(), 'trace', ...params), ⋮---- -export interface NewPortfolioUMOrderReq { +// Enforce testnet ws connections, regardless of supplied wsKey +// testnet: true, +⋮---- +// Note: unless you set this to false, the SDK will automatically call +// the `subscribeUserDataStream()` method again if reconnected (if you called it before): +// resubscribeUserDataStreamAfterReconnect: true, +⋮---- +// 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 +⋮---- +// Optional, 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. Can be used to prepare a connection before sending commands. +// Can be done as part of a bootstrapping workflow, to reduce initial latency when sending the first command +// await wsClient.getWSClient().connectWSAPI(WS_KEY_MAP.mainWSAPI); +⋮---- +// SPOT - Market data requests +⋮---- +// SPOT - Trading requests +⋮---- +// SPOT - Account requests +⋮---- +// FUTURES - Market data requests +⋮---- +// FUTURES - Trading requests +⋮---- +// FUTURES - Account requests +⋮---- +// Start executing the example workflow + +================ +File: examples/WebSockets/WS-API/ws-api-raw-promises.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + DefaultLogger, + WebsocketClient, + WS_KEY_MAP, + WSAPIWsKey, +} from '../../../src/index'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient, WSAPIWsKey } from 'binance'; +⋮---- +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +⋮---- +// testnet: true, +⋮---- +logger, // Optional: inject a custom logger +⋮---- +/** + * General event handlers for monitoring the WebsocketClient + */ +⋮---- +// WS API responses can be processed here too, but that is optional +// console.log('ws response: ', JSON.stringify(data)); +⋮---- +async function main() +⋮---- +/** + * + * 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 (using the connectWSAPI() method shown below). This is optional. + * + */ +⋮---- +/** + * Websockets (with their unique URLs) are tracked using the concept of a "WsKey". + * + * This WsKey identifies the "main" WS API connection URL (e.g. for spot & margin markets): + * wss://ws-api.binance.com:443/ws-api/v3 + * + * Other notable keys: + * - mainWSAPI2: alternative for "main" + * - mainWSAPITestnet: "main" testnet + * - usdmWSAPI: usdm futures + * - usdmWSAPITestnet: usdm futures testnet + * - coinmWSAPI: coinm futures + * - coinmWSAPITestnet: coinm futures testnet + */ +⋮---- +// Note: if you set "testnet: true" in the config, this will automatically resolve to WS_KEY_MAP.mainWSAPITestnet (you can keep using mainWSAPI). +⋮---- +// 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, see above. Can be used to prepare a connection before sending commands. This is not required and will happen automatically +// await wsClient.connectWSAPI(WS_API_WS_KEY); +⋮---- +// rateLimits: wsAPIResponse.result.rateLimits, +// symbols: wsAPIResponse.result.symbols, +⋮---- +// Start executing the example workflow + +================ +File: src/types/portfolio-margin.ts +================ +// Enums +export type PMStrategyType = + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; +⋮---- +export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +⋮---- +export type PMPriceMatch = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; +⋮---- +export type PMSelfTradePreventionMode = + | 'NONE' + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH'; +⋮---- +export type PMMarginOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; +⋮---- +export type PMMarginSideEffectType = + | 'NO_SIDE_EFFECT' + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'AUTO_BORROW_REPAY'; +⋮---- +export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +⋮---- +export interface NewPortfolioUMOrderReq { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode @@ -4614,2343 +4118,2366 @@ export interface PortfolioTradFiPerpsContractSignResponse { } ================ -File: src/types/shared.ts +File: src/index.ts ================ -// Generic numeric value stored as a string. Can be parsed via parseInt or parseFloat. -// Beautifier may convert these to number, if enabled. -export type numberInString = string | number; + + +================ +File: .gitignore +================ +.vscode/ +.idea/ +.nyc_output/ +node_modules/ +util/config.js +coverage/ +yarn-error.log +lib/* +testfile.ts +privaterepotracker +restClientRegex.ts +.DS_Store +dist +localtest.ts +repomix.sh +doc +*.pem + +================ +File: eslint.config.cjs +================ + + +================ +File: examples/WebSockets/Public/ws-usdm-market.ts +================ +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- -export type ExchangeSymbol = string; +// or, with the npm package +/* +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from 'binance'; +*/ ⋮---- -export type BooleanString = 'true' | 'false'; +// Without typescript: +// const logger = { ⋮---- -export type BinanceBaseUrlKey = - | 'spot' - | 'spot1' - | 'spot2' - | 'spot3' - | 'spot4' - | 'spottest' - | 'usdmtest' - | 'usdm' - | 'coinm' - | 'coinmtest' - | 'voptions' - | 'voptionstest' - | 'papi' - | 'www'; +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; +// } ⋮---- -/** - * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. - */ -export type OrderTimeInForce = - | 'GTC' - | 'IOC' - | 'FOK' - | 'GTX' - | 'GTE_GTC' - | 'GTD'; +// Optional: when enabled, the SDK will try to format incoming data into more readable objects. +// Beautified data is emitted via the "formattedMessage" event ⋮---- -export type StringBoolean = 'TRUE' | 'FALSE'; +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -export type SideEffects = - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'NO_SIDE_EFFECT' - | 'AUTO_BORROW_REPAY' - | 'NO_SIDE_EFFECT'; +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -/** - * ACK = confirmation of order acceptance (no placement/fill information) - * RESULT = fill state - * FULL = fill state + detail on fills and other detail - */ -export type OrderResponseType = 'ACK' | 'RESULT' | 'FULL'; +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export type OrderIdProperty = - | 'newClientOrderId' - | 'newClientStrategyId' - | 'listClientOrderId' - | 'limitClientOrderId' - | 'stopClientOrderId' - | 'clientAlgoId' - | 'aboveClientOrderId' - | 'belowClientOrderId' - | 'workingClientOrderId' - | 'pendingAboveClientOrderId' - | 'pendingBelowClientOrderId' - | 'pendingClientOrderId'; -⋮---- -export type OrderSide = 'BUY' | 'SELL'; +// console.log('log rawMessage: ', data); ⋮---- -export type OrderStatus = - | 'NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED'; +// Formatted data that has gone through the beautifier ⋮---- -export type OrderExecutionType = - | 'NEW' - | 'CANCELED' - | 'REJECTED' - | 'TRADE' - | 'EXPIRED'; +// console.log('log formattedMessage: ', data); ⋮---- -// listStatusType -export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; +/** + * Optional: we've included type-guards for many formatted websocket topics. + * + * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). + */ +// if (isWsAggTradeFormatted(data)) { +// console.log('log agg trade: ', data); +// return; +// } ⋮---- -// listOrderStatus -export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -export type OrderType = - | 'LIMIT' - | 'LIMIT_MAKER' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -export type OrderListOrderType = - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -export type SelfTradePreventionMode = - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -export interface BasicAssetParam { - asset: string; -} +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -export interface BasicSymbolParam { - symbol: string; - isIsolated?: StringBoolean; -} +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -export interface SymbolArrayParam { - symbols: string[]; -} +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -export interface BasicAssetPaginatedParams { - asset?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -export interface BasicSymbolPaginatedParams { - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -export interface SymbolPrice { - symbol: string; - price: numberInString; - time?: number; -} +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -// used by spot and usdm -export interface OrderBookParams { - symbol: string; - limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; - symbolStatus?: string; -} +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- -export type KlineInterval = - | '1s' - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '3d' - | '1w' - | '1M'; +/** + * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. + * + * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. + * + * The WsKey is a reference to the connection that this topic should be routed to. + * WS_KEY_MAP is a complete enum with all the available WsKey values. + * + * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data + */ ⋮---- -export interface GetOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// Uses the regular market feeds WS URL dedicated to USDM Futures: wss://fstream.binance.com/market/stream ⋮---- -export interface GetOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Subscribe to each available type of USDM Derivatives market topic, the new way + */ ⋮---- -export interface HistoricalTradesParams { - symbol: string; - limit?: number; - fromId?: number; -} +// Aggregate Trade Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams ⋮---- -export interface KlinesParams { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} +// Mark Price Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream ⋮---- -export type Kline = [ - number, // open time - numberInString, // open - numberInString, // high - numberInString, // low - numberInString, // close - numberInString, // volume - number, // close time - numberInString, // quote asset volume - number, // number of trades - numberInString, // taker buy base asset vol - numberInString, // taker buy quote asset vol - numberInString, // ignore? -]; +// Mark Price Stream for All market +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market ⋮---- -number, // open time -numberInString, // open -numberInString, // high -numberInString, // low -numberInString, // close -numberInString, // volume -number, // close time -numberInString, // quote asset volume -number, // number of trades -numberInString, // taker buy base asset vol -numberInString, // taker buy quote asset vol -numberInString, // ignore? +// Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams ⋮---- -/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ -export type FuturesKline = Kline; -export interface RecentTradesParams { - symbol: string; - limit?: number; -} +// Continuous Contract Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams +'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER ⋮---- -export interface CancelOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// Individual Symbol Mini Ticker Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream +'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE ⋮---- -export interface AmendKeepPriorityParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - newQty: numberInString; -} +// All Market Mini Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream +'!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD ⋮---- -export interface CancelOCOParams { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} +// Individual Symbol Ticker Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams ⋮---- -export interface NewOCOParams { - symbol: string; - listClientOrderId?: string; - side: OrderSide; - quantity: number; - limitClientOrderId?: string; - limitStrategyId?: number; - limitStrategyType?: number; - price: number; - limitIcebergQty?: number; - trailingDelta?: number; - stopClientOrderId?: string; - stopPrice: number; - stopStrategyId?: number; - stopStrategyType?: number; - stopLimitPrice?: number; - stopIcebergQty?: number; - stopLimitTimeInForce?: OrderTimeInForce; - newOrderRespType?: OrderResponseType; - /** For isolated margin trading only */ - isIsolated?: StringBoolean; - /** Define a side effect, only for margin trading */ - sideEffectType?: SideEffects; -} +// All Market Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream +'!ticker@arr', // DOESNT EXIST AS TYPE GUARD ⋮---- -/** For isolated margin trading only */ +// Liquidation Order Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams ⋮---- -/** Define a side effect, only for margin trading */ +// Liquidation Order Stream for All market +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams ⋮---- -export interface NewOrderListParams< - T extends OrderResponseType = OrderResponseType, -> { - symbol: string; - listClientOrderId?: string; - side: OrderSide; - quantity: number; - aboveType: OrderListOrderType; - aboveClientOrderId?: string; - aboveIcebergQty?: number; - abovePrice?: number; - aboveStopPrice?: number; - aboveTrailingDelta?: number; - aboveTimeInForce?: OrderTimeInForce; - aboveStrategyId?: number; - aboveStrategyType?: number; - belowType: OrderListOrderType; - belowClientOrderId?: string; - belowIcebergQty?: number; - belowPrice?: number; - belowStopPrice?: number; - belowTrailingDelta?: number; - belowTimeInForce?: OrderTimeInForce; - belowStrategyId?: number; - belowStrategyType?: number; - newOrderRespType?: T; - selfTradePreventionMode?: SelfTradePreventionMode; -} +// Composite Index Symbol Information Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams ⋮---- -export interface SymbolFromPaginatedRequestFromId { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +'btcusdt@compositeIndex', // DOESNT EXIST AS TYPE GUARD +// Contract Info Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream +'!contractInfo', // DOESNT EXIST AS TYPE GUARD ⋮---- -export interface GetAllOrdersParams { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// Multi-Assets Mode Asset Index Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index +'!assetIndex@arr', // DOESNT EXIST AS TYPE GUARD ⋮---- -export interface RateLimiter { - rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; - interval: 'SECOND' | 'MINUTE' | 'DAY'; - intervalNum: number; - limit: number; -} +// /** +// * +// * For those that used the Node.js Binance SDK before the v3 release, you can +// * still subscribe to available market topics the "old" way, for convenience +// * when migrating from the old WebsocketClient to the new multiplex client): +// * +// */ ⋮---- -export interface SymbolPriceFilter { - filterType: 'PRICE_FILTER'; - minPrice: numberInString; - maxPrice: numberInString; - tickSize: numberInString; -} +// wsClient.subscribeAggregateTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(symbol, 'spot'); +// wsClient.subscribeTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(coinMSymbol, 'coinm'); +// wsClient.subscribeCoinIndexPrice(coinMSymbol2); +// wsClient.subscribeAllBookTickers('usdm'); +// wsClient.subscribeSpotKline(symbol, '1m'); +// wsClient.subscribeMarkPrice(symbol, 'usdm'); +// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMarketMarkPrice('usdm'); +// wsClient.subscribeAllMarketMarkPrice('coinm'); +// wsClient.subscribeKlines(symbol, '1m', 'usdm'); +// wsClient.subscribeContinuousContractKlines( +// symbol, +// 'perpetual', +// '1m', +// 'usdm', +// ); +// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); +// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMini24hrTickers('spot'); +// wsClient.subscribeAllMini24hrTickers('usdm'); +// wsClient.subscribeAllMini24hrTickers('coinm'); +// wsClient.subscribeAll24hrTickers('spot'); +// wsClient.subscribeAll24hrTickers('usdm'); +// wsClient.subscribeAll24hrTickers('coinm'); +// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); +// wsClient.subscribeAllLiquidationOrders('usdm'); +// wsClient.subscribeAllLiquidationOrders('coinm'); +// wsClient.subscribeSpotSymbol24hrTicker(symbol); +// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); +// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); +// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); +// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); +// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); +// wsClient.subscribeContractInfoStream('usdm'); +// wsClient.subscribeContractInfoStream('coinm'); + +================ +File: examples/WebSockets/Public/ws-usdm-public.ts +================ +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- -export interface SymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - avgPriceMins: number; -} +// or, with the npm package +/* +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from 'binance'; +*/ ⋮---- -export interface SymbolPercentPriceBySideFilter { - filterType: 'PERCENT_PRICE_BY_SIDE'; - bidMultiplierUp: numberInString; - bidMultiplierDown: numberInString; - askMultiplierUp: numberInString; - askMultiplierDown: numberInString; - avgPriceMins: number; -} +// Without typescript: +// const logger = { ⋮---- -export interface SymbolLegacyMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - minNotional: numberInString; - applyToMarket: boolean; - avgPriceMins: number; -} +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; +// } ⋮---- -export interface SymbolLotSizeFilter { - filterType: 'LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +// Optional: when enabled, the SDK will try to format incoming data into more readable objects. +// Beautified data is emitted via the "formattedMessage" event ⋮---- -export interface SymbolMinNotionalFilter { - filterType: 'NOTIONAL'; - minNotional: numberInString; - applyMinToMarket: boolean; - maxNotional: numberInString; - applyMaxToMarket: boolean; - avgPriceMins: number; -} +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -export interface SymbolIcebergPartsFilter { - filterType: 'ICEBERG_PARTS'; - limit: number; -} +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -export interface SymbolMarketLotSizeFilter { - filterType: 'MARKET_LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface SymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - maxNumOrders: number; -} +// console.log('log rawMessage: ', data); ⋮---- -export interface SymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +// Formatted data that has gone through the beautifier ⋮---- -export interface SymbolMaxIcebergOrdersFilter { - filterType: 'MAX_NUM_ICEBERG_ORDERS'; - maxNumIcebergOrders: number; -} +// console.log('log formattedMessage: ', data); ⋮---- -export interface SymbolMaxPositionFilter { - filterType: 'MAX_POSITION'; - maxPosition: numberInString; -} +/** + * Optional: we've included type-guards for many formatted websocket topics. + * + * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). + */ +// if (isWsAggTradeFormatted(data)) { +// console.log('log agg trade: ', data); +// return; +// } ⋮---- -export type SymbolFilter = - | SymbolPriceFilter - | SymbolPercentPriceFilter - | SymbolPercentPriceBySideFilter - | SymbolLegacyMinNotionalFilter - | SymbolLotSizeFilter - | SymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | SymbolMaxOrdersFilter - | SymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter; -⋮---- -export interface ExchangeMaxNumOrdersFilter { - filterType: 'EXCHANGE_MAX_NUM_ORDERS'; - maxNumOrders: number; -} -⋮---- -export interface ExchangeMaxAlgoOrdersFilter { - filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} -⋮---- -export type ExchangeFilter = - | ExchangeMaxNumOrdersFilter - | ExchangeMaxAlgoOrdersFilter; +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -export type OrderBookPrice = numberInString; -export type OrderBookAmount = numberInString; +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -export type OrderBookPriceFormatted = number; -export type OrderBookAmountFormatted = number; -export type OrderBookRowFormatted = [ - OrderBookPriceFormatted, - OrderBookAmountFormatted, -]; +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -export interface GenericCodeMsgError { - code: number; - msg: string; -} +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -export interface RowsWithTotal { - rows: T[]; - total: number; -} +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -export interface CoinStartEndLimit { - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} - -================ -File: src/index.ts -================ - - -================ -File: .gitignore -================ -.vscode/ -.idea/ -.nyc_output/ -node_modules/ -util/config.js -coverage/ -yarn-error.log -lib/* -testfile.ts -privaterepotracker -restClientRegex.ts -.DS_Store -dist -localtest.ts -repomix.sh -doc -*.pem - -================ -File: eslint.config.cjs -================ - - -================ -File: examples/WebSockets/Misc/ws-proxy-socks.ts -================ -/** - * Minimal example for using a socks proxy with the ws client, extracted from https://github.com/tiagosiebler/binance/pull/319 - */ -import { WebsocketClient } from '../../../src/index'; +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -// or -// import { WebsocketClient } from 'binance'; +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -import { SocksProxyAgent } from 'socks-proxy-agent'; -// const { SocksProxyAgent } = require('socks-proxy-agent'); - -================ -File: examples/WebSockets/Private(userdata)/ws-userdata-connection-safety.ts -================ -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotUserDataEvent, - isWsFormattedSpotUserDataExecutionReport, - isWsFormattedUserDataEvent, - WebsocketClient, - WsUserDataEvents, -} from '../../../src/index'; +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -// or -// import { DefaultLogger, WebsocketClient } from 'binance'; +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- /** - * This extended example for using the user data stream demonstrates one way to handle failures in the first connection attempt of the user data stream. - * In most cases this is overkill! - */ -⋮---- -// optionally block some silly logs from showing in the logger -⋮---- -// Optional, hook and customise logging behavior -⋮---- -// wsClient.on('message', (data) => { -// console.log('raw message received ', JSON.stringify(data, null, 2)); -// }); -⋮---- -function onUserDataEvent(data: WsUserDataEvents) + * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. + * + * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. + * + * The WsKey is a reference to the connection that this topic should be routed to. + * WS_KEY_MAP is a complete enum with all the available WsKey values. + * + * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data + */ ⋮---- -// the market denotes which API category it came from -// if (data.wsMarket.includes('spot')) { +// Uses the high-frequency order book & core public feeds WS URL dedicated to USDM Futures: +// wss://fstream.binance.com/public/stream ⋮---- -// or use a type guard, if one exists (PRs welcome) +/** + * Subscribe to each available type of USDM Derivatives market topic, the new way + */ ⋮---- -// The wsKey can be parsed to determine the type of message (what websocket it came from) -// if (!Array.isArray(data) && data.wsKey.includes('userData')) { -// return onUserDataEvent(data); -// } +// Individual Symbol Book Ticker Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams ⋮---- -// or use a type guard if available +// All Book Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream +'!bookTicker', // DOESNT EXIST AS TYPE GUARD +// Partial Book Depth Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams ⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +// Diff. Book Depth Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams ⋮---- -// Note: manually re-subscribing like this may only be needed if the FIRST user data connection attempt failed -// Capture exceptions using the error event, and handle this. +// /** +// * +// * For those that used the Node.js Binance SDK before the v3 release, you can +// * still subscribe to available market topics the "old" way, for convenience +// * when migrating from the old WebsocketClient to the new multiplex client): +// * +// */ ⋮---- -// wsClient.subscribeMarginUserDataStream(); -// wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); +// wsClient.subscribeAggregateTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(symbol, 'spot'); +// wsClient.subscribeTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(coinMSymbol, 'coinm'); +// wsClient.subscribeCoinIndexPrice(coinMSymbol2); +// wsClient.subscribeAllBookTickers('usdm'); +// wsClient.subscribeSpotKline(symbol, '1m'); +// wsClient.subscribeMarkPrice(symbol, 'usdm'); +// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMarketMarkPrice('usdm'); +// wsClient.subscribeAllMarketMarkPrice('coinm'); +// wsClient.subscribeKlines(symbol, '1m', 'usdm'); +// wsClient.subscribeContinuousContractKlines( +// symbol, +// 'perpetual', +// '1m', +// 'usdm', +// ); +// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); +// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMini24hrTickers('spot'); +// wsClient.subscribeAllMini24hrTickers('usdm'); +// wsClient.subscribeAllMini24hrTickers('coinm'); +// wsClient.subscribeAll24hrTickers('spot'); +// wsClient.subscribeAll24hrTickers('usdm'); +// wsClient.subscribeAll24hrTickers('coinm'); +// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); +// wsClient.subscribeAllLiquidationOrders('usdm'); +// wsClient.subscribeAllLiquidationOrders('coinm'); +// wsClient.subscribeSpotSymbol24hrTicker(symbol); +// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); +// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); +// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); +// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); +// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); +// wsClient.subscribeContractInfoStream('usdm'); +// wsClient.subscribeContractInfoStream('coinm'); ================ -File: examples/WebSockets/Private(userdata)/ws-userdata-listenKey-testnet.ts +File: examples/WebSockets/README.md ================ -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotUserDataEvent, - isWsFormattedSpotUserDataExecutionReport, - isWsFormattedUserDataEvent, - WebsocketClient, - WsUserDataEvents, -} from '../../../src/index'; -⋮---- -// or -// import { DefaultLogger, WebsocketClient } from 'binance'; -⋮---- -// console.log('using api credentials: ', { key, secret }); -⋮---- -// Optional, hook and customise logging behavior -⋮---- -// If you prefer, you can receive raw unprocessed data without the "beautifier": -// wsClient.on('message', (data) => { -// console.log('raw message received ', JSON.stringify(data, null, 2)); -// }); -⋮---- -function onUserDataEvent(data: WsUserDataEvents) +# Binance WebSocket Streams + +This Node.js, JavaScript & TypeScript SDK for Binance has complete support for all available WebSocket capabilities of Binance's API offering. + +## Capabilities + +These WebSocket capabilities are split into two key groups: + +1. WebSocket Consumers: + - Subscribe to market data & receive realtime updates. + - Subscribe to private account data & receive realtime updates (generally called the user data stream). +2. WebSocket API: + - Send requests & commands over a persistent WebSocket (WSAPI) connection. E.g. Submit an order. + - Subscribe to private account data & receive realtime updates (generally called the user data stream), over a persistent WebSocket (WSAPI) connection. Note: + - This was previously available without the WebSocket API, via a mechanic involving a temporary listenKey. + - In recent updates, the WebSocket API supports subscribing to the user data stream (private updates). + - In some cases, this is the only way to subsrcibe to the user data stream (e.g. in Spot markets). + +## Architecture + +### WebsocketClient + +This SDK has all WebSocket capabilities integrated in the dedicated class called the `WebsocketClient`. This can be imported from the package directly. This all-in-one class handles all aspects of Binance's WebSocket capabilities, across all subdomains & endpoints. It also includes the raw capabilities to support integration with the WebSocket API. Subscriptions, heartbeats and connection recovery after disconnect - these are all included automatically. + +If the answer to any of these is yes, you should be using the WebsocketClient: + +- You want to subscribe to & receive realtime updates for public market data. +- You want raw control over how & where WebSocket API commands are sent. + +If you are looking for a more convenient integration with Binance's WebSocket API, you should look at the `WebsocketAPIClient`. + +### WebsocketAPIClient + +This is a utility class built over the WebsocketClient to especially provide a more convenient way of using Binance's WebSocket API. While WebSockets are asynchronous by design, the WebsocketAPIClient provides a way to send WebSocket API commands and await the result. All commands are wrapped in a promise and internal event tracking ensures promises are resolved or rejected as part of the command life cycle. + +This utility class in this SDK allows you to integrate the WebSocket API in the same way that you would integrate a REST API. Make a request and await the result. + +As of early 2026, some of the user data streams are also only available via the WebSocket API streams. This has been integrated into the WebsocketAPIClient and is available with a number of user data methods, depending on the product group. Some references: + +- Spot: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` +- Margin: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.marginUserData)` +- USDM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.usdmWSAPI)` +- CoinM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.coinmWSAPI)` + +## Key Features + +### Base URL Split & Migration + +On 06/03/2026, Binance announced a routing upgrade to their USDM Futures WebSocket System, titled: "Binance USDⓈ-M Futures WebSocket System Upgrade Notice (2026-03-06)". + +#### Key Highlights: + +- Introduction of three dedicated WebSocket base URLs: + - Public (high-frequency public market data) + - wss://fstream.binance.com/public + - Market (regular market data) + - wss://fstream.binance.com/market + - Private (user data streams) + - wss://fstream.binance.com/private +- New endpoints are supported immediately upon this announcement. +- Legacy WebSocket URLs will be permanently retired on 2026-04-23. +- Documentation including endpoint & stream mapping: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data + +#### Binance JavaScript SDK Support + +All three dedicated WebSocket base URLs are supported. Each with their own unique WsKey, used to track each unique connection. + +Continue to subscribe to market data as before with the dedicated subscribe method, but ensure to provide the connection key depending on the type of market data you are consuming. + +Minimal examples: + +```typescript +// ... + +// For public (high-frequency public data) +const wsKeyUsdmPublic = WS_KEY_MAP.usdmPublic; +wsClient.subscribe(['btcusdt@bookTicker', 'btcusdt@depth'], wsKeyUsdmPublic); + +// For market (regular market data) +const wsKeyUsdmMarket = WS_KEY_MAP.usdmMarket; +wsClient.subscribe(['btcusdt@aggTrade', 'btcusdt@forceOrder'], wsKeyUsdmMarket); + +// For user data, continue using the subscribe user data stream method as before. +// The SDK will automatically route to the "private" endpoint for USDM Futures: +wsClient.subscribeUsdFuturesUserDataStream(); +``` + +#### Legacy `wsClient.subscribe*()` methods + +If you're using any of the per-topic convenience methods, such as `wsClient.subscribeAggregateTrades(...)`, no change is required. The SDK will automatically route the topic subscription request to the appropriate WS URL. + +## Further Reading + +For detailed examples, refer to the examples in this folder, as well as the following documentation: + +- Binance JavaScript SDK QuickStart Guide: https://siebly.io/sdk/binance/javascript +- Binance JavaScript SDK Readme: https://www.npmjs.com/package/binance + +================ +File: examples/README.md +================ +# Binance API - Examples + +This folder contains ready to go examples demonstrating various aspects of this API implementation, written in TypeScript (but they are compatible with pure JavaScript projects). + +Found something difficult to implement? Contribute to these examples and help others! + +## Getting started + +- Clone the project (or download it as a zip, or install the module in your own project `npm install binance`). +- Edit the sample as needed (some samples require edits, e.g API keys or import statements to import from npm, not src). +- Execute the sample using tsx: `tsx examples/REST/rest-spot-public.ts`. + +Samples that refer to API credentials using `process.env.API_KEY_COM` can be spawned with environment variables. Unix/macOS example: +``` +API_KEY_COM='apikeypastedhere' API_SECRET_COM='apisecretpastedhere' tsx "examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts" +``` + +Or edit the example directly to hardcode your API keys. + +### WebSockets + +All examples relating to WebSockets can be found in the [examples/WebSockets](./WebSockets/) folder. High level summary of available examples: + +#### Consumers + +These are purely for receiving data from Binance's WebSockets (market data, account updates, etc). + +##### Market Data + +These examples demonstrate subscribing to & receiving market data from Binance's WebSockets: + +- ws-public.ts + - Demonstration on general usage of the WebSocket client to subscribe to / unsubscribe from one or more market data topics. +- ws-public-spot-orderbook.ts + - Subscribing to orderbook events for multiple symbols in spot markets. +- ws-public-spot-trades.ts + - Subscribing to raw trades for multiple symbols in spot markets. +- ws-unsubscribe.ts + - Subscribing to a list of topics, and then unsubscribing from a few topics in that list. +- ws-public-usdm-funding.ts + - Simple example subscribing to a general topic, and how to process incoming events to only extract funding rates from those events. + +##### Account Data + +These examples demonstrate receiving account update events from Binance's WebSockets: + +- ws-userdata-listenkey.ts + - Demonstration on subscribing to various user data streams (spot, margin, futures), + - Handling incoming user data events + - Using provided type guards to determine which product group the user data event is for (spot, margin, futures, etc). +- ws-userdata-listenKey-testnet.ts + - Similar to above, but on testnet. +- ws-userdata-connection-safety.ts + - Demonstration on extra safety around the first user data stream connection. + - Note: this is overkill in most situations... + +##### WebSocket API + +These examples demonstrate how to send commands using Binance's WebSocket API (e.g. submitting orders). Very similar to the REST API, but using a persisted WebSocket connection instead of HTTP requests. + +- ws-api-client.ts + - Demonstration of using Binance's WebSocket API in Node.js/JavaScript/TypeScript, using the WebsocketAPIClient. + - This WebsocketAPIClient is very similar to a REST client, with one method per available command (endpoint) and fully typed requests & responses. + - Routing is automatically handled via the WebsocketClient, including authentication and connection persistence. Just call the functions you need - the SDK does the rest. + - From a usage perspective, it feels like a REST API - you can await responses just like a HTTP request. +- ws-api-raw-promises.ts + - More verbose usage of the WebSocket API using the `sendWSAPIRequest()` method. + - The `WebsocketAPIClient` uses this method too, so in most cases it is simple to just use the `WebsocketAPIClient` instead. +- ws-userdata-wsapi.ts + - The listenKey workflow for the user data stream is deprecated (in spot markets). + - This example demonstrates how to subscribe to the user data stream in spot markets, without a listen key, using the WebSocket API. + +##### Misc Workflows + +These are miscellaneous examples that cover one or more of the above categories: + +- ws-close.ts + - Closing the (old listen-key driven) user data stream. + - Unsubscribing from various topics. +- ws-proxy-socks.ts + - Using WebSockets over a SOCKS proxy. +- deprecated-ws-public.ts + + +### REST APIs + +All examples relating to REST APIs can be found in the [examples/REST](./REST/) folder. Most examples are named around functionality & product group. Any examples with "private" involve API calls relating to your account (such as changing settings or submitting orders, etc), + +High level summary for some of the available examples, but check the folder for a complete list: + +#### REST USDM Examples + +- `rest-future-bracket-order.ts` Creates an entry order plus a passive reduce-only TP limit order and an SL Algo Service order. +- `rest-usdm-order.ts` Creates a single entry order using `submitNewOrder`. +- `rest-usdm-order-sl.ts` Modifies a Hedge Mode LONG stop-loss order using Algo Service orders. + +================ +File: src/types/websockets/ws-api-responses.ts +================ +import type { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures.js'; +import { + numberInString, + OrderSide, + OrderTimeInForce, + SelfTradePreventionMode, +} from '../shared'; +import { OrderResponse } from '../spot'; ⋮---- -// the market denotes which API category it came from -// if (data.wsMarket.includes('spot')) { +/** + * Error response type + */ +export interface ErrorResponse { + code: number; + msg: string; +} ⋮---- -// or use a type guard, if one exists (PRs welcome) +export interface WSAPISessionStatus { + apiKey: string; + authorizedSince: number; + connectedSince: number; + returnRateLimits: boolean; + serverTime: number; + userDataStream: boolean; +} ⋮---- -// Beautified/formatted events from binance: +/** + * General response types + */ +export interface WSAPIServerTime { + serverTime: number; +} ⋮---- -// The wsKey can be parsed to determine the type of message (what websocket it came from) -// if (!Array.isArray(data) && data.wsKey.includes('userData')) { -// return onUserDataEvent(data); -// } +/** + * Market data response types + */ +export interface WSAPIOrderBook { + lastUpdateId: number; + // [price, quantity] + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} ⋮---- -// or use a type guard if available +// [price, quantity] ⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -⋮---- -// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: -// - fetch balances -// - fetch positions -// - fetch orders +export interface WSAPITrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; +} ⋮---- -// wsClient.subscribeMarginUserDataStream(); -// wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); -// wsClient.subscribeUsdFuturesUserDataStream(); +export interface WSAPIAggregateTrade { + a: number; // Aggregate trade ID + p: numberInString; // Price + q: numberInString; // Quantity + f: number; // First trade ID + l: number; // Last trade ID + T: number; // Timestamp + m: boolean; // Was the buyer the maker? + M: boolean; // Was the trade the best price match? +} ⋮---- -// setTimeout(() => { -// console.log('killing all connections'); -// wsClient.closeAll(); -// }, 1000 * 15); - -================ -File: examples/WebSockets/Public/ws-usdm-market.ts -================ -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from '../../../src'; +a: number; // Aggregate trade ID +p: numberInString; // Price +q: numberInString; // Quantity +f: number; // First trade ID +l: number; // Last trade ID +T: number; // Timestamp +m: boolean; // Was the buyer the maker? +M: boolean; // Was the trade the best price match? ⋮---- -// or, with the npm package -/* -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from 'binance'; -*/ +export type WSAPIKline = [ + number, // Kline open time + numberInString, // Open price + numberInString, // High price + numberInString, // Low price + numberInString, // Close price + numberInString, // Volume + number, // Kline close time + numberInString, // Quote asset volume + number, // Number of trades + numberInString, // Taker buy base asset volume + numberInString, // Taker buy quote asset volume + numberInString, // Unused field +]; ⋮---- -// Without typescript: -// const logger = { +number, // Kline open time +numberInString, // Open price +numberInString, // High price +numberInString, // Low price +numberInString, // Close price +numberInString, // Volume +number, // Kline close time +numberInString, // Quote asset volume +number, // Number of trades +numberInString, // Taker buy base asset volume +numberInString, // Taker buy quote asset volume +numberInString, // Unused field ⋮---- -// A simple way to suppress heartbeats but receive all other traces -// if (params[0].includes('ping') || params[0].includes('pong')) { -// return; -// } +export interface WSAPIAvgPrice { + mins: number; // Average price interval (in minutes) + price: numberInString; // Average price + closeTime: number; // Last trade time +} ⋮---- -// Optional: when enabled, the SDK will try to format incoming data into more readable objects. -// Beautified data is emitted via the "formattedMessage" event +mins: number; // Average price interval (in minutes) +price: numberInString; // Average price +closeTime: number; // Last trade time ⋮---- -logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation +export interface WSAPIFullTicker { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + prevClosePrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; // First trade ID + lastId: number; // Last trade ID + count: number; // Number of trades +} ⋮---- -// Raw unprocessed incoming data, e.g. if you have the beautifier disabled +firstId: number; // First trade ID +lastId: number; // Last trade ID +count: number; // Number of trades ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +export interface WSAPIMiniTicker { + symbol: string; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + lastPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; // First trade ID + lastId: number; // Last trade ID + count: number; // Number of trades +} ⋮---- -// console.log('log rawMessage: ', data); +firstId: number; // First trade ID +lastId: number; // Last trade ID +count: number; // Number of trades ⋮---- -// Formatted data that has gone through the beautifier +export interface WSAPIPriceTicker { + symbol: string; + price: numberInString; +} ⋮---- -// console.log('log formattedMessage: ', data); +export interface WSAPIBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; +} ⋮---- /** - * Optional: we've included type-guards for many formatted websocket topics. - * - * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). - */ -// if (isWsAggTradeFormatted(data)) { -// console.log('log agg trade: ', data); -// return; -// } -⋮---- -// // For one symbol -// if (isWsFormattedMarkPriceUpdateEvent(data)) { -// console.log('log mark price: ', data); -// return; -// } -⋮---- -// // for many symbols -// if (isWsFormattedMarkPriceUpdateArray(data)) { -// console.log('log mark prices: ', data); -// return; -// } -⋮---- -// if (isWsFormattedKline(data)) { -// console.log('log kline: ', data); -// return; -// } -⋮---- -// if (isWsFormattedTrade(data)) { -// return console.log('log trade: ', data); -// } -⋮---- -// if (isWsFormattedForceOrder(data)) { -// return console.log('log force order: ', data); -// } -⋮---- -// if (isWsFormatted24hrTickerArray(data)) { -// return console.log('log 24hr ticker array: ', data); -// } -⋮---- -// if (isWsFormattedRollingWindowTickerArray(data)) { -// return console.log('log rolling window ticker array: ', data); -// } + * Futures market data response types + */ +export interface WSAPIFuturesOrderBook { + lastUpdateId: number; + E: number; // Message output time + T: number; // Transaction time + // [price, quantity] + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} ⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } +E: number; // Message output time +T: number; // Transaction time +// [price, quantity] ⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +export interface WSAPIFuturesPriceTicker { + symbol: string; + price: numberInString; + time: number; // Transaction time +} ⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. +time: number; // Transaction time ⋮---- -/** - * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. - * - * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. - * - * The WsKey is a reference to the connection that this topic should be routed to. - * WS_KEY_MAP is a complete enum with all the available WsKey values. - * - * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data - */ +export interface WSAPIFuturesBookTicker { + lastUpdateId: number; + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; // Transaction time +} ⋮---- -// Uses the regular market feeds WS URL dedicated to USDM Futures: wss://fstream.binance.com/market/stream +time: number; // Transaction time ⋮---- /** - * Subscribe to each available type of USDM Derivatives market topic, the new way - */ -⋮---- -// Aggregate Trade Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams -⋮---- -// Mark Price Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream + * Account response types + */ +export interface WSAPIAccountInformation { + makerCommission: number; + takerCommission: number; + buyerCommission: number; + sellerCommission: number; + canTrade: boolean; + canWithdraw: boolean; + canDeposit: boolean; + commissionRates: { + maker: numberInString; + taker: numberInString; + buyer: numberInString; + seller: numberInString; + }; + brokered: boolean; + requireSelfTradePrevention: boolean; + preventSor: boolean; + updateTime: number; + accountType: string; + balances: { + asset: string; + free: numberInString; + locked: numberInString; + }[]; + permissions: string[]; + uid: number; +} ⋮---- -// Mark Price Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market +export interface WSAPIAccountCommission { + symbol: string; + standardCommission: { + maker: numberInString; + taker: numberInString; + buyer: numberInString; + seller: numberInString; + }; + taxCommission: { + maker: numberInString; + taker: numberInString; + buyer: numberInString; + seller: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + discount: numberInString; + }; +} ⋮---- -// Kline/Candlestick Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams +export interface WSAPIRateLimit { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} ⋮---- -// Continuous Contract Kline/Candlestick Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams -'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER +export interface WSAPIOrder { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice: numberInString; + icebergQty: numberInString; + time: number; + updateTime: number; + isWorking: boolean; + workingTime: number; + origQuoteOrderQty: numberInString; + selfTradePreventionMode: string; + preventedMatchId?: number; + preventedQuantity?: numberInString; + /** Present only for expired orders. */ + expiryReason?: string; +} ⋮---- -// Individual Symbol Mini Ticker Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream -'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE +/** Present only for expired orders. */ ⋮---- -// All Market Mini Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream -'!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD +export interface WSAPIBlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} ⋮---- -// Individual Symbol Ticker Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams +export interface WSAPIOrderList { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; +} ⋮---- -// All Market Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream -'!ticker@arr', // DOESNT EXIST AS TYPE GUARD +export interface WSAPITrade { + symbol: string; + id: number; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isBestMatch: boolean; +} ⋮---- -// Liquidation Order Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams +export interface WSAPIPreventedMatch { + symbol: string; + preventedMatchId: number; + takerOrderId: number; + makerSymbol: string; + makerOrderId: number; + tradeGroupId: number; + selfTradePreventionMode: string; + price: numberInString; + makerPreventedQuantity: numberInString; + transactTime: number; +} ⋮---- -// Liquidation Order Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams +export interface WSAPIAllocation { + symbol: string; + allocationId: number; + allocationType: string; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isAllocator: boolean; +} ⋮---- -// Composite Index Symbol Information Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams +/** + * Trading response types + */ +export interface WSAPIOrderTestResponse { + // Empty response object + [key: string]: never; +} ⋮---- -'btcusdt@compositeIndex', // DOESNT EXIST AS TYPE GUARD -// Contract Info Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream -'!contractInfo', // DOESNT EXIST AS TYPE GUARD +// Empty response object ⋮---- -// Multi-Assets Mode Asset Index Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index -'!assetIndex@arr', // DOESNT EXIST AS TYPE GUARD +export interface WSAPIOrderTestWithCommission { + standardCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + discount: numberInString; + }; +} ⋮---- -// /** -// * -// * For those that used the Node.js Binance SDK before the v3 release, you can -// * still subscribe to available market topics the "old" way, for convenience -// * when migrating from the old WebsocketClient to the new multiplex client): -// * -// */ +export interface WSAPIOrderCancel { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: numberInString; + trailingDelta?: number; + trailingTime?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode: string; +} ⋮---- -// wsClient.subscribeAggregateTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(symbol, 'spot'); -// wsClient.subscribeTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(coinMSymbol, 'coinm'); -// wsClient.subscribeCoinIndexPrice(coinMSymbol2); -// wsClient.subscribeAllBookTickers('usdm'); -// wsClient.subscribeSpotKline(symbol, '1m'); -// wsClient.subscribeMarkPrice(symbol, 'usdm'); -// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMarketMarkPrice('usdm'); -// wsClient.subscribeAllMarketMarkPrice('coinm'); -// wsClient.subscribeKlines(symbol, '1m', 'usdm'); -// wsClient.subscribeContinuousContractKlines( -// symbol, -// 'perpetual', -// '1m', -// 'usdm', -// ); -// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); -// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMini24hrTickers('spot'); -// wsClient.subscribeAllMini24hrTickers('usdm'); -// wsClient.subscribeAllMini24hrTickers('coinm'); -// wsClient.subscribeAll24hrTickers('spot'); -// wsClient.subscribeAll24hrTickers('usdm'); -// wsClient.subscribeAll24hrTickers('coinm'); -// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); -// wsClient.subscribeAllLiquidationOrders('usdm'); -// wsClient.subscribeAllLiquidationOrders('coinm'); -// wsClient.subscribeSpotSymbol24hrTicker(symbol); -// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); -// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); -// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); -// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); -// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); -// wsClient.subscribeContractInfoStream('usdm'); -// wsClient.subscribeContractInfoStream('coinm'); - -================ -File: examples/WebSockets/Public/ws-usdm-public.ts -================ -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from '../../../src'; -⋮---- -// or, with the npm package -/* -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from 'binance'; -*/ +export interface WSAPIOrderCancelReplaceResponse { + cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: WSAPIOrderCancel | ErrorResponse; + newOrderResponse: OrderResponse | ErrorResponse | null; +} ⋮---- -// Without typescript: -// const logger = { +export interface WSAPIOrderListCancelResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: WSAPIOrderCancel[]; +} ⋮---- -// A simple way to suppress heartbeats but receive all other traces -// if (params[0].includes('ping') || params[0].includes('pong')) { -// return; -// } +/** + * Order list response types + */ +export interface WSAPIOrderListPlaceResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: OrderResponse[]; +} ⋮---- -// Optional: when enabled, the SDK will try to format incoming data into more readable objects. -// Beautified data is emitted via the "formattedMessage" event +export interface WSAPIOrderListStatusResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + /** Present only for expired orders. */ + expiryReason?: string; + }[]; +} ⋮---- -logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation +/** Present only for expired orders. */ ⋮---- -// Raw unprocessed incoming data, e.g. if you have the beautifier disabled +/** + * SOR response types + */ +export interface WSAPISOROrderPlaceResponse { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; + fills: { + matchType: string; + price: string; + qty: string; + commission: string; + commissionAsset: string; + tradeId: number; + allocId: number; + }[]; + workingFloor: string; + selfTradePreventionMode: string; + usedSor: boolean; +} ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ ⋮---- -// console.log('log rawMessage: ', data); +export interface WSAPISOROrderTestResponse { + // Empty response object + [key: string]: never; +} ⋮---- -// Formatted data that has gone through the beautifier +// Empty response object ⋮---- -// console.log('log formattedMessage: ', data); +export interface WSAPISOROrderTestResponseWithCommission { + standardCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + discount: numberInString; + }; +} ⋮---- /** - * Optional: we've included type-guards for many formatted websocket topics. - * - * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). - */ -// if (isWsAggTradeFormatted(data)) { -// console.log('log agg trade: ', data); -// return; -// } -⋮---- -// // For one symbol -// if (isWsFormattedMarkPriceUpdateEvent(data)) { -// console.log('log mark price: ', data); -// return; -// } -⋮---- -// // for many symbols -// if (isWsFormattedMarkPriceUpdateArray(data)) { -// console.log('log mark prices: ', data); -// return; -// } -⋮---- -// if (isWsFormattedKline(data)) { -// console.log('log kline: ', data); -// return; -// } -⋮---- -// if (isWsFormattedTrade(data)) { -// return console.log('log trade: ', data); -// } + * Futures trading response types + */ +export interface WSAPIFuturesOrder { + orderId: number; + symbol: string; + status: string; + clientOrderId: string; + price: string; + avgPrice: string; + origQty: string; + executedQty: string; + cumQty: string; + cumQuote: string; + timeInForce: string; + type: string; + reduceOnly: boolean; + closePosition: boolean; + side: string; + positionSide: string; + stopPrice: string; + workingType: string; + priceProtect: boolean; + origType: string; + priceMatch: string; + selfTradePreventionMode: string; + goodTillDate: number; + updateTime: number; + time?: number; + activatePrice?: string; + priceRate?: string; +} ⋮---- -// if (isWsFormattedForceOrder(data)) { -// return console.log('log force order: ', data); -// } +export interface WSAPIFuturesPosition { + entryPrice: string; + breakEvenPrice: string; + marginType: string; + isAutoAddMargin: string; + isolatedMargin: string; + leverage: string; + liquidationPrice: string; + markPrice: string; + maxNotionalValue: string; + positionAmt: string; + notional: string; + isolatedWallet: string; + symbol: string; + unRealizedProfit: string; + positionSide: string; + updateTime: number; +} ⋮---- -// if (isWsFormatted24hrTickerArray(data)) { -// return console.log('log 24hr ticker array: ', data); -// } +export interface WSAPIFuturesPositionV2 { + symbol: string; + positionSide: string; + positionAmt: string; + entryPrice: string; + breakEvenPrice: string; + markPrice: string; + unrealizedProfit: string; + liquidationPrice: string; + isolatedMargin: string; + notional: string; + marginAsset: string; + isolatedWallet: string; + initialMargin: string; + maintMargin: string; + positionInitialMargin: string; + openOrderInitialMargin: string; + adl: number; + bidNotional: string; + askNotional: string; + updateTime: number; +} ⋮---- -// if (isWsFormattedRollingWindowTickerArray(data)) { -// return console.log('log rolling window ticker array: ', data); -// } +export interface WSAPIFuturesAlgoOrder { + algoId: number; + clientAlgoId: string; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; + symbol: string; + side: OrderSide; + positionSide: PositionSide; + timeInForce: OrderTimeInForce; + quantity: numberInString; + algoStatus: FuturesAlgoOrderStatus; + triggerPrice: numberInString; + price: numberInString; + icebergQuantity: numberInString | null; + selfTradePreventionMode: SelfTradePreventionMode; + workingType: WorkingType; + priceMatch: PriceMatchMode; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; +} ⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } +export interface WSAPIFuturesAlgoOrderCancelResponse extends ErrorResponse { + algoId: number; + clientAlgoId: string; +} ⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +/** + * Futures account response types + */ +export interface WSAPIFuturesAccountBalanceItem { + accountAlias: string; + asset: string; + balance: string; + crossWalletBalance: string; + crossUnPnl: string; + availableBalance: string; + maxWithdrawAmount: string; + marginAvailable: boolean; + updateTime: number; +} ⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. +export interface WSAPIFuturesAccountAsset { + asset: string; + walletBalance: string; + unrealizedProfit: string; + marginBalance: string; + maintMargin: string; + initialMargin: string; + positionInitialMargin: string; + openOrderInitialMargin: string; + crossWalletBalance: string; + crossUnPnl: string; + availableBalance: string; + maxWithdrawAmount: string; + marginAvailable?: boolean; + updateTime: number; +} ⋮---- -/** - * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. - * - * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. - * - * The WsKey is a reference to the connection that this topic should be routed to. - * WS_KEY_MAP is a complete enum with all the available WsKey values. - * - * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data - */ +export interface WSAPIFuturesAccountPosition { + symbol: string; + initialMargin?: string; + maintMargin?: string; + unrealizedProfit: string; + positionInitialMargin?: string; + openOrderInitialMargin?: string; + leverage?: string; + isolated?: boolean; + entryPrice?: string; + breakEvenPrice?: string; + maxNotional?: string; + bidNotional?: string; + askNotional?: string; + positionSide: string; + positionAmt: string; + updateTime: number; +} ⋮---- -// Uses the high-frequency order book & core public feeds WS URL dedicated to USDM Futures: -// wss://fstream.binance.com/public/stream +export interface WSAPIFuturesAccountStatus { + feeTier?: number; + canTrade?: boolean; + canDeposit?: boolean; + canWithdraw?: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId?: number; + totalInitialMargin: string; + totalMaintMargin: string; + totalWalletBalance: string; + totalUnrealizedProfit: string; + totalMarginBalance: string; + totalPositionInitialMargin: string; + totalOpenOrderInitialMargin: string; + totalCrossWalletBalance: string; + totalCrossUnPnl: string; + availableBalance: string; + maxWithdrawAmount: string; + assets: WSAPIFuturesAccountAsset[]; + positions: WSAPIFuturesAccountPosition[]; +} ⋮---- /** - * Subscribe to each available type of USDM Derivatives market topic, the new way - */ + * Spot Order response types based on newOrderRespType parameter + */ +export interface WSAPISpotOrderACK { + symbol: string; + orderId: number; + orderListId: number; // always -1 for singular orders + clientOrderId: string; + transactTime: number; +} ⋮---- -// Individual Symbol Book Ticker Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams +orderListId: number; // always -1 for singular orders ⋮---- -// All Book Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream -'!bookTicker', // DOESNT EXIST AS TYPE GUARD -// Partial Book Depth Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams +export interface WSAPISpotOrderRESULT extends WSAPISpotOrderACK { + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; +} ⋮---- -// Diff. Book Depth Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams +/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ ⋮---- -// /** -// * -// * For those that used the Node.js Binance SDK before the v3 release, you can -// * still subscribe to available market topics the "old" way, for convenience -// * when migrating from the old WebsocketClient to the new multiplex client): -// * -// */ +export interface WSAPISpotOrderFill { + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; + tradeId: number; +} ⋮---- -// wsClient.subscribeAggregateTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(symbol, 'spot'); -// wsClient.subscribeTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(coinMSymbol, 'coinm'); -// wsClient.subscribeCoinIndexPrice(coinMSymbol2); -// wsClient.subscribeAllBookTickers('usdm'); -// wsClient.subscribeSpotKline(symbol, '1m'); -// wsClient.subscribeMarkPrice(symbol, 'usdm'); -// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMarketMarkPrice('usdm'); -// wsClient.subscribeAllMarketMarkPrice('coinm'); -// wsClient.subscribeKlines(symbol, '1m', 'usdm'); -// wsClient.subscribeContinuousContractKlines( -// symbol, -// 'perpetual', -// '1m', -// 'usdm', -// ); -// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); -// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMini24hrTickers('spot'); -// wsClient.subscribeAllMini24hrTickers('usdm'); -// wsClient.subscribeAllMini24hrTickers('coinm'); -// wsClient.subscribeAll24hrTickers('spot'); -// wsClient.subscribeAll24hrTickers('usdm'); -// wsClient.subscribeAll24hrTickers('coinm'); -// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); -// wsClient.subscribeAllLiquidationOrders('usdm'); -// wsClient.subscribeAllLiquidationOrders('coinm'); -// wsClient.subscribeSpotSymbol24hrTicker(symbol); -// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); -// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); -// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); -// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); -// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); -// wsClient.subscribeContractInfoStream('usdm'); -// wsClient.subscribeContractInfoStream('coinm'); +export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { + fills: WSAPISpotOrderFill[]; +} +⋮---- +export type WSAPISpotOrderResponse = + | WSAPISpotOrderACK + | WSAPISpotOrderRESULT + | WSAPISpotOrderFULL; ================ -File: examples/WebSockets/WS-API/ws-api-client.ts +File: src/types/websockets/ws-events-formatted.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -// or -// import { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } from 'binance'; -// or -// const { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } = require('binance'); -⋮---- -import { DefaultLogger, WebsocketAPIClient } from '../../../src'; -⋮---- -/** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. - */ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + FuturesContractType, + FuturesOrderType, + MarginType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + KlineInterval, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRowFormatted, + OrderExecutionType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + SelfTradePreventionMode, +} from '../shared'; +import { AccountUpdateEventType } from './ws-events-raw'; +import { WsSharedBase } from './ws-general'; ⋮---- -// returned by binance, generated using the publicKey (above) -// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; -// Your Ed25519 private key is passed as the "secret" -// const secret = privateKey; +export interface WsMessageKlineFormatted extends WsSharedBase { + eventType: 'kline' | 'indexPrice_kline'; + eventTime: number; + symbol: string; + kline: { + startTime: number; + endTime: number; + symbol: string; + interval: KlineInterval; + firstTradeId: number; + lastTradeId: number; + open: number; + close: number; + high: number; + low: number; + volume: number; + trades: number; + final: boolean; + quoteVolume: number; + volumeActive: number; + quoteVolumeActive: number; + ignored: number; + }; +} ⋮---- -// function attachEventHandlers( -// wsClient: TWSClient, -// ): void { -// /** -// * General event handlers for monitoring the WebsocketClient -// */ -// wsClient.on('message', (data) => { -// // console.log('raw message received ', JSON.stringify(data)); -// }); -// wsClient.on('response', (data) => { -// // console.log('ws response: ', JSON.stringify(data)); -// }); -// wsClient.on('open', (data) => { -// console.log('ws connected', data.wsKey); -// }); -// wsClient.on('reconnecting', ({ 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); -// }); -// wsClient.on('exception', (data) => { -// console.error('ws exception: ', JSON.stringify(data)); -// }); -// } +export interface WsMessageContinuousKlineFormatted extends WsSharedBase { + eventType: 'continuous_kline'; + eventTime: number; + symbol: string; + contractType: FuturesContractType; + kline: { + startTime: number; + endTime: number; + symbol: string; + interval: KlineInterval; + firstTradeId: number; + lastTradeId: number; + open: number; + close: number; + high: number; + low: number; + volume: number; + trades: number; + final: boolean; + quoteVolume: number; + volumeActive: number; + quoteVolumeActive: number; + ignored: number; + }; +} ⋮---- -async function main() +export interface WsMessageAggTradeFormatted extends WsSharedBase { + eventType: 'aggTrade'; + eventTime: number; + symbol: string; + tradeId: number; + price: number; + quantity: number; + firstTradeId: number; + lastTradeId: number; + time: number; + maker: boolean; + ignored: boolean; +} ⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: -// trace: (...params) => console.log(new Date(), 'trace', ...params), +export interface WsMessageTradeFormatted extends WsSharedBase { + eventType: 'trade'; + eventTime: number; + symbol: string; + tradeId: number; + price: number; + quantity: number; + buyerOrderId: number; + sellerOrderId: number; + time: number; + maker: boolean; + ignored: boolean; +} ⋮---- -// Enforce testnet ws connections, regardless of supplied wsKey -// testnet: true, +export interface WsMessage24hrMiniTickerFormatted extends WsSharedBase { + eventType: '24hrMiniTicker'; + eventTime: number; + symbol: string; + contractSymbol?: string; //coinm only + close: number; + open: number; + high: number; + low: number; + baseAssetVolume: number; + quoteAssetVolume: number; +} ⋮---- -// Note: unless you set this to false, the SDK will automatically call -// the `subscribeUserDataStream()` method again if reconnected (if you called it before): -// resubscribeUserDataStreamAfterReconnect: true, +contractSymbol?: string; //coinm only ⋮---- -// 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 WsMessage24hrTickerFormatted extends WsSharedBase { + /** + * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). + * Will be retired on 2026-03-26. + * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. + */ + eventType: '24hrTicker' | '!ticker@arr'; + eventTime: number; + symbol: string; + priceChange: number; + priceChangePercent: number; + weightedAveragePrice: number; + previousClose: number; + currentClose: number; + closeQuantity: number; + bestBid: number; + bestBidQuantity: number; + bestAskPrice: number; + bestAskQuantity: number; + open: number; + high: number; + low: number; + baseAssetVolume: number; + quoteAssetVolume: number; + openTime: number; + closeTime: number; + firstTradeId: number; + lastTradeId: number; + trades: number; +} ⋮---- -// Optional, attach basic event handlers, so nothing is left unhandled -// attachEventHandlers(wsClient.getWSClient()); +/** + * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). + * Will be retired on 2026-03-26. + * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. + */ ⋮---- -// 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); +export interface WsMessageRollingWindowTickerFormatted extends WsSharedBase { + eventType: 'ticker'; + eventTime: number; + symbol: string; + priceChange: number; + priceChangePercent: number; + weightedAveragePrice: number; + open: number; + high: number; + low: number; + currentClose: number; + baseAssetVolume: number; + quoteAssetVolume: number; + openTime: number; + closeTime: number; + firstTradeId: number; + lastTradeId: number; + trades: number; + streamName: string; + isWSAPIResponse: false; +} ⋮---- -// Optional. Can be used to prepare a connection before sending commands. -// Can be done as part of a bootstrapping workflow, to reduce initial latency when sending the first command -// await wsClient.getWSClient().connectWSAPI(WS_KEY_MAP.mainWSAPI); +export interface WsMessageBookTickerEventFormatted extends WsSharedBase { + eventType: 'bookTicker'; + updateId: number; + eventTime: number; + transactionTime: number; + symbol: string; + bidPrice: number; + bidQty: number; + askPrice: number; + askQty: number; +} ⋮---- -// SPOT - Market data requests +export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { + eventType: 'partialBookDepth' | 'string'; + lastUpdateId: number; + bids: OrderBookRowFormatted[]; + asks: OrderBookRowFormatted[]; +} ⋮---- -// SPOT - Trading requests +export interface WsMessageDiffBookDepthEventFormatted extends WsSharedBase { + eventType: 'depthUpdate'; + eventTime: number; + transactionTime: number; // futures only + symbol: string; + firstUpdateId: number; + lastUpdateId: number; + finalUpdateId: number; // futures only + bidDepthDelta: { price: number; quantity: number }[]; + askDepthDelta: { price: number; quantity: number }[]; +} ⋮---- -// SPOT - Account requests +transactionTime: number; // futures only ⋮---- -// FUTURES - Market data requests +finalUpdateId: number; // futures only ⋮---- -// FUTURES - Trading requests +/** + * USER DATA WS EVENTS + **/ ⋮---- -// FUTURES - Account requests +interface SpotBalanceFormatted { + asset: string; + availableBalance: number; + onOrderBalance: number; +} ⋮---- -// Start executing the example workflow - -================ -File: examples/WebSockets/WS-API/ws-api-raw-promises.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - DefaultLogger, - WebsocketClient, - WS_KEY_MAP, - WSAPIWsKey, -} from '../../../src/index'; +export interface WsMessageSpotOutboundAccountPositionFormatted + extends WsSharedBase { + eventType: 'outboundAccountPosition'; + eventTime: number; + lastAccountUpdateTime: number; + balances: SpotBalanceFormatted[]; +} ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient, WSAPIWsKey } from 'binance'; +export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { + eventType: 'balanceUpdate'; + eventTime: number; + asset: string; + balanceDelta: number; + clearTime: number; +} ⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +export interface WsMessageSpotUserDataExecutionReportEventFormatted + extends WsSharedBase { + eventType: 'executionReport'; + eventTime: number; + symbol: string; + newClientOrderId: string; + side: OrderSide; + orderType: OrderType; + cancelType: OrderTimeInForce; + quantity: number; + price: number; + stopPrice: number; + icebergQuantity: number; + orderListId: number; + originalClientOrderId: string; + executionType: OrderExecutionType; + orderStatus: OrderStatus; + rejectReason: string; + orderId: number; + lastTradeQuantity: number; + accumulatedQuantity: number; + lastTradePrice: number; + commission: number; + commissionAsset: string | null; + tradeTime: number; + tradeId: number; + ignoreThis1: number; + isOrderOnBook: boolean; + isMaker: boolean; + ignoreThis2: true; + orderCreationTime: number; + cummulativeQuoteAssetTransactedQty: number; + lastQuoteAssetTransactedQty: number; + orderQuoteQty: number; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + expiryReason?: string; + trailingDelta?: number; + preventedMatchId?: number; + trailingTime?: number; + strategyId?: number; + strategyType?: number; + tradeGroupId?: number; + counterOrderId?: number; + preventedQuantity?: number; + lastPreventedQuantity?: number; + counterSymbol?: string; + preventedExecutionQuantity?: number; + preventedExecutionPrice?: number; + preventedExecutionQuoteQty?: number; +} ⋮---- -// testnet: true, +export interface WsMessagePortfolioMarginProAccountUpdateFormatted + extends WsSharedBase { + eventType: 'PM_PRO_ACCOUNT_UPDATE'; + eventTime: number; + uniMMR: number; + accountEquity: number; + actualEquity: number; + initialMargin: number; + maintenanceMargin: number; + availableBalance: number; + virtualMaxWithdraw: number; +} ⋮---- -logger, // Optional: inject a custom logger +export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { + eventType: 'serverShutdown'; + eventTime: number; +} ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +export interface OrderObjectFormatted { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -// WS API responses can be processed here too, but that is optional -// console.log('ws response: ', JSON.stringify(data)); +export interface WsMessageSpotUserDataListStatusEventFormatted + extends WsSharedBase { + eventType: 'listStatus'; + eventTime: number; + symbol: string; + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listRejectReason: string; + listClientOrderId: string; + transactionTime: number; + orders: OrderObjectFormatted[]; +} ⋮---- -async function main() +export interface WsAccountUpdatedBalance { + asset: string; + balanceChange: number; // this is except for pnl and commission + crossWalletBalance: number; + walletBalance: number; +} ⋮---- -/** - * - * 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 (using the connectWSAPI() method shown below). This is optional. - * - */ +balanceChange: number; // this is except for pnl and commission ⋮---- -/** - * Websockets (with their unique URLs) are tracked using the concept of a "WsKey". - * - * This WsKey identifies the "main" WS API connection URL (e.g. for spot & margin markets): - * wss://ws-api.binance.com:443/ws-api/v3 - * - * Other notable keys: - * - mainWSAPI2: alternative for "main" - * - mainWSAPITestnet: "main" testnet - * - usdmWSAPI: usdm futures - * - usdmWSAPITestnet: usdm futures testnet - * - coinmWSAPI: coinm futures - * - coinmWSAPITestnet: coinm futures testnet - */ +export interface WsUpdatedPosition { + symbol: string; + marginAsset: string; + positionAmount: number; + entryPrice: number; + accumulatedRealisedPreFee: number; + unrealisedPnl: number; + marginType: 'cross' | 'isolated'; + isolatedWalletAmount: number; + positionSide: PositionSide; +} ⋮---- -// Note: if you set "testnet: true" in the config, this will automatically resolve to WS_KEY_MAP.mainWSAPITestnet (you can keep using mainWSAPI). +export interface WsMessageFuturesUserDataListenKeyExpiredFormatted + extends WsSharedBase { + eventType: 'listenKeyExpired'; + eventTime: number; +} ⋮---- -// 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); +export interface WsMessageFuturesMarginCalledPositionFormatted { + symbol: string; + positionSide: PositionSide; + positionAmount: number; + marginType: Uppercase; + isolatedWalletAmount: number; + markPrice: number; + unrealisedPnl: number; + maintenanceMarginRequired: number; +} ⋮---- -// Optional, see above. Can be used to prepare a connection before sending commands. This is not required and will happen automatically -// await wsClient.connectWSAPI(WS_API_WS_KEY); +export interface WsMessageFuturesUserDataMarginCallFormatted + extends WsSharedBase { + eventType: 'MARGIN_CALL'; + eventTime: number; + crossWalletBalance: number; + positions: WsMessageFuturesMarginCalledPositionFormatted[]; +} ⋮---- -// rateLimits: wsAPIResponse.result.rateLimits, -// symbols: wsAPIResponse.result.symbols, +export interface WsMessageFuturesUserDataAccountUpdateFormatted + extends WsSharedBase { + eventType: 'ACCOUNT_UPDATE'; + eventTime: number; + transactionTime: number; + updateData: { + updateEventType: AccountUpdateEventType; + updatedBalances: WsAccountUpdatedBalance[]; + updatedPositions: WsUpdatedPosition[]; + }; +} ⋮---- -// Start executing the example workflow - -================ -File: examples/WebSockets/README.md -================ -# Binance WebSocket Streams - -This Node.js, JavaScript & TypeScript SDK for Binance has complete support for all available WebSocket capabilities of Binance's API offering. - -## Capabilities - -These WebSocket capabilities are split into two key groups: - -1. WebSocket Consumers: - - Subscribe to market data & receive realtime updates. - - Subscribe to private account data & receive realtime updates (generally called the user data stream). -2. WebSocket API: - - Send requests & commands over a persistent WebSocket (WSAPI) connection. E.g. Submit an order. - - Subscribe to private account data & receive realtime updates (generally called the user data stream), over a persistent WebSocket (WSAPI) connection. Note: - - This was previously available without the WebSocket API, via a mechanic involving a temporary listenKey. - - In recent updates, the WebSocket API supports subscribing to the user data stream (private updates). - - In some cases, this is the only way to subsrcibe to the user data stream (e.g. in Spot markets). - -## Architecture - -### WebsocketClient - -This SDK has all WebSocket capabilities integrated in the dedicated class called the `WebsocketClient`. This can be imported from the package directly. This all-in-one class handles all aspects of Binance's WebSocket capabilities, across all subdomains & endpoints. It also includes the raw capabilities to support integration with the WebSocket API. Subscriptions, heartbeats and connection recovery after disconnect - these are all included automatically. - -If the answer to any of these is yes, you should be using the WebsocketClient: - -- You want to subscribe to & receive realtime updates for public market data. -- You want raw control over how & where WebSocket API commands are sent. - -If you are looking for a more convenient integration with Binance's WebSocket API, you should look at the `WebsocketAPIClient`. - -### WebsocketAPIClient - -This is a utility class built over the WebsocketClient to especially provide a more convenient way of using Binance's WebSocket API. While WebSockets are asynchronous by design, the WebsocketAPIClient provides a way to send WebSocket API commands and await the result. All commands are wrapped in a promise and internal event tracking ensures promises are resolved or rejected as part of the command life cycle. - -This utility class in this SDK allows you to integrate the WebSocket API in the same way that you would integrate a REST API. Make a request and await the result. - -As of early 2026, some of the user data streams are also only available via the WebSocket API streams. This has been integrated into the WebsocketAPIClient and is available with a number of user data methods, depending on the product group. Some references: - -- Spot: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` -- Margin: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.marginUserData)` -- USDM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.usdmWSAPI)` -- CoinM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.coinmWSAPI)` - -## Key Features - -### Base URL Split & Migration - -On 06/03/2026, Binance announced a routing upgrade to their USDM Futures WebSocket System, titled: "Binance USDⓈ-M Futures WebSocket System Upgrade Notice (2026-03-06)". - -#### Key Highlights: - -- Introduction of three dedicated WebSocket base URLs: - - Public (high-frequency public market data) - - wss://fstream.binance.com/public - - Market (regular market data) - - wss://fstream.binance.com/market - - Private (user data streams) - - wss://fstream.binance.com/private -- New endpoints are supported immediately upon this announcement. -- Legacy WebSocket URLs will be permanently retired on 2026-04-23. -- Documentation including endpoint & stream mapping: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data - -#### Binance JavaScript SDK Support - -All three dedicated WebSocket base URLs are supported. Each with their own unique WsKey, used to track each unique connection. - -Continue to subscribe to market data as before with the dedicated subscribe method, but ensure to provide the connection key depending on the type of market data you are consuming. - -Minimal examples: - -```typescript -// ... - -// For public (high-frequency public data) -const wsKeyUsdmPublic = WS_KEY_MAP.usdmPublic; -wsClient.subscribe(['btcusdt@bookTicker', 'btcusdt@depth'], wsKeyUsdmPublic); - -// For market (regular market data) -const wsKeyUsdmMarket = WS_KEY_MAP.usdmMarket; -wsClient.subscribe(['btcusdt@aggTrade', 'btcusdt@forceOrder'], wsKeyUsdmMarket); - -// For user data, continue using the subscribe user data stream method as before. -// The SDK will automatically route to the "private" endpoint for USDM Futures: -wsClient.subscribeUsdFuturesUserDataStream(); -``` - -#### Legacy `wsClient.subscribe*()` methods - -If you're using any of the per-topic convenience methods, such as `wsClient.subscribeAggregateTrades(...)`, no change is required. The SDK will automatically route the topic subscription request to the appropriate WS URL. - -## Further Reading - -For detailed examples, refer to the examples in this folder, as well as the following documentation: - -- Binance JavaScript SDK QuickStart Guide: https://siebly.io/sdk/binance/javascript -- Binance JavaScript SDK Readme: https://www.npmjs.com/package/binance - -================ -File: examples/README.md -================ -# Binance API - Examples - -This folder contains ready to go examples demonstrating various aspects of this API implementation, written in TypeScript (but they are compatible with pure JavaScript projects). - -Found something difficult to implement? Contribute to these examples and help others! - -## Getting started - -- Clone the project (or download it as a zip, or install the module in your own project `npm install binance`). -- Edit the sample as needed (some samples require edits, e.g API keys or import statements to import from npm, not src). -- Execute the sample using tsx: `tsx examples/REST/rest-spot-public.ts`. - -Samples that refer to API credentials using `process.env.API_KEY_COM` can be spawned with environment variables. Unix/macOS example: -``` -API_KEY_COM='apikeypastedhere' API_SECRET_COM='apisecretpastedhere' tsx "examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts" -``` - -Or edit the example directly to hardcode your API keys. - -### WebSockets - -All examples relating to WebSockets can be found in the [examples/WebSockets](./WebSockets/) folder. High level summary of available examples: - -#### Consumers - -These are purely for receiving data from Binance's WebSockets (market data, account updates, etc). - -##### Market Data - -These examples demonstrate subscribing to & receiving market data from Binance's WebSockets: - -- ws-public.ts - - Demonstration on general usage of the WebSocket client to subscribe to / unsubscribe from one or more market data topics. -- ws-public-spot-orderbook.ts - - Subscribing to orderbook events for multiple symbols in spot markets. -- ws-public-spot-trades.ts - - Subscribing to raw trades for multiple symbols in spot markets. -- ws-unsubscribe.ts - - Subscribing to a list of topics, and then unsubscribing from a few topics in that list. -- ws-public-usdm-funding.ts - - Simple example subscribing to a general topic, and how to process incoming events to only extract funding rates from those events. - -##### Account Data - -These examples demonstrate receiving account update events from Binance's WebSockets: - -- ws-userdata-listenkey.ts - - Demonstration on subscribing to various user data streams (spot, margin, futures), - - Handling incoming user data events - - Using provided type guards to determine which product group the user data event is for (spot, margin, futures, etc). -- ws-userdata-listenKey-testnet.ts - - Similar to above, but on testnet. -- ws-userdata-connection-safety.ts - - Demonstration on extra safety around the first user data stream connection. - - Note: this is overkill in most situations... - -##### WebSocket API - -These examples demonstrate how to send commands using Binance's WebSocket API (e.g. submitting orders). Very similar to the REST API, but using a persisted WebSocket connection instead of HTTP requests. - -- ws-api-client.ts - - Demonstration of using Binance's WebSocket API in Node.js/JavaScript/TypeScript, using the WebsocketAPIClient. - - This WebsocketAPIClient is very similar to a REST client, with one method per available command (endpoint) and fully typed requests & responses. - - Routing is automatically handled via the WebsocketClient, including authentication and connection persistence. Just call the functions you need - the SDK does the rest. - - From a usage perspective, it feels like a REST API - you can await responses just like a HTTP request. -- ws-api-raw-promises.ts - - More verbose usage of the WebSocket API using the `sendWSAPIRequest()` method. - - The `WebsocketAPIClient` uses this method too, so in most cases it is simple to just use the `WebsocketAPIClient` instead. -- ws-userdata-wsapi.ts - - The listenKey workflow for the user data stream is deprecated (in spot markets). - - This example demonstrates how to subscribe to the user data stream in spot markets, without a listen key, using the WebSocket API. - -##### Misc Workflows - -These are miscellaneous examples that cover one or more of the above categories: - -- ws-close.ts - - Closing the (old listen-key driven) user data stream. - - Unsubscribing from various topics. -- ws-proxy-socks.ts - - Using WebSockets over a SOCKS proxy. -- deprecated-ws-public.ts - - -### REST APIs - -All examples relating to REST APIs can be found in the [examples/REST](./REST/) folder. Most examples are named around functionality & product group. Any examples with "private" involve API calls relating to your account (such as changing settings or submitting orders, etc), - -High level summary for some of the available examples, but check the folder for a complete list: - -#### REST USDM Examples - -- `rest-future-bracket-order.ts` Creates an entry order plus a passive reduce-only TP limit order and an SL Algo Service order. -- `rest-usdm-order.ts` Creates a single entry order using `submitNewOrder`. -- `rest-usdm-order-sl.ts` Modifies a Hedge Mode LONG stop-loss order using Algo Service orders. - -================ -File: src/types/websockets/ws-events-formatted.ts -================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - FuturesContractType, - FuturesOrderType, - MarginType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; -import { - KlineInterval, - numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRowFormatted, - OrderExecutionType, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; -import { AccountUpdateEventType } from './ws-events-raw'; -import { WsSharedBase } from './ws-general'; -⋮---- -export interface WsMessageKlineFormatted extends WsSharedBase { - eventType: 'kline' | 'indexPrice_kline'; +export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted + extends WsSharedBase { + eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; eventTime: number; - symbol: string; - kline: { - startTime: number; - endTime: number; + transactionTime: number; + order: { symbol: string; - interval: KlineInterval; - firstTradeId: number; - lastTradeId: number; - open: number; - close: number; - high: number; - low: number; - volume: number; - trades: number; - final: boolean; - quoteVolume: number; - volumeActive: number; - quoteVolumeActive: number; - ignored: number; + orderId: number; + reason: string; }; } ⋮---- -export interface WsMessageContinuousKlineFormatted extends WsSharedBase { - eventType: 'continuous_kline'; +export interface WsMessageFuturesUserDataTradeLiteEventFormatted + extends WsSharedBase { + eventType: 'TRADE_LITE'; eventTime: number; + transactionTime: number; symbol: string; - contractType: FuturesContractType; - kline: { - startTime: number; - endTime: number; + originalQuantity: number; + originalPrice: number; + isMakerSide: boolean; + clientOrderId: string; + side: 'BUY' | 'SELL'; + lastFilledPrice: number; + lastFilledQuantity: number; + tradeId: number; + orderId: number; +} +⋮---- +export interface WsMessageFuturesUserDataTradeUpdateEventFormatted + extends WsSharedBase { + eventType: 'ORDER_TRADE_UPDATE'; + eventTime: number; + transactionTime: number; + order: { symbol: string; - interval: KlineInterval; - firstTradeId: number; - lastTradeId: number; - open: number; - close: number; - high: number; - low: number; - volume: number; - trades: number; - final: boolean; - quoteVolume: number; - volumeActive: number; - quoteVolumeActive: number; - ignored: number; + clientOrderId: string; + orderSide: OrderSide; + orderType: FuturesOrderType; + timeInForce: OrderTimeInForce; + originalQuantity: number; + originalPrice: number; + averagePrice: number; + stopPrice: number; + executionType: OrderExecutionType; + orderStatus: OrderStatus; + orderId: number; + lastFilledQuantity: number; + orderFilledAccumulatedQuantity: number; + lastFilledPrice: number; + commissionAsset: string; + commissionAmount: number; + orderTradeTime: number; + tradeId: number; + bidsNotional: number; + asksNotional: number; + isMakerTrade: boolean; + isReduceOnly: boolean; + stopPriceWorkingType: WorkingType; + originalOrderType: FuturesOrderType; + positionSide: PositionSide; + isCloseAll: boolean; + realisedProfit: number; + trailingStopActivationPrice?: number; + trailingStopCallbackRate?: number; + orderExpireReason?: string; // Order expire reason + pP?: boolean; // ignore + si?: number; // ignore + ss?: number; // ignore }; } ⋮---- -export interface WsMessageAggTradeFormatted extends WsSharedBase { - eventType: 'aggTrade'; - eventTime: number; - symbol: string; - tradeId: number; - price: number; - quantity: number; - firstTradeId: number; - lastTradeId: number; - time: number; - maker: boolean; - ignored: boolean; -} +orderExpireReason?: string; // Order expire reason +pP?: boolean; // ignore +si?: number; // ignore +ss?: number; // ignore ⋮---- -export interface WsMessageTradeFormatted extends WsSharedBase { - eventType: 'trade'; +export interface WsMessageFuturesUserDataAccountConfigUpdateEventFormatted + extends WsSharedBase { + eventType: 'ACCOUNT_CONFIG_UPDATE'; eventTime: number; - symbol: string; - tradeId: number; - price: number; - quantity: number; - buyerOrderId: number; - sellerOrderId: number; - time: number; - maker: boolean; - ignored: boolean; + transactionTime: number; + assetConfiguration?: { + symbol: string; + leverage: number; + }; + accountConfiguration?: { + isMultiAssetsMode: boolean; + }; } ⋮---- -export interface WsMessage24hrMiniTickerFormatted extends WsSharedBase { - eventType: '24hrMiniTicker'; +export interface WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { + eventType: 'indexPriceUpdate'; eventTime: number; symbol: string; - contractSymbol?: string; //coinm only - close: number; - open: number; - high: number; - low: number; - baseAssetVolume: number; - quoteAssetVolume: number; + indexPrice: number; } ⋮---- -contractSymbol?: string; //coinm only -⋮---- -export interface WsMessage24hrTickerFormatted extends WsSharedBase { - /** - * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). - * Will be retired on 2026-03-26. - * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. - */ - eventType: '24hrTicker' | '!ticker@arr'; +export interface WsMessageMarkPriceEventFormatted extends WsSharedBase { + eventType: 'markPriceUpdate'; eventTime: number; symbol: string; - priceChange: number; - priceChangePercent: number; - weightedAveragePrice: number; - previousClose: number; - currentClose: number; - closeQuantity: number; - bestBid: number; - bestBidQuantity: number; - bestAskPrice: number; - bestAskQuantity: number; - open: number; - high: number; - low: number; - baseAssetVolume: number; - quoteAssetVolume: number; - openTime: number; - closeTime: number; - firstTradeId: number; - lastTradeId: number; - trades: number; + markPrice: number; + /** Mark price moving average (USDⓈ-M). */ + markPriceMovingAverage?: number; + settlePriceEstimate: number; + indexPrice?: number; // undefined for coinm + /** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ + fundingRate: number | ''; + nextFundingTime: number; } ⋮---- -/** - * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). - * Will be retired on 2026-03-26. - * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. - */ +/** Mark price moving average (USDⓈ-M). */ ⋮---- -export interface WsMessageRollingWindowTickerFormatted extends WsSharedBase { - eventType: 'ticker'; - eventTime: number; - symbol: string; - priceChange: number; - priceChangePercent: number; - weightedAveragePrice: number; - open: number; - high: number; - low: number; - currentClose: number; - baseAssetVolume: number; - quoteAssetVolume: number; - openTime: number; - closeTime: number; - firstTradeId: number; - lastTradeId: number; - trades: number; - streamName: string; - isWSAPIResponse: false; -} +indexPrice?: number; // undefined for coinm +/** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ ⋮---- -export interface WsMessageBookTickerEventFormatted extends WsSharedBase { - eventType: 'bookTicker'; - updateId: number; - eventTime: number; - transactionTime: number; +export interface WsLiquidationOrderFormatted { symbol: string; - bidPrice: number; - bidQty: number; - askPrice: number; - askQty: number; -} -⋮---- -export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { - eventType: 'partialBookDepth' | 'string'; - lastUpdateId: number; - bids: OrderBookRowFormatted[]; - asks: OrderBookRowFormatted[]; + side: OrderSide; + orderType: FuturesOrderType; + timeInForce: OrderTimeInForce; + quantity: number; + price: number; + averagePrice: number; + orderStatus: OrderStatus; + lastFilledQuantity: number; + orderFilledAccumulatedQuantity: number; + orderTradeTime: number; } ⋮---- -export interface WsMessageDiffBookDepthEventFormatted extends WsSharedBase { - eventType: 'depthUpdate'; +export interface WsMessageForceOrderFormatted extends WsSharedBase { + eventType: 'forceOrder'; eventTime: number; - transactionTime: number; // futures only - symbol: string; - firstUpdateId: number; - lastUpdateId: number; - finalUpdateId: number; // futures only - bidDepthDelta: { price: number; quantity: number }[]; - askDepthDelta: { price: number; quantity: number }[]; -} -⋮---- -transactionTime: number; // futures only -⋮---- -finalUpdateId: number; // futures only -⋮---- -/** - * USER DATA WS EVENTS - **/ -⋮---- -interface SpotBalanceFormatted { - asset: string; - availableBalance: number; - onOrderBalance: number; + liquidationOrder: WsLiquidationOrderFormatted; } ⋮---- -export interface WsMessageSpotOutboundAccountPositionFormatted +export interface WsMessageFuturesUserDataStrategyUpdateFormatted extends WsSharedBase { - eventType: 'outboundAccountPosition'; + eventType: 'STRATEGY_UPDATE'; + transactionTime: number; eventTime: number; - lastAccountUpdateTime: number; - balances: SpotBalanceFormatted[]; + strategy: { + strategyId: number; + strategyType: string; + strategyStatus: string; + symbol: string; + updateTime: number; + opCode: number; + }; } ⋮---- -export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { - eventType: 'balanceUpdate'; +export interface WsMessageFuturesUserDataGridUpdateFormatted + extends WsSharedBase { + eventType: 'GRID_UPDATE'; + transactionTime: number; eventTime: number; - asset: string; - balanceDelta: number; - clearTime: number; + grid: { + strategyId: number; + strategyType: string; + strategyStatus: string; + symbol: string; + realizedPnl: numberInString; + unmatchedAveragePrice: numberInString; + unmatchedQuantity: numberInString; + unmatchedFee: numberInString; + matchedPnl: numberInString; + updateTime: number; + }; } ⋮---- -export interface WsMessageSpotUserDataExecutionReportEventFormatted +export interface WsMessageFuturesUserDataContractInfoFormatted extends WsSharedBase { - eventType: 'executionReport'; + eventType: 'contractInfo'; eventTime: number; symbol: string; - newClientOrderId: string; - side: OrderSide; - orderType: OrderType; - cancelType: OrderTimeInForce; - quantity: number; - price: number; - stopPrice: number; - icebergQuantity: number; - orderListId: number; - originalClientOrderId: string; - executionType: OrderExecutionType; - orderStatus: OrderStatus; - rejectReason: string; - orderId: number; - lastTradeQuantity: number; - accumulatedQuantity: number; - lastTradePrice: number; - commission: number; - commissionAsset: string | null; - tradeTime: number; - tradeId: number; - ignoreThis1: number; - isOrderOnBook: boolean; - isMaker: boolean; - ignoreThis2: true; - orderCreationTime: number; - cummulativeQuoteAssetTransactedQty: number; - lastQuoteAssetTransactedQty: number; - orderQuoteQty: number; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - expiryReason?: string; - trailingDelta?: number; - preventedMatchId?: number; - trailingTime?: number; - strategyId?: number; - strategyType?: number; - tradeGroupId?: number; - counterOrderId?: number; - preventedQuantity?: number; - lastPreventedQuantity?: number; - counterSymbol?: string; - preventedExecutionQuantity?: number; - preventedExecutionPrice?: number; - preventedExecutionQuoteQty?: number; + pair: string; + contractType: string; + deliveryDateTime: number; + onboardDateTime: number; + contractStatus: string; + notionalBrackets: { + notionalBracket: number; + floorNotional: number; + capNotional: number; + maintenanceRatio: number; + auxiliaryNumber: number; + minLeverage: number; + maxLeverage: number; + }[]; } ⋮---- -export interface WsMessagePortfolioMarginProAccountUpdateFormatted +export interface WsMessageFuturesUserDataAlgoUpdateFormatted extends WsSharedBase { - eventType: 'PM_PRO_ACCOUNT_UPDATE'; + eventType: 'ALGO_UPDATE'; eventTime: number; - uniMMR: number; - accountEquity: number; - actualEquity: number; - initialMargin: number; - maintenanceMargin: number; - availableBalance: number; - virtualMaxWithdraw: number; + transactionTime: number; + algoOrder: { + clientAlgoId: string; + algoId: number; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; + symbol: string; + side: OrderSide; + positionSide: PositionSide; + timeInForce: OrderTimeInForce; + quantity: numberInString; + algoStatus: FuturesAlgoOrderStatus; + orderId: string; + averagePrice: numberInString; + executedQty: numberInString; + actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType + triggerPrice: numberInString; + price: numberInString; + selfTradePreventionMode: SelfTradePreventionMode; + workingType: WorkingType; + priceMatch: PriceMatchMode; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + triggerTime: number; + goodTillDate: number; + }; } ⋮---- -export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { - eventType: 'serverShutdown'; - eventTime: number; -} +actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType ⋮---- -export interface OrderObjectFormatted { - symbol: string; - orderId: number; - clientOrderId: string; -} +export type WsMessageSpotUserDataEventFormatted = + | WsMessageSpotUserDataExecutionReportEventFormatted + | WsMessageSpotOutboundAccountPositionFormatted + | WsMessageSpotBalanceUpdateFormatted + | WsMessageSpotUserDataListStatusEventFormatted; ⋮---- -export interface WsMessageSpotUserDataListStatusEventFormatted - extends WsSharedBase { - eventType: 'listStatus'; - eventTime: number; - symbol: string; - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listRejectReason: string; - listClientOrderId: string; - transactionTime: number; - orders: OrderObjectFormatted[]; -} +export type WsMessageFuturesUserDataEventFormatted = + | WsMessageFuturesUserDataAccountUpdateFormatted + | WsMessageFuturesUserDataListenKeyExpiredFormatted + | WsMessageFuturesUserDataMarginCallFormatted + | WsMessageFuturesUserDataTradeUpdateEventFormatted + | WsMessageFuturesUserDataAlgoUpdateFormatted + | WsMessageFuturesUserDataAccountConfigUpdateEventFormatted + | WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted + | WsMessageFuturesUserDataTradeLiteEventFormatted + | WsMessageFuturesUserDataStrategyUpdateFormatted + | WsMessageFuturesUserDataGridUpdateFormatted + | WsMessageFuturesUserDataContractInfoFormatted; ⋮---- -export interface WsAccountUpdatedBalance { - asset: string; - balanceChange: number; // this is except for pnl and commission - crossWalletBalance: number; - walletBalance: number; -} +export type WsUserDataEvents = + | WsMessageSpotUserDataEventFormatted + | WsMessageFuturesUserDataEventFormatted + | WsMessagePortfolioMarginProAccountUpdateFormatted; ⋮---- -balanceChange: number; // this is except for pnl and commission +export type WsFormattedMessage = + | WsUserDataEvents + | WsMessageWsapiServerShutdownFormatted + | WsMessageKlineFormatted + | WsMessageAggTradeFormatted + | WsMessageTradeFormatted + | WsMessage24hrMiniTickerFormatted + | WsMessage24hrTickerFormatted + | WsMessageBookTickerEventFormatted + | WsMessagePartialBookDepthEventFormatted + | WsMessageDiffBookDepthEventFormatted + | WsMessageIndexPriceUpdateEventFormatted + | WsMessageMarkPriceEventFormatted + | WsMessageForceOrderFormatted + | WsMessage24hrMiniTickerFormatted[] + | WsMessage24hrTickerFormatted[] + | WsMessageRollingWindowTickerFormatted[] + | WsMessageMarkPriceEventFormatted[]; + +================ +File: src/types/websockets/ws-events-raw.ts +================ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + FuturesOrderType, + MarginType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + KlineInterval, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRow, + OrderExecutionType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + SelfTradePreventionMode, +} from '../shared'; +import { WsSharedBase } from './ws-general'; ⋮---- -export interface WsUpdatedPosition { - symbol: string; - marginAsset: string; - positionAmount: number; - entryPrice: number; - accumulatedRealisedPreFee: number; - unrealisedPnl: number; - marginType: 'cross' | 'isolated'; - isolatedWalletAmount: number; - positionSide: PositionSide; +export interface WsMessageKlineRaw extends WsSharedBase { + e: 'kline'; + E: number; + s: string; + k: { + t: number; + T: number; + s: string; + i: KlineInterval; + f: number; + L: number; + o: numberInString; + c: numberInString; + h: numberInString; + l: numberInString; + v: numberInString; + n: number; + x: boolean; + q: numberInString; + V: numberInString; + Q: numberInString; + B: numberInString; + }; +} +export interface WsMessageAggTradeRaw extends WsSharedBase { + e: 'aggTrade'; + E: number; + s: string; + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; + M: boolean; } ⋮---- -export interface WsMessageFuturesUserDataListenKeyExpiredFormatted - extends WsSharedBase { - eventType: 'listenKeyExpired'; - eventTime: number; +export interface WsMessageTradeRaw extends WsSharedBase { + e: 'trade'; + E: number; + s: string; + t: number; + p: numberInString; + q: numberInString; + b: number; + a: number; + T: number; + m: boolean; + M: boolean; } ⋮---- -export interface WsMessageFuturesMarginCalledPositionFormatted { - symbol: string; - positionSide: PositionSide; - positionAmount: number; - marginType: Uppercase; - isolatedWalletAmount: number; - markPrice: number; - unrealisedPnl: number; - maintenanceMarginRequired: number; +export interface WsMessage24hrMiniTickerRaw extends WsSharedBase { + e: '24hrMiniTicker'; + E: number; + s: string; + c: numberInString; + o: numberInString; + h: numberInString; + l: numberInString; + v: numberInString; + q: numberInString; } ⋮---- -export interface WsMessageFuturesUserDataMarginCallFormatted - extends WsSharedBase { - eventType: 'MARGIN_CALL'; - eventTime: number; - crossWalletBalance: number; - positions: WsMessageFuturesMarginCalledPositionFormatted[]; +export interface WsMessage24hrTickerRaw extends WsSharedBase { + e: '24hrTicker'; + E: number; + s: string; + p: numberInString; + P: numberInString; + w: numberInString; + x: numberInString; + c: numberInString; + Q: numberInString; + b: numberInString; + B: numberInString; + a: numberInString; + A: numberInString; + o: numberInString; + h: numberInString; + l: numberInString; + v: numberInString; + q: numberInString; + O: numberInString; + C: numberInString; + F: number; + L: number; + n: number; } ⋮---- -export interface WsMessageFuturesUserDataAccountUpdateFormatted - extends WsSharedBase { - eventType: 'ACCOUNT_UPDATE'; - eventTime: number; - transactionTime: number; - updateData: { - updateEventType: AccountUpdateEventType; - updatedBalances: WsAccountUpdatedBalance[]; - updatedPositions: WsUpdatedPosition[]; - }; +export interface WsMessageRollingWindowTickerRaw extends WsSharedBase { + e: '1hTicker' | '4hTicker' | '1dTicker'; + E: number; + s: string; + p: string; + P: string; + w: string; + o: string; + h: string; + l: string; + c: string; + v: string; + q: string; + O: number; + C: number; + F: number; + L: number; + n: number; } ⋮---- -export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted - extends WsSharedBase { - eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; - eventTime: number; - transactionTime: number; - order: { - symbol: string; - orderId: number; - reason: string; - }; +export interface WsMessageBookTickerEventRaw extends WsSharedBase { + e: 'bookTicker'; + u: number; + E: number; // futures only - event time + T: number; // futures only - transaction time + s: string; + b: numberInString; + B: numberInString; + a: numberInString; + A: numberInString; } ⋮---- -export interface WsMessageFuturesUserDataTradeLiteEventFormatted - extends WsSharedBase { - eventType: 'TRADE_LITE'; - eventTime: number; - transactionTime: number; - symbol: string; - originalQuantity: number; - originalPrice: number; - isMakerSide: boolean; - clientOrderId: string; - side: 'BUY' | 'SELL'; - lastFilledPrice: number; - lastFilledQuantity: number; - tradeId: number; - orderId: number; -} +E: number; // futures only - event time +T: number; // futures only - transaction time ⋮---- -export interface WsMessageFuturesUserDataTradeUpdateEventFormatted - extends WsSharedBase { - eventType: 'ORDER_TRADE_UPDATE'; - eventTime: number; - transactionTime: number; - order: { - symbol: string; - clientOrderId: string; - orderSide: OrderSide; - orderType: FuturesOrderType; - timeInForce: OrderTimeInForce; - originalQuantity: number; - originalPrice: number; - averagePrice: number; - stopPrice: number; - executionType: OrderExecutionType; - orderStatus: OrderStatus; - orderId: number; - lastFilledQuantity: number; - orderFilledAccumulatedQuantity: number; - lastFilledPrice: number; - commissionAsset: string; - commissionAmount: number; - orderTradeTime: number; - tradeId: number; - bidsNotional: number; - asksNotional: number; - isMakerTrade: boolean; - isReduceOnly: boolean; - stopPriceWorkingType: WorkingType; - originalOrderType: FuturesOrderType; - positionSide: PositionSide; - isCloseAll: boolean; - realisedProfit: number; - trailingStopActivationPrice?: number; - trailingStopCallbackRate?: number; - orderExpireReason?: string; // Order expire reason - pP?: boolean; // ignore - si?: number; // ignore - ss?: number; // ignore - }; +export interface WsMessagePartialBookDepthEventRaw extends WsSharedBase { + e: 'partialBookDepth'; + lastUpdateId: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; } ⋮---- -orderExpireReason?: string; // Order expire reason -pP?: boolean; // ignore -si?: number; // ignore -ss?: number; // ignore -⋮---- -export interface WsMessageFuturesUserDataAccountConfigUpdateEventFormatted - extends WsSharedBase { - eventType: 'ACCOUNT_CONFIG_UPDATE'; - eventTime: number; - transactionTime: number; - assetConfiguration?: { - symbol: string; - leverage: number; - }; - accountConfiguration?: { - isMultiAssetsMode: boolean; - }; +export interface WsMessageDiffBookDepthEventRaw extends WsSharedBase { + e: 'depthUpdate'; + E: number; + T: number; // futures only + s: string; + U: number; + u: number; + pu: number; // futures only + b: OrderBookRow[]; + a: OrderBookRow[]; } ⋮---- -export interface WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { - eventType: 'indexPriceUpdate'; - eventTime: number; - symbol: string; - indexPrice: number; -} +T: number; // futures only ⋮---- -export interface WsMessageMarkPriceEventFormatted extends WsSharedBase { - eventType: 'markPriceUpdate'; - eventTime: number; - symbol: string; - markPrice: number; - /** Mark price moving average (USDⓈ-M). */ - markPriceMovingAverage?: number; - settlePriceEstimate: number; - indexPrice?: number; // undefined for coinm - /** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ - fundingRate: number | ''; - nextFundingTime: number; -} +pu: number; // futures only ⋮---- -/** Mark price moving average (USDⓈ-M). */ +/** + * USER DATA WS EVENTS + **/ ⋮---- -indexPrice?: number; // undefined for coinm -/** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ +interface SpotBalanceRaw { + a: string; + f: numberInString; + l: numberInString; +} ⋮---- -export interface WsLiquidationOrderFormatted { - symbol: string; - side: OrderSide; - orderType: FuturesOrderType; - timeInForce: OrderTimeInForce; - quantity: number; - price: number; - averagePrice: number; - orderStatus: OrderStatus; - lastFilledQuantity: number; - orderFilledAccumulatedQuantity: number; - orderTradeTime: number; +export interface WsMessageSpotOutboundAccountPositionRaw extends WsSharedBase { + e: 'outboundAccountPosition'; + E: number; + u: number; + B: SpotBalanceRaw[]; } ⋮---- -export interface WsMessageForceOrderFormatted extends WsSharedBase { - eventType: 'forceOrder'; - eventTime: number; - liquidationOrder: WsLiquidationOrderFormatted; +export interface WsMessageSpotBalanceUpdateRaw extends WsSharedBase { + e: 'balanceUpdate'; + E: number; + a: string; + d: numberInString; + T: number; } ⋮---- -export interface WsMessageFuturesUserDataStrategyUpdateFormatted +export interface WsMessageSpotUserDataExecutionReportEventRaw extends WsSharedBase { - eventType: 'STRATEGY_UPDATE'; - transactionTime: number; - eventTime: number; - strategy: { - strategyId: number; - strategyType: string; - strategyStatus: string; - symbol: string; - updateTime: number; - opCode: number; - }; + e: 'executionReport'; + E: number; + s: string; + c: string; + S: OrderSide; + o: OrderType; + f: OrderTimeInForce; + q: numberInString; + p: numberInString; + P: numberInString; + F: numberInString; + g: number; + C: string; + x: OrderExecutionType; + X: OrderStatus; + r: string; + i: number; + l: numberInString; + z: numberInString; + L: numberInString; + n: numberInString; + N: string | null; + T: number; + t: number; + I: number; + w: boolean; + m: boolean; + M: boolean; + O: number; + Z: numberInString; + Y: numberInString; + Q: numberInString; + W: number; + V: SelfTradePreventionMode; + /** Expiry reason when present (user data executionReport). */ + eR?: string; + d?: number; + v?: number; + D?: number; + j?: number; + J?: number; + u?: number; + U?: number; + A?: numberInString; + B?: numberInString; + Cs?: string; + pl?: numberInString; + pL?: numberInString; + pY?: numberInString; } ⋮---- -export interface WsMessageFuturesUserDataGridUpdateFormatted - extends WsSharedBase { - eventType: 'GRID_UPDATE'; - transactionTime: number; - eventTime: number; - grid: { - strategyId: number; - strategyType: string; - strategyStatus: string; - symbol: string; - realizedPnl: numberInString; - unmatchedAveragePrice: numberInString; - unmatchedQuantity: numberInString; - unmatchedFee: numberInString; - matchedPnl: numberInString; - updateTime: number; - }; -} +/** Expiry reason when present (user data executionReport). */ ⋮---- -export interface WsMessageFuturesUserDataContractInfoFormatted +export interface WsMessagePortfolioMarginProAccountUpdateRaw extends WsSharedBase { - eventType: 'contractInfo'; - eventTime: number; - symbol: string; - pair: string; - contractType: string; - deliveryDateTime: number; - onboardDateTime: number; - contractStatus: string; - notionalBrackets: { - notionalBracket: number; - floorNotional: number; - capNotional: number; - maintenanceRatio: number; - auxiliaryNumber: number; - minLeverage: number; - maxLeverage: number; - }[]; + e: 'PM_PRO_ACCOUNT_UPDATE'; + E: number; + u: numberInString; + eq: numberInString; + ae: numberInString; + im: numberInString; + mm: numberInString; + avb: numberInString; + vmw: numberInString; } ⋮---- -export interface WsMessageFuturesUserDataAlgoUpdateFormatted - extends WsSharedBase { - eventType: 'ALGO_UPDATE'; - eventTime: number; - transactionTime: number; - algoOrder: { - clientAlgoId: string; - algoId: number; - algoType: FuturesAlgoOrderType; - orderType: FuturesAlgoConditionalOrderTypes; - symbol: string; - side: OrderSide; - positionSide: PositionSide; - timeInForce: OrderTimeInForce; - quantity: numberInString; - algoStatus: FuturesAlgoOrderStatus; - orderId: string; - averagePrice: numberInString; - executedQty: numberInString; - actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType - triggerPrice: numberInString; - price: numberInString; - selfTradePreventionMode: SelfTradePreventionMode; - workingType: WorkingType; - priceMatch: PriceMatchMode; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - triggerTime: number; - goodTillDate: number; - }; +export interface WsMessageWsapiServerShutdownRaw extends WsSharedBase { + e: 'serverShutdown'; + E: number; } ⋮---- -actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType -⋮---- -export type WsMessageSpotUserDataEventFormatted = - | WsMessageSpotUserDataExecutionReportEventFormatted - | WsMessageSpotOutboundAccountPositionFormatted - | WsMessageSpotBalanceUpdateFormatted - | WsMessageSpotUserDataListStatusEventFormatted; -⋮---- -export type WsMessageFuturesUserDataEventFormatted = - | WsMessageFuturesUserDataAccountUpdateFormatted - | WsMessageFuturesUserDataListenKeyExpiredFormatted - | WsMessageFuturesUserDataMarginCallFormatted - | WsMessageFuturesUserDataTradeUpdateEventFormatted - | WsMessageFuturesUserDataAlgoUpdateFormatted - | WsMessageFuturesUserDataAccountConfigUpdateEventFormatted - | WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted - | WsMessageFuturesUserDataTradeLiteEventFormatted - | WsMessageFuturesUserDataStrategyUpdateFormatted - | WsMessageFuturesUserDataGridUpdateFormatted - | WsMessageFuturesUserDataContractInfoFormatted; -⋮---- -export type WsUserDataEvents = - | WsMessageSpotUserDataEventFormatted - | WsMessageFuturesUserDataEventFormatted - | WsMessagePortfolioMarginProAccountUpdateFormatted; -⋮---- -export type WsFormattedMessage = - | WsUserDataEvents - | WsMessageWsapiServerShutdownFormatted - | WsMessageKlineFormatted - | WsMessageAggTradeFormatted - | WsMessageTradeFormatted - | WsMessage24hrMiniTickerFormatted - | WsMessage24hrTickerFormatted - | WsMessageBookTickerEventFormatted - | WsMessagePartialBookDepthEventFormatted - | WsMessageDiffBookDepthEventFormatted - | WsMessageIndexPriceUpdateEventFormatted - | WsMessageMarkPriceEventFormatted - | WsMessageForceOrderFormatted - | WsMessage24hrMiniTickerFormatted[] - | WsMessage24hrTickerFormatted[] - | WsMessageRollingWindowTickerFormatted[] - | WsMessageMarkPriceEventFormatted[]; - -================ -File: src/types/websockets/ws-events-raw.ts -================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - FuturesOrderType, - MarginType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; -import { - KlineInterval, - numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRow, - OrderExecutionType, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; -import { WsSharedBase } from './ws-general'; -⋮---- -export interface WsMessageKlineRaw extends WsSharedBase { - e: 'kline'; - E: number; +export interface OrderObjectRaw { s: string; - k: { - t: number; - T: number; - s: string; - i: KlineInterval; - f: number; - L: number; - o: numberInString; - c: numberInString; - h: numberInString; - l: numberInString; - v: numberInString; - n: number; - x: boolean; - q: numberInString; - V: numberInString; - Q: numberInString; - B: numberInString; - }; + i: number; + c: string; } -export interface WsMessageAggTradeRaw extends WsSharedBase { - e: 'aggTrade'; +⋮---- +export interface WsMessageSpotUserDataListStatusEventRaw extends WsSharedBase { + e: 'listStatus'; E: number; s: string; - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; + g: number; + c: 'OCO'; + l: OCOStatus; + L: OCOOrderStatus; + r: string; + C: string; T: number; - m: boolean; - M: boolean; -} -⋮---- -export interface WsMessageTradeRaw extends WsSharedBase { - e: 'trade'; - E: number; - s: string; - t: number; - p: numberInString; - q: numberInString; - b: number; - a: number; - T: number; - m: boolean; - M: boolean; -} -⋮---- -export interface WsMessage24hrMiniTickerRaw extends WsSharedBase { - e: '24hrMiniTicker'; - E: number; - s: string; - c: numberInString; - o: numberInString; - h: numberInString; - l: numberInString; - v: numberInString; - q: numberInString; -} -⋮---- -export interface WsMessage24hrTickerRaw extends WsSharedBase { - e: '24hrTicker'; - E: number; - s: string; - p: numberInString; - P: numberInString; - w: numberInString; - x: numberInString; - c: numberInString; - Q: numberInString; - b: numberInString; - B: numberInString; - a: numberInString; - A: numberInString; - o: numberInString; - h: numberInString; - l: numberInString; - v: numberInString; - q: numberInString; - O: numberInString; - C: numberInString; - F: number; - L: number; - n: number; -} -⋮---- -export interface WsMessageRollingWindowTickerRaw extends WsSharedBase { - e: '1hTicker' | '4hTicker' | '1dTicker'; - E: number; - s: string; - p: string; - P: string; - w: string; - o: string; - h: string; - l: string; - c: string; - v: string; - q: string; - O: number; - C: number; - F: number; - L: number; - n: number; -} -⋮---- -export interface WsMessageBookTickerEventRaw extends WsSharedBase { - e: 'bookTicker'; - u: number; - E: number; // futures only - event time - T: number; // futures only - transaction time - s: string; - b: numberInString; - B: numberInString; - a: numberInString; - A: numberInString; -} -⋮---- -E: number; // futures only - event time -T: number; // futures only - transaction time -⋮---- -export interface WsMessagePartialBookDepthEventRaw extends WsSharedBase { - e: 'partialBookDepth'; - lastUpdateId: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; -} -⋮---- -export interface WsMessageDiffBookDepthEventRaw extends WsSharedBase { - e: 'depthUpdate'; - E: number; - T: number; // futures only - s: string; - U: number; - u: number; - pu: number; // futures only - b: OrderBookRow[]; - a: OrderBookRow[]; -} -⋮---- -T: number; // futures only -⋮---- -pu: number; // futures only -⋮---- -/** - * USER DATA WS EVENTS - **/ -⋮---- -interface SpotBalanceRaw { - a: string; - f: numberInString; - l: numberInString; -} -⋮---- -export interface WsMessageSpotOutboundAccountPositionRaw extends WsSharedBase { - e: 'outboundAccountPosition'; - E: number; - u: number; - B: SpotBalanceRaw[]; -} -⋮---- -export interface WsMessageSpotBalanceUpdateRaw extends WsSharedBase { - e: 'balanceUpdate'; - E: number; - a: string; - d: numberInString; - T: number; -} -⋮---- -export interface WsMessageSpotUserDataExecutionReportEventRaw - extends WsSharedBase { - e: 'executionReport'; - E: number; - s: string; - c: string; - S: OrderSide; - o: OrderType; - f: OrderTimeInForce; - q: numberInString; - p: numberInString; - P: numberInString; - F: numberInString; - g: number; - C: string; - x: OrderExecutionType; - X: OrderStatus; - r: string; - i: number; - l: numberInString; - z: numberInString; - L: numberInString; - n: numberInString; - N: string | null; - T: number; - t: number; - I: number; - w: boolean; - m: boolean; - M: boolean; - O: number; - Z: numberInString; - Y: numberInString; - Q: numberInString; - W: number; - V: SelfTradePreventionMode; - /** Expiry reason when present (user data executionReport). */ - eR?: string; - d?: number; - v?: number; - D?: number; - j?: number; - J?: number; - u?: number; - U?: number; - A?: numberInString; - B?: numberInString; - Cs?: string; - pl?: numberInString; - pL?: numberInString; - pY?: numberInString; -} -⋮---- -/** Expiry reason when present (user data executionReport). */ -⋮---- -export interface WsMessagePortfolioMarginProAccountUpdateRaw - extends WsSharedBase { - e: 'PM_PRO_ACCOUNT_UPDATE'; - E: number; - u: numberInString; - eq: numberInString; - ae: numberInString; - im: numberInString; - mm: numberInString; - avb: numberInString; - vmw: numberInString; -} -⋮---- -export interface WsMessageWsapiServerShutdownRaw extends WsSharedBase { - e: 'serverShutdown'; - E: number; -} -⋮---- -export interface OrderObjectRaw { - s: string; - i: number; - c: string; -} -⋮---- -export interface WsMessageSpotUserDataListStatusEventRaw extends WsSharedBase { - e: 'listStatus'; - E: number; - s: string; - g: number; - c: 'OCO'; - l: OCOStatus; - L: OCOOrderStatus; - r: string; - C: string; - T: number; - O: OrderObjectRaw[]; + O: OrderObjectRaw[]; } ⋮---- export type AccountUpdateEventType = @@ -7169,7 +6696,8 @@ export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { e: 'indexPriceUpdate'; E: number; - i: string; + i?: string; + s?: string; p: numberInString; } ⋮---- @@ -7345,585 +6873,570 @@ export type WsRawMessage = | WsMessageIndexPriceUpdateEventRaw; ================ -File: src/coinm-client.ts +File: src/types/shared.ts ================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; +// Generic numeric value stored as a string. Can be parsed via parseInt or parseFloat. +// Beautifier may convert these to number, if enabled. +export type numberInString = string | number; ⋮---- -import { - ClassicPortfolioMarginAccount, - ClassicPortfolioMarginNotionalLimit, - CoinMAccountTradeParams, - CoinMOpenInterest, - CoinMPositionTrade, - CoinMSymbolOrderBookTicker, - FundingRate, - FuturesTransactionHistoryDownloadLink, - GetClassicPortfolioMarginNotionalLimitParams, - PositionRisk, -} from './types/coin'; -import { - AggregateFuturesTrade, - CancelAllOpenOrdersResult, - CancelFuturesOrderResult, - CancelMultipleOrdersParams, - CancelOrdersTimeoutParams, - ChangeStats24hr, - ContinuousContractKlinesParams, - ForceOrderResult, - FundingRateHistory, - FuturesCoinMAccountBalance, - FuturesCoinMAccountInformation, - FuturesCoinMBasisParams, - FuturesCoinMTakerBuySellVolumeParams, - FuturesDataPaginatedParams, - FuturesExchangeInfo, - FuturesOrderBook, - GetForceOrdersParams, - GetIncomeHistoryParams, - GetPositionMarginChangeHistoryParams, - IncomeHistory, - IndexPriceConstituents, - IndexPriceKlinesParams, - MarkPrice, - ModeChangeResult, - ModifyFuturesOrderParams, - ModifyFuturesOrderResult, - NewFuturesOrderParams, - NewOrderError, - NewOrderResult, - OrderAmendment, - OrderResult, - PositionModeParams, - PositionModeResponse, - QuarterlyContractSettlementPrice, - RawFuturesTrade, - RebateDataOverview, - SetCancelTimeoutResult, - SetIsolatedMarginParams, - SetIsolatedMarginResult, - SetLeverageParams, - SetLeverageResult, - SetMarginTypeParams, - SymbolKlinePaginatedParams, - SymbolLeverageBracketsResult, - UserCommissionRate, -} from './types/futures'; -import { - BasicSymbolPaginatedParams, - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - GenericCodeMsgError, - GetAllOrdersParams, - GetOrderModifyHistoryParams, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, - NewOCOParams, - OrderBookParams, - OrderIdProperty, - RecentTradesParams, - SymbolFromPaginatedRequestFromId, - SymbolPrice, -} from './types/shared'; -import BaseRestClient from './util/BaseRestClient'; -import { - asArray, - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, -} from './util/requestUtils'; -⋮---- -export class CoinMClient extends BaseRestClient +export type ExchangeSymbol = string; ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +export type BooleanString = 'true' | 'false'; ⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise +export type BinanceBaseUrlKey = + | 'spot' + | 'spot1' + | 'spot2' + | 'spot3' + | 'spot4' + | 'spottest' + | 'usdmtest' + | 'usdm' + | 'coinm' + | 'coinmtest' + | 'voptions' + | 'voptionstest' + | 'papi' + | 'www'; ⋮---- /** - * - * Market Data Endpoints - * - **/ -⋮---- -testConnectivity(): Promise -⋮---- -getExchangeInfo(): Promise -⋮---- -getOrderBook(params: OrderBookParams): Promise -⋮---- -getRecentTrades(params: RecentTradesParams): Promise + * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. + */ +export type OrderTimeInForce = + | 'GTC' + | 'IOC' + | 'FOK' + | 'GTX' + | 'GTE_GTC' + | 'GTD'; ⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, -): Promise +export type StringBoolean = 'TRUE' | 'FALSE'; ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise +export type SideEffects = + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'NO_SIDE_EFFECT' + | 'AUTO_BORROW_REPAY' + | 'NO_SIDE_EFFECT'; ⋮---- /** - * Index Price and Mark Price - */ -getMarkPrice(params?: -⋮---- -getFundingRateHistory( - params?: Partial, -): Promise -⋮---- -getFundingRate(params?: + * ACK = confirmation of order acceptance (no placement/fill information) + * RESULT = fill state + * FULL = fill state + detail on fills and other detail + */ +export type OrderResponseType = 'ACK' | 'RESULT' | 'FULL'; ⋮---- -getKlines(params: KlinesParams): Promise +export type OrderIdProperty = + | 'newClientOrderId' + | 'newClientStrategyId' + | 'listClientOrderId' + | 'limitClientOrderId' + | 'stopClientOrderId' + | 'clientAlgoId' + | 'aboveClientOrderId' + | 'belowClientOrderId' + | 'workingClientOrderId' + | 'pendingAboveClientOrderId' + | 'pendingBelowClientOrderId' + | 'pendingClientOrderId'; ⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, -): Promise +export type OrderSide = 'BUY' | 'SELL'; ⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +export type OrderStatus = + | 'NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED'; ⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +export type OrderExecutionType = + | 'NEW' + | 'CANCELED' + | 'REJECTED' + | 'TRADE' + | 'EXPIRED'; ⋮---- -getPremiumIndexKlines(params: KlinesParams): Promise +// listStatusType +export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; - pair?: string; -}): Promise +// listOrderStatus +export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; - pair?: string; -}): Promise +export type OrderType = + | 'LIMIT' + | 'LIMIT_MAKER' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; - pair?: string; -}): Promise +export type OrderListOrderType = + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -getOpenInterest(params: +export type SelfTradePreventionMode = + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; ⋮---- -getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise +export interface BasicAssetParam { + asset: string; +} ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +export interface BasicSymbolParam { + symbol: string; + isIsolated?: StringBoolean; +} ⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams & { pair?: string }, -): Promise +export interface SymbolArrayParam { + symbols: string[]; +} ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +export interface BasicAssetPaginatedParams { + asset?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +export interface BasicSymbolPaginatedParams { + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getTakerBuySellVolume( - params: FuturesCoinMTakerBuySellVolumeParams, -): Promise +export interface SymbolPrice { + symbol: string; + price: numberInString; + time?: number; +} ⋮---- -getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise +// used by spot and usdm +export interface OrderBookParams { + symbol: string; + limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; + symbolStatus?: string; +} ⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getIndexPriceConstituents(params: { - symbol: string; -}): Promise -⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getQuarterlyContractSettlementPrices(params: { - pair: string; -}): Promise -⋮---- -/** - * - * Trade Endpoints - * - **/ +export type KlineInterval = + | '1s' + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '3d' + | '1w' + | '1M'; ⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise +export interface GetOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. - * - * Known issue: `quantity` and `price` should be sent as strings - */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> +export interface GetOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue - */ -modifyOrder( - params: ModifyFuturesOrderParams, -): Promise +export interface HistoricalTradesParams { + symbol: string; + limit?: number; + fromId?: number; +} ⋮---- -/** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. - */ -modifyMultipleOrders( - orders: ModifyFuturesOrderParams[], -): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> +export interface KlinesParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} ⋮---- -getOrderModifyHistory( - params: GetOrderModifyHistoryParams, -): Promise +export type Kline = [ + number, // open time + numberInString, // open + numberInString, // high + numberInString, // low + numberInString, // close + numberInString, // volume + number, // close time + numberInString, // quote asset volume + number, // number of trades + numberInString, // taker buy base asset vol + numberInString, // taker buy quote asset vol + numberInString, // ignore? +]; ⋮---- -cancelOrder(params: CancelOrderParams): Promise +number, // open time +numberInString, // open +numberInString, // high +numberInString, // low +numberInString, // close +numberInString, // volume +number, // close time +numberInString, // quote asset volume +number, // number of trades +numberInString, // taker buy base asset vol +numberInString, // taker buy quote asset vol +numberInString, // ignore? ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, -): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ +export type FuturesKline = Kline; +export interface RecentTradesParams { + symbol: string; + limit?: number; +} ⋮---- -cancelAllOpenOrders(params: { - symbol?: string; -}): Promise +export interface CancelOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, -): Promise +export interface AmendKeepPriorityParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + newQty: numberInString; +} ⋮---- -getOrder(params: GetOrderParams): Promise +export interface CancelOCOParams { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +export interface NewOCOParams { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + limitClientOrderId?: string; + limitStrategyId?: number; + limitStrategyType?: number; + price: number; + limitIcebergQty?: number; + trailingDelta?: number; + stopClientOrderId?: string; + stopPrice: number; + stopStrategyId?: number; + stopStrategyType?: number; + stopLimitPrice?: number; + stopIcebergQty?: number; + stopLimitTimeInForce?: OrderTimeInForce; + newOrderRespType?: OrderResponseType; + /** For isolated margin trading only */ + isIsolated?: StringBoolean; + /** Define a side effect, only for margin trading */ + sideEffectType?: SideEffects; +} ⋮---- -getAllOpenOrders(params?: +/** For isolated margin trading only */ ⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +/** Define a side effect, only for margin trading */ ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +export interface NewOrderListParams< + T extends OrderResponseType = OrderResponseType, +> { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + aboveType: OrderListOrderType; + aboveClientOrderId?: string; + aboveIcebergQty?: number; + abovePrice?: number; + aboveStopPrice?: number; + aboveTrailingDelta?: number; + aboveTimeInForce?: OrderTimeInForce; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: OrderListOrderType; + belowClientOrderId?: string; + belowIcebergQty?: number; + belowPrice?: number; + belowStopPrice?: number; + belowTrailingDelta?: number; + belowTimeInForce?: OrderTimeInForce; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: T; + selfTradePreventionMode?: SelfTradePreventionMode; +} ⋮---- -getAccountTrades( - params: CoinMAccountTradeParams & { orderId?: number }, -): Promise +export interface SymbolFromPaginatedRequestFromId { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getPositions(params?: { - marginAsset?: string; - pair?: string; -}): Promise +export interface GetAllOrdersParams { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -setPositionMode(params: PositionModeParams): Promise +export interface RateLimiter { + rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; + interval: 'SECOND' | 'MINUTE' | 'DAY'; + intervalNum: number; + limit: number; +} ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +export interface SymbolPriceFilter { + filterType: 'PRICE_FILTER'; + minPrice: numberInString; + maxPrice: numberInString; + tickSize: numberInString; +} ⋮---- -setLeverage(params: SetLeverageParams): Promise +export interface SymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -getADLQuantileEstimation(params?: +export interface SymbolPercentPriceBySideFilter { + filterType: 'PERCENT_PRICE_BY_SIDE'; + bidMultiplierUp: numberInString; + bidMultiplierDown: numberInString; + askMultiplierUp: numberInString; + askMultiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, -): Promise -⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, -): Promise -/** - * - * Account Endpoints - * - **/ -⋮---- -getBalance(): Promise -⋮---- -getAccountCommissionRate(params: { - symbol?: string; -}): Promise -⋮---- -getAccountInformation(): Promise -⋮---- -/** - * Notional Bracket for Symbol (NOT "pair") - */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; -}): Promise -⋮---- -// TO ADD: dapi/v1/leverageBracket -// can use dapi/v2/leverageBracket -⋮---- -getCurrentPositionMode(): Promise -⋮---- -getIncomeHistory(params?: GetIncomeHistoryParams): Promise -⋮---- -getDownloadIdForFuturesTransactionHistory(params: { - startTime: number; - endTime: number; -}): Promise< -⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; -}): Promise -⋮---- -getDownloadIdForFuturesOrderHistory(params: { - startTime: number; - endTime: number; -}): Promise< -⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; -}): Promise -⋮---- -getDownloadIdForFuturesTradeHistory(params: { - startTime: number; - endTime: number; -}): Promise< +export interface SymbolLegacyMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + minNotional: numberInString; + applyToMarket: boolean; + avgPriceMins: number; +} ⋮---- -getFuturesTradeHistoryDownloadLink(params: { - downloadId: string; -}): Promise +export interface SymbolLotSizeFilter { + filterType: 'LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -/** - * - * Portfolio Margin Endpoints - * - **/ +export interface SymbolMinNotionalFilter { + filterType: 'NOTIONAL'; + minNotional: numberInString; + applyMinToMarket: boolean; + maxNotional: numberInString; + applyMaxToMarket: boolean; + avgPriceMins: number; +} ⋮---- -getClassicPortfolioMarginAccount(params: { - asset: string; -}): Promise +export interface SymbolIcebergPartsFilter { + filterType: 'ICEBERG_PARTS'; + limit: number; +} ⋮---- -/** - * @deprecated at 6th August, 2024 - **/ -getClassicPortfolioMarginNotionalLimits( - params?: GetClassicPortfolioMarginNotionalLimitParams, -): Promise< +export interface SymbolMarketLotSizeFilter { + filterType: 'MARKET_LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -/** - * - * Broker Futures Endpoints - * Possibly @deprecated, found only in old docs - * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker - * - **/ +export interface SymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, -): Promise< +export interface SymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, -): Promise< +export interface SymbolMaxIcebergOrdersFilter { + filterType: 'MAX_NUM_ICEBERG_ORDERS'; + maxNumIcebergOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, -): Promise +export interface SymbolMaxPositionFilter { + filterType: 'MAX_POSITION'; + maxPosition: numberInString; +} ⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise +export type SymbolFilter = + | SymbolPriceFilter + | SymbolPercentPriceFilter + | SymbolPercentPriceBySideFilter + | SymbolLegacyMinNotionalFilter + | SymbolLotSizeFilter + | SymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | SymbolMaxOrdersFilter + | SymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter; ⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +export interface ExchangeMaxNumOrdersFilter { + filterType: 'EXCHANGE_MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +export interface ExchangeMaxAlgoOrdersFilter { + filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +export type ExchangeFilter = + | ExchangeMaxNumOrdersFilter + | ExchangeMaxAlgoOrdersFilter; ⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +export type OrderBookPrice = numberInString; +export type OrderBookAmount = numberInString; ⋮---- -/** - * - * User Data Stream Endpoints - * - **/ +export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; ⋮---- -getFuturesUserDataListenKey(): Promise< +export type OrderBookPriceFormatted = number; +export type OrderBookAmountFormatted = number; +export type OrderBookRowFormatted = [ + OrderBookPriceFormatted, + OrderBookAmountFormatted, +]; ⋮---- -keepAliveFuturesUserDataListenKey(): Promise +export interface GenericCodeMsgError { + code: number; + msg: string; +} ⋮---- -closeFuturesUserDataListenKey(): Promise +export interface RowsWithTotal { + rows: T[]; + total: number; +} ⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewFuturesOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, -): void +export interface CoinStartEndLimit { + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ================ -File: src/portfolio-client.ts +File: src/coinm-client.ts ================ +/* eslint-disable @typescript-eslint/no-explicit-any */ import { AxiosRequestConfig } from 'axios'; ⋮---- import { - CancelPortfolioCMConditionalOrderReq, - CancelPortfolioCMOrderReq, - CancelPortfolioMarginOCOReq, - CancelPortfolioMarginOrderReq, - CancelPortfolioUMAlgoOrderReq, - CancelPortfolioUMConditionalOrderReq, - CancelPortfolioUMOrderReq, - DownloadLinkResponse, - GetMarginInterestHistoryReq, - GetMarginLoanRecordsReq, - GetMarginRepayRecordsReq, - GetPortfolioInterestHistoryReq, - ModifyPortfolioCMOrderReq, - ModifyPortfolioUMOrderReq, - NewPortfolioCMConditionalOrderReq, - NewPortfolioCMConditionalOrderResponse, - NewPortfolioCMOrderReq, - NewPortfolioCMOrderResponse, - NewPortfolioConditionalOrderResponse, - NewPortfolioMarginOCOReq, - NewPortfolioMarginOCOResponse, - NewPortfolioMarginOrderReq, - NewPortfolioMarginOrderResponse, - NewPortfolioUMAlgoOrderReq, - NewPortfolioUMConditionalOrderReq, - NewPortfolioUMOrderReq, - NewPortfolioUMOrderResponse, - PortfolioAccountInformation, - PortfolioADLQuantile, - PortfolioBalance, - PortfolioCMAccountAsset, - PortfolioCMAccountPosition, - PortfolioCMCancelConditionalOrderResponse, - PortfolioCMCancelOrderResponse, - PortfolioCMConditionalHistoryOrder, - PortfolioCMConditionalOrder, - PortfolioCMForceOrder, - PortfolioCMIncome, - PortfolioCMLeverageBracket, - PortfolioCMModifyOrderResponse, - PortfolioCMOrder, - PortfolioCMOrderModificationHistory, - PortfolioCMPosition, - PortfolioCMTrade, - PortfolioMarginCancelAllOrdersResponse, - PortfolioMarginCancelOrderResponse, - PortfolioMarginForceOrder, - PortfolioMarginInterestRecord, - PortfolioMarginLoanRecord, - PortfolioMarginOCO, - PortfolioMarginOCOCancelResponse, - PortfolioMarginOrder, - PortfolioMarginRepayDebtReq, - PortfolioMarginRepayDebtResponse, - PortfolioMarginRepayRecord, - PortfolioMarginTrade, - PortfolioNegativeBalanceInterestRecord, - PortfolioTradFiPerpsContractSignResponse, - PortfolioTradingStatus, - PortfolioUMAccountAsset, - PortfolioUMAccountAssetV2, - PortfolioUMAccountConfig, - PortfolioUMAccountPosition, - PortfolioUMAccountPositionV2, - PortfolioUMAlgoOrder, - PortfolioUMCancelAlgoOrderResponse, - PortfolioUMCancelAllUMAlgoOpenOrdersResponse, - PortfolioUMCancelConditionalOrderResponse, - PortfolioUMCancelOrderResponse, - PortfolioUMConditionalOrder, - PortfolioUMForceOrder, - PortfolioUMIncome, - PortfolioUMLeverageBracket, - PortfolioUMModifyOrderResponse, - PortfolioUMOrder, - PortfolioUMOrderModificationHistory, - PortfolioUMPosition, - PortfolioUMSymbolConfig, - PortfolioUMTrade, - QueryPortfolioAllCMConditionalOrdersReq, - QueryPortfolioAllCMOrdersReq, - QueryPortfolioAllUMAlgoOrdersReq, - QueryPortfolioAllUMConditionalOrdersReq, - QueryPortfolioAllUMOrdersReq, - QueryPortfolioCMConditionalOrderHistoryReq, - QueryPortfolioCMForceOrdersReq, - QueryPortfolioCMIncomeReq, - QueryPortfolioCMOpenOrderReq, - QueryPortfolioCMOrderAmendmentReq, - QueryPortfolioCMOrderReq, - QueryPortfolioCMTradesReq, - QueryPortfolioMarginAllOCOReq, - QueryPortfolioMarginAllOrdersReq, - QueryPortfolioMarginForceOrdersReq, - QueryPortfolioMarginOCOReq, - QueryPortfolioMarginOrderReq, - QueryPortfolioMarginTradesReq, - QueryPortfolioUMAlgoOrderReq, - QueryPortfolioUMConditionalOrderHistoryReq, - QueryPortfolioUMForceOrdersReq, - QueryPortfolioUMIncomeReq, - QueryPortfolioUMOpenConditionalOrderReq, - QueryPortfolioUMOpenOrderReq, - QueryPortfolioUMOrderAmendmentReq, - QueryPortfolioUMOrderReq, - QueryPortfolioUMTradesReq, -} from './types/portfolio-margin'; + ClassicPortfolioMarginAccount, + ClassicPortfolioMarginNotionalLimit, + CoinMAccountTradeParams, + CoinMOpenInterest, + CoinMPositionTrade, + CoinMSymbolOrderBookTicker, + FundingRate, + FuturesTransactionHistoryDownloadLink, + GetClassicPortfolioMarginNotionalLimitParams, + PositionRisk, +} from './types/coin'; +import { + AggregateFuturesTrade, + CancelAllOpenOrdersResult, + CancelFuturesOrderResult, + CancelMultipleOrdersParams, + CancelOrdersTimeoutParams, + ChangeStats24hr, + ContinuousContractKlinesParams, + ForceOrderResult, + FundingRateHistory, + FuturesAlgoOrderResponse, + FuturesCancelAlgoOrderParams, + FuturesCancelAlgoOrderResponse, + FuturesCoinMAccountBalance, + FuturesCoinMAccountInformation, + FuturesCoinMBasisParams, + FuturesCoinMTakerBuySellVolumeParams, + FuturesDataPaginatedParams, + FuturesExchangeInfo, + FuturesNewAlgoOrderParams, + FuturesOrderBook, + FuturesQueryOpenAlgoOrdersParams, + GetForceOrdersParams, + GetIncomeHistoryParams, + GetPositionMarginChangeHistoryParams, + IncomeHistory, + IndexPriceConstituents, + IndexPriceKlinesParams, + MarkPrice, + ModeChangeResult, + ModifyFuturesOrderParams, + ModifyFuturesOrderResult, + NewFuturesOrderParams, + NewOrderError, + NewOrderResult, + OrderAmendment, + OrderResult, + PositionModeParams, + PositionModeResponse, + QuarterlyContractSettlementPrice, + RawFuturesTrade, + RebateDataOverview, + SetCancelTimeoutResult, + SetIsolatedMarginParams, + SetIsolatedMarginResult, + SetLeverageParams, + SetLeverageResult, + SetMarginTypeParams, + SymbolKlinePaginatedParams, + SymbolLeverageBracketsResult, + UserCommissionRate, +} from './types/futures'; import { + BasicSymbolPaginatedParams, BinanceBaseUrlKey, CancelOCOParams, CancelOrderParams, + GenericCodeMsgError, + GetAllOrdersParams, + GetOrderModifyHistoryParams, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, NewOCOParams, + OrderBookParams, OrderIdProperty, + RecentTradesParams, + SymbolFromPaginatedRequestFromId, + SymbolPrice, } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { + asArray, generateNewOrderId, getOrderIdPrefix, getServerTimeEndpoint, @@ -7931,20 +7444,13 @@ import { RestClientOptions, } from './util/requestUtils'; ⋮---- -/** - * REST client for Portfolio Margin APIs (papi) - * - * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info - */ -export class PortfolioClient extends BaseRestClient +export class CoinMClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- -getClientId(): BinanceBaseUrlKey -⋮---- /** * Abstraction required by each client to aid with time sync / drift handling */ @@ -7952,576 +7458,495 @@ async getServerTime(): Promise ⋮---- /** * - * Misc Endpoints + * Market Data Endpoints * **/ ⋮---- testConnectivity(): Promise ⋮---- -signTradFiPerpsContract(): Promise +getExchangeInfo(): Promise ⋮---- -/** - * - * DERIVATIVES -TRADE endpoints - * - **/ +getOrderBook(params: OrderBookParams): Promise ⋮---- -submitNewUMOrder( - params: NewPortfolioUMOrderReq, -): Promise +getRecentTrades(params: RecentTradesParams): Promise +⋮---- +getHistoricalTrades( + params: HistoricalTradesParams, +): Promise +⋮---- +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). + * Index Price and Mark Price */ -submitNewUMConditionalOrder( - params: NewPortfolioUMConditionalOrderReq, -): Promise -⋮---- -submitNewUMAlgoOrder( - params: NewPortfolioUMAlgoOrderReq, -): Promise +getMarkPrice(params?: ⋮---- -submitNewCMOrder( - params: NewPortfolioCMOrderReq, -): Promise +getFundingRateHistory( + params?: Partial, +): Promise ⋮---- -submitNewCMConditionalOrder( - params: NewPortfolioCMConditionalOrderReq, -): Promise +getFundingRate(params?: ⋮---- -submitNewMarginOrder( - params: NewPortfolioMarginOrderReq, -): Promise +getKlines(params: KlinesParams): Promise ⋮---- -submitMarginLoan(params: +getContinuousContractKlines( + params: ContinuousContractKlinesParams, +): Promise ⋮---- -submitMarginRepay(params: +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- -submitNewMarginOCO( - params: NewPortfolioMarginOCOReq, -): Promise +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -cancelUMOrder( - params: CancelPortfolioUMOrderReq, -): Promise +getPremiumIndexKlines(params: KlinesParams): Promise ⋮---- -cancelAllUMOrders(params: +get24hrChangeStatistics(params?: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). - */ -cancelUMConditionalOrder( - params: CancelPortfolioUMConditionalOrderReq, -): Promise -⋮---- -cancelUMAlgoOrder( - params: CancelPortfolioUMAlgoOrderReq, -): Promise +getSymbolPriceTicker(params?: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). - */ -cancelAllUMConditionalOrders(params: +getSymbolOrderBookTicker(params?: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -cancelAllUMAlgoOpenOrders(params: { - symbol: string; -}): Promise +getOpenInterest(params: ⋮---- -cancelCMOrder( - params: CancelPortfolioCMOrderReq, -): Promise +getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise ⋮---- -cancelAllCMOrders(params: +getTopTradersLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -cancelCMConditionalOrder( - params: CancelPortfolioCMConditionalOrderReq, -): Promise +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams & { pair?: string }, +): Promise ⋮---- -cancelAllCMConditionalOrders(params: +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -cancelMarginOrder( - params: CancelPortfolioMarginOrderReq, -): Promise +getTakerBuySellVolume( + params: FuturesCoinMTakerBuySellVolumeParams, +): Promise ⋮---- -cancelMarginOCO( - params: CancelPortfolioMarginOCOReq, -): Promise +getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise ⋮---- -cancelAllMarginOrders(params: { +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getIndexPriceConstituents(params: { symbol: string; -}): Promise -⋮---- -modifyUMOrder( - params: ModifyPortfolioUMOrderReq, -): Promise -⋮---- -modifyCMOrder( - params: ModifyPortfolioCMOrderReq, -): Promise -⋮---- -getUMOrder(params: QueryPortfolioUMOrderReq): Promise -⋮---- -getAllUMOrders( - params: QueryPortfolioAllUMOrdersReq, -): Promise -⋮---- -getUMOpenOrder( - params: QueryPortfolioUMOpenOrderReq, -): Promise +}): Promise ⋮---- -getAllUMOpenOrders(params: +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getQuarterlyContractSettlementPrices(params: { + pair: string; +}): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). - */ -getAllUMConditionalOrders( - params: QueryPortfolioAllUMConditionalOrdersReq, -): Promise + * + * Trade Endpoints + * + **/ ⋮---- -getAllUMAlgoOrders( - params: QueryPortfolioAllUMAlgoOrdersReq, -): Promise +submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). + * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. + * + * Known issue: `quantity` and `price` should be sent as strings */ -getUMOpenConditionalOrders(params: { - symbol?: string; -}): Promise -⋮---- -getUMAlgoOpenOrders(params?: { - symbol?: string; -}): Promise +submitMultipleOrders( + orders: NewFuturesOrderParams[], +): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue */ -getUMOpenConditionalOrder( - params: QueryPortfolioUMOpenConditionalOrderReq, -): Promise -⋮---- -getUMAlgoOrder( - params: QueryPortfolioUMAlgoOrderReq, -): Promise +modifyOrder( + params: ModifyFuturesOrderParams, +): Promise ⋮---- /** - * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. + * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. */ -getUMConditionalOrderHistory( - params: QueryPortfolioUMConditionalOrderHistoryReq, -): Promise +modifyMultipleOrders( + orders: ModifyFuturesOrderParams[], +): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> ⋮---- -getCMOrder(params: QueryPortfolioCMOrderReq): Promise +getOrderModifyHistory( + params: GetOrderModifyHistoryParams, +): Promise ⋮---- -getAllCMOrders( - params: QueryPortfolioAllCMOrdersReq, -): Promise +cancelOrder(params: CancelOrderParams): Promise ⋮---- -getCMOpenOrder( - params: QueryPortfolioCMOpenOrderReq, -): Promise +cancelMultipleOrders( + params: CancelMultipleOrdersParams, +): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- -getAllCMOpenOrders(params: { +cancelAllOpenOrders(params: { symbol?: string; - pair?: string; -}): Promise +}): Promise ⋮---- -getCMOpenConditionalOrders(params: { - symbol?: string; -}): Promise +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, +): Promise ⋮---- -getCMOpenConditionalOrder(params: { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -}): Promise +getOrder(params: GetOrderParams): Promise ⋮---- -getAllCMConditionalOrders( - params: QueryPortfolioAllCMConditionalOrdersReq, -): Promise +getAllOrders(params: GetAllOrdersParams): Promise ⋮---- -getCMConditionalOrderHistory( - params: QueryPortfolioCMConditionalOrderHistoryReq, -): Promise +getAllOpenOrders(params?: ⋮---- -getUMForceOrders( - params: QueryPortfolioUMForceOrdersReq, -): Promise +getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- -getCMForceOrders( - params: QueryPortfolioCMForceOrdersReq, -): Promise +/** + * + * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) + * Conditional orders migrate to Algo Service on COIN-M + * + **/ ⋮---- -getUMOrderModificationHistory( - params: QueryPortfolioUMOrderAmendmentReq, -): Promise +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, +): Promise ⋮---- -getCMOrderModificationHistory( - params: QueryPortfolioCMOrderAmendmentReq, -): Promise +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, +): Promise ⋮---- -getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, +): Promise ⋮---- -getUMTrades(params: QueryPortfolioUMTradesReq): Promise +getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- -getCMTrades(params: QueryPortfolioCMTradesReq): Promise +getAccountTrades( + params: CoinMAccountTradeParams & { orderId?: number }, +): Promise ⋮---- -getUMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > { - return this.getPrivate('papi/v1/um/adlQuantile', params); +getPositions(params?: { + marginAsset?: string; + pair?: string; +}): Promise ⋮---- -getCMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > { - return this.getPrivate('papi/v1/cm/adlQuantile', params); +setPositionMode(params: PositionModeParams): Promise ⋮---- -toggleUMFeeBurn(params: { - feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off -}): Promise< +setMarginType(params: SetMarginTypeParams): Promise ⋮---- -feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +setLeverage(params: SetLeverageParams): Promise ⋮---- -getUMFeeBurnStatus(): Promise< +getADLQuantileEstimation(params?: ⋮---- -getMarginOrder( - params: QueryPortfolioMarginOrderReq, -): Promise +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, +): Promise ⋮---- -getMarginOpenOrders(params: { - symbol: string; -}): Promise +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, +): Promise +/** + * + * Account Endpoints + * + **/ ⋮---- -getAllMarginOrders( - params: QueryPortfolioMarginAllOrdersReq, -): Promise +getBalance(): Promise ⋮---- -getMarginOCO( - params: QueryPortfolioMarginOCOReq, -): Promise -⋮---- -getAllMarginOCO( - params: QueryPortfolioMarginAllOCOReq, -): Promise -⋮---- -getMarginOpenOCO(): Promise -⋮---- -getMarginTrades( - params: QueryPortfolioMarginTradesReq, -): Promise +getAccountCommissionRate(params: { + symbol?: string; +}): Promise ⋮---- -repayMarginDebt( - params: PortfolioMarginRepayDebtReq, -): Promise +getAccountInformation(): Promise ⋮---- /** - * - * DERIVATIVES - ACCOUNT endpoints - * - **/ -⋮---- -getBalance(params?: -⋮---- -getAccountInfo(): Promise -⋮---- -getMarginMaxBorrow(params: -⋮---- -amount: string; // account's currently max borrowable amount with sufficient system availability -borrowLimit: string; // max borrowable amount limited by the account level -⋮---- -getMarginMaxWithdraw(params: -⋮---- -amount: string; // max withdrawable amount -⋮---- -getUMPosition(params?: -⋮---- -getCMPosition(params?: { - marginAsset?: string; - pair?: string; -}): Promise -⋮---- -updateUMLeverage(params: -⋮---- -updateCMLeverage(params: -⋮---- -updateUMPositionMode(params: { - dualSidePosition: 'true' | 'false'; -}): Promise< -⋮---- -updateCMPositionMode(params: { - dualSidePosition: 'true' | 'false'; -}): Promise< -⋮---- -getUMPositionMode(): Promise< -⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode -⋮---- -getCMPositionMode(): Promise< -⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode -⋮---- -getUMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - notionalCoef: string; - brackets: PortfolioUMLeverageBracket[]; - }[] - > { - return this.getPrivate('papi/v1/um/leverageBracket', params); -⋮---- -getCMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - brackets: PortfolioCMLeverageBracket[]; - }[] - > { - return this.getPrivate('papi/v1/cm/leverageBracket', params); -⋮---- -getUMTradingStatus(params?: { + * Notional Bracket for Symbol (NOT "pair") + */ +getNotionalAndLeverageBrackets(params?: { symbol?: string; -}): Promise -⋮---- -getUMCommissionRate(params: -⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% -⋮---- -getCMCommissionRate(params: -⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% -⋮---- -getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise< +}): Promise ⋮---- -getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< +// TO ADD: dapi/v1/leverageBracket +// can use dapi/v2/leverageBracket ⋮---- -getAutoRepayFuturesStatus(): Promise< +getCurrentPositionMode(): Promise ⋮---- -autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off +getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- -updateAutoRepayFuturesStatus(params: { - autoRepay: 'true' | 'false'; +getDownloadIdForFuturesTransactionHistory(params: { + startTime: number; + endTime: number; }): Promise< ⋮---- -getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -repayFuturesNegativeBalance(): Promise< +getDownloadIdForFuturesOrderHistory(params: { + startTime: number; + endTime: number; +}): Promise< ⋮---- -getPortfolioNegativeBalanceInterestHistory( - params?: GetPortfolioInterestHistoryReq, -): Promise +getFuturesOrderHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -autoCollectFunds(): Promise< +getDownloadIdForFuturesTradeHistory(params: { + startTime: number; + endTime: number; +}): Promise< ⋮---- -transferAssetFuturesMargin(params: +getFuturesTradeHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -transferBNB(params: { - amount: string; - transferSide: 'TO_UM' | 'FROM_UM'; -}): Promise< +/** + * + * Portfolio Margin Endpoints + * + **/ ⋮---- -tranId: number; // transaction id +getClassicPortfolioMarginAccount(params: { + asset: string; +}): Promise ⋮---- -getUMIncomeHistory( - params?: QueryPortfolioUMIncomeReq, -): Promise +/** + * @deprecated at 6th August, 2024 + **/ +getClassicPortfolioMarginNotionalLimits( + params?: GetClassicPortfolioMarginNotionalLimitParams, +): Promise< ⋮---- -getCMIncomeHistory( - params?: QueryPortfolioCMIncomeReq, -): Promise +/** + * + * Broker Futures Endpoints + * Possibly @deprecated, found only in old docs + * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker + * + **/ ⋮---- -getUMAccount(): Promise< +/** + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, +): Promise< ⋮---- -positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market +/** + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, +): Promise< ⋮---- -getCMAccount(): Promise< +/** + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, +): Promise ⋮---- -getUMAccountConfig(): Promise +/** + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise ⋮---- -getUMSymbolConfig(params?: { - symbol?: string; -}): Promise +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- -getUMAccountV2(): Promise< +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -getUMTradeHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms -}): Promise< +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +getFuturesUserDataListenKey(): Promise< ⋮---- -getUMTradeDownloadLink(params: { - downloadId: string; -}): Promise +keepAliveFuturesUserDataListenKey(): Promise ⋮---- -getUMOrderHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms -}): Promise< -⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms -⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days -⋮---- -getUMOrderDownloadLink(params: { - downloadId: string; -}): Promise -⋮---- -getUMTransactionHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms -}): Promise< -⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms -⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days -⋮---- -getUMTransactionDownloadLink(params: { - downloadId: string; -}): Promise +closeFuturesUserDataListenKey(): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: - | NewPortfolioUMOrderReq + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void -⋮---- -/** - * - * User Data Stream Endpoints - * - **/ -getPMUserDataListenKey(): Promise< -⋮---- -keepAlivePMUserDataListenKey(): Promise -⋮---- -closePMUserDataListenKey(): Promise ================ -File: src/usdm-client.ts +File: src/portfolio-client.ts ================ -/* eslint-disable @typescript-eslint/no-explicit-any */ import { AxiosRequestConfig } from 'axios'; ⋮---- -import { FundingRate } from './types/coin'; import { - AggregateFuturesTrade, - Basis, - BasisParams, - CancelAllOpenOrdersResult, - CancelFuturesOrderResult, - CancelMultipleOrdersParams, - CancelOrdersTimeoutParams, - ChangeStats24hr, - ContinuousContractKlinesParams, - ForceOrderResult, - FundingRateHistory, - FuturesAccountBalance, - FuturesAccountConfig, - FuturesAccountInformation, - FuturesAlgoOrderResponse, - FuturesCancelAlgoOrderParams, - FuturesCancelAlgoOrderResponse, - FuturesCancelAllAlgoOpenOrdersResponse, - FuturesConvertOrderStatus, - FuturesConvertPair, - FuturesConvertQuote, - FuturesConvertQuoteRequest, - FuturesDataPaginatedParams, - FuturesExchangeInfo, - FuturesNewAlgoOrderParams, - FuturesOrderBook, - FuturesPosition, - FuturesPositionTrade, - FuturesPositionV3, - FuturesQueryAlgoOrderParams, - FuturesQueryAlgoOrderResponse, - FuturesQueryAllAlgoOrdersParams, - FuturesQueryOpenAlgoOrdersParams, - FuturesSymbolOrderBookTicker, - FuturesTradeHistoryDownloadId, - FuturesTransactionDownloadLink, - GetForceOrdersParams, - GetFuturesOrderModifyHistoryParams, - GetIncomeHistoryParams, - GetPositionMarginChangeHistoryParams, - HistoricOpenInterest, - IncomeHistory, - IndexPriceConstituents, - IndexPriceKlinesParams, - InsuranceFundBalance, - MarkPrice, - ModeChangeResult, - ModifyFuturesOrderParams, - ModifyFuturesOrderResult, - ModifyOrderParams, - MultiAssetModeResponse, - MultiAssetsMode, - NewFuturesOrderParams, - NewOrderError, - NewOrderResult, - OpenInterest, - OrderResult, - PortfolioMarginProAccountInfo, - PositionModeParams, - PositionModeResponse, - QuarterlyContractSettlementPrice, - RawFuturesTrade, - RebateDataOverview, - RpiOrderBook, - SetCancelTimeoutResult, - SetIsolatedMarginParams, - SetIsolatedMarginResult, - SetLeverageParams, - SetLeverageResult, - SetMarginTypeParams, - SymbolAdlRisk, - SymbolConfig, - SymbolKlinePaginatedParams, - SymbolLeverageBracketsResult, - TradingSchedule, - UserCommissionRate, - UserForceOrder, -} from './types/futures'; + CancelPortfolioCMConditionalOrderReq, + CancelPortfolioCMOrderReq, + CancelPortfolioMarginOCOReq, + CancelPortfolioMarginOrderReq, + CancelPortfolioUMAlgoOrderReq, + CancelPortfolioUMConditionalOrderReq, + CancelPortfolioUMOrderReq, + DownloadLinkResponse, + GetMarginInterestHistoryReq, + GetMarginLoanRecordsReq, + GetMarginRepayRecordsReq, + GetPortfolioInterestHistoryReq, + ModifyPortfolioCMOrderReq, + ModifyPortfolioUMOrderReq, + NewPortfolioCMConditionalOrderReq, + NewPortfolioCMConditionalOrderResponse, + NewPortfolioCMOrderReq, + NewPortfolioCMOrderResponse, + NewPortfolioConditionalOrderResponse, + NewPortfolioMarginOCOReq, + NewPortfolioMarginOCOResponse, + NewPortfolioMarginOrderReq, + NewPortfolioMarginOrderResponse, + NewPortfolioUMAlgoOrderReq, + NewPortfolioUMConditionalOrderReq, + NewPortfolioUMOrderReq, + NewPortfolioUMOrderResponse, + PortfolioAccountInformation, + PortfolioADLQuantile, + PortfolioBalance, + PortfolioCMAccountAsset, + PortfolioCMAccountPosition, + PortfolioCMCancelConditionalOrderResponse, + PortfolioCMCancelOrderResponse, + PortfolioCMConditionalHistoryOrder, + PortfolioCMConditionalOrder, + PortfolioCMForceOrder, + PortfolioCMIncome, + PortfolioCMLeverageBracket, + PortfolioCMModifyOrderResponse, + PortfolioCMOrder, + PortfolioCMOrderModificationHistory, + PortfolioCMPosition, + PortfolioCMTrade, + PortfolioMarginCancelAllOrdersResponse, + PortfolioMarginCancelOrderResponse, + PortfolioMarginForceOrder, + PortfolioMarginInterestRecord, + PortfolioMarginLoanRecord, + PortfolioMarginOCO, + PortfolioMarginOCOCancelResponse, + PortfolioMarginOrder, + PortfolioMarginRepayDebtReq, + PortfolioMarginRepayDebtResponse, + PortfolioMarginRepayRecord, + PortfolioMarginTrade, + PortfolioNegativeBalanceInterestRecord, + PortfolioTradFiPerpsContractSignResponse, + PortfolioTradingStatus, + PortfolioUMAccountAsset, + PortfolioUMAccountAssetV2, + PortfolioUMAccountConfig, + PortfolioUMAccountPosition, + PortfolioUMAccountPositionV2, + PortfolioUMAlgoOrder, + PortfolioUMCancelAlgoOrderResponse, + PortfolioUMCancelAllUMAlgoOpenOrdersResponse, + PortfolioUMCancelConditionalOrderResponse, + PortfolioUMCancelOrderResponse, + PortfolioUMConditionalOrder, + PortfolioUMForceOrder, + PortfolioUMIncome, + PortfolioUMLeverageBracket, + PortfolioUMModifyOrderResponse, + PortfolioUMOrder, + PortfolioUMOrderModificationHistory, + PortfolioUMPosition, + PortfolioUMSymbolConfig, + PortfolioUMTrade, + QueryPortfolioAllCMConditionalOrdersReq, + QueryPortfolioAllCMOrdersReq, + QueryPortfolioAllUMAlgoOrdersReq, + QueryPortfolioAllUMConditionalOrdersReq, + QueryPortfolioAllUMOrdersReq, + QueryPortfolioCMConditionalOrderHistoryReq, + QueryPortfolioCMForceOrdersReq, + QueryPortfolioCMIncomeReq, + QueryPortfolioCMOpenOrderReq, + QueryPortfolioCMOrderAmendmentReq, + QueryPortfolioCMOrderReq, + QueryPortfolioCMTradesReq, + QueryPortfolioMarginAllOCOReq, + QueryPortfolioMarginAllOrdersReq, + QueryPortfolioMarginForceOrdersReq, + QueryPortfolioMarginOCOReq, + QueryPortfolioMarginOrderReq, + QueryPortfolioMarginTradesReq, + QueryPortfolioUMAlgoOrderReq, + QueryPortfolioUMConditionalOrderHistoryReq, + QueryPortfolioUMForceOrdersReq, + QueryPortfolioUMIncomeReq, + QueryPortfolioUMOpenConditionalOrderReq, + QueryPortfolioUMOpenOrderReq, + QueryPortfolioUMOrderAmendmentReq, + QueryPortfolioUMOrderReq, + QueryPortfolioUMTradesReq, +} from './types/portfolio-margin'; import { - BasicSymbolPaginatedParams, - BasicSymbolParam, BinanceBaseUrlKey, CancelOCOParams, CancelOrderParams, - GenericCodeMsgError, - GetAllOrdersParams, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, NewOCOParams, - numberInString, - OrderBookParams, OrderIdProperty, - RecentTradesParams, - SymbolFromPaginatedRequestFromId, - SymbolPrice, } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { @@ -8532,13 +7957,20 @@ import { RestClientOptions, } from './util/requestUtils'; ⋮---- -export class USDMClient extends BaseRestClient +/** + * REST client for Portfolio Margin APIs (papi) + * + * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info + */ +export class PortfolioClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- +getClientId(): BinanceBaseUrlKey +⋮---- /** * Abstraction required by each client to aid with time sync / drift handling */ @@ -8546,2730 +7978,1306 @@ async getServerTime(): Promise ⋮---- /** * - * MARKET DATA endpoints - Rest API + * Misc Endpoints * **/ ⋮---- testConnectivity(): Promise ⋮---- -getExchangeInfo(): Promise -⋮---- -getOrderBook(params: OrderBookParams): Promise +signTradFiPerpsContract(): Promise ⋮---- -getRpiOrderBook(params: { - symbol: string; - limit?: number; -}): Promise -⋮---- -getRecentTrades(params: RecentTradesParams): Promise +/** + * + * DERIVATIVES -TRADE endpoints + * + **/ ⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, -): Promise +submitNewUMOrder( + params: NewPortfolioUMOrderReq, +): Promise ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). + */ +submitNewUMConditionalOrder( + params: NewPortfolioUMConditionalOrderReq, +): Promise ⋮---- -getKlines(params: KlinesParams): Promise +submitNewUMAlgoOrder( + params: NewPortfolioUMAlgoOrderReq, +): Promise ⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, -): Promise +submitNewCMOrder( + params: NewPortfolioCMOrderReq, +): Promise ⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +submitNewCMConditionalOrder( + params: NewPortfolioCMConditionalOrderReq, +): Promise ⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +submitNewMarginOrder( + params: NewPortfolioMarginOrderReq, +): Promise ⋮---- -getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise +submitMarginLoan(params: ⋮---- -getMarkPrice(params: +submitMarginRepay(params: ⋮---- -getMarkPrice(): Promise; +submitNewMarginOCO( + params: NewPortfolioMarginOCOReq, +): Promise ⋮---- -getMarkPrice(params?: +cancelUMOrder( + params: CancelPortfolioUMOrderReq, +): Promise ⋮---- -getFundingRateHistory( - params?: Partial, -): Promise +cancelAllUMOrders(params: ⋮---- -getFundingRates(): Promise +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). + */ +cancelUMConditionalOrder( + params: CancelPortfolioUMConditionalOrderReq, +): Promise ⋮---- -get24hrChangeStatistics(params: +cancelUMAlgoOrder( + params: CancelPortfolioUMAlgoOrderReq, +): Promise ⋮---- -get24hrChangeStatistics(): Promise; +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). + */ +cancelAllUMConditionalOrders(params: ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; -}): Promise +cancelAllUMAlgoOpenOrders(params: { + symbol: string; +}): Promise ⋮---- -getSymbolPriceTicker(params: +cancelCMOrder( + params: CancelPortfolioCMOrderReq, +): Promise ⋮---- -getSymbolPriceTicker(): Promise; +cancelAllCMOrders(params: ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; -}): Promise +cancelCMConditionalOrder( + params: CancelPortfolioCMConditionalOrderReq, +): Promise ⋮---- -getSymbolPriceTickerV2(params: +cancelAllCMConditionalOrders(params: ⋮---- -getSymbolPriceTickerV2(): Promise; +cancelMarginOrder( + params: CancelPortfolioMarginOrderReq, +): Promise ⋮---- -getSymbolPriceTickerV2(params?: { - symbol?: string; -}): Promise +cancelMarginOCO( + params: CancelPortfolioMarginOCOReq, +): Promise ⋮---- -getSymbolOrderBookTicker(params: { +cancelAllMarginOrders(params: { symbol: string; - }): Promise; -⋮---- -getSymbolOrderBookTicker(): Promise; -⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; -}): Promise -⋮---- -getQuarterlyContractSettlementPrices(params: { - pair: string; -}): Promise -⋮---- -getOpenInterest(params: -⋮---- -getOpenInterestStatistics( - params: FuturesDataPaginatedParams, -): Promise -⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams, -): Promise +}): Promise ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +modifyUMOrder( + params: ModifyPortfolioUMOrderReq, +): Promise ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +modifyCMOrder( + params: ModifyPortfolioCMOrderReq, +): Promise ⋮---- -getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise +getUMOrder(params: QueryPortfolioUMOrderReq): Promise ⋮---- -getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +getAllUMOrders( + params: QueryPortfolioAllUMOrdersReq, +): Promise ⋮---- -getCompositeSymbolIndex(params?: +getUMOpenOrder( + params: QueryPortfolioUMOpenOrderReq, +): Promise ⋮---- -getMultiAssetsModeAssetIndex(params?: +getAllUMOpenOrders(params: ⋮---- /** - * Possibly @deprecated, found only in old docs - **/ -getBasis(params: BasisParams): Promise -⋮---- -getIndexPriceConstituents(params: { - symbol: string; -}): Promise -⋮---- -getInsuranceFundBalance(params?: { - symbol?: string; -}): Promise + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). + */ +getAllUMConditionalOrders( + params: QueryPortfolioAllUMConditionalOrdersReq, +): Promise ⋮---- -getTradingSchedule(): Promise +getAllUMAlgoOrders( + params: QueryPortfolioAllUMAlgoOrdersReq, +): Promise ⋮---- /** - * - * TRADE endpoints - Rest API - * - **/ + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). + */ +getUMOpenConditionalOrders(params: { + symbol?: string; +}): Promise ⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise +getUMAlgoOpenOrders(params?: { + symbol?: string; +}): Promise ⋮---- /** - * Warning: max 5 orders at a time! This method does not throw, instead it returns - * individual errors in the response array if any orders were rejected. - * - * Note: this method will automatically ensure "price" and "quantity" are sent as a - * string, if present in the request. See #523 & #526 for more details. + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> +getUMOpenConditionalOrder( + params: QueryPortfolioUMOpenConditionalOrderReq, +): Promise ⋮---- -// Known issue: `quantity` and `price` should be sent as strings, see #523, #526 +getUMAlgoOrder( + params: QueryPortfolioUMAlgoOrderReq, +): Promise ⋮---- /** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. */ -modifyOrder( - params: ModifyFuturesOrderParams, -): Promise +getUMConditionalOrderHistory( + params: QueryPortfolioUMConditionalOrderHistoryReq, +): Promise ⋮---- -modifyMultipleOrders(orders: ModifyOrderParams[]): Promise +getCMOrder(params: QueryPortfolioCMOrderReq): Promise ⋮---- -getOrderModifyHistory( - params: GetFuturesOrderModifyHistoryParams, -): Promise +getAllCMOrders( + params: QueryPortfolioAllCMOrdersReq, +): Promise ⋮---- -cancelOrder(params: CancelOrderParams): Promise +getCMOpenOrder( + params: QueryPortfolioCMOpenOrderReq, +): Promise ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, -): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +getAllCMOpenOrders(params: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -cancelAllOpenOrders(params: { - symbol: string; -}): Promise +getCMOpenConditionalOrders(params: { + symbol?: string; +}): Promise ⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, -): Promise +getCMOpenConditionalOrder(params: { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +}): Promise ⋮---- -getOrder(params: GetOrderParams): Promise +getAllCMConditionalOrders( + params: QueryPortfolioAllCMConditionalOrdersReq, +): Promise ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +getCMConditionalOrderHistory( + params: QueryPortfolioCMConditionalOrderHistoryReq, +): Promise ⋮---- -getAllOpenOrders(params?: +getUMForceOrders( + params: QueryPortfolioUMForceOrdersReq, +): Promise ⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +getCMForceOrders( + params: QueryPortfolioCMForceOrdersReq, +): Promise ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +getUMOrderModificationHistory( + params: QueryPortfolioUMOrderAmendmentReq, +): Promise ⋮---- -getAccountTrades( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise +getCMOrderModificationHistory( + params: QueryPortfolioCMOrderAmendmentReq, +): Promise ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< ⋮---- -setPositionMode(params: PositionModeParams): Promise +getUMTrades(params: QueryPortfolioUMTradesReq): Promise ⋮---- -setLeverage(params: SetLeverageParams): Promise +getCMTrades(params: QueryPortfolioCMTradesReq): Promise ⋮---- -setMultiAssetsMode(params: { - multiAssetsMargin: MultiAssetsMode; -}): Promise +getUMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > { + return this.getPrivate('papi/v1/um/adlQuantile', params); ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, -): Promise +getCMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > { + return this.getPrivate('papi/v1/cm/adlQuantile', params); ⋮---- -/** - * @deprecated - * Use getPositionsV3() instead - **/ -getPositions(params?: Partial): Promise +toggleUMFeeBurn(params: { + feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +}): Promise< ⋮---- -getPositionsV3(params?: +feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off ⋮---- -getADLQuantileEstimation(params?: +getUMFeeBurnStatus(): Promise< ⋮---- -getSymbolAdlRisk(params: +getMarginOrder( + params: QueryPortfolioMarginOrderReq, +): Promise ⋮---- -getSymbolAdlRisk(): Promise; +getMarginOpenOrders(params: { + symbol: string; +}): Promise ⋮---- -getSymbolAdlRisk(params?: { - symbol?: string; -}): Promise +getAllMarginOrders( + params: QueryPortfolioMarginAllOrdersReq, +): Promise ⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, -): Promise +getMarginOCO( + params: QueryPortfolioMarginOCOReq, +): Promise ⋮---- -/** - * - * ACCOUNT endpoints - Rest API - * - **/ +getAllMarginOCO( + params: QueryPortfolioMarginAllOCOReq, +): Promise ⋮---- -getBalanceV3(): Promise +getMarginOpenOCO(): Promise ⋮---- -/** - * @deprecated - * Use getBalanceV3() instead - **/ -getBalance(): Promise +getMarginTrades( + params: QueryPortfolioMarginTradesReq, +): Promise ⋮---- -getAccountInformationV3(): Promise +repayMarginDebt( + params: PortfolioMarginRepayDebtReq, +): Promise ⋮---- /** - * @deprecated - * Use getAccountInformationV3() instead + * + * DERIVATIVES - ACCOUNT endpoints + * **/ -getAccountInformation(): Promise ⋮---- -getAccountCommissionRate(params: { - symbol: string; -}): Promise +getBalance(params?: ⋮---- -getFuturesAccountConfig(): Promise +getAccountInfo(): Promise ⋮---- -getFuturesSymbolConfig(params: +getMarginMaxBorrow(params: ⋮---- -getUserForceOrders(): Promise +amount: string; // account's currently max borrowable amount with sufficient system availability +borrowLimit: string; // max borrowable amount limited by the account level ⋮---- -/** - * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) - */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; -}): Promise +getMarginMaxWithdraw(params: ⋮---- -getMultiAssetsMode(): Promise +amount: string; // max withdrawable amount ⋮---- -getCurrentPositionMode(): Promise +getUMPosition(params?: ⋮---- -getIncomeHistory(params?: GetIncomeHistoryParams): Promise +getCMPosition(params?: { + marginAsset?: string; + pair?: string; +}): Promise ⋮---- -getApiQuantitativeRulesIndicators(params?: { - symbol?: string; -}): Promise +updateUMLeverage(params: ⋮---- -getFuturesTransactionHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise +updateCMLeverage(params: ⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; -}): Promise +updateUMPositionMode(params: { + dualSidePosition: 'true' | 'false'; +}): Promise< ⋮---- -getFuturesOrderHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise +updateCMPositionMode(params: { + dualSidePosition: 'true' | 'false'; +}): Promise< ⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; -}): Promise +getUMPositionMode(): Promise< ⋮---- -getFuturesTradeHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -getFuturesTradeDownloadLink(params: { - downloadId: string; -}): Promise +getCMPositionMode(): Promise< ⋮---- -setBNBBurnEnabled(params: { - feeBurn: 'true' | 'false'; -}): Promise< +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -getBNBBurnStatus(): Promise< +getUMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + notionalCoef: string; + brackets: PortfolioUMLeverageBracket[]; + }[] + > { + return this.getPrivate('papi/v1/um/leverageBracket', params); ⋮---- -signTradFiPerpsAgreement(): Promise< +getCMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + brackets: PortfolioCMLeverageBracket[]; + }[] + > { + return this.getPrivate('papi/v1/cm/leverageBracket', params); ⋮---- -testOrder(params: NewFuturesOrderParams): Promise +getUMTradingStatus(params?: { + symbol?: string; +}): Promise ⋮---- -/** - * - * Algo Order Endpoints (Effective 2025-12-02) - * Conditional orders migrate to Algo Service - * - **/ +getUMCommissionRate(params: ⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, -): Promise +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, -): Promise +getCMCommissionRate(params: ⋮---- -cancelAllAlgoOpenOrders(params: { - symbol: string; -}): Promise +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -getAlgoOrder( - params: FuturesQueryAlgoOrderParams, -): Promise +getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise< ⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, -): Promise +getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< ⋮---- -getAllAlgoOrders( - params: FuturesQueryAllAlgoOrdersParams, -): Promise +getAutoRepayFuturesStatus(): Promise< ⋮---- -/** - * - * Convert Endpoints - * - **/ +autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off ⋮---- -getAllConvertPairs(params?: { - fromAsset?: string; - toAsset?: string; -}): Promise +updateAutoRepayFuturesStatus(params: { + autoRepay: 'true' | 'false'; +}): Promise< ⋮---- -submitConvertQuoteRequest( - params: FuturesConvertQuoteRequest, -): Promise +getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< ⋮---- -acceptConvertQuote(params: +repayFuturesNegativeBalance(): Promise< ⋮---- -getConvertOrderStatus(params: { - orderId?: string; - quoteId?: string; -}): Promise +getPortfolioNegativeBalanceInterestHistory( + params?: GetPortfolioInterestHistoryReq, +): Promise ⋮---- -/** - * - * Portfolio Margin Pro Endpoints - * - **/ +autoCollectFunds(): Promise< ⋮---- -getPortfolioMarginProAccountInfo(params: { - asset: string; -}): Promise +transferAssetFuturesMargin(params: ⋮---- -/** - * - * Broker Futures Endpoints - * Possibly @deprecated, found only in old docs - * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker - * - **/ +transferBNB(params: { + amount: string; + transferSide: 'TO_UM' | 'FROM_UM'; +}): Promise< ⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, -): Promise< +tranId: number; // transaction id ⋮---- -/** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, -): Promise< +getUMIncomeHistory( + params?: QueryPortfolioUMIncomeReq, +): Promise ⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, -): Promise +getCMIncomeHistory( + params?: QueryPortfolioCMIncomeReq, +): Promise ⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise +getUMAccount(): Promise< ⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market ⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +getCMAccount(): Promise< ⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +getUMAccountConfig(): Promise ⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +getUMSymbolConfig(params?: { + symbol?: string; +}): Promise ⋮---- -/** - * - * User Data Stream Endpoints - * - **/ +getUMAccountV2(): Promise< ⋮---- -// USD-M Futures +positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market ⋮---- -getFuturesUserDataListenKey(): Promise< +getUMTradeHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms +}): Promise< ⋮---- -keepAliveFuturesUserDataListenKey(): Promise +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms ⋮---- -closeFuturesUserDataListenKey(): Promise +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMTradeDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +getUMOrderHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms +}): Promise< +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMOrderDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +getUMTransactionHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms +}): Promise< +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMTransactionDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams + | NewPortfolioUMOrderReq | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +getPMUserDataListenKey(): Promise< +⋮---- +keepAlivePMUserDataListenKey(): Promise +⋮---- +closePMUserDataListenKey(): Promise ================ -File: .nvmrc -================ -v24.14.1 - -================ -File: docs/BINANCE_SDK_QUICKSTART_GUIDE.md -================ -# Binance SDK Quickstart Guide - -> [!TIP] -> This guide can be read in tutorial format on the Siebly Website: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) - -This guide walks through key pieces of a Binance REST API, WebSocket & WebSocket API integration using [`binance`](https://www.npmjs.com/package/binance), the Binance JavaScript and TypeScript SDK by Siebly.io. - -The SDK handles request building and connectivity for you, including request signing, WebSocket management, healthchecks, heartbeats, listen-key refreshes, resubscribe behavior, and WebSocket API response mapping so your code can stay focused on the workflow you are automating. This guide will walk you through installation and client selection, then moves through public calls, private auth, REST API calls, streams, user data, and the WebSocket API. - -**Key links** - -- Binance JavaScript SDK by Siebly: [`binance`](https://www.npmjs.com/package/binance) -- GitHub Repository: [`tiagosiebler/binance`](https://github.com/tiagosiebler/binance) -- SDK function-endpoint map: [Binance JavaScript Endpoint Reference](./endpointFunctionList.md) -- REST API examples: [Binance SDK REST API examples](../examples/Rest) -- WebSocket examples: [Binance SDK WebSocket examples](../examples/WebSockets) -- More SDKs: [Siebly.io](https://siebly.io) - ---- - -## Why use the SDK - -A stable Binance integration is more than a handful of HTTP requests. Binance splits behavior across product groups, transports, key types, and environments: - -- Spot, Margin, Wallet, Convert, Earn, and Sub-Account APIs live behind the main REST API client, but not all of them share the same endpoint prefix or permission model. -- Some of these product groups expect API calls to reach different subdomains. -- USD-M Futures and COIN-M Futures have separate REST API clients, symbols, endpoint prefixes, and WebSocket endpoints. -- Both have their own subdomains as well. -- Portfolio Margin uses a dedicated REST API client and its own account model. -- Public streams, private user data streams, and WebSocket API commands are different flows. -- Private REST API and WebSocket API requests must be signed. -- User data streams can involve listen keys, WebSocket API subscriptions, token refreshes, and reconnect handling. - -Most of that work is handled for you, while the grouping & naming stays close to Binance's API naming. The SDK gives you dedicated REST API clients for the major product groups, `WebsocketClient` for streaming, `WebsocketAPIClient` for awaitable WebSocket API requests. It also includes TypeScript definitions, ESM/CJS support, proxy support, and optional response beautification. - ---- - -## 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/binance) and [npm](https://www.npmjs.com/package/binance), and can therefore be installed with your favourite Node.js compatible package manager. - -Install the SDK with npm: - -```bash -npm install binance -``` - -Or use another npm-compatible package manager: - -```bash -pnpm install binance -yarn add binance -``` - -Create API keys from the relevant Binance page: - -- Binance live API keys: [Binance API Management](https://www.binance.com/en/my/settings/api-management) -- Binance Spot testnet: [Spot Test Network](https://testnet.binance.vision/) -- Binance Futures testnet: [Futures Testnet](https://testnet.binancefuture.com/) -- Binance demo trading: [Binance Demo Trading](https://demo.binance.com/) - -> Always use the minimum permissions needed for your scenario. Trading does not require withdrawal permissions. Analytics does not require trading permissions. -> Always require strict IP whitelisting for any API keys that you create. - -The main auth and environment rules are: - -- Public market data does not require API keys. -- Private REST APIs require `api_key` and `api_secret`. -- Live, testnet, and demo trading credentials are separate, as they are separate environments. -- API permissions must match the product and action your code is using. -- HMAC keys are the common API key + secret flow. These are the "system generated" API keys, selected by default when creating new API keys for Binance. -- RSA and Ed25519 keys use self-generated private keys. -- Ed25519 is recommended for latency-sensitive integrations with the WebSocket API, as this enables session-based WebSocket API authentication, instead of having to authenticate every request. - -All supported key types use the same SDK constructor shape. The SDK will automatically detect your key type and adjust request building & sign automatically: - -```typescript -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); -``` - -For HMAC, `api_secret` is your Binance API secret. For RSA or Ed25519, `api_secret` is your PEM private key. - -Typical environment variables: - -```bash -export BINANCE_API_KEY='your-api-key' -export BINANCE_API_SECRET='your-api-secret-or-private-key' -``` - -If you are only testing public endpoints, you do not need any keys at all. - ---- - -## Products and clients - -Binance is not one single API. The SDK splits API clients around Binance's product groups: - -| Product group | API client | Common usage | -| -------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------- | -| REST API: Spot, Margin, Wallet, Convert, Earn, Sub-accounts, Broker, Alpha | `MainClient` | Spot trading, account data, wallet flows, margin trading, transfers, savings/earn, sub-account management | -| REST API: USD-M Futures | `USDMClient` | USDT/USDC margined futures market data, account data, positions, orders | -| REST API: COIN-M Futures | `CoinMClient` | Coin-margined futures market data, account data, positions, orders | -| REST API: Portfolio Margin | `PortfolioClient` | Portfolio Margin account, UM/CM/margin orders, balances, positions | -| WebSocket streams | `WebsocketClient` | Public market data streams and private user data streams | -| WebSocket API | `WebsocketAPIClient` | REST API-like Spot and Futures commands over persistent WebSocket API connections | - -As a rule of thumb: - -- Use `MainClient` when the Binance docs path starts with `api/` or `sapi/`, including Spot and many account/wallet APIs. -- Use `USDMClient` when the Binance docs path starts with `fapi/`. -- Use `CoinMClient` when the Binance docs path starts with `dapi/`. -- Use `PortfolioClient` when the Binance docs path starts with `papi/`. -- Use `WebsocketClient` when you want to subscribe to streams and receive events. -- Use `WebsocketAPIClient` when you want to send commands over WebSocket and await responses like REST API calls. - -For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). If any endpoints or properties seem to be missing, please open an issue on GitHub and we'll look into it. Targeted PRs are also welcome. - -### REST API, streams, listen keys, and WebSocket API - -Binance uses several related but different integration patterns. It helps to keep them separate: - -| Flow | SDK surface | Best for | What the SDK handles | -| ---------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| REST API | `MainClient`, `USDMClient`, `CoinMClient`, `PortfolioClient` | Request/response calls, broad API coverage, occasional reads/writes, fallback reconciliation | Base URLs, request signing, timestamps, response parsing, errors | -| Public WebSocket streams | `WebsocketClient.subscribe(...)` | Live market data such as trades, klines, tickers, order book updates | Connection routing, subscribe requests, heartbeats, reconnects, resubscribe | -| Listen-key user data streams | `WebsocketClient.subscribeUsdFuturesUserDataStream()`, `subscribeCoinFuturesUserDataStream()`, portfolio helpers | Private account events where Binance still uses listen keys, especially Futures and Portfolio Margin streams | Listen-key creation, keepalive, refresh, reconnect, stream teardown | -| WebSocket API user data | `WebsocketAPIClient.subscribeUserDataStream(...)` | Spot user data and some newer private stream flows without the old Spot listen-key workflow | WebSocket API auth, subscription command, reconnect/resubscribe behavior | -| WebSocket API commands | `WebsocketAPIClient` methods or `WebsocketClient.sendWSAPIRequest(...)` | Lower-latency request/response commands over an already-open WebSocket, such as order tests, order placement, cancellation, status, account reads | WebSocket connection persistence, auth, request IDs, promise resolution, response/error correlation | - -The WebSocket API is not just another stream. It is a request/response API over WebSocket. Since much of the functionality is a better alternative to the REST API, we've introduced the promise-driven `WebsocketAPIClient`. Lets you write code that feels like working with a REST API. Call a function to send a command over WS and await the response, without any of the complexity of managing asynchronous messaging over WebSockets (as well as the life-cycle complexities that come with keeping WebSockets healthy). - -```typescript -const result = await wsApi.testSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', - timestamp: Date.now(), -}); -``` - -Use the REST API when you want maximum endpoint coverage, simple one-off calls, or reconciliation after reconnects. Use the WebSocket API when you want persistent connectivity, lower request overhead, WebSocket API-only features, or a promise-driven command path that can share the same event-driven architecture as your streams. With Ed25519 keys, authentication can happen once per WebSocket API connection, which can improve latency in mid-to-high frequency systems. One less thing to repeat every request, is cumulatively saved time. - ---- - -## Start building: first calls - -If you only want the fastest path to a working integration, start here. - -### 1. First Spot REST API request - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient(); - -async function main() { - const serverTime = await client.getServerTime(); - const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); - const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); - const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); - const candles = await client.getKlines({ - symbol: 'BTCUSDT', - interval: '1m', - limit: 5, - }); - - console.log({ - serverTime, - symbol: exchangeInfo.symbols?.[0]?.symbol, - ticker, - orderBook, - candles, - }); -} - -main().catch(console.error); -``` - -That confirms public Spot REST API access is wired correctly. - -See also: [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) - -### 2. First public Spot WebSocket stream - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ - beautify: true, -}); - -ws.on('open', (data) => console.log('connected', data.wsKey, data.wsUrl)); -ws.on('message', (data) => console.log('raw message', JSON.stringify(data))); -ws.on('formattedMessage', (data) => console.log('formatted', data)); -ws.on('response', (data) => console.log('response', JSON.stringify(data))); -ws.on('reconnecting', (data) => console.log('reconnecting', data?.wsKey)); -ws.on('reconnected', (data) => console.log('reconnected', data?.wsKey)); -ws.on('exception', console.error); - -ws.subscribe(['btcusdt@trade', 'btcusdt@bookTicker'], WS_KEY_MAP.main); -``` - -That gives you a live public Spot stream without any API keys. - -See also: [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) - -### 3. First private Spot user data stream - -For Spot user data streams, prefer the WebSocket API user data flow. It avoids the older Spot listen-key flow and keeps the stream on a managed WebSocket API connection. - -```typescript -import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -wsApi.getWSClient().on('open', (data) => { - console.log('ws api open', data.wsKey); -}); - -wsApi.getWSClient().on('formattedUserDataMessage', (data) => { - console.log('account event', data); -}); - -wsApi.getWSClient().on('exception', console.error); - -async function main() { - await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); -} - -main().catch(console.error); -``` - -The SDK handles authentication and resubscribe behavior for the WebSocket API connection. With Ed25519 keys it can authenticate the WebSocket API session once. With HMAC or RSA keys it signs private WebSocket API commands individually, although that primarily matters in the context of sending regular commands (such as order submissions) via WebSocket API. - -See also: [Spot user data stream over WebSocket API](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) - -### 4. First Spot order over REST API - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -async function placeOrder() { - const orderRequest = { - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - newOrderRespType: 'FULL', - } as const; - - // Validate the request without sending it to the matching engine. - await client.testNewOrder(orderRequest); - - // Remove this comment when you are ready to place a real order. - // const result = await client.submitNewOrder(orderRequest); - // console.log(result); -} - -placeOrder().catch(console.error); -``` - -Use `testNewOrder()` when you want to validate the request shape and signature without placing a live Spot order. Use `submitNewOrder()` only when you are ready to send the order. - -See also: [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) - -### 5. First USD-M Futures order - -For strategy testing, `demoTrading: true` is usually more realistic than testnet because demo trading uses live market data with simulated trading. - -```typescript -import { USDMClient } from 'binance'; - -const client = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - demoTrading: true, -}); - -async function placeFuturesOrder() { - const account = await client.getAccountInformation(); - console.log('demo futures account can trade:', account.canTrade); - - const result = await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'MARKET', - quantity: 0.001, - }); - - console.log(result); -} - -placeFuturesOrder().catch(console.error); -``` - -See also: [USD-M Futures demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) - -### 6. First WebSocket API request - -The WebSocket API lets you send requests over a persistent WebSocket connection and await responses, similar to REST API calls. This is useful for lower-latency workflows and for WebSocket API-only features. - -```typescript -import { WebsocketAPIClient } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -async function main() { - const time = await wsApi.getSpotServerTime(); - - const orderTest = await wsApi.testSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', - timestamp: Date.now(), - }); - - console.log({ time, orderTest }); -} - -main() - .catch(console.error) - .finally(() => wsApi.disconnectAll()); -``` - -See also: [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) - ---- - -## Spot, Margin, and Wallet REST API - -Most Binance integrations start with `MainClient`. It covers Spot trading and many account APIs under Binance's main REST API families. - -### Create a public `MainClient` - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient(); -``` - -Public calls do not require keys. - -### Create a private `MainClient` - -If you plan on making private API calls, include API keys when creating the client: - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautifyResponses: true, -}); -``` - -Private REST API methods are signed automatically. You do not need to manually add timestamps, signatures, or `X-MBX-APIKEY` headers. - -### Common public Spot market data calls - -```typescript -const serverTime = await client.getServerTime(); -const ping = await client.testConnectivity(); -const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); -const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); -const recentTrades = await client.getRecentTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const aggregateTrades = await client.getAggregateTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const candles = await client.getKlines({ - symbol: 'BTCUSDT', - interval: '1m', - limit: 10, -}); -const averagePrice = await client.getAvgPrice({ symbol: 'BTCUSDT' }); -const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); -const bookTicker = await client.getSymbolOrderBookTicker({ - symbol: 'BTCUSDT', -}); -``` - -### Common private Spot account and order calls - -```typescript -const account = await client.getAccountInformation(); -const balances = await client.getBalances(); -const accountInfo = await client.getAccountInfo(); -const openOrders = await client.getOpenOrders({ symbol: 'BTCUSDT' }); -const allOrders = await client.getAllOrders({ symbol: 'BTCUSDT', limit: 10 }); -const myTrades = await client.getAccountTradeList({ - symbol: 'BTCUSDT', - limit: 10, -}); -const tradeFee = await client.getTradeFee({ symbol: 'BTCUSDT' }); -const apiPermissions = await client.getApiKeyPermissions(); -``` - -See also: - -- [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) -- [Spot exchange info example](../examples/Rest/Spot/rest-spot-exchange-info.ts) -- [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) -- [Spot private miscellaneous account example](../examples/Rest/Spot/rest-spot-private-misc.ts) - -### Spot order examples - -Market order: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'MARKET', - quantity: 0.001, - newOrderRespType: 'FULL', -}); -``` - -Limit order: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', -}); -``` - -Limit maker order: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT_MAKER', - quantity: 0.001, - price: 10000, -}); -``` - -Test an order without sending it: - -```typescript -await client.testNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', -}); -``` - -Cancel an order: - -```typescript -await client.cancelOrder({ - symbol: 'BTCUSDT', - orderId: 123456789, -}); -``` - -**Custom client order IDs** - -You do not always need to set a custom client order ID. Most of the time, the cleanest option is to send the order without `newClientOrderId` and let the SDK handle the request normally: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', -}); -``` - -If your system needs to know the client order ID before the order is sent, but the ID does not need to carry any meaning, ask the REST API client to generate one: - -```typescript -const newClientOrderId = client.generateNewOrderId(); - -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', - newClientOrderId, -}); -``` - -`generateNewOrderId()` is available on every REST API client, including `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. The client already knows its product group, so the generated ID uses the right Binance-compatible prefix. - -If you want to include a small piece of your own context in the client order ID, such as a take-profit marker or strategy step, use the product prefix from the client and append your suffix: - -```typescript -const prefix = client.getOrderIdPrefix(); -const suffix = `tp1_${Date.now()}`; -const newClientOrderId = `${prefix}${suffix}`; -const validBinanceClientOrderId = /^[.A-Z:/a-z0-9_-]{1,32}$/; - -if (!validBinanceClientOrderId.test(newClientOrderId)) { - throw new Error(`Invalid Binance client order ID: ${newClientOrderId}`); -} - -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', - newClientOrderId, -}); -``` - -The prefix returned by `getOrderIdPrefix()` is 10 characters long. For endpoints with Binance's common 32-character client order ID limit, that leaves 22 characters for your own suffix. Some fields have a different documented limit, such as USD-M Futures Algo `clientAlgoId`, which currently allows up to 36 characters and therefore leaves 26 characters after the SDK prefix. Keep the suffix short and use only characters Binance allows for that field. - -If you need to track richer metadata than will comfortably fit in the client order ID, do not try to squeeze it into these custom order ID fields. Instead, generate an ID with `client.generateNewOrderId()` before placing the order, use that value as the key for your own metadata, and store the metadata locally or in an external store such as Redis. Later, when order updates arrive through REST API polling or user data events, you can look up the richer context using the seen `newClientOrderId` value like a primary key, while keeping the exchange-facing ID short and valid. - -Regular Spot/Futures/Portfolio orders usually use `newClientOrderId`; newer Futures algo or conditional flows may use `clientAlgoId` instead. The same rule applies: omit it unless you need it, use `generateNewOrderId()` when any unique ID is fine, and use `getOrderIdPrefix()` when building your own value. - -### Margin REST API examples - -Margin APIs also live on `MainClient`. - -```typescript -const marginAssets = await client.getAllMarginAssets(); -const marginPairs = await client.getAllCrossMarginPairs(); -const priceIndex = await client.queryMarginPriceIndex({ symbol: 'BTCUSDT' }); - -const crossMarginAccount = await client.queryCrossMarginAccountDetails(); -const isolatedMarginAccount = await client.getIsolatedMarginAccountInfo({ - symbols: 'BTCUSDT', -}); -const openMarginOrders = await client.queryMarginAccountOpenOrders({ - symbol: 'BTCUSDT', -}); -``` - -Margin order: - -```typescript -await client.marginAccountNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - isIsolated: 'FALSE', - sideEffectType: 'NO_SIDE_EFFECT', -}); -``` - -Borrow or repay: - -```typescript -await client.submitMarginAccountBorrowRepay({ - asset: 'USDT', - symbol: 'BTCUSDT', - amount: 25, - type: 'BORROW', - isIsolated: 'FALSE', -}); -``` - -Margin permissions, collateral, interest, and liquidation behavior are account-specific. Keep margin trading code separate from ordinary Spot trading code even though both use `MainClient`. - -### Wallet and transfer examples - -Wallet and transfer APIs also live on `MainClient`. - -```typescript -const balances = await client.getBalances(); -const depositAddress = await client.getDepositAddress({ - coin: 'USDT', - network: 'ETH', -}); -const depositHistory = await client.getDepositHistory({ coin: 'USDT' }); -const withdrawHistory = await client.getWithdrawHistory({ coin: 'USDT' }); - -const transferHistory = await client.getUniversalTransferHistory({ - type: 'MAIN_UMFUTURE', -}); -``` - -Withdrawal calls are intentionally not shown as a quickstart. Use withdrawal permissions only when your system truly needs them, and isolate those keys from trading keys. - ---- - -## Futures REST API - -Binance Futures are split into USD-M and COIN-M product groups. Use the dedicated client for the product you are integrating. - -### Create public Futures clients - -```typescript -import { CoinMClient, USDMClient } from 'binance'; - -const usdm = new USDMClient(); -const coinm = new CoinMClient(); -``` - -Public futures market data does not require keys. - -### Create private Futures clients - -```typescript -import { CoinMClient, USDMClient } from 'binance'; - -const usdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -const coinm = new CoinMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); -``` - -Use `demoTrading: true` for Binance demo trading or `testnet: true` for testnet where supported: - -```typescript -const demoUsdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - demoTrading: true, -}); - -const testnetUsdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - testnet: true, -}); -``` - -Do not enable both `demoTrading` and `testnet` on the same client. - -### Common public USD-M Futures market data calls - -```typescript -const serverTime = await usdm.getServerTime(); -const exchangeInfo = await usdm.getExchangeInfo(); -const orderBook = await usdm.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); -const recentTrades = await usdm.getRecentTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const candles = await usdm.getKlines({ - symbol: 'BTCUSDT', - interval: '1m', - limit: 10, -}); -const markPrice = await usdm.getMarkPrice({ symbol: 'BTCUSDT' }); -const fundingHistory = await usdm.getFundingRateHistory({ - symbol: 'BTCUSDT', - limit: 10, -}); -const ticker = await usdm.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); -``` - -### Common public COIN-M Futures market data calls - -```typescript -const serverTime = await coinm.getServerTime(); -const exchangeInfo = await coinm.getExchangeInfo(); -const orderBook = await coinm.getOrderBook({ - symbol: 'BTCUSD_PERP', - limit: 10, -}); -const candles = await coinm.getKlines({ - symbol: 'BTCUSD_PERP', - interval: '1m', - limit: 10, -}); -const markPrice = await coinm.getMarkPrice({ symbol: 'BTCUSD_PERP' }); -const ticker = await coinm.getSymbolPriceTicker({ symbol: 'BTCUSD_PERP' }); -``` - -See also: - -- [USD-M public REST API example](../examples/Rest/Futures/rest-usdm-public.ts) -- [USD-M demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) -- [USD-M testnet example](../examples/Rest/Futures/rest-usdm-testnet.ts) - -### Common private Futures account calls - -```typescript -const balance = await usdm.getBalance(); -const account = await usdm.getAccountInformation(); -const positions = await usdm.getPositions({ symbol: 'BTCUSDT' }); -const openOrders = await usdm.getAllOpenOrders({ symbol: 'BTCUSDT' }); -const tradeHistory = await usdm.getAccountTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const income = await usdm.getIncomeHistory({ - symbol: 'BTCUSDT', - limit: 10, -}); -``` - -### Futures order examples - -Market order: - -```typescript -await usdm.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'MARKET', - quantity: 0.001, -}); -``` - -Limit order: - -```typescript -await usdm.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', -}); -``` - -Reduce-only limit order: - -```typescript -await usdm.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - reduceOnly: 'true', -}); -``` - -Batch order management: - -```typescript -await usdm.submitMultipleOrders([ - { - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - }, - { - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', - }, -]); -``` - -See also: - -- [USD-M order example](../examples/Rest/Futures/rest-usdm-order.ts) -- [USD-M stop-loss order example](../examples/Rest/Futures/rest-usdm-order-sl.ts) -- [USD-M bracket order example](../examples/Rest/Futures/rest-future-bracket-order.ts) - ---- - -## Portfolio Margin REST API - -Portfolio Margin has its own account model and a dedicated `PortfolioClient`. - -### Create a Portfolio Margin client - -```typescript -import { PortfolioClient } from 'binance'; - -const portfolio = new PortfolioClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); -``` - -### Common Portfolio Margin calls - -```typescript -const ping = await portfolio.testConnectivity(); -const serverTime = await portfolio.getServerTime(); -const balance = await portfolio.getBalance(); -const account = await portfolio.getAccountInfo(); -const umPositions = await portfolio.getUMPosition({ symbol: 'BTCUSDT' }); -const cmPositions = await portfolio.getCMPosition({ pair: 'BTCUSD' }); -const umOpenOrders = await portfolio.getAllUMOpenOrders({ - symbol: 'BTCUSDT', -}); -const marginOpenOrders = await portfolio.getMarginOpenOrders({ - symbol: 'BTCUSDT', -}); -``` - -Portfolio Margin order examples: - -```typescript -await portfolio.submitNewUMOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', -}); - -await portfolio.submitNewCMOrder({ - symbol: 'BTCUSD_PERP', - side: 'SELL', - type: 'MARKET', - quantity: '1', -}); - -await portfolio.submitNewMarginOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'MARKET', - quantity: '0.001', - sideEffectType: 'NO_SIDE_EFFECT', -}); -``` - -See also: - -- [Portfolio Margin public REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-public.ts) -- [Portfolio Margin private REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-private.ts) - ---- - -## WebSocket Streams - -Use `WebsocketClient` when you want event-driven updates instead of polling the REST API. It is the shared client for public market streams and the older listen-key style user data streams. - -The workflow is simple: create a client, add event handlers, provide API keys if you need private user data, and subscribe to the streams you want. The SDK opens the correct Binance endpoint, applies proxy settings if configured, fetches and refreshes listen keys where required, monitors heartbeats, reconnects stale sockets, and resubscribes cached topics after reconnect. - -### Common `WebsocketClient` events - -| Event | Meaning | -| -------------------------- | --------------------------------------------------------------- | -| `open` | Connection established | -| `message` | Raw streaming data received | -| `formattedMessage` | Beautified public stream data when `beautify: true` | -| `formattedUserDataMessage` | Beautified private user data stream event when `beautify: true` | -| `response` | Subscribe, unsubscribe, auth, or WebSocket API acknowledgement | -| `reconnecting` | Connection dropped and retrying | -| `reconnected` | Connection restored and subscriptions resynced | -| `close` | Socket closed | -| `authenticated` | WebSocket API session authentication succeeded | -| `exception` | Errors and unexpected conditions | - -### Understanding `WS_KEY_MAP` - -`WS_KEY_MAP` tells the SDK which Binance WebSocket endpoint family to use. This matters because Spot, USD-M Futures, COIN-M Futures, Options, Portfolio Margin, and WebSocket API traffic do not all live on the same endpoint. - -Common `WS_KEY_MAP` entries: - -| Key | Use | -| ---------------------------- | ----------------------------------------------------------------------- | -| `main` | Spot, margin, and isolated margin market data streams | -| `main2` | Alternate Spot stream port | -| `main3` | Spot market-data-only stream endpoint | -| `mainWSAPI` | Spot and margin WebSocket API | -| `mainWSAPITestnet` | Spot WebSocket API testnet | -| `marginUserData` | Margin user data over WebSocket API listen-token flow | -| `marginRiskUserData` | Cross-margin risk data stream | -| `usdmPublic` | USD-M high-frequency public market data, such as book and depth streams | -| `usdmMarket` | USD-M regular market data, such as trades, klines, tickers, mark price | -| `usdmPrivate` | USD-M private user data stream endpoint | -| `usdmWSAPI` | USD-M Futures WebSocket API | -| `coinm` | COIN-M market data and user data stream endpoint | -| `coinmWSAPI` | COIN-M Futures WebSocket API | -| `eoptions` | European Options WebSocket streams | -| `portfolioMarginUserData` | Portfolio Margin user data stream | -| `portfolioMarginProUserData` | Portfolio Margin Pro user data stream | -| `alpha` | Alpha market data streams | - -These keys act like connection IDs. The SDK uses them to track connection state, cached subscriptions, reconnect behavior, and endpoint-specific routing. - -### Public Spot WebSocket topics - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ beautify: true }); - -ws.on('formattedMessage', (data) => console.log(data)); -ws.on('exception', console.error); - -ws.subscribe( - [ - 'btcusdt@trade', - 'btcusdt@aggTrade', - 'btcusdt@kline_1m', - 'btcusdt@bookTicker', - 'btcusdt@depth10@100ms', - ], - WS_KEY_MAP.main, -); -``` - -See also: - -- [General public WebSocket example](../examples/WebSockets/Public/ws-public.ts) -- [Spot order book WebSocket example](../examples/WebSockets/Public/ws-public-spot-orderbook.ts) -- [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) - -### Public USD-M Futures WebSocket topics - -USD-M Futures WebSockets have dedicated endpoint families for high-frequency public data and regular market data. - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ beautify: true }); - -ws.on('formattedMessage', (data) => console.log(data)); -ws.on('exception', console.error); - -// High-frequency public data: book ticker and order book depth. -ws.subscribe( - ['btcusdt@bookTicker', 'btcusdt@depth10@100ms', 'btcusdt@depth@100ms'], - WS_KEY_MAP.usdmPublic, -); - -// Regular market data: trades, mark price, klines, mini tickers, liquidations. -ws.subscribe( - ['btcusdt@aggTrade', 'btcusdt@markPrice', 'btcusdt@kline_1m'], - WS_KEY_MAP.usdmMarket, -); -``` - -See also: - -- [USD-M public WebSocket example](../examples/WebSockets/Public/ws-usdm-public.ts) -- [USD-M funding stream example](../examples/WebSockets/Public/ws-public-usdm-funding.ts) - -### Public COIN-M Futures WebSocket topics - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ beautify: true }); - -ws.on('message', (data) => console.log(JSON.stringify(data))); -ws.on('exception', console.error); - -ws.subscribe( - ['btcusd_perp@aggTrade', 'btcusd_perp@markPrice', 'btcusd_perp@kline_1m'], - WS_KEY_MAP.coinm, -); -``` - -COIN-M symbols and stream names are not the same as Spot or USD-M symbols. Treat symbols as product-specific strings. - ---- - -## User Data Streams - -User data streams are how Binance pushes private account events: order updates, execution updates, balance changes, position changes, margin events, and listen-key or subscription expiry events. - -Binance uses two patterns for these streams: WebSocket API user data subscriptions and listen-key user data streams. The SDK supports both; the product group determines which path you should use. - -For either pattern, listen for the WebSocket lifecycle events as well as account events. The event names are `reconnecting` and `reconnected`. `reconnecting` fires when the SDK starts replacing a dropped connection; `reconnected` fires after the replacement connection is open. Both include the `wsKey`, which tells you which connection was affected. For user data streams, `reconnected` is the right place to reconcile private state through the REST API in case account events were missed while the socket was down. - -With `WebsocketAPIClient`, attach those handlers to `wsApi.getWSClient()`. With `WebsocketClient`, attach them directly to the client. - -### Preferred Spot user data stream with `WebsocketAPIClient` - -```typescript -import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -const wsClient = wsApi.getWSClient(); - -wsClient.on('formattedUserDataMessage', (data) => { - console.log('spot account event', data); -}); - -wsClient.on('reconnecting', ({ wsKey }) => { - console.log('spot user data reconnecting', wsKey); -}); - -wsClient.on('reconnected', ({ wsKey }) => { - console.log('spot user data reconnected', wsKey); - // Fetch account state, open orders, or recent fills here if needed. -}); - -wsClient.on('exception', console.error); - -await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); -``` - -This is the recommended path for Spot user data in this SDK version. - -### Margin user data stream with `WebsocketAPIClient` - -```typescript -import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -const wsClient = wsApi.getWSClient(); - -wsClient.on('formattedUserDataMessage', (data) => { - console.log('margin account event', data); -}); - -wsClient.on('reconnecting', ({ wsKey }) => { - console.log('margin user data reconnecting', wsKey); -}); - -wsClient.on('reconnected', ({ wsKey }) => { - console.log('margin user data reconnected', wsKey); -}); - -await wsApi.subscribeUserDataStream(WS_KEY_MAP.marginUserData); -``` - -For margin, the SDK handles the listen-token workflow used by Binance's margin WebSocket API user data endpoint. - -### Futures user data streams with `WebsocketClient` - -For Futures user data streams, the SDK can manage listen keys for you through convenience methods. - -```typescript -import { WebsocketClient } from 'binance'; - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -ws.on('formattedUserDataMessage', (data) => { - console.log('futures account event', data); -}); - -ws.on('reconnecting', ({ wsKey }) => { - console.log('futures user data reconnecting', wsKey); -}); - -ws.on('reconnected', ({ wsKey }) => { - console.log('futures user data reconnected', wsKey); - // Fetch positions, balances, open orders, or fills here if needed. -}); - -ws.on('exception', console.error); - -await ws.subscribeUsdFuturesUserDataStream(); -// await ws.subscribeCoinFuturesUserDataStream(); -``` - -The SDK will fetch the listen key, keep it alive, refresh it when needed, reconnect after network issues, and resubscribe where possible. - -### Portfolio Margin user data stream - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -ws.on('formattedUserDataMessage', (data) => { - console.log('portfolio margin event', data); -}); - -ws.on('reconnecting', ({ wsKey }) => { - console.log('portfolio margin user data reconnecting', wsKey); -}); - -ws.on('reconnected', ({ wsKey }) => { - console.log('portfolio margin user data reconnected', wsKey); -}); - -ws.on('exception', console.error); - -await ws.subscribePortfolioMarginUserDataStream( - WS_KEY_MAP.portfolioMarginUserData, -); -``` - -See also: - -- [User data stream overview](<../examples/WebSockets/Private(userdata)/ws-userdata-README.MD>) -- [Listen-key user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts>) -- [WebSocket API user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) -- [User data connection safety example](<../examples/WebSockets/Private(userdata)/ws-userdata-connection-safety.ts>) - ---- - -## WebSocket API - -Binance's WebSocket API is a request/response API over a persistent WebSocket connection. It is useful when you want lower request overhead than REST API calls, or when a Binance feature is exposed through the WebSocket API flow. - -`WebsocketAPIClient` wraps that in a promise-driven interface: call a method, await a promise, receive the response, and let the SDK manage the underlying WebSocket connection. - -### Authentication - -The SDK supports HMAC, RSA, and Ed25519 keys: - -- HMAC: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. -- RSA: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. -- Ed25519: recommended for WebSocket API because the SDK can authenticate the WebSocket API session once and then send private commands without signing every command. - -If your `api_secret` contains a PEM private key, the SDK automatically detects whether it should use RSA or Ed25519 signing. - -See also: - -- [Ed25519 auth example](../examples/auth/rest-private-ed25519.md) -- [RSA auth example](../examples/auth/rest-private-rsa.md) - -### Spot examples - -```typescript -import { WebsocketAPIClient } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -const exchangeInfo = await wsApi.getSpotExchangeInfo({ - symbol: 'BTCUSDT', -}); - -const orderBook = await wsApi.getSpotOrderBook({ - symbol: 'BTCUSDT', - limit: 10, -}); - -const account = await wsApi.getSpotAccountInformation({ - timestamp: Date.now(), -}); - -await wsApi.testSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', - timestamp: Date.now(), -}); -``` - -Submit a Spot order over the WebSocket API: - -```typescript -await wsApi.submitNewSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', -}); -``` - -### Futures examples - -```typescript -import { WebsocketAPIClient } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -const book = await wsApi.getFuturesOrderBook({ - symbol: 'BTCUSDT', - limit: 10, -}); - -const balance = await wsApi.getFuturesAccountBalance('usdm', { - timestamp: Date.now(), -}); - -await wsApi.submitNewFuturesOrder('usdm', { - symbol: 'BTCUSDT', - side: 'SELL', - type: 'MARKET', - quantity: '0.001', - timestamp: Date.now(), -}); -``` - -See also: - -- [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) -- [Raw WebSocket API promises example](../examples/WebSockets/WS-API/ws-api-raw-promises.ts) - ---- - -## Environments and Special Endpoints - -### Demo trading - -Demo trading uses real market data with simulated trading. For strategy testing, this is usually more useful than testnet. - -```typescript -const client = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - demoTrading: true, -}); -``` - -Demo trading is supported by SDK options for REST API and WebSocket clients where Binance provides demo endpoints. - -### Testnet - -Testnet uses separate credentials and simulated market conditions. - -```typescript -const client = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - testnet: true, -}); -``` - -Use testnet for endpoint wiring and permission checks. Do not use testnet market behavior as evidence that a live strategy is profitable or safe. - -### Market maker endpoints - -Binance provides market maker endpoints for eligible futures users. If you qualify and need those endpoints, enable them with `useMMSubdomain: true`. - -```typescript -const usdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - useMMSubdomain: true, -}); - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - useMMSubdomain: true, -}); -``` - -Market maker endpoints are for supported futures products. They are not a general Spot endpoint override and are not available on testnet. - ---- - -## Production Notes - -Before a Binance integration trades unattended, these are the parts worth making explicit. - -### 1. Roll out in layers - -Move from public reads to private actions one layer at a time: - -1. Public REST APIs -2. Public WebSockets -3. Private REST API account reads -4. Private account/user data streams -5. Order validation -6. Tiny demo or live trading tests - -For Futures, prefer demo trading before live trading if it fits your setup. - -### 2. Reconnect, then backfill - -Listen for `reconnecting` and `reconnected`. A dropped WebSocket connection is a normal production condition, especially during volatility or scheduled exchange disconnects. - -If your system uses WebSockets for account or market state, a reconnect should usually trigger a REST API backfill: - -1. Pause risky order actions when `reconnecting` fires. -2. On `reconnected`, query the REST API for account state, orders, fills, positions, and any market state you depend on. -3. Reconcile internal state. -4. React to any discrepancies in internal vs exchange state, as needed. -5. Resume normal processing. - -### 3. Keep credentials scoped - -Live, demo trading, Spot testnet, and Futures testnet credentials are different. Keep them separate in your secrets manager and deployment configuration. - -Use the minimum permissions needed for each key. A market-data key should not be able to trade. A trading key should not have withdrawal permissions. Do not put live secrets in frontend code. Make use of IP whitelisting for any API keys. These must be protected, treat them like passwords. - -### 4. Keep streams and commands separate - -Use `WebsocketClient` for streams. Use `WebsocketAPIClient` for commands you want to await. They share WebSocket infrastructure, but they solve different problems. - -### 5. Treat symbols and order IDs as product-specific state - -Spot, USD-M Futures, COIN-M Futures, Options, and Portfolio Margin do not all use the same symbol conventions: - -- Spot: `BTCUSDT` -- USD-M Futures: `BTCUSDT` -- COIN-M Futures: `BTCUSD_PERP` -- Stream names are usually lowercase, such as `btcusdt@trade`. Refer to the examples and/or exchange API docs for exact stream names. - -Client order IDs deserve the same care. If you do not need a custom client order ID, omit it. If your strategy relies on idempotency, retries, or reconciliation, generate an ID before sending the order and persist it using the restClient.generateNewOrderId() method. If you build your own value, keep the SDK's product prefix in place (query it using restClient.getOrderIdPrefix()) and stay within Binance's length and character constraints. - -### 6. Watch clocks and rate limits - -Private Binance requests are timestamp-sensitive. Keep your system clock synced and set `recvWindow` intentionally: - -```typescript -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - recvWindow: 5000, -}); - -await client.fetchLatencySummary(); - -// For WebSocket API clients: -wsApi.setTimeOffsetMs(-500); -``` - -The REST API client also tracks Binance rate-limit headers it sees: - -```typescript -const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); -console.log(ticker); - -console.log(client.getRateLimitStates()); -``` - -If you see timestamp errors, fix system clock sync first. If you see rate-limit pressure, reduce polling, batch where the API allows it, and design around Binance's documented request weights. - -For more guidance on resolving timestamp & recvWindow issues, refer to the following guidance: -https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow - -### 7. Logging and large integers - -If you want SDK logs in your own monitoring stack, pass a logger: - -```typescript -import { DefaultLogger, WebsocketClient } from 'binance'; - -const customLogger: typeof DefaultLogger = { - ...DefaultLogger, - trace: () => {}, - info: (...params) => console.info(new Date(), ...params), - error: (...params) => console.error(new Date(), ...params), -}; - -const ws = new WebsocketClient( - { - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, - }, - customLogger, -); -``` - -JavaScript cannot precisely represent integers above `Number.MAX_SAFE_INTEGER`. If you need to preserve very large order IDs from WebSocket messages, provide a custom parser: - -```typescript -import { WebsocketClient } from 'binance'; - -const ws = new WebsocketClient({ - customParseJSONFn: (rawEvent) => { - return JSON.parse( - rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), - ); - }, -}); -``` - -See also: [custom parser example](../examples/WebSockets/Misc/ws-custom-parser.ts) - ---- - -## FAQ - -**Which REST API client should I use?** - -Use `MainClient` for Spot, margin, wallet, Convert, Earn, sub-account, and many account APIs. Use `USDMClient` for USD-M Futures. Use `CoinMClient` for COIN-M Futures. Use `PortfolioClient` for Portfolio Margin. - -**Do I need API keys for public market data?** - -No. Public REST API market data and public WebSocket market data do not require API keys. - -**Can I use one Binance API key for every product group?** - -Sometimes, but only when the key belongs to the right environment and has the required product permissions enabled. Keep live, demo, and testnet credentials separate. Also keep high-risk permissions, especially withdrawals, separate from ordinary trading keys. - -**What is the difference between HMAC, RSA, and Ed25519?** - -HMAC is the standard API key + secret flow. RSA and Ed25519 use self-generated private keys. The SDK detects PEM private keys automatically when they are passed as `api_secret`. Ed25519 is recommended for latency-sensitive WebSocket API usage because it supports WebSocket API session authentication. - -**Why both `WebsocketClient` and `WebsocketAPIClient`?** - -- `WebsocketClient` is for subscriptions and streaming topics. -- `WebsocketAPIClient` is for commands over Binance's WebSocket API. Think "REST API" but over persistent WebSockets. - -**Should I use listen keys for Spot user data?** - -Prefer `WebsocketAPIClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` for Spot user data in this SDK version. The older Spot listen-key workflow is still present in places for compatibility, but Binance has marked the Spot listen-key workflow as deprecated. - -**What happens if a WebSocket connection drops?** - -The SDK supports reconnect and resubscribe flows. Listen for `reconnecting` and `reconnected`. Use `reconnected` as a trigger to reconcile state through the REST API before resuming risky trading actions. - -**Should I use demo trading or testnet?** - -Use demo trading when you want simulated trading with real market data. Use testnet for API wiring, endpoint behavior, and permission checks. Do not treat testnet market behavior as representative of live market behavior. - -**Can I use this Binance API SDK in TypeScript projects?** - -Yes. The package is TypeScript-first and publishes type declarations. - -**Do I need TypeScript to use this JavaScript Binance SDK?** - -No. Pure JavaScript projects can use this SDK too. Type declarations are included and will help your IDE, but TypeScript is not required. - -**Can I use this package in both ESM and CommonJS projects?** - -Yes. The package supports both ESM-style imports and CommonJS `require()`. - -**Does this guide cover every SDK method?** - -No. This guide covers the common first steps and production concerns. For full method coverage, see: - -- [Binance JavaScript endpoint reference](./endpointFunctionList.md) -- [Binance SDK examples](../examples) -- [TSDoc documentation](https://tsdocs.dev/docs/binance) - ---- - -## Next steps - -If you want to learn more about integrating with Binance APIs and WebSockets: - -- Explore the [Binance JavaScript examples on GitHub](../examples) -- Review the full endpoint list: [Binance JavaScript endpoint reference](./endpointFunctionList.md) -- Check the Binance JavaScript SDK on npm: [`binance`](https://www.npmjs.com/package/binance) -- Browse the source code of the Binance JavaScript SDK on GitHub: [`tiagosiebler/binance`](https://github.com/tiagosiebler/binance) -- Review auth examples: [Ed25519](../examples/auth/rest-private-ed25519.md) and [RSA](../examples/auth/rest-private-rsa.md) -- Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) - -================ -File: src/types/websockets/ws-api-requests.ts +File: src/usdm-client.ts ================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; +⋮---- +import { FundingRate } from './types/coin'; import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderType, - FuturesOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; + AggregateFuturesTrade, + Basis, + BasisParams, + CancelAllOpenOrdersResult, + CancelFuturesOrderResult, + CancelMultipleOrdersParams, + CancelOrdersTimeoutParams, + ChangeStats24hr, + ContinuousContractKlinesParams, + ForceOrderResult, + FundingRateHistory, + FuturesAccountBalance, + FuturesAccountConfig, + FuturesAccountInformation, + FuturesAlgoOrderResponse, + FuturesCancelAlgoOrderParams, + FuturesCancelAlgoOrderResponse, + FuturesCancelAllAlgoOpenOrdersResponse, + FuturesConvertOrderStatus, + FuturesConvertPair, + FuturesConvertQuote, + FuturesConvertQuoteRequest, + FuturesDataPaginatedParams, + FuturesExchangeInfo, + FuturesNewAlgoOrderParams, + FuturesOrderBook, + FuturesPosition, + FuturesPositionTrade, + FuturesPositionV3, + FuturesQueryAlgoOrderParams, + FuturesQueryAlgoOrderResponse, + FuturesQueryAllAlgoOrdersParams, + FuturesQueryOpenAlgoOrdersParams, + FuturesSymbolOrderBookTicker, + FuturesTradeHistoryDownloadId, + FuturesTransactionDownloadLink, + GetForceOrdersParams, + GetFuturesOrderModifyHistoryParams, + GetIncomeHistoryParams, + GetPositionMarginChangeHistoryParams, + HistoricOpenInterest, + IncomeHistory, + IndexPriceConstituents, + IndexPriceKlinesParams, + InsuranceFundBalance, + MarkPrice, + ModeChangeResult, + ModifyFuturesOrderParams, + ModifyFuturesOrderResult, + ModifyOrderParams, + MultiAssetModeResponse, + MultiAssetsMode, + NewFuturesOrderParams, + NewOrderError, + NewOrderResult, + OpenInterest, + OrderResult, + PortfolioMarginProAccountInfo, + PositionModeParams, + PositionModeResponse, + QuarterlyContractSettlementPrice, + RawFuturesTrade, + RebateDataOverview, + RpiOrderBook, + SetCancelTimeoutResult, + SetIsolatedMarginParams, + SetIsolatedMarginResult, + SetLeverageParams, + SetLeverageResult, + SetMarginTypeParams, + SymbolAdlRisk, + SymbolConfig, + SymbolKlinePaginatedParams, + SymbolLeverageBracketsResult, + TradingSchedule, + UserCommissionRate, + UserForceOrder, +} from './types/futures'; import { - BooleanString, - KlineInterval, + BasicSymbolPaginatedParams, + BasicSymbolParam, + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + GenericCodeMsgError, + GetAllOrdersParams, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, + NewOCOParams, numberInString, - OrderResponseType, - OrderSide, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; + OrderBookParams, + OrderIdProperty, + RecentTradesParams, + SymbolFromPaginatedRequestFromId, + SymbolPrice, +} from './types/shared'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, +} from './util/requestUtils'; +⋮---- +export class USDMClient extends BaseRestClient +⋮---- +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) +⋮---- +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise +⋮---- +/** + * + * MARKET DATA endpoints - Rest API + * + **/ +⋮---- +testConnectivity(): Promise +⋮---- +getExchangeInfo(): Promise +⋮---- +getOrderBook(params: OrderBookParams): Promise +⋮---- +getRpiOrderBook(params: { + symbol: string; + limit?: number; +}): Promise +⋮---- +getRecentTrades(params: RecentTradesParams): Promise +⋮---- +getHistoricalTrades( + params: HistoricalTradesParams, +): Promise +⋮---- +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise +⋮---- +getKlines(params: KlinesParams): Promise +⋮---- +getContinuousContractKlines( + params: ContinuousContractKlinesParams, +): Promise +⋮---- +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +⋮---- +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +⋮---- +getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise +⋮---- +getMarkPrice(params: +⋮---- +getMarkPrice(): Promise; +⋮---- +getMarkPrice(params?: +⋮---- +getFundingRateHistory( + params?: Partial, +): Promise +⋮---- +getFundingRates(): Promise +⋮---- +get24hrChangeStatistics(params: +⋮---- +get24hrChangeStatistics(): Promise; +⋮---- +get24hrChangeStatistics(params?: { + symbol?: string; +}): Promise +⋮---- +getSymbolPriceTicker(params: +⋮---- +getSymbolPriceTicker(): Promise; +⋮---- +getSymbolPriceTicker(params?: { + symbol?: string; +}): Promise +⋮---- +getSymbolPriceTickerV2(params: +⋮---- +getSymbolPriceTickerV2(): Promise; +⋮---- +getSymbolPriceTickerV2(params?: { + symbol?: string; +}): Promise +⋮---- +getSymbolOrderBookTicker(params: { + symbol: string; + }): Promise; +⋮---- +getSymbolOrderBookTicker(): Promise; +⋮---- +getSymbolOrderBookTicker(params?: { + symbol?: string; +}): Promise +⋮---- +getQuarterlyContractSettlementPrices(params: { + pair: string; +}): Promise +⋮---- +getOpenInterest(params: +⋮---- +getOpenInterestStatistics( + params: FuturesDataPaginatedParams, +): Promise +⋮---- +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams, +): Promise +⋮---- +getTopTradersLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise +⋮---- +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise +⋮---- +getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise +⋮---- +getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +⋮---- +getCompositeSymbolIndex(params?: +⋮---- +getMultiAssetsModeAssetIndex(params?: +⋮---- +/** + * Possibly @deprecated, found only in old docs + **/ +getBasis(params: BasisParams): Promise +⋮---- +getIndexPriceConstituents(params: { + symbol: string; +}): Promise +⋮---- +getInsuranceFundBalance(params?: { + symbol?: string; +}): Promise +⋮---- +getTradingSchedule(): Promise +⋮---- +/** + * + * TRADE endpoints - Rest API + * + **/ +⋮---- +submitNewOrder(params: NewFuturesOrderParams): Promise +⋮---- +/** + * Warning: max 5 orders at a time! This method does not throw, instead it returns + * individual errors in the response array if any orders were rejected. + * + * Note: this method will automatically ensure "price" and "quantity" are sent as a + * string, if present in the request. See #523 & #526 for more details. + */ +submitMultipleOrders( + orders: NewFuturesOrderParams[], +): Promise<(NewOrderResult | NewOrderError)[]> +⋮---- +// Known issue: `quantity` and `price` should be sent as strings, see #523, #526 +⋮---- +/** + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + */ +modifyOrder( + params: ModifyFuturesOrderParams, +): Promise +⋮---- +modifyMultipleOrders(orders: ModifyOrderParams[]): Promise +⋮---- +getOrderModifyHistory( + params: GetFuturesOrderModifyHistoryParams, +): Promise +⋮---- +cancelOrder(params: CancelOrderParams): Promise +⋮---- +cancelMultipleOrders( + params: CancelMultipleOrdersParams, +): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +⋮---- +cancelAllOpenOrders(params: { + symbol: string; +}): Promise +⋮---- +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, +): Promise +⋮---- +getOrder(params: GetOrderParams): Promise +⋮---- +getAllOrders(params: GetAllOrdersParams): Promise +⋮---- +getAllOpenOrders(params?: +⋮---- +getCurrentOpenOrder(params: GetOrderParams): Promise +⋮---- +getForceOrders(params?: GetForceOrdersParams): Promise +⋮---- +getAccountTrades( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, +): Promise +⋮---- +setMarginType(params: SetMarginTypeParams): Promise +⋮---- +setPositionMode(params: PositionModeParams): Promise +⋮---- +setLeverage(params: SetLeverageParams): Promise +⋮---- +setMultiAssetsMode(params: { + multiAssetsMargin: MultiAssetsMode; +}): Promise +⋮---- +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, +): Promise +⋮---- +/** + * @deprecated + * Use getPositionsV3() instead + **/ +getPositions(params?: Partial): Promise +⋮---- +getPositionsV3(params?: +⋮---- +getADLQuantileEstimation(params?: +⋮---- +getSymbolAdlRisk(params: +⋮---- +getSymbolAdlRisk(): Promise; +⋮---- +getSymbolAdlRisk(params?: { + symbol?: string; +}): Promise +⋮---- +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, +): Promise ⋮---- /** - * Simple request params with timestamp (required) & recv window (optional) - */ -export type WSAPIRecvWindowTimestamp = { - recvWindow?: number; - timestamp: number; -}; + * + * ACCOUNT endpoints - Rest API + * + **/ +⋮---- +getBalanceV3(): Promise ⋮---- /** - * - * Authentication request types - * - */ -export interface WSAPISessionLogonRequest { - timestamp: number; -} + * @deprecated + * Use getBalanceV3() instead + **/ +getBalance(): Promise +⋮---- +getAccountInformationV3(): Promise ⋮---- /** - * - * General request types - * - */ -export interface WSAPIExchangeInfoRequest { - symbol?: string; - symbols?: string[]; - permissions?: string[]; - showPermissionSets?: boolean; - symbolStatus?: string; -} + * @deprecated + * Use getAccountInformationV3() instead + **/ +getAccountInformation(): Promise +⋮---- +getAccountCommissionRate(params: { + symbol: string; +}): Promise +⋮---- +getFuturesAccountConfig(): Promise +⋮---- +getFuturesSymbolConfig(params: +⋮---- +getUserForceOrders(): Promise ⋮---- /** - * - * Market data request types - * - */ + * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) + */ +getNotionalAndLeverageBrackets(params?: { + symbol?: string; +}): Promise ⋮---- -export interface WSAPIOrderBookRequest { - symbol: string; - limit?: number; - symbolStatus?: string; -} +getMultiAssetsMode(): Promise ⋮---- -export interface WSAPITradesRecentRequest { - symbol: string; - limit?: number; -} +getCurrentPositionMode(): Promise ⋮---- -export interface WSAPITradesHistoricalRequest { - symbol: string; - fromId?: number; - limit?: number; -} +getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- -export interface WSAPIBlockTradesHistoricalRequest { - symbol: string; - fromId: number; - limit?: number; -} +getApiQuantitativeRulesIndicators(params?: { + symbol?: string; +}): Promise ⋮---- -export interface WSAPITradesAggregateRequest { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +getFuturesTransactionHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise ⋮---- -export interface WSAPIKlinesRequest { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -export interface WSAPIAvgPriceRequest { - symbol: string; -} +getFuturesOrderHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise +⋮---- +getFuturesOrderHistoryDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +getFuturesTradeHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise +⋮---- +getFuturesTradeDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +setBNBBurnEnabled(params: { + feeBurn: 'true' | 'false'; +}): Promise< +⋮---- +getBNBBurnStatus(): Promise< +⋮---- +signTradFiPerpsAgreement(): Promise< +⋮---- +testOrder(params: NewFuturesOrderParams): Promise ⋮---- /** - * Query execution rules (e.g. PRICE_RANGE). Only one of symbol, symbols, or symbolStatus per request. - */ -export interface WSAPIExecutionRulesRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -} + * + * Algo Order Endpoints (Effective 2025-12-02) + * Conditional orders migrate to Algo Service + * + **/ ⋮---- -export interface WSAPIReferencePriceRequest { - symbol: string; -} +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, +): Promise ⋮---- -export interface WSAPIReferencePriceCalculationRequest { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -} +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, +): Promise +⋮---- +cancelAllAlgoOpenOrders(params: { + symbol: string; +}): Promise +⋮---- +getAlgoOrder( + params: FuturesQueryAlgoOrderParams, +): Promise +⋮---- +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, +): Promise +⋮---- +getAllAlgoOrders( + params: FuturesQueryAllAlgoOrdersParams, +): Promise ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITicker24hrRequest { - symbol?: string; - symbols?: string[]; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} + * + * Convert Endpoints + * + **/ +⋮---- +getAllConvertPairs(params?: { + fromAsset?: string; + toAsset?: string; +}): Promise +⋮---- +submitConvertQuoteRequest( + params: FuturesConvertQuoteRequest, +): Promise +⋮---- +acceptConvertQuote(params: +⋮---- +getConvertOrderStatus(params: { + orderId?: string; + quoteId?: string; +}): Promise +⋮---- +/** + * + * Portfolio Margin Pro Endpoints + * + **/ +⋮---- +getPortfolioMarginProAccountInfo(params: { + asset: string; +}): Promise +⋮---- +/** + * + * Broker Futures Endpoints + * Possibly @deprecated, found only in old docs + * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker + * + **/ +⋮---- +/** + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, +): Promise< +⋮---- +/** + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, +): Promise< ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerTradingDayRequest { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, +): Promise ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerRequest { - symbol?: string; - symbols?: string[]; - windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise ⋮---- -windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerPriceRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerBookRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- /** - * - * Account request types - Spot - * - */ + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -export interface WSAPIAllOrdersRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -export interface WSAPIAllOrderListsRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// USD-M Futures ⋮---- -export interface WSAPIMyTradesRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} +getFuturesUserDataListenKey(): Promise< ⋮---- -export interface WSAPIMyPreventedMatchesRequest { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} +keepAliveFuturesUserDataListenKey(): Promise ⋮---- -export interface WSAPIMyAllocationsRequest { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} +closeFuturesUserDataListenKey(): Promise ⋮---- /** - * Trading request types - */ -⋮---- -export interface WSAPINewSpotOrderRequest { - symbol: string; - side: OrderSide; - type: OrderType; - timeInForce?: OrderTimeInForce; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: string; -} -⋮---- -export interface WSAPIOrderTestRequest { - symbol: string; - side: 'BUY' | 'SELL'; - type: string; - timeInForce?: string; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: string; - computeCommissionRates?: boolean; - timestamp: number; - recvWindow?: number; -} + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, +): void + +================ +File: .nvmrc +================ +v24.14.1 + +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts +================ +// or +// import { +// DefaultLogger, +// isWsFormattedFuturesUserDataEvent, +// isWsFormattedSpotUserDataEvent, +// isWsFormattedSpotUserDataExecutionReport, +// isWsFormattedUserDataEvent, +// WebsocketClient, +// WsUserDataEvents, +// } from 'binance'; ⋮---- -export interface WSAPIOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotUserDataEvent, + isWsFormattedSpotUserDataExecutionReport, + isWsFormattedUserDataEvent, + WebsocketClient, + WsConnectionStateEnum, + WsUserDataEvents, +} from '../../../src/index'; ⋮---- -export interface WSAPIOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - recvWindow?: number; - timestamp: number; -} +// Optional, hook and customise logging behavior ⋮---- -export interface WSAPIOrderCancelReplaceRequest { - symbol: string; - cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; - cancelOrderId?: number; - cancelOrigClientOrderId?: string; - cancelNewClientOrderId?: string; - side: 'BUY' | 'SELL'; - type: string; - timeInForce?: string; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; - recvWindow?: number; - timestamp: number; -} +// testnet: true, ⋮---- -export interface WSAPIOrderAmendKeepPriorityRequest { - symbol: string; - orderId?: number | string; - origClientOrderId?: string; - newClientOrderId?: string; - newQty?: string; - recvWindow?: number; - timestamp: number; -} +// wsClient.on('message', (data) => { +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// }); ⋮---- -export interface WSAPIOpenOrdersStatusRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} +function onUserDataEvent(data: WsUserDataEvents) ⋮---- -export interface WSAPIOpenOrdersCancelAllRequest { - symbol: string; - recvWindow?: number; - timestamp: number; -} +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { ⋮---- -/** - * Order list request types - */ -export interface WSAPIOrderListPlaceRequest { - symbol: string; - side: 'BUY' | 'SELL'; - price: numberInString; - quantity: numberInString; - listClientOrderId?: string; - limitClientOrderId?: string; - limitIcebergQty?: numberInString; - limitStrategyId?: number; - limitStrategyType?: number; - stopPrice?: numberInString; - trailingDelta?: number; - stopClientOrderId?: string; - stopLimitPrice?: numberInString; - stopLimitTimeInForce?: string; - stopIcebergQty?: numberInString; - stopStrategyId?: number; - stopStrategyType?: number; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - recvWindow?: number; - timestamp: number; -} +// or use a type guard, if one exists (PRs welcome) ⋮---- -export interface WSAPIOrderListPlaceOCORequest { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: numberInString; - listClientOrderId?: string; - aboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - aboveClientOrderId?: string; - aboveIcebergQty?: numberInString; - abovePrice?: numberInString; - aboveStopPrice?: numberInString; - aboveTrailingDelta?: number; - aboveTimeInForce?: string; - aboveStrategyId?: number; - aboveStrategyType?: number; - belowType: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - belowClientOrderId?: string; - belowIcebergQty?: numberInString; - belowPrice?: numberInString; - belowStopPrice?: numberInString; - belowTrailingDelta?: number; - belowTimeInForce?: string; - belowStrategyId?: number; - belowStrategyType?: number; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - recvWindow?: number; - timestamp: number; -} +// The wsKey can be parsed to determine the type of message (what websocket it came from) +// if (!Array.isArray(data) && data.wsKey.includes('userData')) { +// return onUserDataEvent(data); +// } ⋮---- -export interface WSAPIOrderListPlaceOTORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: numberInString; - pendingStopPrice?: numberInString; - pendingTrailingDelta?: numberInString; - pendingQuantity: numberInString; - pendingIcebergQty?: numberInString; - pendingTimeInForce?: string; - pendingStrategyId?: number; - pendingStrategyType?: number; - recvWindow?: number; - timestamp: number; -} +// or use a type guard if available ⋮---- -export interface WSAPIOrderListPlaceOTOCORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: number | string; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: numberInString; - pendingAboveStopPrice?: numberInString; - pendingAboveTrailingDelta?: numberInString; - pendingAboveIcebergQty?: numberInString; - pendingAboveTimeInForce?: string; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingBelowType: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: numberInString; - pendingBelowStopPrice?: numberInString; - pendingBelowTrailingDelta?: numberInString; - pendingBelowIcebergQty?: numberInString; - pendingBelowTimeInForce?: string; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - recvWindow?: number; - timestamp: number; -} +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -export interface WSAPIOrderListPlaceOPORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: numberInString; - pendingStopPrice?: numberInString; - pendingTrailingDelta?: numberInString; - pendingIcebergQty?: numberInString; - pendingTimeInForce?: string; - pendingStrategyId?: number; - pendingStrategyType?: number; - pendingPegPriceType?: string; - pendingPegOffsetType?: string; - pendingPegOffsetValue?: number; - recvWindow?: number; - timestamp: number; -} +// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: +// - fetch balances +// - fetch positions +// - fetch orders ⋮---- -export interface WSAPIOrderListPlaceOPOCORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingSide: 'BUY' | 'SELL'; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: numberInString; - pendingAboveStopPrice?: numberInString; - pendingAboveTrailingDelta?: numberInString; - pendingAboveIcebergQty?: numberInString; - pendingAboveTimeInForce?: string; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingAbovePegPriceType?: string; - pendingAbovePegOffsetType?: string; - pendingAbovePegOffsetValue?: number; - pendingBelowType?: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: numberInString; - pendingBelowStopPrice?: numberInString; - pendingBelowTrailingDelta?: numberInString; - pendingBelowIcebergQty?: numberInString; - pendingBelowTimeInForce?: string; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - pendingBelowPegPriceType?: string; - pendingBelowPegOffsetType?: string; - pendingBelowPegOffsetValue?: number; - recvWindow?: number; - timestamp: number; -} +/** + * This example demonstrates subscribing to the user data stream via the + * listen key workflow. + * + * Note: the listen key workflow is deprecated for "spot" markets. Use the + * WebSocket API `userDataStream.subscribe` workflow instead (only available + * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + * + * Each method below opens a dedicated WS connection attached to an automatically + * fetched listen key (a session for your user data stream). + * + * Once subscribed, you don't need to do anything else. Listen-key keep-alive, refresh, reconnects, etc are all automatically handled by the SDK. + */ ⋮---- -export interface WSAPIOrderListStatusRequest { - origClientOrderId?: string; - orderListId?: number; - recvWindow?: number; - timestamp: number; -} +/** + * Note: for spot markets, the listen key workflow is deprecated. Use the + * WebSocket API `userDataStream.subscribe` workflow instead (only available + * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + */ +// Deprecated, see above: wsClient.subscribeSpotUserDataStream(); +// Deprecated, see above: wsClient.subscribeSpotUserDataStream('main2'); +// Deprecated, see above: wsClient.subscribeCrossMarginUserDataStream(); +// Deprecated, see above: wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDC'); ⋮---- -export interface WSAPIOrderListCancelRequest { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +/** + * Futures + */ +⋮---- +// Example 5: usdm futures +⋮---- +// Example 6: coinm futures +⋮---- +// Example 7: portfolio margin +⋮---- +// Example 8: portfolio margin pro +⋮---- +// after 15 seconds, kill user data connections one by one (or all at once) +⋮---- +// console.log('killing all connections at once'); +// wsClient.closeAll(); +⋮---- +// or: +⋮---- +// console.log('killing all connections'); +// wsClient.closeAll(); +// Example 5: usdm futures +⋮---- +// Example 6: coinm futures +⋮---- +// // Example 7: portfolio margin +// wsClient.unsubscribePortfolioMarginUserDataStream(); +// // Example 8: portfolio margin pro +// wsClient.unsubscribePortfolioMarginUserDataStream( +// 'portfolioMarginProUserData', +// ); +⋮---- +// after 20 seconds, list the remaining open connections + +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +// or +// import { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } from 'binance'; +// or +// const { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } = require('binance'); +⋮---- +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotBalanceUpdate, + isWsFormattedSpotOutboundAccountPosition, + isWsFormattedSpotUserDataEvent, + isWsFormattedUserDataEvent, + WebsocketAPIClient, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- /** - * SOR request types + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. */ -export interface WSAPISOROrderPlaceRequest { - symbol: string; - side: 'BUY' | 'SELL'; - type: 'LIMIT' | 'MARKET'; - timeInForce?: string; - price?: numberInString; - quantity: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: string; - timestamp: number; - recvWindow?: number; -} ⋮---- -export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { - computeCommissionRates?: boolean; -}; +// returned by binance, generated using the publicKey (above) +// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; +// Your Ed25519 private key is passed as the "secret" +// const secret = privateKey; +⋮---- +function attachEventHandlers( + wsClient: TWSClient, +): void ⋮---- /** - * Futures market data request types - */ + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -export interface WSAPIFuturesOrderBookRequest { - symbol: string; - limit?: number; -} +// Raw events received from binance, as is: ⋮---- -export interface WSAPIFuturesTickerPriceRequest { - symbol?: string; -} +// console.log('raw message received ', JSON.stringify(data)); ⋮---- -export interface WSAPIFuturesTickerBookRequest { - symbol?: string; -} +// Formatted events from the built-in beautifier, with fully readable property names and parsed floats: ⋮---- -/** - * Futures trading request types - */ +// We've included type guards for many events, especially on the user data stream, to help easily +// identify events using simple `if` checks. +// +// Use `if` checks to narrow down specific events from the user data stream ⋮---- -export interface WSAPINewFuturesOrderRequest { - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesOrderType; - timeInForce?: OrderTimeInForce; - quantity?: numberType; - reduceOnly?: BooleanString; - price?: numberType; - newClientOrderId?: string; - stopPrice?: numberType; - closePosition?: BooleanString; - activationPrice?: numberType; - callbackRate?: numberType; - workingType?: WorkingType; - priceProtect?: BooleanString; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: SelfTradePreventionMode; - priceMatch?: PriceMatchMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD - recvWindow?: number; - timestamp: number; -} +//// More general handlers, if you prefer: ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +// Any user data event in spot: ⋮---- -export interface WSAPIFuturesOrderModifyRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - side: 'BUY' | 'SELL'; - quantity: numberInString; - price: numberInString; - priceMatch?: - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; - origType?: string; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - recvWindow?: number; - timestamp: number; -} +// Any user data event in futures: ⋮---- -export interface WSAPIFuturesOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +// Any user data event on any market (spot + futures) ⋮---- -export interface WSAPIFuturesOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +// Formatted user data events also have a dedicated event handler, but that's optional and no different to the above +// wsClient.on('formattedUserDataMessage', (data) => { +// if (isWsFormattedSpotOutboundAccountPosition(data)) { +// return; +// // console.log( +// // 'formattedUserDataMessage->isWsFormattedSpotOutboundAccountPosition: ', +// // data, +// // ); +// } +// if (isWsFormattedSpotBalanceUpdate(data)) { +// return console.log( +// 'formattedUserDataMessage->isWsFormattedSpotBalanceUpdate: ', +// data, +// ); +// } +// console.log('formattedUserDataMessage: ', data); +// }); ⋮---- -export interface WSAPIFuturesPositionRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} +// console.log('ws response: ', JSON.stringify(data)); ⋮---- -export interface WSAPIFuturesPositionV2Request { - symbol?: string; - recvWindow?: number; - timestamp: number; -} +async function main() ⋮---- -export interface WSAPIAccountInformationRequest { - omitZeroBalances?: boolean; - recvWindow?: number; - timestamp: number; -} +// Optional, hook and customise logging behavior +⋮---- +// Enforce testnet ws connections, regardless of supplied wsKey: +// testnet: true, +⋮---- +// Note: unless you set this to false, the SDK will automatically call +// the `subscribeUserDataStream()` method again if reconnected (if you called it before): +// resubscribeUserDataStreamAfterReconnect: true, +⋮---- +keepMarginListenTokenRefreshed: false, // Optional, if you don't want the SDK to automatically refresh your margin listen token (if you use it for subscribing to margin user data stream) +⋮---- +// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: +⋮---- +logger, // Optional: inject a custom logger, especially to see trace events +⋮---- +// Attach your own event handlers to process incoming events +// You may want to disable the default ones to avoid unnecessary logs (via attachEventListeners:false, above) ⋮---- -export interface WSAPIAccountCommissionWSAPIRequest { - symbol: string; -} +// 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); ⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api - */ -export interface WSAPINewFuturesAlgoOrderRequest { - algoType: FuturesAlgoOrderType; - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesAlgoConditionalOrderTypes; - timeInForce?: OrderTimeInForce; - quantity?: numberType; - reduceOnly?: BooleanString; - price?: numberInString; - clientAlgoId?: string; - triggerPrice?: numberInString; - closePosition?: BooleanString; - activatePrice?: numberInString; - callbackRate?: numberInString; - workingType?: WorkingType; - priceProtect?: BooleanString; - newOrderRespType?: OrderResponseType; - priceMatch?: PriceMatchMode; - selfTradePreventionMode?: SelfTradePreventionMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD - recvWindow?: number; - timestamp: number; -} +// Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will +// automatically call this method again if reconnected, ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +WS_KEY_MAP.mainWSAPI, // The `mainWSAPI` wsKey will connect to the "spot" Websocket API on Binance. ⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order - */ -export interface WSAPIFuturesAlgoOrderCancelRequest { - algoid?: number; - clientalgoid?: string; - recvWindow?: number; - timestamp: number; -} +// Start executing the example workflow ================ File: src/types/websockets/ws-general.ts @@ -13118,3361 +11126,3463 @@ public subscribeIndexKlines( */ public subscribeMarkPriceKlines( symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to rolling window ticker statistics for all market symbols, - * computed over multiple windows. Note that only tickers that have - * changed will be present in the array. - * - * Notes: - * - Supported window sizes: 1h,4h,1d. - * - Supported markets: spot - */ -public subscribeAllRollingWindowTickers( - market: 'spot', - windowSize: '1h' | '4h' | '1d', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to partial book depths (snapshots). - * - * Note: - * - spot only supports 1000ms or 100ms for updateMs - * - futures only support 100, 250 or 500ms for updateMs - * - * Use getContextFromWsKey(data.wsKey) to extract symbol from events - */ -public subscribePartialBookDepths( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 100 | 250 | 500 | 1000, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to orderbook depth updates to locally manage an order book. - * - * Note that the updatems parameter depends on which market you're trading - * - * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream - * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams - * - * Use getContextFromWsKey(data.wsKey) to extract symbol from events - */ -public subscribeDiffBookDepth( - symbol: string, - updateMs: 100 | 250 | 500 | 1000 = 100, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ -⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket -⋮---- -/** - * Subscribe to top bid/ask levels for symbol in spot markets. - */ -public subscribeSpotPartialBookDepth( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 1000 | 100 = 1000, + interval: KlineInterval, forceNewConnection?: boolean, ): WebSocket ⋮---- /** - * Subscribe to spot orderbook depth updates to locally manage an order book. + * Subscribe to mini 24hr ticker for a symbol in market category. */ -public subscribeSpotDiffBookDepth( +public subscribeSymbolMini24hrTicker( symbol: string, - updateMs: 1000 | 100 = 1000, + market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** - * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. - * Supports spot, margin & isolated margin listen keys. + * Subscribe to mini 24hr mini ticker in market category. */ -public subscribeSpotUserDataStreamWithListenKey( - listenKey: string, +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, - isReconnecting?: boolean, -): WebSocket | undefined -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +): WebSocket ⋮---- /** - * Subscribe to spot user data stream - listen key is automaticallyr generated. Calling multiple times only opens one connection. + * Subscribe to 24hr ticker for a symbol in any market. */ -public async subscribeSpotUserDataStream( +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise +): WebSocket ⋮---- /** - * Subscribe to margin user data stream - listen key is automatically generated. + * Subscribe to 24hr ticker in any market. */ -public async subscribeMarginUserDataStream( +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +): WebSocket ⋮---- /** - * Subscribe to isolated margin user data stream - listen key is automatically generated. + * Subscribe to rolling window ticker statistics for all market symbols, + * computed over multiple windows. Note that only tickers that have + * changed will be present in the array. + * + * Notes: + * - Supported window sizes: 1h,4h,1d. + * - Supported markets: spot */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, +public subscribeAllRollingWindowTickers( + market: 'spot', + windowSize: '1h' | '4h' | '1d', forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) -⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ +): WebSocket ⋮---- /** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + * Subscribe to best bid/ask for symbol in spot markets. */ -public async subscribeUsdFuturesUserDataStream( - isTestnet?: boolean, +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Necessary so client knows this is a reconnect -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +): WebSocket ⋮---- /** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. + * Subscribe to best bid/ask for all symbols in spot markets. */ -public async subscribeCoinFuturesUserDataStream( - isTestnet?: boolean, +public subscribeAllBookTickers( + market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Necessary so client knows this is a reconnect -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) - -================ -File: examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts -================ -// or -// import { -// DefaultLogger, -// isWsFormattedFuturesUserDataEvent, -// isWsFormattedSpotUserDataEvent, -// isWsFormattedSpotUserDataExecutionReport, -// isWsFormattedUserDataEvent, -// WebsocketClient, -// WsUserDataEvents, -// } from 'binance'; -⋮---- -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotUserDataEvent, - isWsFormattedSpotUserDataExecutionReport, - isWsFormattedUserDataEvent, - WebsocketClient, - WsConnectionStateEnum, - WsUserDataEvents, -} from '../../../src/index'; -⋮---- -// Optional, hook and customise logging behavior -⋮---- -// testnet: true, -⋮---- -// wsClient.on('message', (data) => { -// console.log('raw message received ', JSON.stringify(data, null, 2)); -// }); -⋮---- -function onUserDataEvent(data: WsUserDataEvents) -⋮---- -// the market denotes which API category it came from -// if (data.wsMarket.includes('spot')) { -⋮---- -// or use a type guard, if one exists (PRs welcome) -⋮---- -// The wsKey can be parsed to determine the type of message (what websocket it came from) -// if (!Array.isArray(data) && data.wsKey.includes('userData')) { -// return onUserDataEvent(data); -// } -⋮---- -// or use a type guard if available -⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -⋮---- -// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: -// - fetch balances -// - fetch positions -// - fetch orders +): WebSocket ⋮---- /** - * This example demonstrates subscribing to the user data stream via the - * listen key workflow. - * - * Note: the listen key workflow is deprecated for "spot" markets. Use the - * WebSocket API `userDataStream.subscribe` workflow instead (only available - * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. - * - * Each method below opens a dedicated WS connection attached to an automatically - * fetched listen key (a session for your user data stream). - * - * Once subscribed, you don't need to do anything else. Listen-key keep-alive, refresh, reconnects, etc are all automatically handled by the SDK. + * Subscribe to best bid/ask for symbol in spot markets. */ +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Note: for spot markets, the listen key workflow is deprecated. Use the - * WebSocket API `userDataStream.subscribe` workflow instead (only available - * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + * Subscribe to best bid/ask for all symbols in spot markets. */ -// Deprecated, see above: wsClient.subscribeSpotUserDataStream(); -// Deprecated, see above: wsClient.subscribeSpotUserDataStream('main2'); -// Deprecated, see above: wsClient.subscribeCrossMarginUserDataStream(); -// Deprecated, see above: wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDC'); +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Futures + * Subscribe to partial book depths (snapshots). + * + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs + * + * Use getContextFromWsKey(data.wsKey) to extract symbol from events */ -⋮---- -// Example 5: usdm futures -⋮---- -// Example 6: coinm futures -⋮---- -// Example 7: portfolio margin -⋮---- -// Example 8: portfolio margin pro -⋮---- -// after 15 seconds, kill user data connections one by one (or all at once) -⋮---- -// console.log('killing all connections at once'); -// wsClient.closeAll(); -⋮---- -// or: -⋮---- -// console.log('killing all connections'); -// wsClient.closeAll(); -// Example 5: usdm futures -⋮---- -// Example 6: coinm futures -⋮---- -// // Example 7: portfolio margin -// wsClient.unsubscribePortfolioMarginUserDataStream(); -// // Example 8: portfolio margin pro -// wsClient.unsubscribePortfolioMarginUserDataStream( -// 'portfolioMarginProUserData', -// ); -⋮---- -// after 20 seconds, list the remaining open connections - -================ -File: examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -// or -// import { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } from 'binance'; -// or -// const { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } = require('binance'); -⋮---- -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotBalanceUpdate, - isWsFormattedSpotOutboundAccountPosition, - isWsFormattedSpotUserDataEvent, - isWsFormattedUserDataEvent, - WebsocketAPIClient, - WebsocketClient, - WS_KEY_MAP, -} from '../../../src'; +public subscribePartialBookDepths( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 100 | 250 | 500 | 1000, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. - */ -⋮---- -// returned by binance, generated using the publicKey (above) -// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; -// Your Ed25519 private key is passed as the "secret" -// const secret = privateKey; -⋮---- -function attachEventHandlers( - wsClient: TWSClient, -): void + * Subscribe to orderbook depth updates to locally manage an order book. + * + * Note that the updatems parameter depends on which market you're trading + * + * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream + * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams + * + * Use getContextFromWsKey(data.wsKey) to extract symbol from events + */ +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * General event handlers for monitoring the WebsocketClient + * Subscribe to best bid/ask for all symbols in spot markets. */ +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- -// Raw events received from binance, as is: -⋮---- -// console.log('raw message received ', JSON.stringify(data)); -⋮---- -// Formatted events from the built-in beautifier, with fully readable property names and parsed floats: -⋮---- -// We've included type guards for many events, especially on the user data stream, to help easily -// identify events using simple `if` checks. -// -// Use `if` checks to narrow down specific events from the user data stream -⋮---- -//// More general handlers, if you prefer: -⋮---- -// Any user data event in spot: -⋮---- -// Any user data event in futures: -⋮---- -// Any user data event on any market (spot + futures) -⋮---- -// Formatted user data events also have a dedicated event handler, but that's optional and no different to the above -// wsClient.on('formattedUserDataMessage', (data) => { -// if (isWsFormattedSpotOutboundAccountPosition(data)) { -// return; -// // console.log( -// // 'formattedUserDataMessage->isWsFormattedSpotOutboundAccountPosition: ', -// // data, -// // ); -// } -// if (isWsFormattedSpotBalanceUpdate(data)) { -// return console.log( -// 'formattedUserDataMessage->isWsFormattedSpotBalanceUpdate: ', -// data, -// ); -// } -// console.log('formattedUserDataMessage: ', data); -// }); -⋮---- -// console.log('ws response: ', JSON.stringify(data)); -⋮---- -async function main() +/** + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- -// Optional, hook and customise logging behavior +/** + * Subscribe to aggregate trades for a symbol in spot markets. + */ +public subscribeSpotAggregateTrades( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- -// Enforce testnet ws connections, regardless of supplied wsKey: -// testnet: true, +/** + * Subscribe to trades for a symbol in spot markets. + */ +public subscribeSpotTrades( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- -// Note: unless you set this to false, the SDK will automatically call -// the `subscribeUserDataStream()` method again if reconnected (if you called it before): -// resubscribeUserDataStreamAfterReconnect: true, +/** + * Subscribe to candles for a symbol in spot markets. + */ +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, +): WebSocket ⋮---- -keepMarginListenTokenRefreshed: false, // Optional, if you don't want the SDK to automatically refresh your margin listen token (if you use it for subscribing to margin user data stream) +/** + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- -// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: +/** + * Subscribe to mini 24hr mini ticker in spot markets. + */ +public subscribeSpotAllMini24hrTickers( + forceNewConnection?: boolean, +): WebSocket ⋮---- -logger, // Optional: inject a custom logger, especially to see trace events +/** + * Subscribe to 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbol24hrTicker( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- -// Attach your own event handlers to process incoming events -// You may want to disable the default ones to avoid unnecessary logs (via attachEventListeners:false, above) +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket ⋮---- -// 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); +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- -// Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will -// automatically call this method again if reconnected, +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket ⋮---- -WS_KEY_MAP.mainWSAPI, // The `mainWSAPI` wsKey will connect to the "spot" Websocket API on Binance. +/** + * Subscribe to top bid/ask levels for symbol in spot markets. + */ +public subscribeSpotPartialBookDepth( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, +): WebSocket ⋮---- -// Start executing the example workflow - -================ -File: src/types/websockets/ws-api.ts -================ -import { WS_KEY_MAP, WsKey } from '../../util/websockets/websocket-util'; -import { FuturesExchangeInfo } from '../futures'; -import { - ExchangeInfo, - SpotExecutionRulesResponse, - SpotReferencePriceCalculationResponse, - SpotReferencePriceResult, -} from '../spot'; -import { - WSAPIAccountCommissionWSAPIRequest, - WSAPIAccountInformationRequest, - WSAPIAllOrderListsRequest, - WSAPIAllOrdersRequest, - WSAPIAvgPriceRequest, - WSAPIBlockTradesHistoricalRequest, - WSAPIExchangeInfoRequest, - WSAPIExecutionRulesRequest, - WSAPIFuturesAlgoOrderCancelRequest, - WSAPIFuturesOrderBookRequest, - WSAPIFuturesOrderCancelRequest, - WSAPIFuturesOrderModifyRequest, - WSAPIFuturesOrderStatusRequest, - WSAPIFuturesTickerBookRequest, - WSAPIFuturesTickerPriceRequest, - WSAPIKlinesRequest, - WSAPIMyAllocationsRequest, - WSAPIMyPreventedMatchesRequest, - WSAPIMyTradesRequest, - WSAPINewFuturesAlgoOrderRequest, - WSAPINewFuturesOrderRequest, - WSAPINewSpotOrderRequest, - WSAPIOpenOrdersCancelAllRequest, - WSAPIOpenOrdersStatusRequest, - WSAPIOrderAmendKeepPriorityRequest, - WSAPIOrderBookRequest, - WSAPIOrderCancelReplaceRequest, - WSAPIOrderCancelRequest, - WSAPIOrderListCancelRequest, - WSAPIOrderListPlaceOCORequest, - WSAPIOrderListPlaceOPOCORequest, - WSAPIOrderListPlaceOPORequest, - WSAPIOrderListPlaceOTOCORequest, - WSAPIOrderListPlaceOTORequest, - WSAPIOrderListPlaceRequest, - WSAPIOrderListStatusRequest, - WSAPIOrderStatusRequest, - WSAPIOrderTestRequest, - WSAPIRecvWindowTimestamp, - WSAPIReferencePriceCalculationRequest, - WSAPIReferencePriceRequest, - WSAPISessionLogonRequest, - WSAPISOROrderPlaceRequest, - WSAPISOROrderTestRequest, - WSAPITicker24hrRequest, - WSAPITickerBookRequest, - WSAPITickerPriceRequest, - WSAPITickerRequest, - WSAPITickerTradingDayRequest, - WSAPITradesAggregateRequest, - WSAPITradesHistoricalRequest, - WSAPITradesRecentRequest, -} from './ws-api-requests'; -import { - WSAPIAccountCommission, - WSAPIAccountInformation, - WSAPIAggregateTrade, - WSAPIAllocation, - WSAPIAvgPrice, - WSAPIBlockTrade, - WSAPIBookTicker, - WSAPIFullTicker, - WSAPIFuturesAccountBalanceItem, - WSAPIFuturesAccountStatus, - WSAPIFuturesAlgoOrder, - WSAPIFuturesAlgoOrderCancelResponse, - WSAPIFuturesBookTicker, - WSAPIFuturesOrder, - WSAPIFuturesOrderBook, - WSAPIFuturesPosition, - WSAPIFuturesPositionV2, - WSAPIFuturesPriceTicker, - WSAPIKline, - WSAPIMiniTicker, - WSAPIOrder, - WSAPIOrderBook, - WSAPIOrderCancel, - WSAPIOrderCancelReplaceResponse, - WSAPIOrderListCancelResponse, - WSAPIOrderListPlaceResponse, - WSAPIOrderListStatusResponse, - WSAPIOrderTestResponse, - WSAPIOrderTestWithCommission, - WSAPIPreventedMatch, - WSAPIPriceTicker, - WSAPIRateLimit, - WSAPIServerTime, - WSAPISessionStatus, - WSAPISOROrderPlaceResponse, - WSAPISOROrderTestResponse, - WSAPISOROrderTestResponseWithCommission, - WSAPISpotOrderResponse, - WSAPITrade, -} from './ws-api-responses'; +/** + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Standard WS commands (for consumers) - */ -export type WsOperation = - | 'SUBSCRIBE' - | 'UNSUBSCRIBE' - | 'LIST_SUBSCRIPTIONS' - | 'SET_PROPERTY' - | 'GET_PROPERTY'; + * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. + * Supports spot, margin & isolated margin listen keys. + */ +public subscribeSpotUserDataStreamWithListenKey( + listenKey: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): WebSocket | undefined +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * WS API commands (for sending requests via WS) - */ + * Subscribe to spot user data stream - listen key is automaticallyr generated. Calling multiple times only opens one connection. + */ +public async subscribeSpotUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -//// General commands +/** + * Subscribe to margin user data stream - listen key is automatically generated. + */ +public async subscribeMarginUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -//// Market data commands +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -//// Account commands -// Spot +/** + * Subscribe to isolated margin user data stream - listen key is automatically generated. + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -// Futures +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -//// Trading commands +/** + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- -// Order list commands +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeUsdFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -// SOR commands +// Necessary so client knows this is a reconnect ⋮---- -// user data stream +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -export interface WSAPIUserDataListenKeyRequest { - apiKey: string; - listenKey: string; +/** + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeCoinFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise +⋮---- +// Necessary so client knows this is a reconnect +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) + +================ +File: docs/BINANCE_SDK_QUICKSTART_GUIDE.md +================ +# Binance SDK Quickstart Guide + +> [!TIP] +> This guide can be read in tutorial format on the Siebly Website: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) + +This guide walks through key pieces of a Binance REST API, WebSocket & WebSocket API integration using [`binance`](https://www.npmjs.com/package/binance), the Binance JavaScript and TypeScript SDK by Siebly.io. + +The SDK handles request building and connectivity for you, including request signing, WebSocket management, healthchecks, heartbeats, listen-key refreshes, resubscribe behavior, and WebSocket API response mapping so your code can stay focused on the workflow you are automating. This guide will walk you through installation and client selection, then moves through public calls, private auth, REST API calls, streams, user data, and the WebSocket API. + +**Key links** + +- Binance JavaScript SDK by Siebly: [`binance`](https://www.npmjs.com/package/binance) +- GitHub Repository: [`tiagosiebler/binance`](https://github.com/tiagosiebler/binance) +- SDK function-endpoint map: [Binance JavaScript Endpoint Reference](./endpointFunctionList.md) +- REST API examples: [Binance SDK REST API examples](../examples/Rest) +- WebSocket examples: [Binance SDK WebSocket examples](../examples/WebSockets) +- More SDKs: [Siebly.io](https://siebly.io) + +--- + +## Why use the SDK + +A stable Binance integration is more than a handful of HTTP requests. Binance splits behavior across product groups, transports, key types, and environments: + +- Spot, Margin, Wallet, Convert, Earn, and Sub-Account APIs live behind the main REST API client, but not all of them share the same endpoint prefix or permission model. +- Some of these product groups expect API calls to reach different subdomains. +- USD-M Futures and COIN-M Futures have separate REST API clients, symbols, endpoint prefixes, and WebSocket endpoints. +- Both have their own subdomains as well. +- Portfolio Margin uses a dedicated REST API client and its own account model. +- Public streams, private user data streams, and WebSocket API commands are different flows. +- Private REST API and WebSocket API requests must be signed. +- User data streams can involve listen keys, WebSocket API subscriptions, token refreshes, and reconnect handling. + +Most of that work is handled for you, while the grouping & naming stays close to Binance's API naming. The SDK gives you dedicated REST API clients for the major product groups, `WebsocketClient` for streaming, `WebsocketAPIClient` for awaitable WebSocket API requests. It also includes TypeScript definitions, ESM/CJS support, proxy support, and optional response beautification. + +--- + +## 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/binance) and [npm](https://www.npmjs.com/package/binance), and can therefore be installed with your favourite Node.js compatible package manager. + +Install the SDK with npm: + +```bash +npm install binance +``` + +Or use another npm-compatible package manager: + +```bash +pnpm install binance +yarn add binance +``` + +Create API keys from the relevant Binance page: + +- Binance live API keys: [Binance API Management](https://www.binance.com/en/my/settings/api-management) +- Binance Spot testnet: [Spot Test Network](https://testnet.binance.vision/) +- Binance Futures testnet: [Futures Testnet](https://testnet.binancefuture.com/) +- Binance demo trading: [Binance Demo Trading](https://demo.binance.com/) + +> Always use the minimum permissions needed for your scenario. Trading does not require withdrawal permissions. Analytics does not require trading permissions. +> Always require strict IP whitelisting for any API keys that you create. + +The main auth and environment rules are: + +- Public market data does not require API keys. +- Private REST APIs require `api_key` and `api_secret`. +- Live, testnet, and demo trading credentials are separate, as they are separate environments. +- API permissions must match the product and action your code is using. +- HMAC keys are the common API key + secret flow. These are the "system generated" API keys, selected by default when creating new API keys for Binance. +- RSA and Ed25519 keys use self-generated private keys. +- Ed25519 is recommended for latency-sensitive integrations with the WebSocket API, as this enables session-based WebSocket API authentication, instead of having to authenticate every request. + +All supported key types use the same SDK constructor shape. The SDK will automatically detect your key type and adjust request building and signing automatically: + +```typescript +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); +``` + +For HMAC, `api_secret` is your Binance API secret. For RSA or Ed25519, `api_secret` is your PEM private key. + +Typical environment variables: + +```bash +export BINANCE_API_KEY='your-api-key' +export BINANCE_API_SECRET='your-api-secret-or-private-key' +``` + +If you are only testing public endpoints, you do not need any keys at all. + +--- + +## Products and clients + +Binance is not one single API. The SDK splits API clients around Binance's product groups: + +| Product group | API client | Common usage | +| -------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------- | +| REST API: Spot, Margin, Wallet, Convert, Earn, Sub-accounts, Broker, Alpha | `MainClient` | Spot trading, account data, wallet flows, margin trading, transfers, savings/earn, sub-account management | +| REST API: USD-M Futures | `USDMClient` | USDT/USDC margined futures market data, account data, positions, orders | +| REST API: COIN-M Futures | `CoinMClient` | Coin-margined futures market data, account data, positions, orders | +| REST API: Portfolio Margin | `PortfolioClient` | Portfolio Margin account, UM/CM/margin orders, balances, positions | +| WebSocket streams | `WebsocketClient` | Public market data streams and private user data streams | +| WebSocket API | `WebsocketAPIClient` | REST API-like Spot and Futures commands over persistent WebSocket API connections | + +As a rule of thumb: + +- Use `MainClient` when the Binance docs path starts with `api/` or `sapi/`, including Spot and many account/wallet APIs. +- Use `USDMClient` when the Binance docs path starts with `fapi/`. +- Use `CoinMClient` when the Binance docs path starts with `dapi/`. +- Use `PortfolioClient` when the Binance docs path starts with `papi/`. +- Use `WebsocketClient` when you want to subscribe to streams and receive events. +- Use `WebsocketAPIClient` when you want to send commands over WebSocket and await responses like REST API calls. + +For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). If any endpoints or properties seem to be missing, please open an issue on GitHub and we'll look into it. Targeted PRs are also welcome. + +### REST API, streams, listen keys, and WebSocket API + +Binance uses several related but different integration patterns. It helps to keep them separate: + +| Flow | SDK surface | Best for | What the SDK handles | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| REST API | `MainClient`, `USDMClient`, `CoinMClient`, `PortfolioClient` | Request/response calls, broad API coverage, occasional reads/writes, fallback reconciliation | Base URLs, request signing, timestamps, response parsing, errors | +| Public WebSocket streams | `WebsocketClient.subscribe(...)` | Live market data such as trades, klines, tickers, order book updates | Connection routing, subscribe requests, heartbeats, reconnects, resubscribe | +| Listen-key user data streams | `WebsocketClient.subscribeUsdFuturesUserDataStream()`, `subscribeCoinFuturesUserDataStream()`, portfolio helpers | Private account events where Binance still uses listen keys, especially Futures and Portfolio Margin streams | Listen-key creation, keepalive, refresh, reconnect, stream teardown | +| WebSocket API user data | `WebsocketAPIClient.subscribeUserDataStream(...)` | Spot user data and some newer private stream flows without the old Spot listen-key workflow | WebSocket API auth, subscription command, reconnect/resubscribe behavior | +| WebSocket API commands | `WebsocketAPIClient` methods or `WebsocketClient.sendWSAPIRequest(...)` | Lower-latency request/response commands over an already-open WebSocket, such as order tests, order placement, cancellation, status, account reads | WebSocket connection persistence, auth, request IDs, promise resolution, response/error correlation | + +The WebSocket API is not just another stream. It is a request/response API over WebSocket. Since much of the functionality is a better alternative to the REST API, we've introduced the promise-driven `WebsocketAPIClient`. It lets you write code that feels like working with a REST API. Call a function to send a command over WS and await the response, without any of the complexity of managing asynchronous messaging over WebSockets (as well as the life-cycle complexities that come with keeping WebSockets healthy). + +```typescript +const result = await wsApi.testSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', + timestamp: Date.now(), +}); +``` + +Use the REST API when you want maximum endpoint coverage, simple one-off calls, or reconciliation after reconnects. Use the WebSocket API when you want persistent connectivity, lower request overhead, WebSocket API-only features, or a promise-driven command path that can share the same event-driven architecture as your streams. With Ed25519 keys, authentication can happen once per WebSocket API connection, which can improve latency in mid-to-high frequency systems. Removing repeated authentication work from every request can save time cumulatively. + +--- + +## Start building: first calls + +If you only want the fastest path to a working integration, start here. + +### 1. First Spot REST API request + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient(); + +async function main() { + const serverTime = await client.getServerTime(); + const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); + const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); + const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); + const candles = await client.getKlines({ + symbol: 'BTCUSDT', + interval: '1m', + limit: 5, + }); + + console.log({ + serverTime, + symbol: exchangeInfo.symbols?.[0]?.symbol, + ticker, + orderBook, + candles, + }); } -⋮---- -export type WsAPIOperation = (typeof WS_API_Operations)[number]; -⋮---- -export interface WsRequestOperationBinance< - TWSTopic extends string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - TWSParams extends object = any, -> { - method: WsOperation | WsAPIOperation; - params?: (TWSTopic | string | number)[] | TWSParams; - id: number; + +main().catch(console.error); +``` + +That confirms public Spot REST API access is wired correctly. + +See also: [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) + +### 2. First public Spot WebSocket stream + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ + beautify: true, +}); + +ws.on('open', (data) => console.log('connected', data.wsKey, data.wsUrl)); +ws.on('message', (data) => console.log('raw message', JSON.stringify(data))); +ws.on('formattedMessage', (data) => console.log('formatted', data)); +ws.on('response', (data) => console.log('response', JSON.stringify(data))); +ws.on('reconnecting', (data) => console.log('reconnecting', data?.wsKey)); +ws.on('reconnected', (data) => console.log('reconnected', data?.wsKey)); +ws.on('exception', console.error); + +ws.subscribe(['btcusdt@trade', 'btcusdt@bookTicker'], WS_KEY_MAP.main); +``` + +That gives you a live public Spot stream without any API keys. + +See also: [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) + +### 3. First private Spot user data stream + +For Spot user data streams, prefer the WebSocket API user data flow. It avoids the older Spot listen-key flow and keeps the stream on a managed WebSocket API connection. + +```typescript +import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); + +wsApi.getWSClient().on('open', (data) => { + console.log('ws api open', data.wsKey); +}); + +wsApi.getWSClient().on('formattedUserDataMessage', (data) => { + console.log('account event', data); +}); + +wsApi.getWSClient().on('exception', console.error); + +async function main() { + await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); } -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface WSAPIResponse { - /** Auto-generated */ - id: string; - status: number; - result: TResponseData; - rateLimits: { - rateLimitType: 'REQUEST_WEIGHT'; - interval: 'MINUTE'; - intervalNum: number; - limit: number; - count: number; - }[]; +main().catch(console.error); +``` + +The SDK handles authentication and resubscribe behavior for the WebSocket API connection. With Ed25519 keys it can authenticate the WebSocket API session once. With HMAC or RSA keys it signs private WebSocket API commands individually, although that primarily matters in the context of sending regular commands (such as order submissions) via WebSocket API. + +See also: [Spot user data stream over WebSocket API](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) + +### 4. First Spot order over REST API + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +async function placeOrder() { + const orderRequest = { + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + newOrderRespType: 'FULL', + } as const; + + // Validate the request without sending it to the matching engine. + await client.testNewOrder(orderRequest); + + // Remove this comment when you are ready to place a real order. + // const result = await client.submitNewOrder(orderRequest); + // console.log(result); +} + +placeOrder().catch(console.error); +``` + +Use `testNewOrder()` when you want to validate the request shape and signature without placing a live Spot order. Use `submitNewOrder()` only when you are ready to send the order. + +See also: [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) + +### 5. First USD-M Futures order + +For strategy testing, `demoTrading: true` is usually more realistic than testnet because demo trading uses live market data with simulated trading. + +```typescript +import { USDMClient } from 'binance'; + +const client = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + demoTrading: true, +}); + +async function placeFuturesOrder() { + const account = await client.getAccountInformation(); + console.log('demo futures account can trade:', account.canTrade); + + const result = await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'MARKET', + quantity: 0.001, + }); + + console.log(result); +} + +placeFuturesOrder().catch(console.error); +``` + +See also: [USD-M Futures demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) + +### 6. First WebSocket API request + +The WebSocket API lets you send requests over a persistent WebSocket connection and await responses, similar to REST API calls. This is useful for lower-latency workflows and for WebSocket API-only features. + +```typescript +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +async function main() { + const time = await wsApi.getSpotServerTime(); + + const orderTest = await wsApi.testSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', + timestamp: Date.now(), + }); + + console.log({ time, orderTest }); +} + +main() + .catch(console.error) + .finally(() => wsApi.disconnectAll()); +``` + +See also: [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) + +--- + +## Spot, Margin, and Wallet REST API + +Most Binance integrations start with `MainClient`. It covers Spot trading and many account APIs under Binance's main REST API families. + +### Create a public `MainClient` + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient(); +``` + +Public calls do not require keys. + +### Create a private `MainClient` + +If you plan on making private API calls, include API keys when creating the client: + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautifyResponses: true, +}); +``` + +Private REST API methods are signed automatically. You do not need to manually add timestamps, signatures, or `X-MBX-APIKEY` headers. + +### Common public Spot market data calls + +```typescript +const serverTime = await client.getServerTime(); +const ping = await client.testConnectivity(); +const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); +const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); +const recentTrades = await client.getRecentTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const aggregateTrades = await client.getAggregateTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const candles = await client.getKlines({ + symbol: 'BTCUSDT', + interval: '1m', + limit: 10, +}); +const averagePrice = await client.getAvgPrice({ symbol: 'BTCUSDT' }); +const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); +const bookTicker = await client.getSymbolOrderBookTicker({ + symbol: 'BTCUSDT', +}); +``` + +### Common private Spot account and order calls - wsKey: WsKey; - isWSAPIResponse: boolean; +```typescript +const account = await client.getAccountInformation(); +const balances = await client.getBalances(); +const accountInfo = await client.getAccountInfo(); +const openOrders = await client.getOpenOrders({ symbol: 'BTCUSDT' }); +const allOrders = await client.getAllOrders({ symbol: 'BTCUSDT', limit: 10 }); +const myTrades = await client.getAccountTradeList({ + symbol: 'BTCUSDT', + limit: 10, +}); +const tradeFee = await client.getTradeFee({ symbol: 'BTCUSDT' }); +const apiPermissions = await client.getApiKeyPermissions(); +``` - // eslint-disable-next-line @typescript-eslint/no-explicit-any - request?: any; -} -⋮---- -/** Auto-generated */ -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export type Exact = { - // This part says: if there's any key that's not in T, it's an error - // This conflicts sometimes for some reason... - // [K: string]: never; -} & { - [K in keyof T]: T[K]; -}; -⋮---- -// This part says: if there's any key that's not in T, it's an error -// This conflicts sometimes for some reason... -// [K: string]: never; -⋮---- -/** - * List of operations supported for this WsKey (connection) - */ -export interface WsAPIWsKeyTopicMap { - [WS_KEY_MAP.main]: WsOperation; - [WS_KEY_MAP.main2]: WsOperation; - [WS_KEY_MAP.main3]: WsOperation; +See also: - [WS_KEY_MAP.mainTestnetPublic]: WsOperation; - [WS_KEY_MAP.mainTestnetUserData]: WsOperation; +- [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) +- [Spot exchange info example](../examples/Rest/Spot/rest-spot-exchange-info.ts) +- [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) +- [Spot private miscellaneous account example](../examples/Rest/Spot/rest-spot-private-misc.ts) - [WS_KEY_MAP.marginRiskUserData]: WsOperation; - [WS_KEY_MAP.marginUserData]: WsAPIOperation; - [WS_KEY_MAP.usdm]: WsOperation; - [WS_KEY_MAP.usdmTestnet]: WsOperation; +### Spot order examples - [WS_KEY_MAP.coinm]: WsOperation; - [WS_KEY_MAP.coinm2]: WsOperation; - [WS_KEY_MAP.coinmTestnet]: WsOperation; - [WS_KEY_MAP.eoptions]: WsOperation; - [WS_KEY_MAP.portfolioMarginUserData]: WsOperation; - [WS_KEY_MAP.portfolioMarginProUserData]: WsOperation; +Market order: - [WS_KEY_MAP.alpha]: WsOperation; +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'MARKET', + quantity: 0.001, + newOrderRespType: 'FULL', +}); +``` - [WS_KEY_MAP.mainWSAPI]: WsAPIOperation; - [WS_KEY_MAP.mainWSAPI2]: WsAPIOperation; - [WS_KEY_MAP.mainWSAPITestnet]: WsAPIOperation; +Limit order: - [WS_KEY_MAP.usdmWSAPI]: WsAPIOperation; - [WS_KEY_MAP.usdmWSAPITestnet]: WsAPIOperation; +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', +}); +``` - [WS_KEY_MAP.coinmWSAPI]: WsAPIOperation; - [WS_KEY_MAP.coinmWSAPITestnet]: WsAPIOperation; +Limit maker order: + +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT_MAKER', + quantity: 0.001, + price: 10000, +}); +``` + +Test an order without sending it: + +```typescript +await client.testNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', +}); +``` + +Cancel an order: + +```typescript +await client.cancelOrder({ + symbol: 'BTCUSDT', + orderId: 123456789, +}); +``` + +**Custom client order IDs** + +You do not always need to set a custom client order ID. Most of the time, the cleanest option is to send the order without `newClientOrderId` or the equivalent custom ID field for that endpoint, and let the SDK handle the request normally: + +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', +}); +``` + +If your system needs to know the client order ID before the order is sent, but the ID does not need to carry any meaning, ask the REST API client to generate one: + +```typescript +const newClientOrderId = client.generateNewOrderId(); + +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', + newClientOrderId, +}); +``` + +`generateNewOrderId()` is available on every REST API client, including `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. The client already knows its product group, so the generated ID uses the right Binance-compatible prefix. + +If you want to include a small piece of your own context in the client order ID, such as a take-profit marker or strategy step, use the product prefix from the client and append your suffix: + +```typescript +const prefix = client.getOrderIdPrefix(); +const suffix = `tp1_${Date.now()}`; +const newClientOrderId = `${prefix}${suffix}`; +const validBinanceClientOrderId = /^[.A-Z:/a-z0-9_-]{1,32}$/; + +if (!validBinanceClientOrderId.test(newClientOrderId)) { + throw new Error(`Invalid Binance client order ID: ${newClientOrderId}`); } -⋮---- -export type WsAPIFuturesWsKey = - | typeof WS_KEY_MAP.usdmWSAPI - | typeof WS_KEY_MAP.usdmWSAPITestnet; -⋮---- -/** - * Request parameters expected per operation. - * - * - Each "key" here is the name of the command/operation. - * - Each "value" here has the parameters required for the command. - * - * Make sure to add new topics to WS_API_Operations and the response param map too. - */ -export interface WsAPITopicRequestParamMap { - SUBSCRIBE: never; - UNSUBSCRIBE: never; - LIST_SUBSCRIPTIONS: never; - SET_PROPERTY: never; - GET_PROPERTY: never; - /** - * Authentication commands & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ - 'session.logon': WSAPISessionLogonRequest; - 'session.status': void; - 'session.logout': void; +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', + newClientOrderId, +}); +``` - /** - * General requests & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ - ping: void; - time: void; +The prefix returned by `getOrderIdPrefix()` is 10 characters long. For endpoints with Binance's common 32-character client order ID limit, that leaves 22 characters for your own suffix. Keep the suffix short and use only characters Binance allows for that field. - exchangeInfo: void | WSAPIExchangeInfoRequest; +If you need to track richer metadata than will comfortably fit in the client order ID, do not try to squeeze it into these custom order ID fields. Instead, generate an ID with `client.generateNewOrderId()` before placing the order, use that value as the key for your own metadata, and store the metadata locally or in an external store such as Redis. Later, when order updates arrive through REST API polling or user data events, you can look up the richer context using the seen Binance client ID value like a primary key, while keeping the exchange-facing ID short and valid. - /** - * Market data requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ - depth: TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesOrderBookRequest - : WSAPIOrderBookRequest; - 'trades.recent': WSAPITradesRecentRequest; - 'trades.historical': WSAPITradesHistoricalRequest; - 'blockTrades.historical': WSAPIBlockTradesHistoricalRequest; - 'trades.aggregate': WSAPITradesAggregateRequest; - klines: WSAPIKlinesRequest; - uiKlines: WSAPIKlinesRequest; - avgPrice: WSAPIAvgPriceRequest; - executionRules: void | WSAPIExecutionRulesRequest; - referencePrice: WSAPIReferencePriceRequest; - 'referencePrice.calculation': WSAPIReferencePriceCalculationRequest; - 'ticker.24hr': void | WSAPITicker24hrRequest; - 'ticker.tradingDay': WSAPITickerTradingDayRequest; - ticker: WSAPITickerRequest; - 'ticker.price': void | TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesTickerPriceRequest | undefined - : WSAPITickerPriceRequest | undefined; - 'ticker.book': void | TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesTickerBookRequest | undefined - : WSAPITickerBookRequest | undefined; +Regular Spot, Futures, and Portfolio orders usually use `newClientOrderId`; newer Futures algo or conditional flows may use `clientAlgoId` instead. Treat both fields, and any similar Binance custom order ID field, as the same kind of SDK-prefixed client ID. The same rule applies: omit it unless you need it, use `generateNewOrderId()` when any unique ID is fine, and use `getOrderIdPrefix()` when building your own value. Do not bypass the SDK prefix, length, or character checks just because the endpoint uses a different field name. + +### Margin REST API examples + +Margin APIs also live on `MainClient`. + +```typescript +const marginAssets = await client.getAllMarginAssets(); +const marginPairs = await client.getAllCrossMarginPairs(); +const priceIndex = await client.queryMarginPriceIndex({ symbol: 'BTCUSDT' }); - /** - * Account requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ +const crossMarginAccount = await client.queryCrossMarginAccountDetails(); +const isolatedMarginAccount = await client.getIsolatedMarginAccountInfo({ + symbols: 'BTCUSDT', +}); +const openMarginOrders = await client.queryMarginAccountOpenOrders({ + symbol: 'BTCUSDT', +}); +``` - 'account.status': - | void - | (TWSKey extends WsAPIFuturesWsKey - ? WSAPIRecvWindowTimestamp - : WSAPIAccountInformationRequest); +Margin order: - 'account.rateLimits.orders': void | WSAPIRecvWindowTimestamp; +```typescript +await client.marginAccountNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + isIsolated: 'FALSE', + sideEffectType: 'NO_SIDE_EFFECT', +}); +``` - allOrders: WSAPIAllOrdersRequest; +Borrow or repay: - allOrderLists: void | WSAPIAllOrderListsRequest; +```typescript +await client.submitMarginAccountBorrowRepay({ + asset: 'USDT', + symbol: 'BTCUSDT', + amount: 25, + type: 'BORROW', + isIsolated: 'FALSE', +}); +``` - myTrades: WSAPIMyTradesRequest; +Margin permissions, collateral, interest, and liquidation behavior are account-specific. Keep margin trading code separate from ordinary Spot trading code even though both use `MainClient`. - myPreventedMatches: WSAPIMyPreventedMatchesRequest; +### Wallet and transfer examples - myAllocations: WSAPIMyAllocationsRequest; +Wallet and transfer APIs also live on `MainClient`. - 'account.commission': WSAPIAccountCommissionWSAPIRequest; +```typescript +const balances = await client.getBalances(); +const depositAddress = await client.getDepositAddress({ + coin: 'USDT', + network: 'ETH', +}); +const depositHistory = await client.getDepositHistory({ coin: 'USDT' }); +const withdrawHistory = await client.getWithdrawHistory({ coin: 'USDT' }); - /** - * Futures account requests & parameters: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ - 'account.position': WSAPIRecvWindowTimestamp; +const transferHistory = await client.getUniversalTransferHistory({ + type: 'MAIN_UMFUTURE', +}); +``` - 'v2/account.position': WSAPIRecvWindowTimestamp; +Withdrawal calls are intentionally not shown as a quickstart. Use withdrawal permissions only when your system truly needs them, and isolate those keys from trading keys. - 'account.balance': WSAPIRecvWindowTimestamp; +--- - 'v2/account.balance': WSAPIRecvWindowTimestamp; +## Futures REST API - 'v2/account.status': WSAPIRecvWindowTimestamp; +Binance Futures are split into USD-M and COIN-M product groups. Use the dedicated client for the product you are integrating. - /** - * Trading requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ - 'order.place': (TWSKey extends WsAPIFuturesWsKey - ? WSAPINewFuturesOrderRequest - : WSAPINewSpotOrderRequest) & { - timestamp?: number; - }; - 'order.test': WSAPIOrderTestRequest; - 'order.status': TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesOrderStatusRequest - : WSAPIOrderStatusRequest; - 'order.cancel': TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesOrderCancelRequest - : WSAPIOrderCancelRequest; - 'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures - 'order.cancelReplace': WSAPIOrderCancelReplaceRequest; - 'order.amend.keepPriority': WSAPIOrderAmendKeepPriorityRequest; - 'openOrders.status': WSAPIOpenOrdersStatusRequest; - 'openOrders.cancelAll': WSAPIOpenOrdersCancelAllRequest; +### Create public Futures clients - 'algoOrder.place': WSAPINewFuturesAlgoOrderRequest; - 'algoOrder.cancel': WSAPIFuturesAlgoOrderCancelRequest; +```typescript +import { CoinMClient, USDMClient } from 'binance'; - /** - * Order list requests & parameters: - */ - 'orderList.place': WSAPIOrderListPlaceRequest; - 'orderList.place.oco': WSAPIOrderListPlaceOCORequest; - 'orderList.place.oto': WSAPIOrderListPlaceOTORequest; - 'orderList.place.otoco': WSAPIOrderListPlaceOTOCORequest; - 'orderList.place.opo': WSAPIOrderListPlaceOPORequest; - 'orderList.place.opoco': WSAPIOrderListPlaceOPOCORequest; - 'orderList.status': WSAPIOrderListStatusRequest; - 'orderList.cancel': WSAPIOrderListCancelRequest; +const usdm = new USDMClient(); +const coinm = new CoinMClient(); +``` - 'openOrderLists.status': WSAPIRecvWindowTimestamp; +Public futures market data does not require keys. - /** - * SOR requests & parameters: - */ - 'sor.order.place': WSAPISOROrderPlaceRequest; - 'sor.order.test': WSAPISOROrderTestRequest; +### Create private Futures clients - /** - * User data stream: - * - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests - * - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - * - * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. - */ - 'userDataStream.start': { apiKey: string }; - 'userDataStream.ping': WSAPIUserDataListenKeyRequest; - 'userDataStream.stop': WSAPIUserDataListenKeyRequest; - 'userDataStream.subscribe': void; - 'userDataStream.subscribe.signature': { timestamp: number }; - 'userDataStream.unsubscribe': void; +```typescript +import { CoinMClient, USDMClient } from 'binance'; - /** - * User data streams, margin: - */ - 'userDataStream.subscribe.listenToken': { listenToken: string }; -} -⋮---- -/** - * Authentication commands & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ -⋮---- -/** - * General requests & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ -⋮---- -/** - * Market data requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ -⋮---- -/** - * Account requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ -⋮---- -/** - * Futures account requests & parameters: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ -⋮---- -/** - * Trading requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ -⋮---- -'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures -⋮---- -/** - * Order list requests & parameters: - */ -⋮---- -/** - * SOR requests & parameters: - */ -⋮---- -/** - * User data stream: - * - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests - * - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - * - * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. - */ -⋮---- -/** - * User data streams, margin: - */ -⋮---- -/** - * Response structure expected for each operation - * - * - Each "key" here is a command/request supported by the WS API - * - Each "value" here is the response schema for that command. - */ -export interface WsAPIOperationResponseMap { - [key: string]: unknown; +const usdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); - SUBSCRIBE: never; - UNSUBSCRIBE: never; - LIST_SUBSCRIPTIONS: never; - SET_PROPERTY: never; - GET_PROPERTY: never; +const coinm = new CoinMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); +``` - /** - * Session authentication responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ - 'session.login': WSAPIResponse; - 'session.status': WSAPIResponse; - 'session.logout': WSAPIResponse; +Use `demoTrading: true` for Binance demo trading or `testnet: true` for testnet where supported: + +```typescript +const demoUsdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + demoTrading: true, +}); - /** - * General responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ +const testnetUsdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + testnet: true, +}); +``` - ping: unknown; - time: WSAPIResponse; - exchangeInfo: WSAPIResponse; +Do not enable both `demoTrading` and `testnet` on the same client. - /** - * Market data responses - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ - depth: WSAPIResponse; - 'trades.recent': WSAPIResponse; - 'trades.historical': WSAPIResponse; - 'blockTrades.historical': WSAPIResponse; - 'trades.aggregate': WSAPIResponse; - klines: WSAPIResponse; - uiKlines: WSAPIResponse; - avgPrice: WSAPIResponse; - executionRules: WSAPIResponse; - referencePrice: WSAPIResponse; - 'referencePrice.calculation': WSAPIResponse; - 'ticker.24hr': WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - >; - 'ticker.tradingDay': WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - >; - ticker: WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - >; - 'ticker.price': WSAPIResponse< - | WSAPIPriceTicker - | WSAPIPriceTicker[] - | WSAPIFuturesPriceTicker - | WSAPIFuturesPriceTicker[] - >; - 'ticker.book': WSAPIResponse< - | WSAPIBookTicker - | WSAPIBookTicker[] - | WSAPIFuturesBookTicker - | WSAPIFuturesBookTicker[] - >; +### Common public USD-M Futures market data calls - /** - * Account responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - */ +```typescript +const serverTime = await usdm.getServerTime(); +const exchangeInfo = await usdm.getExchangeInfo(); +const orderBook = await usdm.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); +const recentTrades = await usdm.getRecentTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const candles = await usdm.getKlines({ + symbol: 'BTCUSDT', + interval: '1m', + limit: 10, +}); +const markPrice = await usdm.getMarkPrice({ symbol: 'BTCUSDT' }); +const fundingHistory = await usdm.getFundingRateHistory({ + symbol: 'BTCUSDT', + limit: 10, +}); +const ticker = await usdm.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); +``` - 'account.status': WSAPIResponse< - WSAPIAccountInformation | WSAPIFuturesAccountStatus - >; - 'account.commission': WSAPIResponse; - 'account.rateLimits.orders': WSAPIResponse; - allOrders: WSAPIResponse; - allOrderLists: WSAPIResponse; - myTrades: WSAPIResponse; - myPreventedMatches: WSAPIResponse; - myAllocations: WSAPIResponse; +### Common public COIN-M Futures market data calls - /** - * Futures account responses: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ - 'account.position': WSAPIResponse; - 'v2/account.position': WSAPIResponse; - 'account.balance': WSAPIResponse; - 'v2/account.balance': WSAPIResponse; - 'v2/account.status': WSAPIResponse; +```typescript +const serverTime = await coinm.getServerTime(); +const exchangeInfo = await coinm.getExchangeInfo(); +const orderBook = await coinm.getOrderBook({ + symbol: 'BTCUSD_PERP', + limit: 10, +}); +const candles = await coinm.getKlines({ + symbol: 'BTCUSD_PERP', + interval: '1m', + limit: 10, +}); +const markPrice = await coinm.getMarkPrice({ symbol: 'BTCUSD_PERP' }); +const ticker = await coinm.getSymbolPriceTicker({ symbol: 'BTCUSD_PERP' }); +``` - /** - * Trading responses - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ - 'order.place': WSAPIResponse; - 'order.test': WSAPIResponse< - WSAPIOrderTestResponse | WSAPIOrderTestWithCommission - >; - 'order.status': WSAPIResponse; - 'order.cancel': WSAPIResponse; - 'order.modify': WSAPIResponse; - 'order.cancelReplace': WSAPIResponse; - 'openOrders.status': WSAPIResponse; - 'openOrders.cancelAll': WSAPIResponse< - (WSAPIOrderCancel | WSAPIOrderListCancelResponse)[] - >; - 'algoOrder.place': WSAPIResponse; - 'algoOrder.cancel': WSAPIResponse; - /** - * Order list responses - */ - 'orderList.place': WSAPIResponse; - 'orderList.place.oco': WSAPIResponse; - 'orderList.place.oto': WSAPIResponse; - 'orderList.place.otoco': WSAPIResponse; - 'orderList.place.opo': WSAPIResponse; - 'orderList.place.opoco': WSAPIResponse; - 'orderList.status': WSAPIResponse; - 'orderList.cancel': WSAPIResponse; - 'openOrderLists.status': WSAPIResponse; +See also: - /** - * SOR responses - */ - 'sor.order.place': WSAPIResponse; - 'sor.order.test': WSAPIResponse< - WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission - >; +- [USD-M public REST API example](../examples/Rest/Futures/rest-usdm-public.ts) +- [USD-M demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) +- [USD-M testnet example](../examples/Rest/Futures/rest-usdm-testnet.ts) - 'userDataStream.start': WSAPIResponse<{ listenKey: string }>; - 'userDataStream.ping': WSAPIResponse; - 'userDataStream.stop': WSAPIResponse; - 'userDataStream.subscribe': WSAPIResponse; - 'userDataStream.subscribe.signature': WSAPIResponse; - 'userDataStream.unsubscribe': WSAPIResponse; -} -⋮---- -/** - * Session authentication responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ -⋮---- -/** - * General responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ -⋮---- -/** - * Market data responses - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ -⋮---- -/** - * Account responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - */ -⋮---- -/** - * Futures account responses: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ -⋮---- -/** - * Trading responses - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ -⋮---- -/** - * Order list responses - */ -⋮---- -/** - * SOR responses - */ +### Common private Futures account calls -================ -File: README.md -================ -# Node.js & JavaScript SDK for Binance REST APIs & WebSockets +```typescript +const balance = await usdm.getBalance(); +const account = await usdm.getAccountInformation(); +const positions = await usdm.getPositions({ symbol: 'BTCUSDT' }); +const openOrders = await usdm.getAllOpenOrders({ symbol: 'BTCUSDT' }); +const tradeHistory = await usdm.getAccountTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const income = await usdm.getIncomeHistory({ + symbol: 'BTCUSDT', + limit: 10, +}); +``` -[![Build & Test](https://github.com/tiagosiebler/binance/actions/workflows/test.yml/badge.svg)](https://github.com/tiagosiebler/binance/actions/workflows/test.yml) -[![npm version](https://img.shields.io/npm/v/binance)][1] -[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1] -[![users count](https://dependents.info/tiagosiebler/binance/badge?label=users)](https://dependents.info/tiagosiebler/binance) -[![npm downloads](https://img.shields.io/npm/dt/binance)][1] -[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/binance)][1] -[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/binance/badge)](https://www.codefactor.io/repository/github/tiagosiebler/binance) -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) +### Futures order examples -

- - - - SDK Logo - - -

+Market order: + +```typescript +await usdm.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'MARKET', + quantity: 0.001, +}); +``` -[1]: https://www.npmjs.com/package/binance +Limit order: -> [!TIP] -> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK will soon be hosted under the [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. +```typescript +await usdm.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', +}); +``` -Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets: +Reduce-only limit order: -- Professional, robust & performant Binance SDK with leading trading volume in production (livenet). -- Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. -- Complete TypeScript support (with type declarations for all API requests & responses). -- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. - - Strongly typed requests and responses. - - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. -- Actively maintained with a modern, promise-driven interface. -- Support for all authentication mechanisms available on Binance: - - HMAC - - RSA - - Ed25519 (required for WS API login, else each request is signed). - - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication. -- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures. - - Event driven messaging. - - Smart WebSocket persistence - - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - - Automatically handle listenKey persistence and expiration/refresh. - - Emit `reconnected` event when dropped connection is restored. - - Strongly typed on most WebSocket events, with typeguards available for TypeScript users. - - Optional: - - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers). - - Automatic beautification of REST responses (parsing numbers in strings to numbers). -- Supports WebSocket API on all available product groups, including Spot & Futures: - - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or; - - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. -- Heavy automated end-to-end testing with real API calls. - - End-to-end testing before any release. - - Real API calls in e2e tests. -- Proxy support via axios integration. -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). -- QuickStart Guide: [Binance JavaScript QuickStart Guide](https://siebly.io/sdk/binance/javascript) -- Binance JavaScript Tutorial: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) +```typescript +await usdm.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + reduceOnly: 'true', +}); +``` -## Table of Contents +Batch order management: -- [Installation](#installation) -- [Examples](#examples) - - [REST API Examples](./examples/REST) - - [WebSocket Examples](./examples/WebSockets) - - [WebSocket Consumers](./examples/WebSockets/) - - [WebSocket API](./examples/WebSockets/ws-api-client.ts) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation Links](#documentation) -- [Usage](#usage) - - [Demo Trading vs Testnet](#demo-trading-vs-testnet) - - [REST API Clients](#rest-api-clients) - - [REST Main Client](#rest-main-client) - - [REST USD-M Futures](#rest-usd-m-futures) - - [REST COIN-M Futures](#rest-coin-m-futures) - - [REST Portfolio Margin](#rest-portfolio-margin) - - [WebSockets](#websockets) - - [WebSocket Consumers](#websocket-consumers) - - [WebSocket API](#websocket-api) - - [Event Driven API](#event-driven-api) - - [Promise Driven API](#async-await-api) - - [Market Maker Endpoints](#market-maker-endpoints) - - [Using Market Maker Endpoints](#using-market-maker-endpoints) - - [Best practice](#best-practice) - - [Customise Logging](#customise-logging) - - [Frontend Usage](#browserfrontend-usage) - - [Import](#import) - - [Webpack](#webpack) -- [LLMs & AI](#use-with-llms--ai) -- [Contributions & Thanks](#contributions--thanks) +```typescript +await usdm.submitMultipleOrders([ + { + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + }, + { + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', + }, +]); +``` -## Installation +See also: -`npm install binance --save` +- [USD-M order example](../examples/Rest/Futures/rest-usdm-order.ts) +- [USD-M stop-loss order example](../examples/Rest/Futures/rest-usdm-order-sl.ts) +- [USD-M bracket order example](../examples/Rest/Futures/rest-future-bracket-order.ts) -## Examples +--- -Refer to the [examples](./examples) folder for implementation demos. +## Portfolio Margin REST API -## Issues & Discussion +Portfolio Margin has its own account model and a dedicated `PortfolioClient`. -- Issues? Check the [issues tab](https://github.com/tiagosiebler/binance/issues). -- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. -- Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. -- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) +### Create a Portfolio Margin client - +```typescript +import { PortfolioClient } from 'binance'; -## Related Projects +const portfolio = new PortfolioClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); +``` -Check out my related JavaScript/TypeScript/Node.js projects: +### Common Portfolio Margin calls -- Try our REST API & WebSocket SDKs published on npmjs: - - [Bybit Node.js SDK: bybit-api](https://www.npmjs.com/package/bybit-api) - - [Kraken Node.js SDK: @siebly/kraken-api](https://www.npmjs.com/package/coinbase-api) - - [OKX Node.js SDK: okx-api](https://www.npmjs.com/package/okx-api) - - [Binance Node.js SDK: binance](https://www.npmjs.com/package/binance) - - [Gate (gate.com) Node.js SDK: gateio-api](https://www.npmjs.com/package/gateio-api) - - [Bitget Node.js SDK: bitget-api](https://www.npmjs.com/package/bitget-api) - - [Kucoin Node.js SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) - - [Coinbase Node.js SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) - - [Bitmart Node.js SDK: bitmart-api](https://www.npmjs.com/package/bitmart-api) -- Try my misc utilities: - - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) -- Check out my examples: - - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) - +```typescript +const ping = await portfolio.testConnectivity(); +const serverTime = await portfolio.getServerTime(); +const balance = await portfolio.getBalance(); +const account = await portfolio.getAccountInfo(); +const umPositions = await portfolio.getUMPosition({ symbol: 'BTCUSDT' }); +const cmPositions = await portfolio.getCMPosition({ pair: 'BTCUSD' }); +const umOpenOrders = await portfolio.getAllUMOpenOrders({ + symbol: 'BTCUSDT', +}); +const marginOpenOrders = await portfolio.getMarginOpenOrders({ + symbol: 'BTCUSDT', +}); +``` -## Documentation +Portfolio Margin order examples: -Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. +```typescript +await portfolio.submitNewUMOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', +}); -- Binance API Documentation - - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) - - [ Derivatives ](https://developers.binance.com/docs/derivatives) - - [ Margin ](https://developers.binance.com/docs/margin_trading) - - [ Wallet ](https://developers.binance.com/docs/wallet) -- [Find all products here](https://developers.binance.com/en) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) -- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) +await portfolio.submitNewCMOrder({ + symbol: 'BTCUSD_PERP', + side: 'SELL', + type: 'MARKET', + quantity: '1', +}); -## Structure +await portfolio.submitNewMarginOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'MARKET', + quantity: '0.001', + sideEffectType: 'NO_SIDE_EFFECT', +}); +``` -This project uses typescript. Resources are stored in 3 key structures: +See also: -- [src](./src) - the whole connector written in typescript -- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. -- [dist](./dist) - the packed bundle of the project for use in browser environments. +- [Portfolio Margin public REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-public.ts) +- [Portfolio Margin private REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-private.ts) --- -# Usage +## WebSocket Streams -Create API credentials at Binance +Use `WebsocketClient` when you want event-driven updates instead of polling the REST API. It is the shared client for public market streams and the older listen-key style user data streams. -- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) -- [Testnet](https://testnet.binance.vision/). -- [Testnet Futures](testnet.binancefuture.com). -- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading. +The workflow is simple: create a client, add event handlers, provide API keys if you need private user data, and subscribe to the streams you want. The SDK opens the correct Binance endpoint, applies proxy settings if configured, fetches and refreshes listen keys where required, monitors heartbeats, reconnects stale sockets, and resubscribes cached topics after reconnect. -### Demo Trading vs Testnet +### Common `WebsocketClient` events -Binance offers two testing environments: +| Event | Meaning | +| -------------------------- | --------------------------------------------------------------- | +| `open` | Connection established | +| `message` | Raw streaming data received | +| `formattedMessage` | Beautified public stream data when `beautify: true` | +| `formattedUserDataMessage` | Beautified private user data stream event when `beautify: true` | +| `response` | Subscribe, unsubscribe, auth, or WebSocket API acknowledgement | +| `reconnecting` | Connection dropped and retrying | +| `reconnected` | Connection restored and subscriptions resynced | +| `close` | Socket closed | +| `authenticated` | WebSocket API session authentication succeeded | +| `exception` | Errors and unexpected conditions | + +### Understanding `WS_KEY_MAP` + +[`WS_KEY_MAP`](/reference/glossary#ws-key) tells the SDK which Binance WebSocket endpoint family to use. This matters because Spot, USD-M Futures, COIN-M Futures, Options, Portfolio Margin, and WebSocket API traffic do not all live on the same endpoint. + +Common `WS_KEY_MAP` entries: + +| Key | Use | +| ---------------------------- | ----------------------------------------------------------------------- | +| `main` | Spot, margin, and isolated margin market data streams | +| `main2` | Alternate Spot stream port | +| `main3` | Spot market-data-only stream endpoint | +| `mainWSAPI` | Spot and margin WebSocket API | +| `mainWSAPITestnet` | Spot WebSocket API testnet | +| `marginUserData` | Margin user data over WebSocket API listen-token flow | +| `marginRiskUserData` | Cross-margin risk data stream | +| `usdmPublic` | USD-M high-frequency public market data, such as book and depth streams | +| `usdmMarket` | USD-M regular market data, such as trades, klines, tickers, mark price | +| `usdmPrivate` | USD-M private user data stream endpoint | +| `usdmWSAPI` | USD-M Futures WebSocket API | +| `coinm` | COIN-M market data and user data stream endpoint | +| `coinmWSAPI` | COIN-M Futures WebSocket API | +| `eoptions` | European Options WebSocket streams | +| `portfolioMarginUserData` | Portfolio Margin user data stream | +| `portfolioMarginProUserData` | Portfolio Margin Pro user data stream | +| `alpha` | Alpha market data streams | -- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures. -- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing. +These keys act like connection IDs. The SDK uses them to track connection state, cached subscriptions, reconnect behavior, and endpoint-specific routing. -To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information. +### Public Spot WebSocket topics -## REST API Clients +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; -There are several REST API modules as there are some differences in each API group. +const ws = new WebsocketClient({ beautify: true }); -1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management. -2. `USDMClient` for USD-M futures APIs. -3. `CoinMClient` for COIN-M futures APIs. -4. `PortfolioClient` for Portfolio Margin APIs. +ws.on('formattedMessage', (data) => console.log(data)); +ws.on('exception', console.error); -Vanilla Options is not yet available. Please get in touch if you're looking for this. +ws.subscribe( + [ + 'btcusdt@trade', + 'btcusdt@aggTrade', + 'btcusdt@kline_1m', + 'btcusdt@bookTicker', + 'btcusdt@depth10@100ms', + ], + WS_KEY_MAP.main, +); +``` -### REST Main Client +See also: -The MainClient covers all endpoints under the main "api\*.binance.com" subdomains, including but not limited to endpoints in the following product groups: +- [General public WebSocket example](../examples/WebSockets/Public/ws-public.ts) +- [Spot order book WebSocket example](../examples/WebSockets/Public/ws-public-spot-orderbook.ts) +- [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) -- Spot -- Cross & isolated margin -- Convert -- Wallet -- Futures management (transfers & history) -- Sub account management -- Misc transfers -- Auto & dual invest -- Staking -- Mining -- Loans & VIP loans -- Simple Earn -- NFTs -- C2C -- Exchange Link -- Alpha trading +### Public USD-M Futures WebSocket topics -Refer to the following links for a complete list of available endpoints: +USD-M Futures WebSockets have dedicated endpoint families for high-frequency public data and regular market data. -- [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/tiagosiebler/binance/blob/master/docs/endpointFunctionList.md) -- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; -Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. +const ws = new WebsocketClient({ beautify: true }); -```javascript -import { MainClient } from 'binance'; +ws.on('formattedMessage', (data) => console.log(data)); +ws.on('exception', console.error); -// or, if you prefer `require()`: -// const { MainClient } = require('binance'); +// High-frequency public data: book ticker and order book depth. +ws.subscribe( + ['btcusdt@bookTicker', 'btcusdt@depth10@100ms', 'btcusdt@depth@100ms'], + WS_KEY_MAP.usdmPublic, +); -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +// Regular market data: trades, mark price, klines, mini tickers, liquidations. +ws.subscribe(['btcusdt@aggTrade', 'btcusdt@markPrice', 'btcusdt@kline_1m'], WS_KEY_MAP.usdmMarket); +``` -const client = new MainClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); +See also: -client - .getAccountTradeList({ symbol: 'BTCUSDT' }) - .then((result) => { - console.log('getAccountTradeList result: ', result); - }) - .catch((err) => { - console.error('getAccountTradeList error: ', err); - }); +- [USD-M public WebSocket example](../examples/WebSockets/Public/ws-usdm-public.ts) +- [USD-M funding stream example](../examples/WebSockets/Public/ws-public-usdm-funding.ts) -client - .getExchangeInfo() - .then((result) => { - console.log('getExchangeInfo inverse result: ', result); - }) - .catch((err) => { - console.error('getExchangeInfo inverse error: ', err); - }); -``` +### Public COIN-M Futures WebSocket topics -See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; -### REST USD-M Futures +const ws = new WebsocketClient({ beautify: true }); -Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. +ws.on('message', (data) => console.log(JSON.stringify(data))); +ws.on('exception', console.error); -```javascript -import { USDMClient } from 'binance'; +ws.subscribe( + ['btcusd_perp@aggTrade', 'btcusd_perp@markPrice', 'btcusd_perp@kline_1m'], + WS_KEY_MAP.coinm, +); +``` -// or, if you prefer `require()`: -// const { USDMClient } = require('binance'); +COIN-M symbols and stream names are not the same as Spot or USD-M symbols. Treat symbols as product-specific strings. -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +--- -const client = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); +## User Data Streams -client - .getBalance() - .then((result) => { - console.log('getBalance result: ', result); - }) - .catch((err) => { - console.error('getBalance error: ', err); - }); +User data streams are how Binance pushes private account events: order updates, execution updates, balance changes, position changes, margin events, and listen-key or subscription expiry events. -client - .submitNewOrder({ - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - }) - .then((result) => { - console.log('submitNewOrder result: ', result); - }) - .catch((err) => { - console.error('submitNewOrder error: ', err); - }); -``` +Binance uses two patterns for these streams: WebSocket API user data subscriptions and listen-key user data streams. The SDK supports both; the product group determines which path you should use. -See [usdm-client.ts](./src/usdm-client.ts) for further information. +For either pattern, listen for the WebSocket lifecycle events as well as account events. The event names are `reconnecting` and `reconnected`. `reconnecting` fires when the SDK starts replacing a dropped connection; `reconnected` fires after the replacement connection is open. Both include the [`wsKey`](/reference/glossary#ws-key), which tells you which connection was affected. For user data streams, `reconnected` is the right place to reconcile private state through the REST API in case account events were missed while the socket was down. -### REST COIN-M Futures +With `WebsocketAPIClient`, attach those handlers to `wsApi.getWSClient()`. With `WebsocketClient`, attach them directly to the client. -Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. +### Preferred Spot user data stream with `WebsocketAPIClient` -```javascript -import { CoinMClient } from 'binance'; +```typescript +import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; -// or, if you prefer `require()`: -// const { CoinMClient } = require('binance'); +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +const wsClient = wsApi.getWSClient(); -const client = new CoinMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, +wsClient.on('formattedUserDataMessage', (data) => { + console.log('spot account event', data); }); -client - .getSymbolOrderBookTicker() - .then((result) => { - console.log('getSymbolOrderBookTicker result: ', result); - }) - .catch((err) => { - console.error('getSymbolOrderBookTicker error: ', err); - }); -``` +wsClient.on('reconnecting', ({ wsKey }) => { + console.log('spot user data reconnecting', wsKey); +}); -See [coinm-client.ts](./src/coinm-client.ts) for further information. +wsClient.on('reconnected', ({ wsKey }) => { + console.log('spot user data reconnected', wsKey); + // Fetch account state, open orders, or recent fills here if needed. +}); -### REST Portfolio Margin +wsClient.on('exception', console.error); -Start by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. +await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); +``` -```javascript -import { PortfolioClient } from 'binance'; +This is the recommended path for Spot user data in this SDK version. -// or, if you prefer `require()`: -// const { PortfolioClient } = require('binance'); +### Margin user data stream with `WebsocketAPIClient` -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +```typescript +import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; -const client = new PortfolioClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, }); -client - .getBalance() - .then((result) => { - console.log('getBalance result: ', result); - }) - .catch((err) => { - console.error('getBalance error: ', err); - }); - -client - .submitNewUMOrder({ - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - }) - .then((result) => { - console.log('submitNewUMOrder result: ', result); - }) - .catch((err) => { - console.error('submitNewUMOrder error: ', err); - }); -``` +const wsClient = wsApi.getWSClient(); -See [portfolio-client.ts](./src/portfolio-client.ts) for further information. +wsClient.on('formattedUserDataMessage', (data) => { + console.log('margin account event', data); +}); -## WebSockets +wsClient.on('reconnecting', ({ wsKey }) => { + console.log('margin user data reconnecting', wsKey); +}); -### WebSocket Consumers +wsClient.on('reconnected', ({ wsKey }) => { + console.log('margin user data reconnected', wsKey); +}); -All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. +await wsApi.subscribeUserDataStream(WS_KEY_MAP.marginUserData); +``` -The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: +For margin, the SDK handles the listen-token workflow used by Binance's margin WebSocket API user data endpoint. -```javascript -import { WebsocketClient } from 'binance'; +### Futures user data streams with `WebsocketClient` -// or, if you prefer `require()`: -// const { WebsocketClient } = require('binance'); +For Futures user data streams, the SDK can manage listen keys for you through convenience methods. -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +```typescript +import { WebsocketClient } from 'binance'; -/** - * The WebsocketClient will manage individual connections for you, under the hood. - * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. - */ -const wsClient = new WebsocketClient({ - api_key: key, - api_secret: secret, - // Optional: when enabled, the SDK will try to format incoming data into more readable objects. - // Beautified data is emitted via the "formattedMessage" event +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, beautify: true, - // Disable ping/pong ws heartbeat mechanism (not recommended) - // disableHeartbeat: true, - // Connect to testnet environment - // testnet: true, }); -// receive raw events -wsClient.on('message', (data) => { - console.log('raw message received ', JSON.stringify(data, null, 2)); +ws.on('formattedUserDataMessage', (data) => { + console.log('futures account event', data); }); -// notification when a connection is opened -wsClient.on('open', (data) => { - console.log('connection opened open:', data.wsKey, data.wsUrl); +ws.on('reconnecting', ({ wsKey }) => { + console.log('futures user data reconnecting', wsKey); }); -// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. -wsClient.on('formattedMessage', (data) => { - console.log('formattedMessage: ', data); +ws.on('reconnected', ({ wsKey }) => { + console.log('futures user data reconnected', wsKey); + // Fetch positions, balances, open orders, or fills here if needed. }); -// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -wsClient.on('response', (data) => { - console.log('log response: ', JSON.stringify(data, null, 2)); +ws.on('exception', console.error); + +await ws.subscribeUsdFuturesUserDataStream(); +// await ws.subscribeCoinFuturesUserDataStream(); +``` + +The SDK will fetch the listen key, keep it alive, refresh it when needed, reconnect after network issues, and resubscribe where possible. + +### Portfolio Margin user data stream + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, }); -// receive notification when a ws connection is reconnecting automatically -wsClient.on('reconnecting', (data) => { - console.log('ws automatically reconnecting.... ', data?.wsKey); +ws.on('formattedUserDataMessage', (data) => { + console.log('portfolio margin event', data); }); -// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) -wsClient.on('reconnected', (data) => { - console.log('ws has reconnected ', data?.wsKey); +ws.on('reconnecting', ({ wsKey }) => { + console.log('portfolio margin user data reconnecting', wsKey); }); -// Recommended: receive error events (e.g. first reconnection failed) -wsClient.on('exception', (data) => { - console.log('ws saw error ', data?.wsKey); +ws.on('reconnected', ({ wsKey }) => { + console.log('portfolio margin user data reconnected', wsKey); }); -/** - * Subscribe to public topics either one at a time or many in an array - */ +ws.on('exception', console.error); -// E.g. one at a time, routed to the coinm futures websockets: -wsClient.subscribe('btcusd@indexPrice', 'coinm'); -wsClient.subscribe('btcusd@miniTicker', 'coinm'); +await ws.subscribePortfolioMarginUserDataStream(WS_KEY_MAP.portfolioMarginUserData); +``` -// Or send many topics at once to a stream, e.g. the usdm futures stream: -wsClient.subscribe( - ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], - 'usdm', -); +See also: -// spot & margin topics should go to "main" -// (similar how the MainClient is for REST APIs in that product group) -wsClient.subscribe( - [ - // All Market Rolling Window Statistics Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams - '!ticker_1h@arr', - // Individual Symbol Book Ticker Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams - 'btcusdt@bookTicker', - // Average Price - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price - 'btcusdt@avgPrice', - // Partial Book Depth Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams - 'btcusdt@depth10@100ms', - // Diff. Depth Stream - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream - 'btcusdt@depth', - ], - // Look at the `WS_KEY_URL_MAP` for a list of values here: - // https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts - // "main" connects to wss://stream.binance.com:9443/stream - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams - 'main', -); +- [User data stream overview](<../examples/WebSockets/Private(userdata)/ws-userdata-README.MD>) +- [Listen-key user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts>) +- [WebSocket API user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) +- [User data connection safety example](<../examples/WebSockets/Private(userdata)/ws-userdata-connection-safety.ts>) -/** - * For the user data stream, these convenient subscribe methods open a dedicated - * connection with the listen key workflow: - */ +--- -wsClient.subscribeSpotUserDataStream(); -wsClient.subscribeMarginUserDataStream(); -wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); -wsClient.subscribeUsdFuturesUserDataStream(); -wsClient.subscribePortfolioMarginUserDataStream(); -``` +## WebSocket API -See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. +Binance's WebSocket API is a request/response API over a persistent WebSocket connection. It is useful when you want lower request overhead than REST API calls, or when a Binance feature is exposed through the WebSocket API flow. -#### Preserving large integers in WebSocket messages +`WebsocketAPIClient` wraps that in a promise-driven interface: call a method, await a promise, receive the response, and let the SDK manage the underlying WebSocket connection. -By default, messages are parsed using `JSON.parse`, which cannot precisely represent integers larger than `Number.MAX_SAFE_INTEGER`. -If you need to preserve large integers (e.g., order IDs), provide a custom parser via `customParseJSONFn`. +### Authentication -Example using RegEx below, although alternatives are possible too if desired. For more exampes check [ws-custom-parser.ts](./examples/WebSockets/ws-custom-parser.ts) in the examples folder: +The SDK supports HMAC, RSA, and Ed25519 keys: -```ts -import { WebsocketClient } from 'binance'; +- HMAC: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. +- RSA: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. +- Ed25519: recommended for WebSocket API because the SDK can authenticate the WebSocket API session once and then send private commands without signing every command. -/** - * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: - * https://github.com/tiagosiebler/binance/issues/208 - * - * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: - */ -const ws = new WebsocketClient({ - // Default behaviour, if you don't include this: - // customParseJSONFn: (rawEvent) => { - // return JSON.parse(rawEvent); - // }, +If your `api_secret` contains a PEM private key, the SDK automatically detects whether it should use RSA or Ed25519 signing. - // Or, pre-process the raw event using RegEx, before using the same workflow: - customParseJSONFn: (rawEvent) => { - return JSON.parse( - rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), - ); - }, +See also: - // Or, use a 3rd party library such as json-bigint: - // customParseJSONFn: (rawEvent) => { - // return JSONbig({ storeAsString: true }).parse(rawEvent); - // }, +- [Ed25519 auth example](../examples/auth/rest-private-ed25519.md) +- [RSA auth example](../examples/auth/rest-private-rsa.md) + +### Spot examples + +```typescript +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, }); -ws.on('message', (msg) => { - console.log(msg); +const exchangeInfo = await wsApi.getSpotExchangeInfo({ + symbol: 'BTCUSDT', }); -// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values. -// Use a custom replacer or JSONbig.stringify if you need to log/serialize: -// const replacer = (_k: string, v: unknown) => typeof v === 'bigint' ? v.toString() : v; -// console.log(JSON.stringify(msg, replacer)); +const orderBook = await wsApi.getSpotOrderBook({ + symbol: 'BTCUSDT', + limit: 10, +}); + +const account = await wsApi.getSpotAccountInformation({ + timestamp: Date.now(), +}); + +await wsApi.testSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', + timestamp: Date.now(), +}); +``` + +Submit a Spot order over the WebSocket API: + +```typescript +await wsApi.submitNewSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', +}); +``` + +### Futures examples + +```typescript +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +const book = await wsApi.getFuturesOrderBook({ + symbol: 'BTCUSDT', + limit: 10, +}); + +const balance = await wsApi.getFuturesAccountBalance('usdm', { + timestamp: Date.now(), +}); + +await wsApi.submitNewFuturesOrder('usdm', { + symbol: 'BTCUSDT', + side: 'SELL', + type: 'MARKET', + quantity: '0.001', + timestamp: Date.now(), +}); ``` -### WebSocket API - -Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. - -#### Authentication +See also: -HMAC, RSA and Ed25519 keys are supported for the WebSocket API. However, only Ed25519 keys support WebSocket API login. When using HMAC or RSA keys, each WebSocket API command will need to be individually signed. +- [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) +- [Raw WebSocket API promises example](../examples/WebSockets/WS-API/ws-api-raw-promises.ts) -This is no issue for most use cases, but if you are latency sensitive, you should consider using Ed25519 keys. This will allow the WebSocket API client to authenticate once after the connection opens, and all commands can then be sent without additional request signatures. +--- -#### Event Driven API +## Environments and Special Endpoints -The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method. +### Demo trading -Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. +Demo trading uses real market data with simulated trading. For strategy testing, this is usually more useful than testnet. -#### Async Await API +```typescript +const client = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + demoTrading: true, +}); +``` -The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient). +Demo trading is supported by SDK options for REST API and WebSocket clients where Binance provides demo endpoints. -It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. +### Testnet -Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. +Testnet uses separate credentials and simulated market conditions. ```typescript -import { WebsocketAPIClient } from 'binance'; - -// or, if you prefer `require()`: -// const { WebsocketAPIClient } = require('binance'); - -/** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. - */ +const client = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + testnet: true, +}); +``` -const publicKey = `-----BEGIN PUBLIC KEY----- -MCexampleQTxwLU9o= ------END PUBLIC KEY----- -`; +Use testnet for endpoint wiring and permission checks. Do not use testnet market behavior as evidence that a live strategy is profitable or safe. -const privateKey = `-----BEGIN PRIVATE KEY----- -MC4CAQAexamplewqj5CzUuTy1 ------END PRIVATE KEY----- -`; +### Market maker endpoints -// API Key returned by binance, generated using the publicKey (above) via Binance's website -const apiKey = 'TQpJexamplerobdG'; +Binance provides market maker endpoints for eligible futures users. If you qualify and need those endpoints, enable them with `useMMSubdomain: true`. -// Make an instance of the WS API Client -const wsClient = new WebsocketAPIClient({ - api_key: apiKey, - api_secret: privateKey, - beautify: true, +```typescript +const usdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + useMMSubdomain: true, +}); - // Enforce testnet ws connections, regardless of supplied wsKey - // testnet: true, +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + useMMSubdomain: true, }); +``` -// 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); +Market maker endpoints are for supported futures products. They are not a general Spot endpoint override and are not available on testnet. -// Optional, see above. Can be used to prepare a connection before sending commands -// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); +--- -// Make WebSocket API calls, very similar to a REST API: +## Production Notes -wsClient - .getFuturesAccountBalanceV2({ - timestamp: Date.now(), - recvWindow: 5000, - }) - .then((result) => { - console.log('getFuturesAccountBalanceV2 result: ', result); - }) - .catch((err) => { - console.error('getFuturesAccountBalanceV2 error: ', err); - }); +Before a Binance integration trades unattended, these are the parts worth making explicit. -wsClient - .submitNewFuturesOrder('usdm', { - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - timestamp: Date.now(), - // recvWindow: 5000, - }) - .then((result) => { - console.log('getFuturesAccountBalanceV2 result: ', result); - }) - .catch((err) => { - console.error('getFuturesAccountBalanceV2 error: ', err); - }); -``` +### 1. Roll out in layers ---- +Move from public reads to private actions one layer at a time: -## Market Maker Endpoints +1. Public REST APIs +2. Public WebSockets +3. Private REST API account reads +4. Private account/user data streams +5. Order validation +6. Tiny demo or live trading tests -Binance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program. +For Futures, prefer demo trading before live trading if it fits your setup. -These endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 +### 2. Reconnect, then backfill -### Using Market Maker Endpoints +Listen for `reconnecting` and `reconnected`. A dropped WebSocket connection is a normal production condition, especially during volatility or scheduled exchange disconnects. -To use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients): +If your system uses WebSockets for account or market state, a reconnect should usually trigger a REST API backfill: -#### Market Maker REST API Clients +1. Pause risky order actions when `reconnecting` fires. +2. On `reconnected`, query the REST API for account state, orders, fills, positions, and any market state you depend on. +3. Reconcile internal state. +4. React to any discrepancies in internal vs exchange state, as needed. +5. Resume normal processing. -```javascript -import { USDMClient, CoinMClient } from 'binance'; +### 3. Keep credentials scoped -// USD-M Futures with MM endpoints -const usdmClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); +Live, demo trading, Spot testnet, and Futures testnet credentials are different. Keep them separate in your secrets manager and deployment configuration. -// COIN-M Futures with MM endpoints -const coinmClient = new CoinMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); -``` +Use the minimum permissions needed for each key. A market-data key should not be able to trade. A trading key should not have withdrawal permissions. Do not put live secrets in frontend code. Make use of IP whitelisting for any API keys. These must be protected, treat them like passwords. -#### Market Maker WebSocket Clients +### 4. Keep streams and commands separate -```javascript -import { WebsocketClient, WebsocketAPIClient } from 'binance'; +Use `WebsocketClient` for streams. Use `WebsocketAPIClient` for commands you want to await. They share WebSocket infrastructure, but they solve different problems. -// WebSocket consumer with MM endpoints -const wsClient = new WebsocketClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); +### 5. Treat symbols and order IDs as product-specific state -// WebSocket API client with MM endpoints -const wsApiClient = new WebsocketAPIClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); -``` +Spot, USD-M Futures, COIN-M Futures, Options, and Portfolio Margin do not all use the same symbol conventions: -**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments. +- Spot: `BTCUSDT` +- USD-M Futures: `BTCUSDT` +- COIN-M Futures: `BTCUSD_PERP` +- Stream names are usually lowercase, such as `btcusdt@trade`. Refer to the examples and/or exchange API docs for exact stream names. -### Best practice +Client order IDs deserve the same care. If you do not need a custom client order ID, omit it. If your strategy relies on idempotency, retries, or reconciliation, generate an ID before sending the order and persist it using the restClient.generateNewOrderId() method. If you build your own value, keep the SDK's product prefix in place (query it using restClient.getOrderIdPrefix()) and stay within Binance's length and character constraints. -Since market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints. +### 6. Watch clocks and rate limits -```javascript -import { USDMClient } from 'binance'; +Private Binance requests are timestamp-sensitive. Keep your system clock synced and set `recvWindow` intentionally: -// MM client for USD-M futures -const futuresMMClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMEndpoints: true, // Use MM endpoints for futures +```typescript +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + recvWindow: 5000, }); -// Regular client for USD-M futures -const futuresRegularClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMEndpoints: false, // Use regular endpoints for futures -}); +await client.fetchLatencySummary(); + +// For WebSocket API clients: +wsApi.setTimeOffsetMs(-500); ``` -## Customise Logging +The REST API client also tracks Binance rate-limit headers it sees: -Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. +```typescript +const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); +console.log(ticker); -```javascript -import { WebsocketClient, DefaultLogger } from 'binance'; +console.log(client.getRateLimitStates()); +``` -// or, if you prefer `require()`: -// const { WebsocketClient, DefaultLogger } = require('binance'); +If you see timestamp errors, fix system clock sync first. If you see rate-limit pressure, reduce polling, batch where the API allows it, and design around Binance's documented request weights. -// Enable all logging on the trace level (disabled by default) -DefaultLogger.trace = (...params) => { - console.trace('trace: ', params); -}; +For more guidance on resolving timestamp & recvWindow issues, refer to the following guidance: +https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow -// Pass the updated logger as the 2nd parameter -const ws = new WebsocketClient( - { - api_key: key, - api_secret: secret, - beautify: true, - }, - DefaultLogger -); +### 7. Logging and large integers -// Or, create a completely custom logger with the 3 available functions -const customLogger = { - trace: (...params: LogParams): void => { - console.trace(new Date(), params); - }, - info: (...params: LogParams): void => { - console.info(new Date(), params); - }, - error: (...params: LogParams): void => { - console.error(new Date(), params); - }, -} +If you want SDK logs in your own monitoring stack, pass a logger: + +```typescript +import { DefaultLogger, WebsocketClient } from 'binance'; + +const customLogger: typeof DefaultLogger = { + ...DefaultLogger, + trace: () => {}, + info: (...params) => console.info(new Date(), ...params), + error: (...params) => console.error(new Date(), ...params), +}; -// Pass the custom logger as the 2nd parameter const ws = new WebsocketClient( { - api_key: key, - api_secret: secret, + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, beautify: true, }, - customLogger + customLogger, ); ``` -## Browser/Frontend Usage +JavaScript cannot precisely represent integers above `Number.MAX_SAFE_INTEGER`. If you need to preserve very large order IDs from WebSocket messages, provide a custom parser: -### Import +```typescript +import { WebsocketClient } from 'binance'; -This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. +const ws = new WebsocketClient({ + customParseJSONFn: (rawEvent) => { + return JSON.parse(rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"')); + }, +}); +``` -1. Install these dependencies - ```sh - npm install crypto-browserify stream-browserify - ``` -2. Add this to your `tsconfig.json` - ```json - { - "compilerOptions": { - "paths": { - "crypto": [ - "./node_modules/crypto-browserify" - ], - "stream": [ - "./node_modules/stream-browserify" - ] - } - ``` -3. Declare this in the global context of your application (ex: in polyfills for angular) - ```js - (window as any).global = window; - ``` +See also: [custom parser example](../examples/WebSockets/Misc/ws-custom-parser.ts) -### Webpack +--- -This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. +## FAQ -Build a bundle using webpack: +**Which REST API client should I use?** -- `npm install` -- `npm build` -- `npm pack` +Use `MainClient` for Spot, margin, wallet, Convert, Earn, sub-account, and many account APIs. Use `USDMClient` for USD-M Futures. Use `CoinMClient` for COIN-M Futures. Use `PortfolioClient` for Portfolio Margin. -The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. +**Do I need API keys for public market data?** -## Use with LLMs & AI +No. Public REST API market data and public WebSocket market data do not require API keys. -This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. +**Can I use one Binance API key for every product group?** -This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. +Sometimes, but only when the key belongs to the right environment and has the required product permissions enabled. Keep live, demo, and testnet credentials separate. Also keep high-risk permissions, especially withdrawals, separate from ordinary trading keys. ---- +**What is the difference between HMAC, RSA, and Ed25519?** - +HMAC is the standard API key + secret flow. RSA and Ed25519 use self-generated private keys. The SDK detects PEM private keys automatically when they are passed as `api_secret`. Ed25519 is recommended for latency-sensitive WebSocket API usage because it supports WebSocket API session authentication. -### Contributions & Thanks +**Why both `WebsocketClient` and `WebsocketAPIClient`?** -Have my projects helped you? Share the love, there are many ways you can show your thanks: +- `WebsocketClient` is for subscriptions and streaming topics. +- `WebsocketAPIClient` is for commands over Binance's WebSocket API. Think "REST API" but over persistent WebSockets. -- Star & share my projects. -- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler -- Have an interesting project? Get in touch & invite me to it. -- Or buy me all the coffee: - - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` -- Sign up with my referral links: - - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 - - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ - - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SDK - - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 +**Should I use listen keys for Spot user data?** - - +**What happens if a WebSocket connection drops?** -### Contributions & Pull Requests +The SDK supports reconnect and resubscribe flows. Listen for `reconnecting` and `reconnected`. Use `reconnected` as a trigger to reconcile state through the REST API before resuming risky trading actions. -Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. +**Should I use demo trading or testnet?** -## Used By +Use demo trading when you want simulated trading with real market data. Use testnet for API wiring, endpoint behavior, and permission checks. Do not treat testnet market behavior as representative of live market behavior. -[![Repository Users Preview Image](https://dependents.info/tiagosiebler/binance/image)](https://github.com/tiagosiebler/binance/network/dependents) +**Can I use this Binance API SDK in TypeScript projects?** - +Yes. The package is TypeScript-first and publishes type declarations. -## Star History +**Do I need TypeScript to use this JavaScript Binance SDK?** -[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) +No. Pure JavaScript projects can use this SDK too. Type declarations are included and will help your IDE, but TypeScript is not required. - +**Can I use this package in both ESM and CommonJS projects?** + +Yes. The package supports both ESM-style imports and CommonJS `require()`. + +**Does this guide cover every SDK method?** + +No. This guide covers the common first steps and production concerns. For full method coverage, see: + +- [Binance JavaScript endpoint reference](./endpointFunctionList.md) +- [Binance SDK examples](../examples) +- [TSDoc documentation](https://tsdocs.dev/docs/binance) + +--- + +## Next steps + +If you want to learn more about integrating with Binance APIs and WebSockets: + +- Explore the [Binance JavaScript examples on GitHub](../examples) +- Review the full endpoint list: [Binance JavaScript endpoint reference](./endpointFunctionList.md) +- Check the Binance JavaScript SDK on npm: [`binance`](https://www.npmjs.com/package/binance) +- Browse the source code of the Binance JavaScript SDK on GitHub: [`tiagosiebler/binance`](https://github.com/tiagosiebler/binance) +- Review auth examples: [Ed25519](../examples/auth/rest-private-ed25519.md) and [RSA](../examples/auth/rest-private-rsa.md) +- Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) ================ -File: src/types/spot.ts +File: src/types/websockets/ws-api-requests.ts ================ import { - ExchangeFilter, - ExchangeSymbol, - GenericCodeMsgError, + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderType, + FuturesOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + BooleanString, + KlineInterval, numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRow, OrderResponseType, OrderSide, - OrderStatus, OrderTimeInForce, OrderType, - RateLimiter, SelfTradePreventionMode, - SideEffects, - StringBoolean, - SymbolFilter, -} from './shared'; -⋮---- -export interface BasicTimeRangeParam { - startTime?: number; - endTime?: number; -} -⋮---- -export interface BasicFromPaginatedParams { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export type SymbolStatus = - | 'PRE_TRADING' - | 'TRADING' - | 'POST_TRADING' - | 'END_OF_DAY' - | 'HALT' - | 'AUCTION_MATCH' - | 'BREAK'; -⋮---- -export interface SystemStatusResponse { - status: 0 | 1; - msg: 'normal' | 'system maintenance'; -} -⋮---- -export interface DailyAccountSnapshotParams { - type: 'SPOT' | 'MARGIN' | 'FUTURES'; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface SpotBalance { - asset: string; - free: numberInString; - locked: numberInString; -} -⋮---- -export interface MarginBalance { - asset: string; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; -} -⋮---- -export interface DailyFuturesBalance { - asset: string; - marginBalance: numberInString; - walletBalance: numberInString; -} -⋮---- -export interface DailyFuturesPositionState { - entryPrice: numberInString; - markPrice: numberInString; - positionAmt: numberInString; - symbol: string; - unRealizedProfit: numberInString; -} -⋮---- -export interface DailySpotAccountSnapshot { - data: { - balances: SpotBalance[]; - totalAssetOfBtc: numberInString; - }; - type: 'spot'; - updateTime: number; -} -⋮---- -export interface DailyMarginAccountSnapshot { - data: { - marginLevel: numberInString; - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; - userAssets: MarginBalance[]; - }; - type: 'margin'; - updateTime: number; -} -⋮---- -export interface DailyFuturesAccountSnapshot { - data: { - assets: DailyFuturesBalance[]; - position: DailyFuturesPositionState[]; - }; - type: 'futures'; - updateTime: number; -} -⋮---- -export type DailyAccountSnapshotElement = - | DailySpotAccountSnapshot - | DailyMarginAccountSnapshot - | DailyFuturesAccountSnapshot; +} from '../shared'; ⋮---- -export interface DailyAccountSnapshot { - code: number; - msg: string; - snapshotVos: DailyAccountSnapshotElement[]; -} +/** + * Simple request params with timestamp (required) & recv window (optional) + */ +export type WSAPIRecvWindowTimestamp = { + recvWindow?: number; + timestamp: number; +}; ⋮---- -export interface CoinNetwork { - addressRegex: string; - coin: string; - depositDesc: string; - depositEnable: boolean; - isDefault: boolean; - memoRegex: string; - minConfirm: number; - name: string; - network: string; - resetAddressStatus: boolean; - specialTips?: string; - specialWithdrawTips?: string; - unlockConfirm: number; - withdrawDesc: string; - withdrawEnable: boolean; - withdrawFee: numberInString; - withdrawMin: numberInString; - withdrawMax: numberInString; - withdrawInternalMin: numberInString; - withdrawIntegerMultiple: numberInString; - depositDust?: numberInString; - sameAddress: boolean; - estimatedArrivalTime: number; - busy: boolean; - contractAddressUrl?: string; - contractAddress?: string; +/** + * + * Authentication request types + * + */ +export interface WSAPISessionLogonRequest { + timestamp: number; } ⋮---- -export interface AllCoinsInformationResponse { - coin: string; - depositAllEnable: boolean; - free: numberInString; - freeze: numberInString; - ipoable: numberInString; - ipoing: numberInString; - isLegalMoney: boolean; - locked: numberInString; - name: string; - networkList: CoinNetwork[]; - storage: numberInString; - trading: boolean; - withdrawAllEnable: boolean; - withdrawing: numberInString; +/** + * + * General request types + * + */ +export interface WSAPIExchangeInfoRequest { + symbol?: string; + symbols?: string[]; + permissions?: string[]; + showPermissionSets?: boolean; + symbolStatus?: string; } ⋮---- -export interface WithdrawParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; -} +/** + * + * Market data request types + * + */ ⋮---- -export interface TransferBrokerSubAccountParams { - fromId?: string; - toId?: string; - clientTranId?: string; - asset: string; - amount: number; +export interface WSAPIOrderBookRequest { + symbol: string; + limit?: number; + symbolStatus?: string; } ⋮---- -export interface ConvertQuoteRequestParams { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - walletType?: string; - validTime?: string; +export interface WSAPITradesRecentRequest { + symbol: string; + limit?: number; } ⋮---- -export interface EnableConvertSubAccountParams { - subAccountId: string; - convert: boolean; +export interface WSAPITradesHistoricalRequest { + symbol: string; + fromId?: number; + limit?: number; } ⋮---- -export interface AcceptQuoteRequestParams { - quoteId: string; +export interface WSAPIBlockTradesHistoricalRequest { + symbol: string; + fromId: number; + limit?: number; } ⋮---- -export interface GetOrderStatusParams { - orderId?: string; - quoteId?: string; +export interface WSAPITradesAggregateRequest { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface GetConvertTradeHistoryParams { - startTime: number; +export interface WSAPIKlinesRequest { + symbol: string; + interval: KlineInterval; + startTime?: number; endTime?: number; - limit?: string; + timeZone?: string; + limit?: number; } ⋮---- -export interface TransferBrokerSubAccount { - txnId: numberInString; +export interface WSAPIAvgPriceRequest { + symbol: string; } ⋮---- -export enum EnumDepositStatus { - Pending = 0, - CreditedButCannotWithdraw = 6, - WrongDeposit = 7, - WaitingUserConfirm = 8, - Success = 1, - Rejected = 2, +/** + * Query execution rules (e.g. PRICE_RANGE). Only one of symbol, symbols, or symbolStatus per request. + */ +export interface WSAPIExecutionRulesRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; } ⋮---- -export type DepositStatusCode = `${EnumDepositStatus}`; -⋮---- -export interface DepositHistoryParams { - coin?: string; // Optional: Filter by coin - status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) - startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) - endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) - offset?: number; // Optional: Pagination offset (Default: 0) - limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) - txId?: string; // Optional: Filter by transaction ID - includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +export interface WSAPIReferencePriceRequest { + symbol: string; } ⋮---- -coin?: string; // Optional: Filter by coin -status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) -startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) -endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) -offset?: number; // Optional: Pagination offset (Default: 0) -limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) -txId?: string; // Optional: Filter by transaction ID -includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) -⋮---- -export interface DepositHistory { - amount: numberInString; - coin: string; - network: string; - status: number; - address: string; - addressTag: string; - txId: string; - insertTime: number; - transferType: number; - confirmTimes: string; +export interface WSAPIReferencePriceCalculationRequest { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; } ⋮---- -export enum EnumWithdrawStatus { - EmailSent = 0, - Cancelled = 1, - AwaitingApproval = 2, - Rejected = 3, - Processing = 4, - Failure = 5, - Completed = 6, +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITicker24hrRequest { + symbol?: string; + symbols?: string[]; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; } ⋮---- -export type WithdrawStatusCode = `${EnumWithdrawStatus}`; +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerTradingDayRequest { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} ⋮---- -export interface WithdrawHistoryParams { - coin?: string; // Optional: Filter by coin - withdrawOrderId?: string; // Optional: Filter by withdraw order ID - status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) - offset?: number; // Optional: Pagination offset - limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) - idList?: string; // Optional: Comma-separated list of withdrawal IDs - startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) - endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerRequest { + symbol?: string; + symbols?: string[]; + windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' + type?: 'FULL' | 'MINI'; + symbolStatus?: string; } ⋮---- -coin?: string; // Optional: Filter by coin -withdrawOrderId?: string; // Optional: Filter by withdraw order ID -status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) -offset?: number; // Optional: Pagination offset -limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) -idList?: string; // Optional: Comma-separated list of withdrawal IDs -startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) -endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerPriceRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} ⋮---- -export enum EnumWithdrawTransferType { - External = 0, - Interal = 1, +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerBookRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; } ⋮---- -export type WithdrawTransferType = `${EnumWithdrawTransferType}`; +/** + * + * Account request types - Spot + * + */ ⋮---- -export interface WithdrawHistory { - address: string; - amount: numberInString; - applyTime: string; - coin: string; - id: string; - withdrawOrderId: string; - network: string; - transferType: WithdrawTransferType; - status: number; - transactionFee: numberInString; - txId: string; +export interface WSAPIAllOrdersRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface DepositAddressParams { - coin: string; - network?: string; - amount?: number; +export interface WSAPIAllOrderListsRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface DepositAddressResponse { - address: string; - coin: string; - tag: string; - url: string; +export interface WSAPIMyTradesRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; } ⋮---- -export interface ConvertDustParams { - asset: string[]; - accountType?: 'SPOT' | 'MARGIN'; +export interface WSAPIMyPreventedMatchesRequest { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; } ⋮---- -export type DustConvertAccountType = 'SPOT' | 'MARGIN'; -⋮---- -export interface DustConvertParams { - asset: string[]; - accountType?: DustConvertAccountType; - clientId?: string; - targetAsset?: string; - thirdPartyClientId?: string; - dustQuotaAssetToTargetAssetPrice?: numberInString; +export interface WSAPIMyAllocationsRequest { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; } ⋮---- -export interface DustConvertibleAssetsParams { - targetAsset: string; - accountType?: DustConvertAccountType; - dustQuotaAssetToTargetAssetPrice?: numberInString; -} +/** + * Trading request types + */ ⋮---- -export interface DustConvertibleAssetDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - exchange: numberInString; - toQuotaAssetAmount: numberInString; - toTargetAssetAmount: numberInString; - toTargetAssetOffExchange: numberInString; +export interface WSAPINewSpotOrderRequest { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: string; } ⋮---- -export interface DustConvertibleAssetsResponse { - dribbletPercentage: numberInString; - totalTransferQuotaAssetAmount: numberInString; - totalTransferTargetAssetAmount: numberInString; - dribbletBase: numberInString; - details: DustConvertibleAssetDetail[]; +export interface WSAPIOrderTestRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: string; + computeCommissionRates?: boolean; + timestamp: number; + recvWindow?: number; } ⋮---- -export interface DustInfoDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - toBTC: numberInString; - toBNB: numberInString; - toBNBOffExchange: numberInString; - exchange: numberInString; +export interface WSAPIOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface DustInfo { - details: DustInfoDetail[]; - totalTransferBtc: numberInString; - totalTransferBNB: numberInString; - dribbletPercentage: numberInString; +export interface WSAPIOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface DustConversionResult { - amount: numberInString; - fromAsset: string; - operateTime: number; - serviceChargeAmount: numberInString; - tranId: number; - transferedAmount: numberInString; +export interface WSAPIOrderCancelReplaceRequest { + symbol: string; + cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; + cancelOrderId?: number; + cancelOrigClientOrderId?: string; + cancelNewClientOrderId?: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface DustConversion { - totalServiceCharge: numberInString; - totalTransfered: numberInString; - transferResult: DustConversionResult[]; +export interface WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface UserAssetDribbletDetail { - transId: number; - serviceChargeAmount: numberInString; - amount: numberInString; - operateTime: number; - transferedAmount: numberInString; - fromAsset: string; +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface UserAssetDribblet { - operateTime: number; - totalTransferedAmount: numberInString; - totalServiceChargeAmount: numberInString; - transId: number; - userAssetDribbletDetails: UserAssetDribbletDetail[]; +export interface WSAPIOpenOrdersCancelAllRequest { + symbol: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface DustLog { - total: number; - userAssetDribblets: UserAssetDribblet[]; +/** + * Order list request types + */ +export interface WSAPIOrderListPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + price: numberInString; + quantity: numberInString; + listClientOrderId?: string; + limitClientOrderId?: string; + limitIcebergQty?: numberInString; + limitStrategyId?: number; + limitStrategyType?: number; + stopPrice?: numberInString; + trailingDelta?: number; + stopClientOrderId?: string; + stopLimitPrice?: numberInString; + stopLimitTimeInForce?: string; + stopIcebergQty?: numberInString; + stopStrategyId?: number; + stopStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export enum EnumUniversalTransferType { - SpotToUSDM = 'MAIN_UMFUTURE', - SpotToCOINM = 'MAIN_CMFUTURE', - SpotToMargin = 'MAIN_MARGIN', - SpotToFunding = 'MAIN_FUNDING', - SpotToOptions = 'MAIN_OPTION', - FundingToSpot = 'FUNDING_MAIN', - FundingToUSDM = 'FUNDING_UMFUTURE', - FundingToCOINM = 'FUNDING_CMFUTURE', - FundingToMargin = 'FUNDING_MARGIN', - FundingToOptions = 'FUNDING_OPTION', - USDMToSpot = 'UMFUTURE_MAIN', - USDMToFunding = 'UMFUTURE_FUNDING', - USDMToMargin = 'UMFUTURE_MARGIN', - USDMToOptions = 'UMFUTURE_OPTION', - COINMToSpot = 'CMFUTURE_MAIN', - COINMToFunding = 'CMFUTURE_FUNDING', - COINMToMargin = 'CMFUTURE_MARGIN', - MarginToSpot = 'MARGIN_MAIN', - MarginToUSDM = 'MARGIN_UMFUTURE', - MarginToCOINM = 'MARGIN_CMFUTURE', - MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', - MarginToFunding = 'MARGIN_FUNDING', - MarginToOptions = 'MARGIN_OPTION', - IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', - IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', - OptionsToSpot = 'OPTION_MAIN', - OptionsToUSDM = 'OPTION_UMFUTURE', - OptionsToFunding = 'OPTION_FUNDING', - OptionsToMargin = 'OPTION_MARGIN', +export interface WSAPIOrderListPlaceOCORequest { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: numberInString; + listClientOrderId?: string; + aboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + aboveClientOrderId?: string; + aboveIcebergQty?: numberInString; + abovePrice?: numberInString; + aboveStopPrice?: numberInString; + aboveTrailingDelta?: number; + aboveTimeInForce?: string; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + belowClientOrderId?: string; + belowIcebergQty?: numberInString; + belowPrice?: numberInString; + belowStopPrice?: numberInString; + belowTrailingDelta?: number; + belowTimeInForce?: string; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export type UniversalTransferType = `${EnumUniversalTransferType}`; -⋮---- -export interface UniversalTransferParams { - type: UniversalTransferType; - asset: string; - amount: number; - fromSymbol: string; - toSymbol: string; +export interface WSAPIOrderListPlaceOTORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingQuantity: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface UniversalTransferHistoryParams { - type: UniversalTransferType; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface WSAPIOrderListPlaceOTOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: number | string; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: numberInString; + pendingAboveStopPrice?: numberInString; + pendingAboveTrailingDelta?: numberInString; + pendingAboveIcebergQty?: numberInString; + pendingAboveTimeInForce?: string; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingBelowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface ExchangeInfoParams { - symbol?: string; - symbols?: string[]; - permissions?: string | string[]; - showPermissionSets?: boolean; - symbolStatus?: string; +export interface WSAPIOrderListPlaceOPORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface NewSpotOrderParams< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> { +export interface WSAPIOrderListPlaceOPOCORequest { symbol: string; - side: OrderSide; - type: T; - timeInForce?: OrderTimeInForce; - quantity?: number; - quoteOrderQty?: number; - price?: number; - newClientOrderId?: string; - strategyId?: number; - strategyType?: number; - stopPrice?: number; - trailingDelta?: number; - icebergQty?: number; - newOrderRespType?: RT; - isIsolated?: StringBoolean; - sideEffectType?: SideEffects; - autoRepayAtCancel?: StringBoolean; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingSide: 'BUY' | 'SELL'; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: numberInString; + pendingAboveStopPrice?: numberInString; + pendingAboveTrailingDelta?: numberInString; + pendingAboveIcebergQty?: numberInString; + pendingAboveTimeInForce?: string; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingAbovePegPriceType?: string; + pendingAbovePegOffsetType?: string; + pendingAbovePegOffsetValue?: number; + pendingBelowType?: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; -export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; -⋮---- -export interface ReplaceSpotOrderParams< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends NewSpotOrderParams { - cancelReplaceMode: CancelReplaceMode; - cancelNewClientOrderId?: string; - cancelOrigClientOrderId?: string; - cancelOrderId?: number; - cancelRestrictions?: CancelRestrictions; +export interface WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface GetOCOParams { - symbol?: string; +export interface WSAPIOrderListCancelRequest { + symbol: string; orderListId?: number; - origClientOrderId?: string; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface NewSpotSOROrderParams { +/** + * SOR request types + */ +export interface WSAPISOROrderPlaceRequest { symbol: string; - side: OrderSide; - type: OrderType; - timeInForce?: OrderTimeInForce; - quantity: number; - price?: number; + side: 'BUY' | 'SELL'; + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + price?: numberInString; + quantity: numberInString; newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + icebergQty?: numberInString; strategyId?: number; strategyType?: number; - icebergQty?: number; - newOrderRespType?: OrderResponseType; - selfTradePreventionMode?: SelfTradePreventionMode; -} -⋮---- -export type APILockTriggerCondition = 'GCR' | 'IFER' | 'UFR'; -⋮---- -export interface APITriggerConditionSymbolStatus { - i: APILockTriggerCondition; - c: number; - v: number; - t: number; -} -⋮---- -export interface APITradingStatus { - data: { - isLocked: boolean; - plannedRecoverTime: number; - triggerCondition: Record; - indicators: Record; - updateTime: number; - }; -} -⋮---- -export interface APIPermissions { - ipRestrict: boolean; - createTime: number; - enableReading: boolean; - enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals - enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly - enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed - enableFutures: boolean; // API Key created before your futures account opened does not support futures API service - permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization - enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading - enableSpotAndMarginTrading: boolean; // Spot and margin trading - tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission - enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading - enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading - enablePortfolioMarginTrading: true; + selfTradePreventionMode?: string; + timestamp: number; + recvWindow?: number; } ⋮---- -enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals -enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly -enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed -enableFutures: boolean; // API Key created before your futures account opened does not support futures API service -permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization -enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading -enableSpotAndMarginTrading: boolean; // Spot and margin trading -tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission -enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading -enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading -⋮---- -export interface AssetDetail { - minWithdrawAmount: numberInString; - depositStatus: boolean; - withdrawFee: number; - withdrawStatus: boolean; - depositTip?: string; -} +export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { + computeCommissionRates?: boolean; +}; ⋮---- -export interface SymbolTradeFee { - symbol: string; - makerCommission: numberInString; - takerCommission: numberInString; -} +/** + * Futures market data request types + */ ⋮---- -export interface SymbolExchangeInfo { +export interface WSAPIFuturesOrderBookRequest { symbol: string; - status: string; - baseAsset: string; - baseAssetPrecision: number; - quoteAsset: string; - quotePrecision: number; - quoteAssetPrecision: number; - baseCommissionPrecision: number; - quoteCommissionPrecision: number; - orderTypes: OrderType[]; - icebergAllowed: boolean; - ocoAllowed: boolean; - opoAllowed: boolean; - quoteOrderQtyMarketAllowed: boolean; - allowTrailingStop: boolean; - cancelReplaceAllowed: boolean; - isSpotTradingAllowed: boolean; - isMarginTradingAllowed: boolean; - filters: SymbolFilter[]; - permissions: ('SPOT' | 'MARGIN')[]; - defaultSelfTradePreventionMode: SelfTradePreventionMode; - allowedSelfTradePreventionModes: SelfTradePreventionMode[]; -} -⋮---- -export interface ExchangeInfo { - timezone: string; - serverTime: number; - rateLimits: RateLimiter[]; - exchangeFilters: ExchangeFilter[]; - symbols: SymbolExchangeInfo[]; -} -⋮---- -export interface OrderBookResponse { - lastUpdateId: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; + limit?: number; } ⋮---- -export interface RawTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; } ⋮---- -export interface BlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; } ⋮---- -export interface HistoricalBlockTradesParams { - symbol: string; - fromId: number; - limit?: number; -} +/** + * Futures trading request types + */ ⋮---- -export interface RawAccountTrade { +export interface WSAPINewFuturesOrderRequest { symbol: string; - id: number; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isBestMatch: boolean; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesOrderType; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberType; + newClientOrderId?: string; + stopPrice?: numberType; + closePosition?: BooleanString; + activationPrice?: numberType; + callbackRate?: numberType; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: 'ACK' | 'RESULT'; + selfTradePreventionMode?: SelfTradePreventionMode; + priceMatch?: PriceMatchMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD + recvWindow?: number; + timestamp: number; } ⋮---- -export interface AggregateTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; - M: boolean; -} +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -export interface CurrentAvgPrice { - mins: number; +export interface WSAPIFuturesOrderModifyRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + side: 'BUY' | 'SELL'; + quantity: numberInString; price: numberInString; - closeTime: number; -} -⋮---- -/** Spot PRICE_RANGE execution rule (GET /api/v3/executionRules). */ -export interface SpotPriceRangeExecutionRule { - ruleType: 'PRICE_RANGE'; - bidLimitMultUp: numberInString; - bidLimitMultDown: numberInString; - askLimitMultUp: numberInString; - askLimitMultDown: numberInString; + priceMatch?: + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; + origType?: string; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface SpotSymbolExecutionRules { +export interface WSAPIFuturesOrderCancelRequest { symbol: string; - rules: SpotPriceRangeExecutionRule[]; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface SpotExecutionRulesResponse { - symbolRules: SpotSymbolExecutionRules[]; +export interface WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ -export interface SpotExecutionRulesParams { +export interface WSAPIFuturesPositionRequest { symbol?: string; - symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + recvWindow?: number; + timestamp: number; } ⋮---- -/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ -export interface SpotReferencePriceResponse { - symbol: string; - referencePrice: numberInString | null; +export interface WSAPIFuturesPositionV2Request { + symbol?: string; + recvWindow?: number; timestamp: number; } ⋮---- -/** GET /api/v3/referencePrice or /referencePrice/calculation when no reference price has ever been set (code -2043). */ -export interface SpotReferencePriceNeverSetError { - code: -2043; - msg: string; +export interface WSAPIAccountInformationRequest { + omitZeroBalances?: boolean; + recvWindow?: number; + timestamp: number; } ⋮---- -export type SpotReferencePriceResult = - | SpotReferencePriceResponse - | SpotReferencePriceNeverSetError; -⋮---- -/** Reference price is computed as an arithmetic mean in the matching engine. */ -export interface SpotReferencePriceCalculationArithmeticMean { +export interface WSAPIAccountCommissionWSAPIRequest { symbol: string; - calculationType: 'ARITHMETIC_MEAN'; - bucketCount: number; - bucketWidthMs: number; } ⋮---- -/** Reference price is computed outside the matching engine. */ -export interface SpotReferencePriceCalculationExternal { +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api + */ +export interface WSAPINewFuturesAlgoOrderRequest { + algoType: FuturesAlgoOrderType; symbol: string; - calculationType: 'EXTERNAL'; - externalCalculationId: number; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesAlgoConditionalOrderTypes; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberInString; + clientAlgoId?: string; + triggerPrice?: numberInString; + closePosition?: BooleanString; + activatePrice?: numberInString; + callbackRate?: numberInString; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: OrderResponseType; + priceMatch?: PriceMatchMode; + selfTradePreventionMode?: SelfTradePreventionMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD + recvWindow?: number; + timestamp: number; } ⋮---- -export type SpotReferencePriceCalculationResponse = - | SpotReferencePriceCalculationArithmeticMean - | SpotReferencePriceCalculationExternal - | SpotReferencePriceNeverSetError; +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -export interface DailyChangeStatistic { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - prevClosePrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order + */ +export interface WSAPIFuturesAlgoOrderCancelRequest { + algoid?: number; + clientalgoid?: string; + recvWindow?: number; + timestamp: number; } + +================ +File: src/types/websockets/ws-api.ts +================ +import { WS_KEY_MAP, WsKey } from '../../util/websockets/websocket-util'; +import { FuturesExchangeInfo } from '../futures'; +import { + ExchangeInfo, + SpotExecutionRulesResponse, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, +} from '../spot'; +import { + WSAPIAccountCommissionWSAPIRequest, + WSAPIAccountInformationRequest, + WSAPIAllOrderListsRequest, + WSAPIAllOrdersRequest, + WSAPIAvgPriceRequest, + WSAPIBlockTradesHistoricalRequest, + WSAPIExchangeInfoRequest, + WSAPIExecutionRulesRequest, + WSAPIFuturesAlgoOrderCancelRequest, + WSAPIFuturesOrderBookRequest, + WSAPIFuturesOrderCancelRequest, + WSAPIFuturesOrderModifyRequest, + WSAPIFuturesOrderStatusRequest, + WSAPIFuturesTickerBookRequest, + WSAPIFuturesTickerPriceRequest, + WSAPIKlinesRequest, + WSAPIMyAllocationsRequest, + WSAPIMyPreventedMatchesRequest, + WSAPIMyTradesRequest, + WSAPINewFuturesAlgoOrderRequest, + WSAPINewFuturesOrderRequest, + WSAPINewSpotOrderRequest, + WSAPIOpenOrdersCancelAllRequest, + WSAPIOpenOrdersStatusRequest, + WSAPIOrderAmendKeepPriorityRequest, + WSAPIOrderBookRequest, + WSAPIOrderCancelReplaceRequest, + WSAPIOrderCancelRequest, + WSAPIOrderListCancelRequest, + WSAPIOrderListPlaceOCORequest, + WSAPIOrderListPlaceOPOCORequest, + WSAPIOrderListPlaceOPORequest, + WSAPIOrderListPlaceOTOCORequest, + WSAPIOrderListPlaceOTORequest, + WSAPIOrderListPlaceRequest, + WSAPIOrderListStatusRequest, + WSAPIOrderStatusRequest, + WSAPIOrderTestRequest, + WSAPIRecvWindowTimestamp, + WSAPIReferencePriceCalculationRequest, + WSAPIReferencePriceRequest, + WSAPISessionLogonRequest, + WSAPISOROrderPlaceRequest, + WSAPISOROrderTestRequest, + WSAPITicker24hrRequest, + WSAPITickerBookRequest, + WSAPITickerPriceRequest, + WSAPITickerRequest, + WSAPITickerTradingDayRequest, + WSAPITradesAggregateRequest, + WSAPITradesHistoricalRequest, + WSAPITradesRecentRequest, +} from './ws-api-requests'; +import { + WSAPIAccountCommission, + WSAPIAccountInformation, + WSAPIAggregateTrade, + WSAPIAllocation, + WSAPIAvgPrice, + WSAPIBlockTrade, + WSAPIBookTicker, + WSAPIFullTicker, + WSAPIFuturesAccountBalanceItem, + WSAPIFuturesAccountStatus, + WSAPIFuturesAlgoOrder, + WSAPIFuturesAlgoOrderCancelResponse, + WSAPIFuturesBookTicker, + WSAPIFuturesOrder, + WSAPIFuturesOrderBook, + WSAPIFuturesPosition, + WSAPIFuturesPositionV2, + WSAPIFuturesPriceTicker, + WSAPIKline, + WSAPIMiniTicker, + WSAPIOrder, + WSAPIOrderBook, + WSAPIOrderCancel, + WSAPIOrderCancelReplaceResponse, + WSAPIOrderListCancelResponse, + WSAPIOrderListPlaceResponse, + WSAPIOrderListStatusResponse, + WSAPIOrderTestResponse, + WSAPIOrderTestWithCommission, + WSAPIPreventedMatch, + WSAPIPriceTicker, + WSAPIRateLimit, + WSAPIServerTime, + WSAPISessionStatus, + WSAPISOROrderPlaceResponse, + WSAPISOROrderTestResponse, + WSAPISOROrderTestResponseWithCommission, + WSAPISpotOrderResponse, + WSAPITrade, +} from './ws-api-responses'; +⋮---- +/** + * Standard WS commands (for consumers) + */ +export type WsOperation = + | 'SUBSCRIBE' + | 'UNSUBSCRIBE' + | 'LIST_SUBSCRIPTIONS' + | 'SET_PROPERTY' + | 'GET_PROPERTY'; +⋮---- +/** + * WS API commands (for sending requests via WS) + */ +⋮---- +//// General commands +⋮---- +//// Market data commands +⋮---- +//// Account commands +// Spot +⋮---- +// Futures +⋮---- +//// Trading commands +⋮---- +// Order list commands +⋮---- +// SOR commands +⋮---- +// user data stream ⋮---- -export interface SymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; +export interface WSAPIUserDataListenKeyRequest { + apiKey: string; + listenKey: string; } ⋮---- -export interface OrderResponseACK { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; -} +export type WsAPIOperation = (typeof WS_API_Operations)[number]; ⋮---- -export interface OrderResponseResult { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; +export interface WsRequestOperationBinance< + TWSTopic extends string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + TWSParams extends object = any, +> { + method: WsOperation | WsAPIOperation; + params?: (TWSTopic | string | number)[] | TWSParams; + id: number; } ⋮---- -/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -export interface OrderFill { - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; +export interface WSAPIResponse { + /** Auto-generated */ + id: string; + + status: number; + result: TResponseData; + rateLimits: { + rateLimitType: 'REQUEST_WEIGHT'; + interval: 'MINUTE'; + intervalNum: number; + limit: number; + count: number; + }[]; + + wsKey: WsKey; + isWSAPIResponse: boolean; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + request?: any; } ⋮---- -export interface OrderResponseFull { - symbol: string; - orderId: number; - orderListId?: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - marginBuyBorrowAmount?: number; - marginBuyBorrowAsset?: string; - isIsolated?: boolean; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; - fills: OrderFill[]; -} +/** Auto-generated */ ⋮---- -/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -export type OrderResponse = - | OrderResponseACK - | OrderResponseResult - | OrderResponseFull; +export type Exact = { + // This part says: if there's any key that's not in T, it's an error + // This conflicts sometimes for some reason... + // [K: string]: never; +} & { + [K in keyof T]: T[K]; +}; ⋮---- -export type OrderResponseTypeFor< - RT extends OrderResponseType | undefined = undefined, - T extends OrderType | undefined = undefined, -> = RT extends 'ACK' - ? OrderResponseACK - : RT extends 'RESULT' - ? OrderResponseResult - : RT extends 'FULL' - ? OrderResponseFull - : T extends 'MARKET' | 'LIMIT' - ? OrderResponseFull - : OrderResponseACK; +// This part says: if there's any key that's not in T, it's an error +// This conflicts sometimes for some reason... +// [K: string]: never; ⋮---- -export interface OrderListOrder { - symbol: string; - orderId: number; - clientOrderId: string; - /** Present only for expired orders. */ - expiryReason?: string; +/** + * List of operations supported for this WsKey (connection) + */ +export interface WsAPIWsKeyTopicMap { + [WS_KEY_MAP.main]: WsOperation; + [WS_KEY_MAP.main2]: WsOperation; + [WS_KEY_MAP.main3]: WsOperation; + + [WS_KEY_MAP.mainTestnetPublic]: WsOperation; + [WS_KEY_MAP.mainTestnetUserData]: WsOperation; + + [WS_KEY_MAP.marginRiskUserData]: WsOperation; + [WS_KEY_MAP.marginUserData]: WsAPIOperation; + [WS_KEY_MAP.usdm]: WsOperation; + [WS_KEY_MAP.usdmTestnet]: WsOperation; + + [WS_KEY_MAP.coinm]: WsOperation; + [WS_KEY_MAP.coinm2]: WsOperation; + [WS_KEY_MAP.coinmTestnet]: WsOperation; + [WS_KEY_MAP.eoptions]: WsOperation; + [WS_KEY_MAP.portfolioMarginUserData]: WsOperation; + [WS_KEY_MAP.portfolioMarginProUserData]: WsOperation; + + [WS_KEY_MAP.alpha]: WsOperation; + + [WS_KEY_MAP.mainWSAPI]: WsAPIOperation; + [WS_KEY_MAP.mainWSAPI2]: WsAPIOperation; + [WS_KEY_MAP.mainWSAPITestnet]: WsAPIOperation; + + [WS_KEY_MAP.usdmWSAPI]: WsAPIOperation; + [WS_KEY_MAP.usdmWSAPITestnet]: WsAPIOperation; + + [WS_KEY_MAP.coinmWSAPI]: WsAPIOperation; + [WS_KEY_MAP.coinmWSAPITestnet]: WsAPIOperation; +} +⋮---- +export type WsAPIFuturesWsKey = + | typeof WS_KEY_MAP.usdmWSAPI + | typeof WS_KEY_MAP.usdmWSAPITestnet; +⋮---- +/** + * Request parameters expected per operation. + * + * - Each "key" here is the name of the command/operation. + * - Each "value" here has the parameters required for the command. + * + * Make sure to add new topics to WS_API_Operations and the response param map too. + */ +export interface WsAPITopicRequestParamMap { + SUBSCRIBE: never; + UNSUBSCRIBE: never; + LIST_SUBSCRIPTIONS: never; + SET_PROPERTY: never; + GET_PROPERTY: never; + + /** + * Authentication commands & parameters: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests + */ + 'session.logon': WSAPISessionLogonRequest; + 'session.status': void; + 'session.logout': void; + + /** + * General requests & parameters: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests + */ + ping: void; + time: void; + + exchangeInfo: void | WSAPIExchangeInfoRequest; + + /** + * Market data requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api + */ + depth: TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesOrderBookRequest + : WSAPIOrderBookRequest; + 'trades.recent': WSAPITradesRecentRequest; + 'trades.historical': WSAPITradesHistoricalRequest; + 'blockTrades.historical': WSAPIBlockTradesHistoricalRequest; + 'trades.aggregate': WSAPITradesAggregateRequest; + klines: WSAPIKlinesRequest; + uiKlines: WSAPIKlinesRequest; + avgPrice: WSAPIAvgPriceRequest; + executionRules: void | WSAPIExecutionRulesRequest; + referencePrice: WSAPIReferencePriceRequest; + 'referencePrice.calculation': WSAPIReferencePriceCalculationRequest; + 'ticker.24hr': void | WSAPITicker24hrRequest; + 'ticker.tradingDay': WSAPITickerTradingDayRequest; + ticker: WSAPITickerRequest; + 'ticker.price': void | TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesTickerPriceRequest | undefined + : WSAPITickerPriceRequest | undefined; + 'ticker.book': void | TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesTickerBookRequest | undefined + : WSAPITickerBookRequest | undefined; + + /** + * Account requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ + + 'account.status': + | void + | (TWSKey extends WsAPIFuturesWsKey + ? WSAPIRecvWindowTimestamp + : WSAPIAccountInformationRequest); + + 'account.rateLimits.orders': void | WSAPIRecvWindowTimestamp; + + allOrders: WSAPIAllOrdersRequest; + + allOrderLists: void | WSAPIAllOrderListsRequest; + + myTrades: WSAPIMyTradesRequest; + + myPreventedMatches: WSAPIMyPreventedMatchesRequest; + + myAllocations: WSAPIMyAllocationsRequest; + + 'account.commission': WSAPIAccountCommissionWSAPIRequest; + + /** + * Futures account requests & parameters: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ + 'account.position': WSAPIRecvWindowTimestamp; + + 'v2/account.position': WSAPIRecvWindowTimestamp; + + 'account.balance': WSAPIRecvWindowTimestamp; + + 'v2/account.balance': WSAPIRecvWindowTimestamp; + + 'v2/account.status': WSAPIRecvWindowTimestamp; + + /** + * Trading requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ + 'order.place': (TWSKey extends WsAPIFuturesWsKey + ? WSAPINewFuturesOrderRequest + : WSAPINewSpotOrderRequest) & { + timestamp?: number; + }; + 'order.test': WSAPIOrderTestRequest; + 'order.status': TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesOrderStatusRequest + : WSAPIOrderStatusRequest; + 'order.cancel': TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesOrderCancelRequest + : WSAPIOrderCancelRequest; + 'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures + 'order.cancelReplace': WSAPIOrderCancelReplaceRequest; + 'order.amend.keepPriority': WSAPIOrderAmendKeepPriorityRequest; + 'openOrders.status': WSAPIOpenOrdersStatusRequest; + 'openOrders.cancelAll': WSAPIOpenOrdersCancelAllRequest; + + 'algoOrder.place': WSAPINewFuturesAlgoOrderRequest; + 'algoOrder.cancel': WSAPIFuturesAlgoOrderCancelRequest; + + /** + * Order list requests & parameters: + */ + 'orderList.place': WSAPIOrderListPlaceRequest; + 'orderList.place.oco': WSAPIOrderListPlaceOCORequest; + 'orderList.place.oto': WSAPIOrderListPlaceOTORequest; + 'orderList.place.otoco': WSAPIOrderListPlaceOTOCORequest; + 'orderList.place.opo': WSAPIOrderListPlaceOPORequest; + 'orderList.place.opoco': WSAPIOrderListPlaceOPOCORequest; + 'orderList.status': WSAPIOrderListStatusRequest; + 'orderList.cancel': WSAPIOrderListCancelRequest; + + 'openOrderLists.status': WSAPIRecvWindowTimestamp; + + /** + * SOR requests & parameters: + */ + 'sor.order.place': WSAPISOROrderPlaceRequest; + 'sor.order.test': WSAPISOROrderTestRequest; + + /** + * User data stream: + * + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests + * + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + * + * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. + */ + 'userDataStream.start': { apiKey: string }; + 'userDataStream.ping': WSAPIUserDataListenKeyRequest; + 'userDataStream.stop': WSAPIUserDataListenKeyRequest; + 'userDataStream.subscribe': void; + 'userDataStream.subscribe.signature': { timestamp: number }; + 'userDataStream.unsubscribe': void; + + /** + * User data streams, margin: + */ + 'userDataStream.subscribe.listenToken': { listenToken: string }; } ⋮---- -/** Present only for expired orders. */ -⋮---- -export interface OrderListResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: [OrderListOrder, OrderListOrder]; - orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; -} +/** + * Authentication commands & parameters: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests + */ ⋮---- -export interface OrderList { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: [OrderListOrder, OrderListOrder]; -} -export interface SOROrderFill { - matchType: string; - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; - tradeId: number; - allocId: number; -} +/** + * General requests & parameters: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests + */ ⋮---- -export type SOROrderResponseFull = OrderResponseFull & { - workingTime: number; - fills: SOROrderFill[]; - workingFloor: string; - selfTradePreventionMode: string; - usedSor: true; -}; +/** + * Market data requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api + */ ⋮---- -export interface SORTestOrderResponse { - standardCommissionForOrder: { - //Standard commission rates on trades from the order. - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - //Tax commission rates for trades from the order. - maker: numberInString; - taker: numberInString; - }; - discount: { - //Discount on standard commissions when paying in BNB. - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. - }; -} +/** + * Account requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ ⋮---- -//Standard commission rates on trades from the order. +/** + * Futures account requests & parameters: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ ⋮---- -//Tax commission rates for trades from the order. +/** + * Trading requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ ⋮---- -//Discount on standard commissions when paying in BNB. +'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures ⋮---- -discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. +/** + * Order list requests & parameters: + */ ⋮---- -export interface CancelSpotOrderResult { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - selfTradePreventionMode: SelfTradePreventionMode; -} +/** + * SOR requests & parameters: + */ ⋮---- -export interface CancelOrderListResult extends OrderList { - orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; -} +/** + * User data stream: + * + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests + * + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + * + * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. + */ ⋮---- -export interface GenericReplaceSpotOrderResult { - cancelResult: 'SUCCESS' | 'FAILURE'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: C; - newOrderResponse: N; -} +/** + * User data streams, margin: + */ ⋮---- -export interface ReplaceSpotOrderCancelStopFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'NOT_ATTEMPTED'; +/** + * Response structure expected for each operation + * + * - Each "key" here is a command/request supported by the WS API + * - Each "value" here is the response schema for that command. + */ +export interface WsAPIOperationResponseMap { + [key: string]: unknown; + + SUBSCRIBE: never; + UNSUBSCRIBE: never; + LIST_SUBSCRIPTIONS: never; + SET_PROPERTY: never; + GET_PROPERTY: never; + + /** + * Session authentication responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests + */ + 'session.login': WSAPIResponse; + 'session.status': WSAPIResponse; + 'session.logout': WSAPIResponse; + + /** + * General responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests + */ + + ping: unknown; + time: WSAPIResponse; + exchangeInfo: WSAPIResponse; + + /** + * Market data responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api + */ + depth: WSAPIResponse; + 'trades.recent': WSAPIResponse; + 'trades.historical': WSAPIResponse; + 'blockTrades.historical': WSAPIResponse; + 'trades.aggregate': WSAPIResponse; + klines: WSAPIResponse; + uiKlines: WSAPIResponse; + avgPrice: WSAPIResponse; + executionRules: WSAPIResponse; + referencePrice: WSAPIResponse; + 'referencePrice.calculation': WSAPIResponse; + 'ticker.24hr': WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + >; + 'ticker.tradingDay': WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + >; + ticker: WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + >; + 'ticker.price': WSAPIResponse< + | WSAPIPriceTicker + | WSAPIPriceTicker[] + | WSAPIFuturesPriceTicker + | WSAPIFuturesPriceTicker[] + >; + 'ticker.book': WSAPIResponse< + | WSAPIBookTicker + | WSAPIBookTicker[] + | WSAPIFuturesBookTicker + | WSAPIFuturesBookTicker[] + >; + + /** + * Account responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + */ + + 'account.status': WSAPIResponse< + WSAPIAccountInformation | WSAPIFuturesAccountStatus + >; + 'account.commission': WSAPIResponse; + 'account.rateLimits.orders': WSAPIResponse; + allOrders: WSAPIResponse; + allOrderLists: WSAPIResponse; + myTrades: WSAPIResponse; + myPreventedMatches: WSAPIResponse; + myAllocations: WSAPIResponse; + + /** + * Futures account responses: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ + 'account.position': WSAPIResponse; + 'v2/account.position': WSAPIResponse; + 'account.balance': WSAPIResponse; + 'v2/account.balance': WSAPIResponse; + 'v2/account.status': WSAPIResponse; + + /** + * Trading responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ + 'order.place': WSAPIResponse; + 'order.test': WSAPIResponse< + WSAPIOrderTestResponse | WSAPIOrderTestWithCommission + >; + 'order.status': WSAPIResponse; + 'order.cancel': WSAPIResponse; + 'order.modify': WSAPIResponse; + 'order.cancelReplace': WSAPIResponse; + 'openOrders.status': WSAPIResponse; + 'openOrders.cancelAll': WSAPIResponse< + (WSAPIOrderCancel | WSAPIOrderListCancelResponse)[] + >; + 'algoOrder.place': WSAPIResponse; + 'algoOrder.cancel': WSAPIResponse; + /** + * Order list responses + */ + 'orderList.place': WSAPIResponse; + 'orderList.place.oco': WSAPIResponse; + 'orderList.place.oto': WSAPIResponse; + 'orderList.place.otoco': WSAPIResponse; + 'orderList.place.opo': WSAPIResponse; + 'orderList.place.opoco': WSAPIResponse; + 'orderList.status': WSAPIResponse; + 'orderList.cancel': WSAPIResponse; + 'openOrderLists.status': WSAPIResponse; + + /** + * SOR responses + */ + 'sor.order.place': WSAPIResponse; + 'sor.order.test': WSAPIResponse< + WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission + >; + + 'userDataStream.start': WSAPIResponse<{ listenKey: string }>; + 'userDataStream.ping': WSAPIResponse; + 'userDataStream.stop': WSAPIResponse; + 'userDataStream.subscribe': WSAPIResponse; + 'userDataStream.subscribe.signature': WSAPIResponse; + 'userDataStream.unsubscribe': WSAPIResponse; } ⋮---- -export interface ReplaceSpotOrderNewFailure - extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - GenericCodeMsgError - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'FAILURE'; -} +/** + * Session authentication responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests + */ ⋮---- -export interface ReplaceSpotOrderCancelAllowFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'SUCCESS'; -} +/** + * General responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests + */ ⋮---- -export interface ReplaceSpotOrderCancelAllFailure - extends GenericReplaceSpotOrderResult< - GenericCodeMsgError, - GenericCodeMsgError - > { - cancelResult: 'FAILURE'; - newOrderResult: 'FAILURE'; -} +/** + * Market data responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api + */ ⋮---- -export interface ReplaceSpotOrderResultError { - data: - | ReplaceSpotOrderCancelStopFailure - | ReplaceSpotOrderNewFailure - | ReplaceSpotOrderCancelAllowFailure - | ReplaceSpotOrderCancelAllFailure; -} +/** + * Account responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + */ ⋮---- -export interface ReplaceSpotOrderResultSuccess< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - OrderResponseTypeFor - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'SUCCESS'; -} +/** + * Futures account responses: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ ⋮---- -export interface SpotOrder { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - stopPrice: numberInString; - icebergQty: numberInString; - time: number; - updateTime: number; - isWorking: boolean; - origQuoteOrderQty: numberInString; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present only for expired orders. */ - expiryReason?: string; -} +/** + * Trading responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ ⋮---- -/** Present only for expired orders. */ +/** + * Order list responses + */ ⋮---- -export interface SpotAmendKeepPriorityResult { - transactTime: number; - executionId: number; - amendedOrder: { - symbol: string; - orderId: number; - orderListId: number; - origClientOrderId: string; - clientOrderId: string; - price: string; - qty: string; - executedQty: string; - preventedQty: string; - quoteOrderQty: string; - cumulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }; - listStatus?: { - orderListId: number; - contingencyType: string; - listOrderStatus: string; - listClientOrderId: string; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - }; -} +/** + * SOR responses + */ + +================ +File: src/types/spot.ts +================ +import { + ExchangeFilter, + ExchangeSymbol, + GenericCodeMsgError, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRow, + OrderResponseType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SideEffects, + StringBoolean, + SymbolFilter, +} from './shared'; ⋮---- -export interface SpotAssetBalance { - asset: string; - free: numberInString; - locked: numberInString; +export interface BasicTimeRangeParam { + startTime?: number; + endTime?: number; } ⋮---- -export interface AccountInformation { - makerCommission: number; - takerCommission: number; - buyerCommission: number; - sellerCommission: number; - commissionRates: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - canTrade: boolean; - canWithdraw: boolean; - canDeposit: boolean; - brokered: boolean; - requireSelfTradePrevention: boolean; - preventSor: boolean; - updateTime: number; - accoountType: string; - balances: SpotAssetBalance[]; - permissions: string[]; - uid: number; +export interface BasicFromPaginatedParams { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface CrossMarginAccountTransferParams { - asset: string; - amount: number; - type: 1 | 2; +export type SymbolStatus = + | 'PRE_TRADING' + | 'TRADING' + | 'POST_TRADING' + | 'END_OF_DAY' + | 'HALT' + | 'AUCTION_MATCH' + | 'BREAK' + | 'CANCEL_ONLY'; +⋮---- +export interface SystemStatusResponse { + status: 0 | 1; + msg: 'normal' | 'system maintenance'; } ⋮---- -export interface MarginTransactionResponse { - tranId: number; +export interface DailyAccountSnapshotParams { + type: 'SPOT' | 'MARGIN' | 'FUTURES'; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface MarginAccountLoanParams { +export interface SpotBalance { asset: string; - isIsolated: StringBoolean; - symbol: string; - amount: number; - type: 'BORROW' | 'REPAY'; + free: numberInString; + locked: numberInString; } ⋮---- -export interface QueryMarginAssetParams { +export interface MarginBalance { asset: string; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; } ⋮---- -export interface QueryMarginAssetResponse { - assetFullName: string; - assetName: string; - isBorrowable: boolean; - isMortgageable: boolean; - userMinBorrow: numberInString; - userMinRepay: numberInString; +export interface DailyFuturesBalance { + asset: string; + marginBalance: numberInString; + walletBalance: numberInString; } ⋮---- -export interface QueryCrossMarginPairParams { +export interface DailyFuturesPositionState { + entryPrice: numberInString; + markPrice: numberInString; + positionAmt: numberInString; symbol: string; + unRealizedProfit: numberInString; } ⋮---- -export interface QueryCrossMarginPairResponse { - id: number; - symbol: string; - base: string; - quote: string; - isMarginTrade: boolean; - isBuyAllowed: boolean; - isSellAllowed: boolean; +export interface DailySpotAccountSnapshot { + data: { + balances: SpotBalance[]; + totalAssetOfBtc: numberInString; + }; + type: 'spot'; + updateTime: number; } ⋮---- -export interface QueryMarginPriceIndexResponse { - calcTime: number; - price: numberInString; - symbol: string; +export interface DailyMarginAccountSnapshot { + data: { + marginLevel: numberInString; + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; + userAssets: MarginBalance[]; + }; + type: 'margin'; + updateTime: number; } ⋮---- -export interface QueryMarginRecordParams { - asset: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - archived?: boolean; +export interface DailyFuturesAccountSnapshot { + data: { + assets: DailyFuturesBalance[]; + position: DailyFuturesPositionState[]; + }; + type: 'futures'; + updateTime: number; } ⋮---- -export interface GetMarginAccountBorrowRepayRecordsParams { - asset?: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - type: 'BORROW' | 'REPAY'; +export type DailyAccountSnapshotElement = + | DailySpotAccountSnapshot + | DailyMarginAccountSnapshot + | DailyFuturesAccountSnapshot; +⋮---- +export interface DailyAccountSnapshot { + code: number; + msg: string; + snapshotVos: DailyAccountSnapshotElement[]; } ⋮---- -export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; +export interface CoinNetwork { + addressRegex: string; + coin: string; + depositDesc: string; + depositEnable: boolean; + isDefault: boolean; + memoRegex: string; + minConfirm: number; + name: string; + network: string; + resetAddressStatus: boolean; + specialTips?: string; + specialWithdrawTips?: string; + unlockConfirm: number; + withdrawDesc: string; + withdrawEnable: boolean; + withdrawFee: numberInString; + withdrawMin: numberInString; + withdrawMax: numberInString; + withdrawInternalMin: numberInString; + withdrawIntegerMultiple: numberInString; + depositDust?: numberInString; + sameAddress: boolean; + estimatedArrivalTime: number; + busy: boolean; + contractAddressUrl?: string; + contractAddress?: string; +} ⋮---- -export interface MarginAccountRecord { - isolatedSymbol?: string; - asset: string; - principal: numberInString; - status: LoanStatus; - timestamp: number; - txId: number; +export interface AllCoinsInformationResponse { + coin: string; + depositAllEnable: boolean; + free: numberInString; + freeze: numberInString; + ipoable: numberInString; + ipoing: numberInString; + isLegalMoney: boolean; + locked: numberInString; + name: string; + networkList: CoinNetwork[]; + storage: numberInString; + trading: boolean; + withdrawAllEnable: boolean; + withdrawing: numberInString; } ⋮---- -export interface QueryCrossMarginAccountDetailsParams { - created: boolean; - borrowEnabled: boolean; - marginLevel: numberInString; - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; - totalCollateralValueInUSDT: numberInString; - totalOpenOrderLossInUSDT: numberInString; - tradeEnabled: boolean; - transferInEnabled: boolean; - transferOutEnabled: boolean; - accountType: string; - userAssets: MarginBalance[]; +export interface WithdrawParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; + amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; } ⋮---- -export interface BasicMarginAssetParams { +export interface TransferBrokerSubAccountParams { + fromId?: string; + toId?: string; + clientTranId?: string; asset: string; - isolatedSymbol?: string; + amount: number; } ⋮---- -export interface QueryMaxBorrowResponse { - amount: numberInString; - borrowLimit: numberInString; +export interface ConvertQuoteRequestParams { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + walletType?: string; + validTime?: string; } ⋮---- -export interface QueryMaxTransferOutAmountResponse { - amount: numberInString; +export interface EnableConvertSubAccountParams { + subAccountId: string; + convert: boolean; } ⋮---- -export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; -⋮---- -export interface IsolatedMarginAccountTransferParams { - asset: string; - symbol: string; - transFrom: IsolatedMarginTransfer; - transTo: IsolatedMarginTransfer; - amount: number; +export interface AcceptQuoteRequestParams { + quoteId: string; } ⋮---- -export interface IsolatedMarginAccountAsset { - asset: string; - borrowEnabled: boolean; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; - netAssetOfBtc: numberInString; - repayEnabled: boolean; - totalAsset: numberInString; +export interface GetOrderStatusParams { + orderId?: string; + quoteId?: string; } ⋮---- -export type IsolatedMarginLevelStatus = - | 'EXCESSIVE' - | 'NORMAL' - | 'MARGIN_CALL' - | 'PRE_LIQUIDATION' - | 'FORCE_LIQUIDATION'; -⋮---- -export interface IsolatedMarginAccountAssets { - baseAsset: IsolatedMarginAccountAsset; - quoteAsset: IsolatedMarginAccountAsset; - symbol: string; - isolatedCreated: boolean; - enabled: boolean; - marginLevel: numberInString; - marginLevelStatus: IsolatedMarginLevelStatus; - marginRatio: numberInString; - indexPrice: numberInString; - liquidatePrice: numberInString; - liquidateRate: numberInString; - tradeEnabled: boolean; +export interface GetConvertTradeHistoryParams { + startTime: number; + endTime?: number; + limit?: string; } ⋮---- -export interface IsolatedMarginAccountInfo { - assets: IsolatedMarginAccountAssets[]; - totalAssetOfBtc?: numberInString; - totalLiabilityOfBtc?: numberInString; - totalNetAssetOfBtc?: numberInString; +export interface TransferBrokerSubAccount { + txnId: numberInString; } ⋮---- -export interface SpotSubUserAssetBtcList { - email: string; - totalAsset: numberInString; +export enum EnumDepositStatus { + Pending = 0, + CreditedButCannotWithdraw = 6, + WrongDeposit = 7, + WaitingUserConfirm = 8, + Success = 1, + Rejected = 2, } ⋮---- -export interface SubAccountList { - email: string; - isFreeze: boolean; - createTime: number; - isManagedSubAccount: boolean; - isAssetManagementSubAccount: boolean; +export type DepositStatusCode = `${EnumDepositStatus}`; +⋮---- +export interface DepositHistoryParams { + coin?: string; // Optional: Filter by coin + status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) + startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) + endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) + offset?: number; // Optional: Pagination offset (Default: 0) + limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) + txId?: string; // Optional: Filter by transaction ID + includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) } ⋮---- -export interface SubAccountDepositHistoryList { - depositId: number; - subAccountId: string; - amount: string; +coin?: string; // Optional: Filter by coin +status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) +startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) +endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +offset?: number; // Optional: Pagination offset (Default: 0) +limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) +txId?: string; // Optional: Filter by transaction ID +includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +⋮---- +export interface DepositHistory { + amount: numberInString; coin: string; network: string; status: number; @@ -16480,2758 +14590,3046 @@ export interface SubAccountDepositHistoryList { addressTag: string; txId: string; insertTime: number; - sourceAddress: string; + transferType: number; confirmTimes: string; } ⋮---- -export interface SubAccountTransferHistoryList { - fromId?: string; - toId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountBasicTransfer { - from: string; - to: string; - asset: string; - qty: numberInString; - tranId: number; - time: number; -} -⋮---- -export interface MarginTradeCoeffVo { - forceLiquidationBar: numberInString; - marginCallBar: numberInString; - normalBar: numberInString; +export enum EnumWithdrawStatus { + EmailSent = 0, + Cancelled = 1, + AwaitingApproval = 2, + Rejected = 3, + Processing = 4, + Failure = 5, + Completed = 6, } ⋮---- -export interface SubAccountStatus { - email: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - insertTime: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - mobile: number; -} +export type WithdrawStatusCode = `${EnumWithdrawStatus}`; ⋮---- -export interface BasicBtcTotals { - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; +export interface WithdrawHistoryParams { + coin?: string; // Optional: Filter by coin + withdrawOrderId?: string; // Optional: Filter by withdraw order ID + status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) + offset?: number; // Optional: Pagination offset + limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) + idList?: string; // Optional: Comma-separated list of withdrawal IDs + startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) + endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) } ⋮---- -export interface FuturesSubAccountAssets { - asset: string; - initialMargin: numberInString; - maintenanceMargin: numberInString; - marginBalance: numberInString; - maxWithdrawAmount: numberInString; - openOrderInitialMargin: numberInString; - positionInitialMargin: numberInString; - unrealizedProfit: numberInString; - walletBalance: numberInString; -} +coin?: string; // Optional: Filter by coin +withdrawOrderId?: string; // Optional: Filter by withdraw order ID +status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) +offset?: number; // Optional: Pagination offset +limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) +idList?: string; // Optional: Comma-separated list of withdrawal IDs +startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) +endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) ⋮---- -export interface FuturesSubAccountList { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - email: string; +export enum EnumWithdrawTransferType { + External = 0, + Interal = 1, } ⋮---- -export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; -⋮---- -export interface SubAccountTransferHistory { - counterParty: string; - email: string; - type: number; - asset: string; - qty: numberInString; - fromAccountType: AccountType; - toAccountType: AccountType; - status: string; - tranId: number; - time: number; -} +export type WithdrawTransferType = `${EnumWithdrawTransferType}`; ⋮---- -export interface SubAccountUniversalTransferHistory { - tranId: number; - fromEmail: string; - toEmail: string; - asset: string; +export interface WithdrawHistory { + address: string; amount: numberInString; - createTimeStamp: number; - fromAccountType: AccountType; - toAccountType: AccountType; - status: string; - clientTranId?: string; -} -⋮---- -export interface BasicSubAccount { - email: string; - subAccountApiKey: string; -} -⋮---- -export interface CreateSubAccountParams { - subAccountString: string; -} -⋮---- -export interface EnableOrDisableIPRestrictionForSubAccountParams - extends BasicSubAccount { - ipAddress?: string; -} -⋮---- -export interface GetBrokerSubAccountHistoryParams { - fromId?: string; - toId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; + applyTime: string; + coin: string; + id: string; + withdrawOrderId: string; + network: string; + transferType: WithdrawTransferType; + status: number; + transactionFee: numberInString; + txId: string; } ⋮---- -export interface CreateBrokerSubAccountParams { - tag?: string; +export interface DepositAddressParams { + coin: string; + network?: string; + amount?: number; } ⋮---- -export interface GetBrokerSubAccountParams { - subAccountId?: string; - page?: number; - size?: number; +export interface DepositAddressResponse { + address: string; + coin: string; + tag: string; + url: string; } ⋮---- -export interface GetApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey?: string; - page?: number; - size?: number; +export interface ConvertDustParams { + asset: string[]; + accountType?: 'SPOT' | 'MARGIN'; } ⋮---- -export interface CreateApiKeyBrokerSubAccountParams { - subAccountId: string; - canTrade: boolean; - marginTrade?: boolean; - futuresTrade?: boolean; -} -export interface ApiKeyBrokerSubAccount { - subAccountId: string; - apiKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} +export type DustConvertAccountType = 'SPOT' | 'MARGIN'; ⋮---- -export interface UpdateIpRestrictionForSubApiKey { - subAccountId: string; - ipAddress?: string; - subAccountApiKey: string; - status: string; +export interface DustConvertParams { + asset: string[]; + accountType?: DustConvertAccountType; + clientId?: string; + targetAsset?: string; + thirdPartyClientId?: string; + dustQuotaAssetToTargetAssetPrice?: numberInString; } ⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canUniversalTransfer: boolean; +export interface DustConvertibleAssetsParams { + targetAsset: string; + accountType?: DustConvertAccountType; + dustQuotaAssetToTargetAssetPrice?: numberInString; } ⋮---- -export interface EnableMarginBrokerSubAccountParams { - subAccountId: string; - margin: boolean; +export interface DustConvertibleAssetDetail { + asset: string; + assetFullName: string; + amountFree: numberInString; + exchange: numberInString; + toQuotaAssetAmount: numberInString; + toTargetAssetAmount: numberInString; + toTargetAssetOffExchange: numberInString; } ⋮---- -export interface EnableMarginBrokerSubAccountResponse { - subAccountId: string; - enableMargin: boolean; - updateTime: number; +export interface DustConvertibleAssetsResponse { + dribbletPercentage: numberInString; + totalTransferQuotaAssetAmount: numberInString; + totalTransferTargetAssetAmount: numberInString; + dribbletBase: numberInString; + details: DustConvertibleAssetDetail[]; } ⋮---- -export interface EnableFuturesBrokerSubAccountParams { - subAccountId: string; - futures: boolean; +export interface DustInfoDetail { + asset: string; + assetFullName: string; + amountFree: numberInString; + toBTC: numberInString; + toBNB: numberInString; + toBNBOffExchange: numberInString; + exchange: numberInString; } ⋮---- -export interface EnableFuturesBrokerSubAccountResponse { - subAccountId: string; - enableFutures: boolean; - updateTime: number; +export interface DustInfo { + details: DustInfoDetail[]; + totalTransferBtc: numberInString; + totalTransferBNB: numberInString; + dribbletPercentage: numberInString; } ⋮---- -export interface EnableMarginApiKeyBrokerSubAccountParams { - subAccountId: string; - margin: boolean; +export interface DustConversionResult { + amount: numberInString; + fromAsset: string; + operateTime: number; + serviceChargeAmount: numberInString; + tranId: number; + transferedAmount: numberInString; } -export interface UniversalTransferBrokerParams { - fromId?: string; - toId?: string; - fromAccountType: string; - toAccountType: string; - asset: string; - amount: number; +⋮---- +export interface DustConversion { + totalServiceCharge: numberInString; + totalTransfered: numberInString; + transferResult: DustConversionResult[]; } ⋮---- -export interface GetUniversalTransferBrokerParams { - fromId?: string; - toId?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; +export interface UserAssetDribbletDetail { + transId: number; + serviceChargeAmount: numberInString; + amount: numberInString; + operateTime: number; + transferedAmount: numberInString; + fromAsset: string; } ⋮---- -export interface GetBrokerSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; +export interface UserAssetDribblet { + operateTime: number; + totalTransferedAmount: numberInString; + totalServiceChargeAmount: numberInString; + transId: number; + userAssetDribbletDetails: UserAssetDribbletDetail[]; } ⋮---- -export interface DeleteApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; +export interface DustLog { + total: number; + userAssetDribblets: UserAssetDribblet[]; } ⋮---- -export interface ChangePermissionApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; +export enum EnumUniversalTransferType { + SpotToUSDM = 'MAIN_UMFUTURE', + SpotToCOINM = 'MAIN_CMFUTURE', + SpotToMargin = 'MAIN_MARGIN', + SpotToFunding = 'MAIN_FUNDING', + SpotToOptions = 'MAIN_OPTION', + FundingToSpot = 'FUNDING_MAIN', + FundingToUSDM = 'FUNDING_UMFUTURE', + FundingToCOINM = 'FUNDING_CMFUTURE', + FundingToMargin = 'FUNDING_MARGIN', + FundingToOptions = 'FUNDING_OPTION', + USDMToSpot = 'UMFUTURE_MAIN', + USDMToFunding = 'UMFUTURE_FUNDING', + USDMToMargin = 'UMFUTURE_MARGIN', + USDMToOptions = 'UMFUTURE_OPTION', + COINMToSpot = 'CMFUTURE_MAIN', + COINMToFunding = 'CMFUTURE_FUNDING', + COINMToMargin = 'CMFUTURE_MARGIN', + MarginToSpot = 'MARGIN_MAIN', + MarginToUSDM = 'MARGIN_UMFUTURE', + MarginToCOINM = 'MARGIN_CMFUTURE', + MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', + MarginToFunding = 'MARGIN_FUNDING', + MarginToOptions = 'MARGIN_OPTION', + IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', + IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', + OptionsToSpot = 'OPTION_MAIN', + OptionsToUSDM = 'OPTION_UMFUTURE', + OptionsToFunding = 'OPTION_FUNDING', + OptionsToMargin = 'OPTION_MARGIN', } ⋮---- -export interface ChangePermissionApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; +export type UniversalTransferType = `${EnumUniversalTransferType}`; +⋮---- +export interface UniversalTransferParams { + type: UniversalTransferType; + asset: string; + amount: number; + fromSymbol: string; + toSymbol: string; } ⋮---- -export interface VirtualSubAccount { - email: string; +export interface UniversalTransferHistoryParams { + type: UniversalTransferType; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface BrokerSubAccountHistory { - subAccountsHistory: SubAccountTransferHistoryList[]; +export interface ExchangeInfoParams { + symbol?: string; + symbols?: string[]; + permissions?: string | string[]; + showPermissionSets?: boolean; + symbolStatus?: string; } ⋮---- -export interface BrokerSubAccount { - subaccountId: string; - email: string; - makerCommission?: string; - takerCommission?: string; - marginMakerCommission?: string; - marginTakerCommission?: string; - createTime?: number; - tag: string; +export interface NewSpotOrderParams< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> { + symbol: string; + side: OrderSide; + type: T; + timeInForce?: OrderTimeInForce; + quantity?: number; + quoteOrderQty?: number; + price?: number; + newClientOrderId?: string; + strategyId?: number; + strategyType?: number; + stopPrice?: number; + trailingDelta?: number; + icebergQty?: number; + newOrderRespType?: RT; + isIsolated?: StringBoolean; + sideEffectType?: SideEffects; + autoRepayAtCancel?: StringBoolean; } ⋮---- -export interface CreateApiKeyBrokerSubAccountResponse { - subaccountId: string; - apiKey: string; - secretKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} +export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; +export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; ⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canUniversalTransfer: boolean; +export interface ReplaceSpotOrderParams< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends NewSpotOrderParams { + cancelReplaceMode: CancelReplaceMode; + cancelNewClientOrderId?: string; + cancelOrigClientOrderId?: string; + cancelOrderId?: number; + cancelRestrictions?: CancelRestrictions; } ⋮---- -export interface GetBrokerInfoResponse { - maxMakerCommission: string; - minMakerCommission: string; - maxTakerCommission: string; - minTakerCommission: string; - subAccountQty: number; - maxSubAccountQty: number; +export interface GetOCOParams { + symbol?: string; + orderListId?: number; + origClientOrderId?: string; } -export interface SubAccountListParams { - email?: string; - isFreeze?: StringBoolean; - page?: number; - limit?: number; +⋮---- +export interface NewSpotSOROrderParams { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + quantity: number; + price?: number; + newClientOrderId?: string; + strategyId?: number; + strategyType?: number; + icebergQty?: number; + newOrderRespType?: OrderResponseType; + selfTradePreventionMode?: SelfTradePreventionMode; } ⋮---- -export interface SubAccountListResponse { - subAccounts: SubAccountList[]; +export type APILockTriggerCondition = 'GCR' | 'IFER' | 'UFR'; +⋮---- +export interface APITriggerConditionSymbolStatus { + i: APILockTriggerCondition; + c: number; + v: number; + t: number; } ⋮---- -export interface SubAccountSpotAssetTransferHistoryParams { - fromEmail?: string; - toEmail?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; +export interface APITradingStatus { + data: { + isLocked: boolean; + plannedRecoverTime: number; + triggerCondition: Record; + indicators: Record; + updateTime: number; + }; } ⋮---- -export interface SubAccountSpotAssetTransferHistory - extends SubAccountBasicTransfer { - status: string; +export interface APIPermissions { + ipRestrict: boolean; + createTime: number; + enableReading: boolean; + enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals + enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly + enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed + enableFutures: boolean; // API Key created before your futures account opened does not support futures API service + permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization + enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading + enableSpotAndMarginTrading: boolean; // Spot and margin trading + tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission + enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading + enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading + enablePortfolioMarginTrading: true; } ⋮---- -export interface SubAccountFuturesAssetTransferHistoryParams { - email: string; - futuresType: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; +enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals +enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly +enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed +enableFutures: boolean; // API Key created before your futures account opened does not support futures API service +permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization +enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading +enableSpotAndMarginTrading: boolean; // Spot and margin trading +tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission +enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading +enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading +⋮---- +export interface AssetDetail { + minWithdrawAmount: numberInString; + depositStatus: boolean; + withdrawFee: number; + withdrawStatus: boolean; + depositTip?: string; } ⋮---- -export interface SubAccountFuturesAssetTransferHistory { - success: boolean; - futuresType: number; - transfers: SubAccountBasicTransfer[]; +export interface SymbolTradeFee { + symbol: string; + makerCommission: numberInString; + takerCommission: numberInString; } ⋮---- -export interface SubAccountFuturesAssetTransferParams { - fromEmail: string; - toEmail: string; - futuresType: number; - asset: string; - amount: number; +export interface SymbolExchangeInfo { + symbol: string; + status: string; + baseAsset: string; + baseAssetPrecision: number; + quoteAsset: string; + quotePrecision: number; + quoteAssetPrecision: number; + baseCommissionPrecision: number; + quoteCommissionPrecision: number; + orderTypes: OrderType[]; + icebergAllowed: boolean; + ocoAllowed: boolean; + opoAllowed: boolean; + quoteOrderQtyMarketAllowed: boolean; + allowTrailingStop: boolean; + cancelReplaceAllowed: boolean; + isSpotTradingAllowed: boolean; + isMarginTradingAllowed: boolean; + filters: SymbolFilter[]; + permissions: ('SPOT' | 'MARGIN')[]; + defaultSelfTradePreventionMode: SelfTradePreventionMode; + allowedSelfTradePreventionModes: SelfTradePreventionMode[]; } ⋮---- -export interface SubAccountFuturesAssetTransfer { - success: boolean; - txnId: numberInString; +export interface ExchangeInfo { + timezone: string; + serverTime: number; + rateLimits: RateLimiter[]; + exchangeFilters: ExchangeFilter[]; + symbols: SymbolExchangeInfo[]; } ⋮---- -export interface SubAccountAssetsParams { - email: string; +export interface OrderBookResponse { + lastUpdateId: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; } ⋮---- -export interface SubAccountAssets { - balances: SpotBalance[]; +export interface RawTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; } ⋮---- -export interface SubAccountSpotAssetsSummaryParams { - email?: string; - page?: number; - size?: number; +export interface BlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; } ⋮---- -export interface SubAccountSpotAssetsSummary { - totalCount: number; - masterAccountTotalAsset: numberInString; - spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; +export interface HistoricalBlockTradesParams { + symbol: string; + fromId: number; + limit?: number; } ⋮---- -export interface SubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; +export interface RawAccountTrade { + symbol: string; + id: number; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isBestMatch: boolean; } ⋮---- -export interface SubAccountDepositAddress { - address: string; - coin: string; - tag: string; - url: string; +export interface AggregateTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; + M: boolean; } ⋮---- -export interface SubAccountDepositHistoryParams extends DepositHistoryParams { - email: string; +export interface CurrentAvgPrice { + mins: number; + price: numberInString; + closeTime: number; } ⋮---- -export interface SubAccountEnableMargin { - email: string; - isMarginEnabled: boolean; +/** Spot PRICE_RANGE execution rule (GET /api/v3/executionRules). */ +export interface SpotPriceRangeExecutionRule { + ruleType: 'PRICE_RANGE'; + bidLimitMultUp: numberInString; + bidLimitMultDown: numberInString; + askLimitMultUp: numberInString; + askLimitMultDown: numberInString; } ⋮---- -export interface SubAccountMarginAccountDetail extends BasicBtcTotals { - email: string; - marginLevel: numberInString; - marginTradeCoeffVo: MarginTradeCoeffVo; - marginUserAssetVoList: MarginBalance[]; +export interface SpotSymbolExecutionRules { + symbol: string; + rules: SpotPriceRangeExecutionRule[]; } ⋮---- -export interface SubAccountListBtc extends BasicBtcTotals { - email: string; +export interface SpotExecutionRulesResponse { + symbolRules: SpotSymbolExecutionRules[]; } ⋮---- -export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { - subAccountList: SubAccountListBtc; +/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ +export interface SpotExecutionRulesParams { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; } ⋮---- -export interface SubAccountEnableFutures { - email: string; - isFuturesEnabled: boolean; +/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ +export interface SpotReferencePriceResponse { + symbol: string; + referencePrice: numberInString | null; + timestamp: number; } ⋮---- -export interface SubAccountFuturesAccountDetail { - email: string; - asset: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - maxWithdrawAmount: numberInString; - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - updateTime: number; +/** GET /api/v3/referencePrice or /referencePrice/calculation when no reference price has ever been set (code -2043). */ +export interface SpotReferencePriceNeverSetError { + code: -2043; + msg: string; } ⋮---- -export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { - subAccountList: FuturesSubAccountList[]; -} +export type SpotReferencePriceResult = + | SpotReferencePriceResponse + | SpotReferencePriceNeverSetError; ⋮---- -export interface FuturesPositionRisk { - entryPrice: numberInString; - leverage: numberInString; - maxNotional: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - positionAmount: numberInString; +/** Reference price is computed as an arithmetic mean in the matching engine. */ +export interface SpotReferencePriceCalculationArithmeticMean { symbol: string; - unrealizedProfit: numberInString; + calculationType: 'ARITHMETIC_MEAN'; + bucketCount: number; + bucketWidthMs: number; } ⋮---- -export interface SubAccountTransferParams { - email: string; - asset: string; - amount: number; - type: number; +/** Reference price is computed outside the matching engine. */ +export interface SpotReferencePriceCalculationExternal { + symbol: string; + calculationType: 'EXTERNAL'; + externalCalculationId: number; } ⋮---- -export interface SubAccountTransfer { - txnId: numberInString; +export type SpotReferencePriceCalculationResponse = + | SpotReferencePriceCalculationArithmeticMean + | SpotReferencePriceCalculationExternal + | SpotReferencePriceNeverSetError; +⋮---- +export interface DailyChangeStatistic { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + prevClosePrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; } ⋮---- -export interface SubAccountTransferToSameMasterParams { - toEmail: string; - asset: string; - amount: number; +export interface SymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; } ⋮---- -export interface SubAccountTransferToMasterParams { - asset: string; - amount: number; +export interface OrderResponseACK { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; } ⋮---- -export interface SubAccountTransferHistoryParams { - asset?: string; - type?: number; - startTime?: number; - endTime?: number; - limit?: number; +export interface OrderResponseResult { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; } ⋮---- -export interface SubAccountUniversalTransferParams { - fromEmail?: string; - toEmail?: string; - fromAccountType: AccountType; - toAccountType: AccountType; - clientTranId?: string; - asset: string; - amount: number; +/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +⋮---- +export interface OrderFill { + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; } ⋮---- -export interface SubAccountMovePositionParams { - fromUserEmail: string; - toUserEmail: string; - productType: string; - orderArgs: { - symbol: string; - quantity: number; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - }[]; +export interface OrderResponseFull { + symbol: string; + orderId: number; + orderListId?: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + marginBuyBorrowAmount?: number; + marginBuyBorrowAsset?: string; + isIsolated?: boolean; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; + fills: OrderFill[]; } -export interface SubAccountUniversalTransfer extends SubAccountTransfer { - clientTranId?: string; +⋮---- +/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +⋮---- +export type OrderResponse = + | OrderResponseACK + | OrderResponseResult + | OrderResponseFull; +⋮---- +export type OrderResponseTypeFor< + RT extends OrderResponseType | undefined = undefined, + T extends OrderType | undefined = undefined, +> = RT extends 'ACK' + ? OrderResponseACK + : RT extends 'RESULT' + ? OrderResponseResult + : RT extends 'FULL' + ? OrderResponseFull + : T extends 'MARKET' | 'LIMIT' + ? OrderResponseFull + : OrderResponseACK; +⋮---- +export interface OrderListOrder { + symbol: string; + orderId: number; + clientOrderId: string; + /** Present only for expired orders. */ + expiryReason?: string; } ⋮---- -export interface SubAccountMovePosition { - fromUserEmail: string; - toUserEmail: string; - productType: string; +/** Present only for expired orders. */ +⋮---- +export interface OrderListResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listClientOrderId: string; + transactionTime: number; symbol: string; - priceType: string; - price: string; - quantity: string; - positionSide: string; - side: string; - success: boolean; + orders: [OrderListOrder, OrderListOrder]; + orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; } ⋮---- -export interface SubAccountMovePositionHistoryParams { +export interface OrderList { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listClientOrderId: string; + transactionTime: number; symbol: string; - startTime?: number; - endTime?: number; - page: number; - row: number; + orders: [OrderListOrder, OrderListOrder]; +} +export interface SOROrderFill { + matchType: string; + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; + tradeId: number; + allocId: number; } ⋮---- -export interface SubAccountMovePositionHistory { - fromUserEmail: string; - toUserEmail: string; - productType: string; - symbol: string; - price: string; - quantity: string; - positionSide: string; - side: string; - timeStamp: number; -} +export type SOROrderResponseFull = OrderResponseFull & { + workingTime: number; + fills: SOROrderFill[]; + workingFloor: string; + selfTradePreventionMode: string; + usedSor: true; +}; ⋮---- -export interface SubAccountUniversalTransferHistoryParams { - fromEmail?: string; - toEmail?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; +export interface SORTestOrderResponse { + standardCommissionForOrder: { + //Standard commission rates on trades from the order. + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + //Tax commission rates for trades from the order. + maker: numberInString; + taker: numberInString; + }; + discount: { + //Discount on standard commissions when paying in BNB. + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. + }; } ⋮---- -export interface SubAccountUniversalTransferHistoryResponse { - result: SubAccountUniversalTransferHistory[]; - totalCount: number; -} +//Standard commission rates on trades from the order. ⋮---- -export interface SubAccountEnableLeverageToken { - email: string; - enableBlvt: boolean; -} +//Tax commission rates for trades from the order. ⋮---- -export interface AddIpRestriction extends BasicSubAccount { - status: string; - ipAddress: string; -} +//Discount on standard commissions when paying in BNB. ⋮---- -export interface SubAccountEnableOrDisableIPRestriction { - ipRestrict: boolean; - ipList: string[]; - updateTime: number; - apiKey: string; -} +discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. ⋮---- -export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { - ipAddress: string; +export interface CancelSpotOrderResult { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + selfTradePreventionMode: SelfTradePreventionMode; } ⋮---- -export interface AddIPListForSubAccountResponseParams { - ip: string; - updateTime: number; - apiKey: string; +export interface CancelOrderListResult extends OrderList { + orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; } ⋮---- -export interface SubAccountAssetDetails { - coin: string; - name: string; - totalBalance: numberInString; - availableBalance: numberInString; - inOrder: numberInString; - btcValue: numberInString; +export interface GenericReplaceSpotOrderResult { + cancelResult: 'SUCCESS' | 'FAILURE'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: C; + newOrderResponse: N; } ⋮---- -export interface WithdrawAssetsFromManagedSubAccountParams { - fromEmail: string; - asset: string; - amount: number; - transferDate?: number; +export interface ReplaceSpotOrderCancelStopFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'NOT_ATTEMPTED'; } ⋮---- -export interface BasicFuturesSubAccountParams { - email: string; - futuresType: 1 | 2; +export interface ReplaceSpotOrderNewFailure + extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + GenericCodeMsgError + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'FAILURE'; } ⋮---- -export interface SubAccountSummaryOnFuturesAccountV2Params { - futuresType: 1 | 2; - page?: number; - limit?: number; +export interface ReplaceSpotOrderCancelAllowFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'SUCCESS'; } ⋮---- -export interface SubAccountUSDMDetail { - futureAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - maxWithdrawAmount: numberInString; - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - updateTime: number; - }; +export interface ReplaceSpotOrderCancelAllFailure + extends GenericReplaceSpotOrderResult< + GenericCodeMsgError, + GenericCodeMsgError + > { + cancelResult: 'FAILURE'; + newOrderResult: 'FAILURE'; } ⋮---- -export interface COINMSubAccount { - email: string; - totalMarginBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; +export interface ReplaceSpotOrderResultError { + data: + | ReplaceSpotOrderCancelStopFailure + | ReplaceSpotOrderNewFailure + | ReplaceSpotOrderCancelAllowFailure + | ReplaceSpotOrderCancelAllFailure; } ⋮---- -export interface SubAccountCOINMDetail { - deliveryAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; - }; +export interface ReplaceSpotOrderResultSuccess< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + OrderResponseTypeFor + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'SUCCESS'; } ⋮---- -export interface SubAccountUSDMSummary { - futureAccountSummaryResp: { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - subAccountList: FuturesSubAccountList[]; - }; +export interface SpotOrder { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + stopPrice: numberInString; + icebergQty: numberInString; + time: number; + updateTime: number; + isWorking: boolean; + origQuoteOrderQty: numberInString; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present only for expired orders. */ + expiryReason?: string; } ⋮---- -export interface SubAccountCOINMSummary { - deliveryAccountSummaryResp: { - totalMarginBalanceOfBTC: numberInString; - totalUnrealizedProfitOfBTC: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; - subAccountList: COINMSubAccount[]; +/** Present only for expired orders. */ +⋮---- +export interface SpotAmendKeepPriorityResult { + transactTime: number; + executionId: number; + amendedOrder: { + symbol: string; + orderId: number; + orderListId: number; + origClientOrderId: string; + clientOrderId: string; + price: string; + qty: string; + executedQty: string; + preventedQty: string; + quoteOrderQty: string; + cumulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }; + listStatus?: { + orderListId: number; + contingencyType: string; + listOrderStatus: string; + listClientOrderId: string; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; }; } ⋮---- -export interface COINMPositionRisk { - entryPrice: numberInString; - markPrice: numberInString; - leverage: numberInString; - isolated: numberInString; - isolatedWallet: numberInString; - isolatedMargin: numberInString; - isAutoAddMargin: numberInString; - positionSide: string; - positionAmount: numberInString; - symbol: string; - unrealizedProfit: numberInString; -} -⋮---- -export interface SubAccountUSDMPositionRisk { - futurePositionRiskVos: FuturesPositionRisk[]; +export interface SpotAssetBalance { + asset: string; + free: numberInString; + locked: numberInString; } ⋮---- -export interface SubAccountCOINMPositionRisk { - deliveryPositionRiskVos: COINMPositionRisk[]; +export interface AccountInformation { + makerCommission: number; + takerCommission: number; + buyerCommission: number; + sellerCommission: number; + commissionRates: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + canTrade: boolean; + canWithdraw: boolean; + canDeposit: boolean; + brokered: boolean; + requireSelfTradePrevention: boolean; + preventSor: boolean; + updateTime: number; + accoountType: string; + balances: SpotAssetBalance[]; + permissions: string[]; + uid: number; } ⋮---- -export interface StakingProductDetail { +export interface CrossMarginAccountTransferParams { asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - apy: numberInString; -} -⋮---- -export interface StakingProductQuota { - totalPersonalQuota: numberInString; - minimum: numberInString; + amount: number; + type: 1 | 2; } ⋮---- -export interface StakingProduct { - projectId: string; - detail: StakingProductDetail; - quota: StakingProductQuota; +export interface MarginTransactionResponse { + tranId: number; } ⋮---- -export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; -export type StakingStatus = 'HOLDING' | 'REDEEMED'; -export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; -export type BSwapType = 'SINGLE' | 'COMBINATION'; -export type BSwapOperationType = 'ADD' | 'REMOVE'; -⋮---- -export interface StakingProductPosition { - positionId: numberInString; - projectId: string; +export interface MarginAccountLoanParams { asset: string; - amount: numberInString; - purchaseTime: numberInString; - duration: numberInString; - accrualDays: numberInString; - rewardAsset: string; - APY: numberInString; - rewardAmt: numberInString; - extraRewardAsset: string; - extraRewardAPY: numberInString; - estExtraRewardAmt: numberInString; - nextInterestPay: numberInString; - nextInterestPayDate: numberInString; - payInterestPeriod: numberInString; - redeemAmountEarly: numberInString; - interestEndDate: numberInString; - deliverDate: numberInString; - redeemPeriod: numberInString; - redeemingAmt: numberInString; - partialAmtDeliverDate: numberInString; - canRedeemEarly: boolean; - renewable: boolean; - type: string; - status: StakingStatus; -} -export interface StakingBasicParams { - product: StakingProductType; - current?: number; - size?: number; + isIsolated: StringBoolean; + symbol: string; + amount: number; + type: 'BORROW' | 'REPAY'; } ⋮---- -export interface FlexibleSavingBasicParams { - status?: string; - featured?: number; - current?: number; - size?: number; - asset?: string; +export interface QueryMarginAssetParams { + asset: string; } ⋮---- -export interface FlexibleProductPositionParams { - status?: string; - featured?: number; - current?: number; - size?: number; +export interface QueryMarginAssetResponse { + assetFullName: string; + assetName: string; + isBorrowable: boolean; + isMortgageable: boolean; + userMinBorrow: numberInString; + userMinRepay: numberInString; } ⋮---- -export interface PurchaseFlexibleProductParams { - productId: string; - amount: number; - autoSubscribe: boolean; +export interface QueryCrossMarginPairParams { + symbol: string; } ⋮---- -export interface PurchaseFlexibleProductResponse { - purchaseId: number; +export interface QueryCrossMarginPairResponse { + id: number; + symbol: string; + base: string; + quote: string; + isMarginTrade: boolean; + isBuyAllowed: boolean; + isSellAllowed: boolean; } ⋮---- -export interface RedeemFlexibleProductParams { - productId: string; - amount: number; - type: 'FAST' | 'NORMAL'; +export interface QueryMarginPriceIndexResponse { + calcTime: number; + price: numberInString; + symbol: string; } ⋮---- -export interface LeftDailyPurchaseQuotaFlexibleProductResponse { +export interface QueryMarginRecordParams { asset: string; - leftQuota: string; -} -⋮---- -export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; -export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; -export type ProjectSortBy = - | 'START_TIME' - | 'LOT_SIZE' - | 'INTEREST_RATE' - | 'DURATION'; -⋮---- -export interface FixedAndActivityProjectParams { - asset?: string; - type: ProjectType; - status?: ProjectStatus; - isSortAsc?: boolean; - sortBy?: ProjectSortBy; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; current?: number; size?: number; + archived?: boolean; } -export interface FixedAndActivityProjectPositionParams { - asset?: string; - projectId?: string; - status?: StakingStatus; -} -⋮---- -export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; ⋮---- -export interface PurchaseRecordParams { - lendingType: LendingType; +export interface GetMarginAccountBorrowRepayRecordsParams { asset?: string; + isolatedSymbol?: string; + txId?: number; startTime?: number; endTime?: number; current?: number; size?: number; + type: 'BORROW' | 'REPAY'; } ⋮---- -export interface NewFutureAccountTransferParams { - asset: string; - amount: number; - type: 1 | 2 | 3 | 4; -} -⋮---- -export interface GetFutureAccountTransferHistoryParams { - asset: string; - startTime: number; - endTime?: number; - current?: number; - size?: number; -} +export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- -export interface FutureAccountTransfer { +export interface MarginAccountRecord { + isolatedSymbol?: string; asset: string; - tranId: number; - amount: string; - type: string; + principal: numberInString; + status: LoanStatus; timestamp: number; - status: 'PENDING' | 'CONFIRMED' | 'FAILED'; -} -⋮---- -export interface GetLoanCoinPaginatedHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -/** - * - * STAKING - * - */ -⋮---- -export interface StakingHistory { - positionId: numberInString; - time: number; - asset: string; - project?: string; - amount: numberInString; - lockPeriod?: numberInString; - deliverDate?: numberInString; - type?: string; - status: string; + txId: number; } ⋮---- -export interface StakingPersonalLeftQuota { - leftPersonalQuota: numberInString; +export interface QueryCrossMarginAccountDetailsParams { + created: boolean; + borrowEnabled: boolean; + marginLevel: numberInString; + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; + totalCollateralValueInUSDT: numberInString; + totalOpenOrderLossInUSDT: numberInString; + tradeEnabled: boolean; + transferInEnabled: boolean; + transferOutEnabled: boolean; + accountType: string; + userAssets: MarginBalance[]; } ⋮---- -export interface StakingHistoryParams extends StakingBasicParams { - txnType: StakingTxnType; - asset?: string; - startTime?: number; - endTime?: number; +export interface BasicMarginAssetParams { + asset: string; + isolatedSymbol?: string; } -export interface BSwapOperationsParams { - operationId?: number; - poolId?: number; - operation: BSwapOperationType; - startTime?: number; - endTime?: number; - limit: number; +⋮---- +export interface QueryMaxBorrowResponse { + amount: numberInString; + borrowLimit: numberInString; } ⋮---- -export interface BSwapOperations { - operationId: number; - poolId: number; - poolName: string; - operation: BSwapOperationType; - status: number; - updateTime: number; - shareAmount: numberInString; +export interface QueryMaxTransferOutAmountResponse { + amount: numberInString; } -export interface RemoveBSwapLiquidityParams { - poolId: number; - type: BSwapType; - asset?: string; - shareAmount: number; +⋮---- +export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; +⋮---- +export interface IsolatedMarginAccountTransferParams { + asset: string; + symbol: string; + transFrom: IsolatedMarginTransfer; + transTo: IsolatedMarginTransfer; + amount: number; } ⋮---- -export interface AddBSwapLiquidityParams { - poolId: number; - type?: BSwapType; +export interface IsolatedMarginAccountAsset { asset: string; - quantity: number; + borrowEnabled: boolean; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; + netAssetOfBtc: numberInString; + repayEnabled: boolean; + totalAsset: numberInString; } ⋮---- -export interface BSwapShare { - shareAmount: number; - sharePercentage: number; - asset: { [k: string]: number }; +export type IsolatedMarginLevelStatus = + | 'EXCESSIVE' + | 'NORMAL' + | 'MARGIN_CALL' + | 'PRE_LIQUIDATION' + | 'FORCE_LIQUIDATION'; +⋮---- +export interface IsolatedMarginAccountAssets { + baseAsset: IsolatedMarginAccountAsset; + quoteAsset: IsolatedMarginAccountAsset; + symbol: string; + isolatedCreated: boolean; + enabled: boolean; + marginLevel: numberInString; + marginLevelStatus: IsolatedMarginLevelStatus; + marginRatio: numberInString; + indexPrice: numberInString; + liquidatePrice: numberInString; + liquidateRate: numberInString; + tradeEnabled: boolean; } ⋮---- -export interface BSwapLiquidity { - poolId: number; - poolNmae: string; - updateTime: number; - liquidity: { [k: string]: number }; - share: BSwapShare; +export interface IsolatedMarginAccountInfo { + assets: IsolatedMarginAccountAssets[]; + totalAssetOfBtc?: numberInString; + totalLiabilityOfBtc?: numberInString; + totalNetAssetOfBtc?: numberInString; } ⋮---- -export interface FundingAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - btcValuation: string; +export interface SpotSubUserAssetBtcList { + email: string; + totalAsset: numberInString; } ⋮---- -export interface GetAssetParams { - asset?: string; - needBtcValuation?: boolean; +export interface SubAccountList { + email: string; + isFreeze: boolean; + createTime: number; + isManagedSubAccount: boolean; + isAssetManagementSubAccount: boolean; } ⋮---- -export interface UserAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - ipoable: string; - btcValuation: string; +export interface SubAccountDepositHistoryList { + depositId: number; + subAccountId: string; + amount: string; + coin: string; + network: string; + status: number; + address: string; + addressTag: string; + txId: string; + insertTime: number; + sourceAddress: string; + confirmTimes: string; } ⋮---- -export interface ConvertTransfer { - clientTranId: string; - asset: string; - amount: number; - targetAsset: string; - accountType?: string; +export interface SubAccountTransferHistoryList { + fromId?: string; + toId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; } ⋮---- -export interface ConvertTransferResponse { +export interface SubAccountBasicTransfer { + from: string; + to: string; + asset: string; + qty: numberInString; tranId: number; - status: string; + time: number; } ⋮---- -export interface GetConvertBUSDHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - accountType?: string; - current?: number; - size?: number; +export interface MarginTradeCoeffVo { + forceLiquidationBar: numberInString; + marginCallBar: numberInString; + normalBar: numberInString; } ⋮---- -export interface BUSDConversionRecord { - tranId: number; - type: number; - time: number; - deductedAsset: string; - deductedAmount: string; - targetAsset: string; - targetAmount: string; - status: string; - accountType: string; +export interface SubAccountStatus { + email: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + insertTime: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + mobile: number; } ⋮---- -export interface CloudMiningHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - current?: number; - size?: number; +export interface BasicBtcTotals { + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; } ⋮---- -export interface CloudMining { - createTime: number; - tranId: number; - type: number; +export interface FuturesSubAccountAssets { asset: string; - amount: string; - status: string; + initialMargin: numberInString; + maintenanceMargin: numberInString; + marginBalance: numberInString; + maxWithdrawAmount: numberInString; + openOrderInitialMargin: numberInString; + positionInitialMargin: numberInString; + unrealizedProfit: numberInString; + walletBalance: numberInString; } ⋮---- -export interface ConvertibleCoinsResponse { - convertEnabled: boolean; - coins: string[]; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - exchangeRates: any; +export interface FuturesSubAccountList { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + email: string; } ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; ⋮---- -export interface ConvertibleCoinsParams { - coin: string; - enable: boolean; +export interface SubAccountTransferHistory { + counterParty: string; + email: string; + type: number; + asset: string; + qty: numberInString; + fromAccountType: AccountType; + toAccountType: AccountType; + status: string; + tranId: number; + time: number; } ⋮---- -export interface SubmitDepositCreditParams { - depositId?: number; - txId?: string; - subAccountId?: number; - subUserId?: number; +export interface SubAccountUniversalTransferHistory { + tranId: number; + fromEmail: string; + toEmail: string; + asset: string; + amount: numberInString; + createTimeStamp: number; + fromAccountType: AccountType; + toAccountType: AccountType; + status: string; + clientTranId?: string; } ⋮---- -export interface SubmitDepositCreditResponse { - code: string; - message: string; - data: boolean; - success: boolean; +export interface BasicSubAccount { + email: string; + subAccountApiKey: string; } ⋮---- -export interface DepositAddressListParams { - coin: string; - network?: string; +export interface CreateSubAccountParams { + subAccountString: string; } ⋮---- -export interface DepositAddress { - coin: string; - address: string; - tag: string; - isDefault: number; +export interface EnableOrDisableIPRestrictionForSubAccountParams + extends BasicSubAccount { + ipAddress?: string; } ⋮---- -export interface WalletBalance { - activate: boolean; - balance: string; - walletName: string; +export interface GetBrokerSubAccountHistoryParams { + fromId?: string; + toId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; } ⋮---- -export interface DelegationHistoryParams { - email: string; - startTime: number; - endTime: number; - type?: 'Delegate' | 'Undelegate'; - asset?: string; - current?: number; - size?: number; +export interface CreateBrokerSubAccountParams { + tag?: string; } ⋮---- -export interface DelegationHistory { - clientTranId: string; - transferType: 'Delegate' | 'Undelegate'; - asset: string; - amount: string; - time: number; +export interface GetBrokerSubAccountParams { + subAccountId?: string; + page?: number; + size?: number; } ⋮---- -export interface DelistScheduleResponse { - delistTime: number; - symbols: string[]; +export interface GetApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey?: string; + page?: number; + size?: number; } ⋮---- -export interface WithdrawAddress { - address: string; - addressTag: string; - coin: string; - name: string; - network: string; - origin: string; - originType: string; - whiteStatus: boolean; +export interface CreateApiKeyBrokerSubAccountParams { + subAccountId: string; + canTrade: boolean; + marginTrade?: boolean; + futuresTrade?: boolean; } -⋮---- -export interface AccountInfo { - vipLevel: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - isOptionsEnabled: boolean; - isPortfolioMarginRetailEnabled: boolean; +export interface ApiKeyBrokerSubAccount { + subAccountId: string; + apiKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; } ⋮---- -export interface ManagedSubAccountSnapshotParams { - email: string; - type: 'SPOT' | 'MARGIN' | 'FUTURES'; - startTime?: number; - endTime?: number; - limit?: number; +export interface UpdateIpRestrictionForSubApiKey { + subAccountId: string; + ipAddress?: string; + subAccountApiKey: string; + status: string; } ⋮---- -export interface SubaccountBalances { - asset: string; - free: string; - locked: string; +export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canUniversalTransfer: boolean; } ⋮---- -export interface SubaccountUserAssets { - asset: string; - borrowed: string; - free: string; - interest: string; - locked: string; - netAsset: string; +export interface EnableMarginBrokerSubAccountParams { + subAccountId: string; + margin: boolean; } ⋮---- -export interface SubaccountAssets { - asset: string; - marginBalance: string; - walletBalance: string; +export interface EnableMarginBrokerSubAccountResponse { + subAccountId: string; + enableMargin: boolean; + updateTime: number; } ⋮---- -export interface SubaccountPosition { - entryPrice: string; - markPrice: string; - positionAmt: string; - symbol: string; - unRealizedProfit: string; +export interface EnableFuturesBrokerSubAccountParams { + subAccountId: string; + futures: boolean; } ⋮---- -export interface ManagedSubAccountSnapshot { - code: number; - msg: string; - snapshotVos: { - data: { - balances?: SubaccountBalances[]; - totalAssetOfBtc?: string; - marginLevel?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - userAssets?: SubaccountUserAssets[]; - assets?: SubaccountAssets[]; - position?: SubaccountPosition[]; - }; - type: string; - updateTime: number; - }[]; +export interface EnableFuturesBrokerSubAccountResponse { + subAccountId: string; + enableFutures: boolean; + updateTime: number; } ⋮---- -export interface ManagedSubAccountTransferLogParams { - email: string; - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: 'from' | 'to'; - transferFunctionAccountType?: - | 'SPOT' - | 'MARGIN' - | 'ISOLATED_MARGIN' - | 'USDT_FUTURE' - | 'COIN_FUTURE'; +export interface EnableMarginApiKeyBrokerSubAccountParams { + subAccountId: string; + margin: boolean; } -⋮---- -export interface ManagerSubTransferHistoryVos { - fromEmail: string; +export interface UniversalTransferBrokerParams { + fromId?: string; + toId?: string; fromAccountType: string; - toEmail: string; toAccountType: string; asset: string; - amount: string; - scheduledData: number; - createTime: number; - status: string; - tranId: number; + amount: number; } ⋮---- -export interface ManagedSubAccountFuturesAssetsResponse { - code: string; - message: string; - snapshotVos: { - type: string; - updateTime: number; - data: { - assets: SubaccountAssets[]; - position: SubaccountPosition[]; - }; - }[]; +export interface GetUniversalTransferBrokerParams { + fromId?: string; + toId?: string; + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; } ⋮---- -export interface ManagedSubAccountMarginAssetsResponse { - marginLevel: string; - totalAssetOfBtc: string; - totalLiabilityOfBtc: string; - totalNetAssetOfBtc: string; - userAssets: SubaccountUserAssets[]; +export interface GetBrokerSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; } ⋮---- -export interface ManagedSubAccountListParams { - email?: string; - page?: number; - limit?: number; +export interface DeleteApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; } ⋮---- -export interface ManagerSubUserInfoVo { - rootUserId: number; - managersubUserId: number; - bindParentUserId: number; +export interface ChangePermissionApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface ChangePermissionApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface VirtualSubAccount { email: string; - insertTimeStamp: number; - bindParentEmail: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - isSignedLVTRiskAgreement: boolean; } ⋮---- -export interface SubaccountTradeInfoVos { - userId: number; - btc: number; - btcFutures: number; - btcMargin: number; - busd: number; - busdFutures: number; - busdMargin: number; - date: number; -} -export interface SubAccountTransactionStatistics { - recent30BtcTotal: string; - recent30BtcFuturesTotal: string; - recent30BtcMarginTotal: string; - recent30BusdTotal: string; - recent30BusdFuturesTotal: string; - recent30BusdMarginTotal: string; - tradeInfoVos: SubaccountTradeInfoVos[]; +export interface BrokerSubAccountHistory { + subAccountsHistory: SubAccountTransferHistoryList[]; } ⋮---- -export interface ManagedSubAccountDepositAddressParams { +export interface BrokerSubAccount { + subaccountId: string; email: string; - coin: string; - network?: string; + makerCommission?: string; + takerCommission?: string; + marginMakerCommission?: string; + marginTakerCommission?: string; + createTime?: number; + tag: string; } ⋮---- -export interface ManagedSubAccountDepositAddress { - coin: string; - address: string; - tag: string; - url: string; +export interface CreateApiKeyBrokerSubAccountResponse { + subaccountId: string; + apiKey: string; + secretKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; } ⋮---- -export interface EnableOptionsForSubAccountResponse { - email: string; - isEOptionsEnabled: boolean; +export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canUniversalTransfer: boolean; } ⋮---- -export interface ManagedSubAccountTransferTTLogParams { - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: string; - transferFunctionAccountType?: string; +export interface GetBrokerInfoResponse { + maxMakerCommission: string; + minMakerCommission: string; + maxTakerCommission: string; + minTakerCommission: string; + subAccountQty: number; + maxSubAccountQty: number; +} +export interface SubAccountListParams { + email?: string; + isFreeze?: StringBoolean; + page?: number; + limit?: number; } ⋮---- -export interface UIKlinesParams { - symbol: string; - interval: string; +export interface SubAccountListResponse { + subAccounts: SubAccountList[]; +} +⋮---- +export interface SubAccountSpotAssetTransferHistoryParams { + fromEmail?: string; + toEmail?: string; startTime?: number; endTime?: number; - timeZone?: string; + page?: number; limit?: number; } ⋮---- -export interface Ticker24hrFull { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - prevClosePrice: string; - lastPrice: string; - lastQty: string; - bidPrice: string; - bidQty: string; - askPrice: string; - askQty: string; - openPrice: string; - highPrice: string; - lowPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; +export interface SubAccountSpotAssetTransferHistory + extends SubAccountBasicTransfer { + status: string; } ⋮---- -export interface Ticker24hrMini { - symbol: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; +export interface SubAccountFuturesAssetTransferHistoryParams { + email: string; + futuresType: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; } ⋮---- -export type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; -⋮---- -export interface TradingDayTickerParams { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; +export interface SubAccountFuturesAssetTransferHistory { + success: boolean; + futuresType: number; + transfers: SubAccountBasicTransfer[]; } ⋮---- -export interface TradingDayTickerFull { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; +export interface SubAccountFuturesAssetTransferParams { + fromEmail: string; + toEmail: string; + futuresType: number; + asset: string; + amount: number; } ⋮---- -export interface TradingDayTickerMini { - symbol: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; +export interface SubAccountFuturesAssetTransfer { + success: boolean; + txnId: numberInString; } ⋮---- -export type TradingDayTickerSingle = - | TradingDayTickerFull - | TradingDayTickerMini; -⋮---- -export type TradingDayTickerArray = - | TradingDayTickerFull[] - | TradingDayTickerMini[]; +export interface SubAccountAssetsParams { + email: string; +} ⋮---- -export interface RollingWindowTickerParams { - symbol?: string; - symbols?: string[]; - windowSize?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; +export interface SubAccountAssets { + balances: SpotBalance[]; } ⋮---- -export interface NewOrderListOTOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; - workingStrategyId?: number; - workingStrategyType?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: string; - pendingStopPrice?: string; - pendingTrailingDelta?: string; - pendingQuantity: string; - pendingIcebergQty?: string; - pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingStrategyId?: number; - pendingStrategyType?: number; +export interface SubAccountSpotAssetsSummaryParams { + email?: string; + page?: number; + size?: number; } ⋮---- -export interface NewOrderListOTOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; +export interface SubAccountSpotAssetsSummary { + totalCount: number; + masterAccountTotalAsset: numberInString; + spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; } ⋮---- -export interface NewOrderListOTOCOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESPONSE'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - workingStrategyId?: number; - workingStrategyType?: number; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: string; - pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; +export interface SubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; } ⋮---- -export interface NewOrderListOTOCOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; +export interface SubAccountDepositAddress { + address: string; + coin: string; + tag: string; + url: string; } ⋮---- -export interface NewOrderListOPOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: string; - pendingStopPrice?: string; - pendingTrailingDelta?: string; - pendingIcebergQty?: string; - pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingStrategyId?: number; - pendingStrategyType?: number; - pendingPegPriceType?: string; - pendingPegOffsetType?: string; - pendingPegOffsetValue?: number; +export interface SubAccountDepositHistoryParams extends DepositHistoryParams { + email: string; } ⋮---- -export interface NewOrderListOPOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty?: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; +export interface SubAccountEnableMargin { + email: string; + isMarginEnabled: boolean; } ⋮---- -export interface NewOrderListOPOCOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingSide: 'BUY' | 'SELL'; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingAbovePegPriceType?: string; - pendingAbovePegOffsetType?: string; - pendingAbovePegOffsetValue?: number; - pendingBelowType?: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - pendingBelowPegPriceType?: string; - pendingBelowPegOffsetType?: string; - pendingBelowPegOffsetValue?: number; +export interface SubAccountMarginAccountDetail extends BasicBtcTotals { + email: string; + marginLevel: numberInString; + marginTradeCoeffVo: MarginTradeCoeffVo; + marginUserAssetVoList: MarginBalance[]; } ⋮---- -export interface NewOrderListOPOCOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty?: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; +export interface SubAccountListBtc extends BasicBtcTotals { + email: string; +} +⋮---- +export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { + subAccountList: SubAccountListBtc; +} +⋮---- +export interface SubAccountEnableFutures { + email: string; + isFuturesEnabled: boolean; +} +⋮---- +export interface SubAccountFuturesAccountDetail { + email: string; + asset: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + maxWithdrawAmount: numberInString; + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + updateTime: number; } ⋮---- -export interface OrderRateLimitUsage { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; +export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { + subAccountList: FuturesSubAccountList[]; } ⋮---- -export interface PreventedMatchesParams { +export interface FuturesPositionRisk { + entryPrice: numberInString; + leverage: numberInString; + maxNotional: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + positionAmount: numberInString; symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; + unrealizedProfit: numberInString; } ⋮---- -export interface PreventedMatch { - symbol: string; - preventedMatchId: number; - takerOrderId: number; - makerSymbol: string; - makerOrderId: number; - tradeGroupId: number; - selfTradePreventionMode: SelfTradePreventionMode; - price: string; - makerPreventedQuantity: string; - transactTime: number; +export interface SubAccountTransferParams { + email: string; + asset: string; + amount: number; + type: number; } ⋮---- -export interface AllocationsParams { - symbol: string; +export interface SubAccountTransfer { + txnId: numberInString; +} +⋮---- +export interface SubAccountTransferToSameMasterParams { + toEmail: string; + asset: string; + amount: number; +} +⋮---- +export interface SubAccountTransferToMasterParams { + asset: string; + amount: number; +} +⋮---- +export interface SubAccountTransferHistoryParams { + asset?: string; + type?: number; startTime?: number; endTime?: number; - fromAllocationId?: number; limit?: number; - orderId?: number; } ⋮---- -export interface Allocation { +export interface SubAccountUniversalTransferParams { + fromEmail?: string; + toEmail?: string; + fromAccountType: AccountType; + toAccountType: AccountType; + clientTranId?: string; + asset: string; + amount: number; +} +⋮---- +export interface SubAccountMovePositionParams { + fromUserEmail: string; + toUserEmail: string; + productType: string; + orderArgs: { + symbol: string; + quantity: number; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + }[]; +} +export interface SubAccountUniversalTransfer extends SubAccountTransfer { + clientTranId?: string; +} +⋮---- +export interface SubAccountMovePosition { + fromUserEmail: string; + toUserEmail: string; + productType: string; symbol: string; - allocationId: number; - allocationType: string; - orderId: number; - orderListId: number; + priceType: string; price: string; - qty: string; - quoteQty: string; - commission: string; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isAllocator: boolean; + quantity: string; + positionSide: string; + side: string; + success: boolean; } ⋮---- -export interface CommissionRates { +export interface SubAccountMovePositionHistoryParams { symbol: string; - standardCommission: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - taxCommission: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - discount: string; - }; + startTime?: number; + endTime?: number; + page: number; + row: number; } ⋮---- -export interface GetCrossMarginTransferHistoryParams { - asset?: string; - type?: 'ROLL_IN' | 'ROLL_OUT'; +export interface SubAccountMovePositionHistory { + fromUserEmail: string; + toUserEmail: string; + productType: string; + symbol: string; + price: string; + quantity: string; + positionSide: string; + side: string; + timeStamp: number; +} +⋮---- +export interface SubAccountUniversalTransferHistoryParams { + fromEmail?: string; + toEmail?: string; + clientTranId?: string; startTime?: number; endTime?: number; - current?: number; - size?: number; - isolatedSymbol?: string; + page?: number; + limit?: number; } ⋮---- -export interface CrossMarginTransferHistory { - amount: string; - asset: string; +export interface SubAccountUniversalTransferHistoryResponse { + result: SubAccountUniversalTransferHistory[]; + totalCount: number; +} +⋮---- +export interface SubAccountEnableLeverageToken { + email: string; + enableBlvt: boolean; +} +⋮---- +export interface AddIpRestriction extends BasicSubAccount { status: string; - timestamp: number; - txId: number; - type: 'ROLL_IN' | 'ROLL_OUT'; - transFrom?: string; - transTo?: string; - fromSymbol?: string; - toSymbol?: string; + ipAddress: string; } ⋮---- -export interface GetMarginInterestHistoryParams { - asset?: string; - isolatedSymbol?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface SubAccountEnableOrDisableIPRestriction { + ipRestrict: boolean; + ipList: string[]; + updateTime: number; + apiKey: string; } ⋮---- -export interface MarginInterestHistory { - txId: number; - interestAccuredTime: number; +export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { + ipAddress: string; +} +⋮---- +export interface AddIPListForSubAccountResponseParams { + ip: string; + updateTime: number; + apiKey: string; +} +⋮---- +export interface SubAccountAssetDetails { + coin: string; + name: string; + totalBalance: numberInString; + availableBalance: numberInString; + inOrder: numberInString; + btcValue: numberInString; +} +⋮---- +export interface WithdrawAssetsFromManagedSubAccountParams { + fromEmail: string; asset: string; - rawAsset?: string; - principal: string; - interest: string; - interestRate: string; - type: - | 'PERIODIC' - | 'ON_BORROW' - | 'PERIODIC_CONVERTED' - | 'ON_BORROW_CONVERTED' - | 'PORTFOLIO'; - isolatedSymbol?: string; + amount: number; + transferDate?: number; +} +⋮---- +export interface BasicFuturesSubAccountParams { + email: string; + futuresType: 1 | 2; +} +⋮---- +export interface SubAccountSummaryOnFuturesAccountV2Params { + futuresType: 1 | 2; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountUSDMDetail { + futureAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + maxWithdrawAmount: numberInString; + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + updateTime: number; + }; } ⋮---- -export interface GetForceLiquidationRecordParams { - startTime?: number; - endTime?: number; - isolatedSymbol?: string; - current?: number; - size?: number; +export interface COINMSubAccount { + email: string; + totalMarginBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; } ⋮---- -export interface ForceLiquidationRecord { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - isIsolated: boolean; - updatedTime: number; +export interface SubAccountCOINMDetail { + deliveryAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; + }; } ⋮---- -export interface QueryMarginAccountAllOCOParams { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; +export interface SubAccountUSDMSummary { + futureAccountSummaryResp: { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + subAccountList: FuturesSubAccountList[]; + }; } ⋮---- -export interface QueryMarginAccountTradeListParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; +export interface SubAccountCOINMSummary { + deliveryAccountSummaryResp: { + totalMarginBalanceOfBTC: numberInString; + totalUnrealizedProfitOfBTC: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; + subAccountList: COINMSubAccount[]; + }; } ⋮---- -export interface IsolatedMarginSymbol { - base: string; - isBuyAllowed: boolean; - isMarginTrade: boolean; - isSellAllowed: boolean; - quote: string; +export interface COINMPositionRisk { + entryPrice: numberInString; + markPrice: numberInString; + leverage: numberInString; + isolated: numberInString; + isolatedWallet: numberInString; + isolatedMargin: numberInString; + isAutoAddMargin: numberInString; + positionSide: string; + positionAmount: numberInString; symbol: string; - delistTime?: number; + unrealizedProfit: numberInString; } ⋮---- -export interface ToggleBNBBurnParams { - spotBNBBurn?: 'true' | 'false'; - interestBNBBurn?: 'true' | 'false'; +export interface SubAccountUSDMPositionRisk { + futurePositionRiskVos: FuturesPositionRisk[]; } ⋮---- -export interface BNBBurnResponse { - spotBNBBurn: boolean; - interestBNBBurn: boolean; +export interface SubAccountCOINMPositionRisk { + deliveryPositionRiskVos: COINMPositionRisk[]; } ⋮---- -export interface QueryMarginInterestRateHistoryParams { +export interface StakingProductDetail { asset: string; - vipLevel?: number; - startTime?: number; - endTime?: number; + rewardAsset: string; + duration: number; + renewable: boolean; + apy: numberInString; } ⋮---- -export interface MarginInterestRateHistory { +export interface StakingProductQuota { + totalPersonalQuota: numberInString; + minimum: numberInString; +} +⋮---- +export interface StakingProduct { + projectId: string; + detail: StakingProductDetail; + quota: StakingProductQuota; +} +⋮---- +export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; +export type StakingStatus = 'HOLDING' | 'REDEEMED'; +export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; +export type BSwapType = 'SINGLE' | 'COMBINATION'; +export type BSwapOperationType = 'ADD' | 'REMOVE'; +⋮---- +export interface StakingProductPosition { + positionId: numberInString; + projectId: string; asset: string; - dailyInterestRate: string; - timestamp: number; - vipLevel: number; + amount: numberInString; + purchaseTime: numberInString; + duration: numberInString; + accrualDays: numberInString; + rewardAsset: string; + APY: numberInString; + rewardAmt: numberInString; + extraRewardAsset: string; + extraRewardAPY: numberInString; + estExtraRewardAmt: numberInString; + nextInterestPay: numberInString; + nextInterestPayDate: numberInString; + payInterestPeriod: numberInString; + redeemAmountEarly: numberInString; + interestEndDate: numberInString; + deliverDate: numberInString; + redeemPeriod: numberInString; + redeemingAmt: numberInString; + partialAmtDeliverDate: numberInString; + canRedeemEarly: boolean; + renewable: boolean; + type: string; + status: StakingStatus; +} +export interface StakingBasicParams { + product: StakingProductType; + current?: number; + size?: number; } ⋮---- -export interface QueryCrossMarginFeeDataParams { - vipLevel?: number; - coin?: string; +export interface FlexibleSavingBasicParams { + status?: string; + featured?: number; + current?: number; + size?: number; + asset?: string; } ⋮---- -export interface CrossMarginFeeData { - vipLevel: number; - coin: string; - transferIn: boolean; - borrowable: boolean; - dailyInterest: string; - yearlyInterest: string; - borrowLimit: string; - marginablePairs: string[]; +export interface FlexibleProductPositionParams { + status?: string; + featured?: number; + current?: number; + size?: number; } ⋮---- -export interface IsolatedMarginFeeData { - vipLevel: number; - symbol: string; - leverage: string; - data: { - coin: string; - dailyInterest: string; - borrowLimit: string; - }[]; +export interface PurchaseFlexibleProductParams { + productId: string; + amount: number; + autoSubscribe: boolean; } ⋮---- -export interface QueryIsolatedMarginTierDataParams { - symbol: string; - tier?: number; +export interface PurchaseFlexibleProductResponse { + purchaseId: number; } ⋮---- -export interface IsolatedMarginTierData { - symbol: string; - tier: number; - effectiveMultiple: string; - initialRiskRatio: string; - liquidationRiskRatio: string; - baseAssetMaxBorrowable: string; - quoteAssetMaxBorrowable: string; +export interface RedeemFlexibleProductParams { + productId: string; + amount: number; + type: 'FAST' | 'NORMAL'; } ⋮---- -export interface GetMarginOrderCountUsageParams { - isIsolated?: string; - symbol?: string; +export interface LeftDailyPurchaseQuotaFlexibleProductResponse { + asset: string; + leftQuota: string; } ⋮---- -export interface MarginOrderCountUsageResponse { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; +export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; +export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +export type ProjectSortBy = + | 'START_TIME' + | 'LOT_SIZE' + | 'INTEREST_RATE' + | 'DURATION'; +⋮---- +export interface FixedAndActivityProjectParams { + asset?: string; + type: ProjectType; + status?: ProjectStatus; + isSortAsc?: boolean; + sortBy?: ProjectSortBy; + current?: number; + size?: number; +} +export interface FixedAndActivityProjectPositionParams { + asset?: string; + projectId?: string; + status?: StakingStatus; } ⋮---- -export interface Collateral { - minUsdValue: string; - maxUsdValue?: string; - discountRate: string; +export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +⋮---- +export interface PurchaseRecordParams { + lendingType: LendingType; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface SmallLiabilityExchangeCoin { +export interface NewFutureAccountTransferParams { asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; + amount: number; + type: 1 | 2 | 3 | 4; } -export interface GetSmallLiabilityExchangeHistoryParams { - current: number; - size: number; - startTime?: number; +⋮---- +export interface GetFutureAccountTransferHistoryParams { + asset: string; + startTime: number; endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface SmallLiabilityExchangeHistory { +export interface FutureAccountTransfer { asset: string; + tranId: number; amount: string; - targetAsset: string; - targetAmount: string; - bizType: string; + type: string; timestamp: number; + status: 'PENDING' | 'CONFIRMED' | 'FAILED'; } ⋮---- -export interface GetNextHourlyInterestRateParams { - assets: string; - isIsolated: boolean; +export interface GetLoanCoinPaginatedHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface NextHourlyInterestRate { +/** + * + * STAKING + * + */ +⋮---- +export interface StakingHistory { + positionId: numberInString; + time: number; asset: string; - nextHourlyInterestRate: string; + project?: string; + amount: numberInString; + lockPeriod?: numberInString; + deliverDate?: numberInString; + type?: string; + status: string; } ⋮---- -export interface GetMarginCapitalFlowParams { +export interface StakingPersonalLeftQuota { + leftPersonalQuota: numberInString; +} +⋮---- +export interface StakingHistoryParams extends StakingBasicParams { + txnType: StakingTxnType; asset?: string; - symbol?: string; - type?: string; startTime?: number; endTime?: number; - fromId?: number; - limit?: number; +} +export interface BSwapOperationsParams { + operationId?: number; + poolId?: number; + operation: BSwapOperationType; + startTime?: number; + endTime?: number; + limit: number; } ⋮---- -export interface MarginCapitalFlow { - id: number; - tranId: number; - timestamp: number; +export interface BSwapOperations { + operationId: number; + poolId: number; + poolName: string; + operation: BSwapOperationType; + status: number; + updateTime: number; + shareAmount: numberInString; +} +export interface RemoveBSwapLiquidityParams { + poolId: number; + type: BSwapType; + asset?: string; + shareAmount: number; +} +⋮---- +export interface AddBSwapLiquidityParams { + poolId: number; + type?: BSwapType; asset: string; - symbol: string; - type: string; - amount: string; + quantity: number; } ⋮---- -export interface MarginDelistSchedule { - delistTime: number; - crossMarginAssets: string[]; - isolatedMarginSymbols: string[]; - updateTime: number; +export interface BSwapShare { + shareAmount: number; + sharePercentage: number; + asset: { [k: string]: number }; } ⋮---- -export interface MarginAvailableInventoryResponse { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any; +export interface BSwapLiquidity { + poolId: number; + poolNmae: string; updateTime: number; + liquidity: { [k: string]: number }; + share: BSwapShare; } ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface FundingAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + btcValuation: string; +} ⋮---- -export interface ManualLiquidationParams { - type: string; - symbol?: string; +export interface GetAssetParams { + asset?: string; + needBtcValuation?: boolean; } ⋮---- -export interface ManualLiquidationResponse { +export interface UserAsset { asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; + free: string; + locked: string; + freeze: string; + withdrawing: string; + ipoable: string; + btcValuation: string; } ⋮---- -export interface LeverageBracket { - leverage: number; - maxDebt: number; - maintenanceMarginRate: number; - initialMarginRate: number; - fastNum: number; +export interface ConvertTransfer { + clientTranId: string; + asset: string; + amount: number; + targetAsset: string; + accountType?: string; } ⋮---- -export interface LiabilityCoinLeverageBracket { - assetNames: string[]; - rank: number; - brackets: LeverageBracket[]; +export interface ConvertTransferResponse { + tranId: number; + status: string; } -export interface GetFlexibleSubscriptionRecordParams { - productId?: string; - purchaseId?: string; +⋮---- +export interface GetConvertBUSDHistoryParams { + tranId?: number; + clientTranId?: string; asset?: string; - startTime?: number; - endTime?: number; + startTime: number; + endTime: number; + accountType?: string; current?: number; size?: number; } ⋮---- -export interface GetFlexibleSubscriptionRecordResponse { - amount: string; - asset: string; +export interface BUSDConversionRecord { + tranId: number; + type: number; time: number; - purchaseId: number; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; + deductedAsset: string; + deductedAmount: string; + targetAsset: string; + targetAmount: string; status: string; + accountType: string; } ⋮---- -export interface GetLockedSubscriptionRecordParams { - purchaseId?: string; +export interface CloudMiningHistoryParams { + tranId?: number; + clientTranId?: string; asset?: string; - startTime?: number; - endTime?: number; + startTime: number; + endTime: number; current?: number; size?: number; } ⋮---- -export interface LockedSubscriptionRecord { - positionId: string; - purchaseId: number; - time: number; +export interface CloudMining { + createTime: number; + tranId: number; + type: number; asset: string; amount: string; - lockPeriod: string; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; status: string; } ⋮---- -export interface GetFlexibleRedemptionRecordParams { - productId?: string; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface ConvertibleCoinsResponse { + convertEnabled: boolean; + coins: string[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exchangeRates: any; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface ConvertibleCoinsParams { + coin: string; + enable: boolean; +} +⋮---- +export interface SubmitDepositCreditParams { + depositId?: number; + txId?: string; + subAccountId?: number; + subUserId?: number; +} +⋮---- +export interface SubmitDepositCreditResponse { + code: string; + message: string; + data: boolean; + success: boolean; +} +⋮---- +export interface DepositAddressListParams { + coin: string; + network?: string; +} +⋮---- +export interface DepositAddress { + coin: string; + address: string; + tag: string; + isDefault: number; } ⋮---- -export interface FlexibleRedemptionRecord { - amount: string; - asset: string; - time: number; - productId: string; - redeemId: number; - destAccount: string; - status: string; +export interface WalletBalance { + activate: boolean; + balance: string; + walletName: string; } ⋮---- -export interface GetLockedRedemptionRecordParams { - positionId?: string; - redeemId?: string; +export interface DelegationHistoryParams { + email: string; + startTime: number; + endTime: number; + type?: 'Delegate' | 'Undelegate'; asset?: string; - startTime?: number; - endTime?: number; current?: number; size?: number; } ⋮---- -export interface LockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; +export interface DelegationHistory { + clientTranId: string; + transferType: 'Delegate' | 'Undelegate'; asset: string; - lockPeriod: string; amount: string; - type: string; - deliverDate: string; - status: string; + time: number; } ⋮---- -export interface GetFlexibleRewardsHistoryParams { - productId?: string; - asset?: string; - startTime?: number; - endTime?: number; - type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; - current?: number; - size?: number; +export interface DelistScheduleResponse { + delistTime: number; + symbols: string[]; } ⋮---- -export interface FlexibleRewardsHistory { - asset: string; - rewards: string; - projectId: string; - type: string; - time: number; +export interface WithdrawAddress { + address: string; + addressTag: string; + coin: string; + name: string; + network: string; + origin: string; + originType: string; + whiteStatus: boolean; } ⋮---- -export interface GetLockedRewardsHistoryParams { - positionId?: string; - asset?: string; +export interface AccountInfo { + vipLevel: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + isOptionsEnabled: boolean; + isPortfolioMarginRetailEnabled: boolean; +} +⋮---- +export interface ManagedSubAccountSnapshotParams { + email: string; + type: 'SPOT' | 'MARGIN' | 'FUTURES'; startTime?: number; endTime?: number; - current?: number; - size?: number; + limit?: number; } ⋮---- -export interface GetLockedRewardsHistory { - positionId: string; - time: number; +export interface SubaccountBalances { asset: string; - lockPeriod: string; - amount: string; - type: string; -} -⋮---- -export interface SetAutoSubscribeParams { - productId: string; - autoSubscribe: boolean; + free: string; + locked: string; } ⋮---- -export interface GetFlexibleSubscriptionPreviewParams { - productId: string; - amount: number; +export interface SubaccountUserAssets { + asset: string; + borrowed: string; + free: string; + interest: string; + locked: string; + netAsset: string; } ⋮---- -export interface FlexibleSubscriptionPreview { - totalAmount: string; - rewardAsset: string; - airDropAsset: string; - estDailyBonusRewards: string; - estDailyRealTimeRewards: string; - estDailyAirdropRewards: string; +export interface SubaccountAssets { + asset: string; + marginBalance: string; + walletBalance: string; } ⋮---- -export interface GetLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; +export interface SubaccountPosition { + entryPrice: string; + markPrice: string; + positionAmt: string; + symbol: string; + unRealizedProfit: string; } ⋮---- -export interface LockedSubscriptionPreview { - rewardAsset: string; - totalRewardAmt: string; - extraRewardAsset: string; - estTotalExtraRewardAmt: string; - nextPay: string; - nextPayDate: string; - valueDate: string; - rewardsEndDate: string; - deliverDate: string; - nextSubscriptionDate: string; - boostRewardAsset: string; - estDailyRewardAmt: string; +export interface ManagedSubAccountSnapshot { + code: number; + msg: string; + snapshotVos: { + data: { + balances?: SubaccountBalances[]; + totalAssetOfBtc?: string; + marginLevel?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + userAssets?: SubaccountUserAssets[]; + assets?: SubaccountAssets[]; + position?: SubaccountPosition[]; + }; + type: string; + updateTime: number; + }[]; } ⋮---- -export interface GetRateHistoryParams { - productId: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface ManagedSubAccountTransferLogParams { + email: string; + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: 'from' | 'to'; + transferFunctionAccountType?: + | 'SPOT' + | 'MARGIN' + | 'ISOLATED_MARGIN' + | 'USDT_FUTURE' + | 'COIN_FUTURE'; } ⋮---- -export interface GetRateHistory { - productId: string; +export interface ManagerSubTransferHistoryVos { + fromEmail: string; + fromAccountType: string; + toEmail: string; + toAccountType: string; asset: string; - annualPercentageRate: string; - time: number; + amount: string; + scheduledData: number; + createTime: number; + status: string; + tranId: number; } ⋮---- -export interface GetCollateralRecordParams { - productId?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface ManagedSubAccountFuturesAssetsResponse { + code: string; + message: string; + snapshotVos: { + type: string; + updateTime: number; + data: { + assets: SubaccountAssets[]; + position: SubaccountPosition[]; + }; + }[]; } ⋮---- -export interface CollateralRecord { - amount: string; - productId: string; - asset: string; - createTime: number; - type: string; - productName: string; - orderId: number; +export interface ManagedSubAccountMarginAssetsResponse { + marginLevel: string; + totalAssetOfBtc: string; + totalLiabilityOfBtc: string; + totalNetAssetOfBtc: string; + userAssets: SubaccountUserAssets[]; } ⋮---- -export interface GetDualInvestmentProductListParams { - optionType: string; - exercisedCoin: string; - investCoin: string; - pageSize?: number; - pageIndex?: number; +export interface ManagedSubAccountListParams { + email?: string; + page?: number; + limit?: number; } ⋮---- -export interface DualInvestmentProduct { - id: string; - investCoin: string; - exercisedCoin: string; - strikePrice: string; - duration: number; - settleDate: number; - purchaseDecimal: number; - purchaseEndTime: number; - canPurchase: boolean; - apr: string; - orderId: number; - minAmount: string; - maxAmount: string; - createTimestamp: number; - optionType: string; - isAutoCompoundEnable: boolean; - autoCompoundPlanList: string[]; +export interface ManagerSubUserInfoVo { + rootUserId: number; + managersubUserId: number; + bindParentUserId: number; + email: string; + insertTimeStamp: number; + bindParentEmail: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + isSignedLVTRiskAgreement: boolean; } ⋮---- -export interface SubscribeDualInvestmentProductParams { - id: string; - orderId: string; - depositAmount: number; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +export interface SubaccountTradeInfoVos { + userId: number; + btc: number; + btcFutures: number; + btcMargin: number; + busd: number; + busdFutures: number; + busdMargin: number; + date: number; } -⋮---- -export interface SubscribeDualInvestmentProductResponse { - positionId: number; - investCoin: string; - exercisedCoin: string; - subscriptionAmount: string; - duration: number; - autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; - strikePrice: string; - settleDate: number; - purchaseStatus: string; - apr: string; - orderId: number; - purchaseTime: number; - optionType: string; +export interface SubAccountTransactionStatistics { + recent30BtcTotal: string; + recent30BtcFuturesTotal: string; + recent30BtcMarginTotal: string; + recent30BusdTotal: string; + recent30BusdFuturesTotal: string; + recent30BusdMarginTotal: string; + tradeInfoVos: SubaccountTradeInfoVos[]; } ⋮---- -export interface GetDualInvestmentPositionsParams { - status?: - | 'PENDING' - | 'PURCHASE_SUCCESS' - | 'SETTLED' - | 'PURCHASE_FAIL' - | 'REFUNDING' - | 'REFUND_SUCCESS' - | 'SETTLING'; - pageSize?: number; - pageIndex?: number; +export interface ManagedSubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; } ⋮---- -export interface DualInvestmentPosition { - id: string; - investCoin: string; - exercisedCoin: string; - subscriptionAmount: string; - strikePrice: string; - duration: number; - settleDate: number; - purchaseStatus: string; - apr: string; - orderId: number; - purchaseEndTime: number; - optionType: string; - autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; - settlePrice?: string; - isExercised?: boolean; - settleAsset?: string; - settleAmount?: string; - subscriptionTime?: number; +export interface ManagedSubAccountDepositAddress { + coin: string; + address: string; + tag: string; + url: string; } ⋮---- -export interface CheckDualInvestmentAccountsResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; +export interface EnableOptionsForSubAccountResponse { + email: string; + isEOptionsEnabled: boolean; } ⋮---- -export interface ChangeAutoCompoundStatusParams { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +export interface ManagedSubAccountTransferTTLogParams { + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: string; + transferFunctionAccountType?: string; } ⋮---- -export interface ChangeAutoCompoundStatusResponse { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +export interface UIKlinesParams { + symbol: string; + interval: string; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; } ⋮---- -export interface GetTargetAssetListParams { - targetAsset?: string; - size?: number; - current?: number; +export interface Ticker24hrFull { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + prevClosePrice: string; + lastPrice: string; + lastQty: string; + bidPrice: string; + bidQty: string; + askPrice: string; + askQty: string; + openPrice: string; + highPrice: string; + lowPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; } ⋮---- -export interface RoiAndDimensionType { - simulateRoi: string; - dimensionValue: string; - dimensionUnit: string; +export interface Ticker24hrMini { + symbol: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; } ⋮---- -export interface AutoInvestAsset { - targetAsset: string; - roiAndDimensionTypeList: RoiAndDimensionType[]; +export type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; +⋮---- +export interface TradingDayTickerParams { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; } ⋮---- -export interface GetTargetAssetListResponse { - targetAssets: string[]; - autoInvestAssetList: AutoInvestAsset[]; +export interface TradingDayTickerFull { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; } ⋮---- -export interface GetTargetAssetROIParams { - targetAsset: string; - hisRoiType: - | 'FIVE_YEAR' - | 'THREE_YEAR' - | 'ONE_YEAR' - | 'SIX_MONTH' - | 'THREE_MONTH' - | 'SEVEN_DAY'; +export interface TradingDayTickerMini { + symbol: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; } ⋮---- -export interface TargetAssetROI { - date: string; - simulateRoi: string; +export type TradingDayTickerSingle = + | TradingDayTickerFull + | TradingDayTickerMini; +⋮---- +export type TradingDayTickerArray = + | TradingDayTickerFull[] + | TradingDayTickerMini[]; +⋮---- +export interface RollingWindowTickerParams { + symbol?: string; + symbols?: string[]; + windowSize?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; } ⋮---- -export interface GetSourceAssetListParams { - targetAsset?: string[]; - indexId?: number; - usageType: 'RECURRING' | 'ONE_TIME'; - flexibleAllowedToUse?: boolean; - sourceType?: 'MAIN_SITE' | 'TR'; +export interface NewOrderListOTOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: string; + pendingStopPrice?: string; + pendingTrailingDelta?: string; + pendingQuantity: string; + pendingIcebergQty?: string; + pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingStrategyId?: number; + pendingStrategyType?: number; } ⋮---- -export interface SourceAsset { - sourceAsset: string; - assetMinAmount: string; - assetMaxAmount: string; - scale: string; - flexibleAmount: string; +export interface NewOrderListOTOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; } ⋮---- -export interface GetSourceAssetListResponse { - feeRate: string; - taxRate: string; - sourceAssets: SourceAsset[]; +export interface NewOrderListOTOCOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESPONSE'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + workingStrategyId?: number; + workingStrategyType?: number; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: string; + pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; } ⋮---- -export interface AutoInvestPortfolioDetail { - targetAsset: string; - percentage: number; +export interface NewOrderListOTOCOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; } ⋮---- -export interface CreateInvestmentPlanParams { - UID: string; - sourceType: 'MAIN_SITE' | 'TR'; - requestId?: string; - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; - indexId?: number; - subscriptionAmount: number; - subscriptionCycle: - | 'H1' - | 'H4' - | 'H8' - | 'H12' - | 'WEEKLY' - | 'DAILY' - | 'MONTHLY' - | 'BI_WEEKLY'; - subscriptionStartDay?: number; - subscriptionStartWeekday?: - | 'MON' - | 'TUE' - | 'WED' - | 'THU' - | 'FRI' - | 'SAT' - | 'SUN'; - subscriptionStartTime: number; - sourceAsset: string; - flexibleAllowedToUse: boolean; - details: AutoInvestPortfolioDetail[]; +export interface NewOrderListOPOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: string; + pendingStopPrice?: string; + pendingTrailingDelta?: string; + pendingIcebergQty?: string; + pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; } ⋮---- -export interface CreateInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; +export interface NewOrderListOPOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty?: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; } ⋮---- -export interface EditInvestmentPlanParams { - planId: number; - subscriptionAmount: number; - subscriptionCycle: - | 'H1' - | 'H4' - | 'H8' - | 'H12' - | 'WEEKLY' - | 'DAILY' - | 'MONTHLY' - | 'BI_WEEKLY'; - subscriptionStartDay?: number; - subscriptionStartWeekday?: - | 'MON' - | 'TUE' - | 'WED' - | 'THU' - | 'FRI' - | 'SAT' - | 'SUN'; - subscriptionStartTime: number; - sourceAsset: string; - flexibleAllowedToUse?: boolean; - details: AutoInvestPortfolioDetail[]; +export interface NewOrderListOPOCOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingSide: 'BUY' | 'SELL'; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingAbovePegPriceType?: string; + pendingAbovePegOffsetType?: string; + pendingAbovePegOffsetValue?: number; + pendingBelowType?: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; } ⋮---- -export interface EditInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; +export interface NewOrderListOPOCOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty?: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; } ⋮---- -export interface ChangePlanStatusParams { - planId: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +export interface OrderRateLimitUsage { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; } ⋮---- -export interface ChangePlanStatusResponse { - planId: number; - nextExecutionDateTime: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +export interface PreventedMatchesParams { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; } ⋮---- -export interface GetPlanDetailsParams { - planId?: number; - requestId?: string; +export interface PreventedMatch { + symbol: string; + preventedMatchId: number; + takerOrderId: number; + makerSymbol: string; + makerOrderId: number; + tradeGroupId: number; + selfTradePreventionMode: SelfTradePreventionMode; + price: string; + makerPreventedQuantity: string; + transactTime: number; } ⋮---- -export interface GetSubscriptionTransactionHistoryParams { - planId?: number; +export interface AllocationsParams { + symbol: string; startTime?: number; endTime?: number; - targetAsset?: string; - planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; - size?: number; - current?: number; -} -⋮---- -export interface AssetAllocation { - targetAsset: string; - allocation: string; -} -⋮---- -export interface GetIndexDetailsResponse { - indexId: number; - indexName: string; - status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; - assetAllocation: AssetAllocation[]; -} -⋮---- -export interface IndexLinkedPlanDetail { - targetAsset: string; - averagePriceInUSD: string; - totalInvestedInUSD: string; - currentInvestedInUSD: string; - purchasedAmount: string; - pnlInUSD: string; - roi: string; - percentage: string; - availableAmount: string; - redeemedAmount: string; - assetValueInUSD: string; -} -⋮---- -export interface GetIndexLinkedPlanPositionDetailsResponse { - indexId: number; - totalInvestedInUSD: string; - currentInvestedInUSD: string; - pnlInUSD: string; - roi: string; - assetAllocation: { targetAsset: string; allocation: string }[]; - details: IndexLinkedPlanDetail[]; -} -⋮---- -export interface SubmitOneTimeTransactionParams { - sourceType: 'MAIN_SITE' | 'TR'; - requestId?: string; - subscriptionAmount: number; - sourceAsset: string; - flexibleAllowedToUse?: boolean; - planId?: number; - indexId?: number; - details: AutoInvestPortfolioDetail[]; -} -⋮---- -export interface SubmitOneTimeTransactionResponse { - transactionId: number; - waitSecond: number; -} -⋮---- -export interface GetOneTimeTransactionStatusParams { - transactionId: number; - requestId?: string; + fromAllocationId?: number; + limit?: number; + orderId?: number; } ⋮---- -export interface GetOneTimeTransactionStatusResponse { - transactionId: number; - status: 'SUCCESS' | 'CONVERTING'; +export interface Allocation { + symbol: string; + allocationId: number; + allocationType: string; + orderId: number; + orderListId: number; + price: string; + qty: string; + quoteQty: string; + commission: string; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isAllocator: boolean; } ⋮---- -export interface SubmitIndexLinkedPlanRedemptionParams { - indexId: number; - requestId?: string; - redemptionPercentage: number; +export interface CommissionRates { + symbol: string; + standardCommission: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + taxCommission: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + discount: string; + }; } ⋮---- -export interface GetIndexLinkedPlanRedemptionHistoryParams { - requestId: number; +export interface GetCrossMarginTransferHistoryParams { + asset?: string; + type?: 'ROLL_IN' | 'ROLL_OUT'; startTime?: number; endTime?: number; current?: number; - asset?: string; size?: number; + isolatedSymbol?: string; } ⋮---- -export interface IndexLinkedPlanRedemptionRecord { - indexId: number; - indexName: string; - redemptionId: number; - status: 'SUCCESS' | 'FAILED'; - asset: string; +export interface CrossMarginTransferHistory { amount: string; - redemptionDateTime: number; - transactionFee: string; - transactionFeeUnit: string; + asset: string; + status: string; + timestamp: number; + txId: number; + type: 'ROLL_IN' | 'ROLL_OUT'; + transFrom?: string; + transTo?: string; + fromSymbol?: string; + toSymbol?: string; } ⋮---- -export interface GetIndexLinkedPlanRebalanceHistoryParams { +export interface GetMarginInterestHistoryParams { + asset?: string; + isolatedSymbol?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- -export interface RebalanceTransactionDetail { +export interface MarginInterestHistory { + txId: number; + interestAccuredTime: number; asset: string; - transactionDateTime: number; - rebalanceDirection: 'BUY' | 'SELL'; - rebalanceAmount: string; -} -⋮---- -export interface IndexLinkedPlanRebalanceRecord { - indexId: number; - indexName: string; - rebalanceId: number; - status: 'SUCCESS' | 'INIT'; - rebalanceFee: string; - rebalanceFeeUnit: string; - transactionDetails: RebalanceTransactionDetail[]; -} -⋮---- -export interface SubscribeEthStakingV2Response { - success: boolean; - wbethAmount: string; - conversionRatio: string; -} -⋮---- -export interface RedeemEthParams { - asset?: string; - amount: number; -} -⋮---- -export interface RedeemEthResponse { - success: boolean; - arrivalTime: number; - ethAmount: string; - conversionRatio: string; + rawAsset?: string; + principal: string; + interest: string; + interestRate: string; + type: + | 'PERIODIC' + | 'ON_BORROW' + | 'PERIODIC_CONVERTED' + | 'ON_BORROW_CONVERTED' + | 'PORTFOLIO'; + isolatedSymbol?: string; } ⋮---- -export interface GetEthStakingHistoryParams { +export interface GetForceLiquidationRecordParams { startTime?: number; endTime?: number; + isolatedSymbol?: string; current?: number; size?: number; } ⋮---- -export interface EthStakingHistory { - time: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAmount: string; - conversionRatio: string; +export interface ForceLiquidationRecord { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + isIsolated: boolean; + updatedTime: number; } ⋮---- -export interface GetEthRedemptionHistoryParams { +export interface QueryMarginAccountAllOCOParams { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; + fromId?: number; startTime?: number; endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface EthRedemptionHistory { - time: number; - arrivalTime: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAsset: string; - distributeAmount: string; - conversionRatio: string; + limit?: number; } ⋮---- -export interface GetBethRewardsHistoryParams { +export interface QueryMarginAccountTradeListParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + orderId?: number; startTime?: number; endTime?: number; - current?: number; - size?: number; + fromId?: number; + limit?: number; } ⋮---- -export interface BethRewardsHistory { - time: number; - asset: string; - holding: string; - amount: string; - annualPercentageRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; +export interface IsolatedMarginSymbol { + base: string; + isBuyAllowed: boolean; + isMarginTrade: boolean; + isSellAllowed: boolean; + quote: string; + symbol: string; + delistTime?: number; } ⋮---- -export interface GetEthStakingQuotaResponse { - leftStakingPersonalQuota: string; - leftRedemptionPersonalQuota: string; +export interface ToggleBNBBurnParams { + spotBNBBurn?: 'true' | 'false'; + interestBNBBurn?: 'true' | 'false'; } ⋮---- -export interface GetETHRateHistoryParams { +export interface BNBBurnResponse { + spotBNBBurn: boolean; + interestBNBBurn: boolean; +} +⋮---- +export interface QueryMarginInterestRateHistoryParams { + asset: string; + vipLevel?: number; startTime?: number; endTime?: number; - current?: number; - size?: number; } ⋮---- -export interface ETHRateHistory { - annualPercentageRate: string; - exchangeRate: string; - time: number; +export interface MarginInterestRateHistory { + asset: string; + dailyInterestRate: string; + timestamp: number; + vipLevel: number; } ⋮---- -export interface GetEthStakingAccountResponse { - cumulativeProfitInBETH: string; - lastDayProfitInBETH: string; +export interface QueryCrossMarginFeeDataParams { + vipLevel?: number; + coin?: string; } ⋮---- -export interface GetEthStakingAccountV2Response { - holdingInETH: string; - holdings: { - wbethAmount: string; - bethAmount: string; - }; - thirtyDaysProfitInETH: string; - profit: { - amountFromWBETH: string; - amountFromBETH: string; - }; +export interface CrossMarginFeeData { + vipLevel: number; + coin: string; + transferIn: boolean; + borrowable: boolean; + dailyInterest: string; + yearlyInterest: string; + borrowLimit: string; + marginablePairs: string[]; } ⋮---- -export interface WrapBethResponse { - success: boolean; - wbethAmount: string; - exchangeRate: string; +export interface IsolatedMarginFeeData { + vipLevel: number; + symbol: string; + leverage: string; + data: { + coin: string; + dailyInterest: string; + borrowLimit: string; + }[]; } ⋮---- -export interface GetWrapHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface QueryIsolatedMarginTierDataParams { + symbol: string; + tier?: number; } ⋮---- -export interface WrapHistory { - time: number; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - exchangeRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; +export interface IsolatedMarginTierData { + symbol: string; + tier: number; + effectiveMultiple: string; + initialRiskRatio: string; + liquidationRiskRatio: string; + baseAssetMaxBorrowable: string; + quoteAssetMaxBorrowable: string; } ⋮---- -export interface WbethRewardsHistory { - time: number; - amountInETH: string; - holding: string; - holdingInETH: string; - annualPercentageRate: string; +export interface GetMarginOrderCountUsageParams { + isIsolated?: string; + symbol?: string; } ⋮---- -export interface GetWbethRewardsHistoryResponse { - estRewardsInETH: string; - rows: WbethRewardsHistory[]; - total: number; +export interface MarginOrderCountUsageResponse { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; } ⋮---- -/** - * BFUSD (sapi/v1/bfusd/*) - */ +export interface Collateral { + minUsdValue: string; + maxUsdValue?: string; + discountRate: string; +} ⋮---- -export interface BfusdAccountResponse { - bfusdAmount: string; - usdtProfit: string; - bfusdProfit: string; +export interface SmallLiabilityExchangeCoin { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; +} +export interface GetSmallLiabilityExchangeHistoryParams { + current: number; + size: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface BfusdSubscriptionQuota { - leftQuota: string; +export interface SmallLiabilityExchangeHistory { + asset: string; + amount: string; + targetAsset: string; + targetAmount: string; + bizType: string; + timestamp: number; } ⋮---- -export interface BfusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; +export interface GetNextHourlyInterestRateParams { + assets: string; + isIsolated: boolean; } ⋮---- -export interface BfusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; +export interface NextHourlyInterestRate { + asset: string; + nextHourlyInterestRate: string; } ⋮---- -export interface BfusdQuotaResponse { - subscriptionQuota: BfusdSubscriptionQuota; - fastRedemptionQuota: BfusdFastRedemptionQuota; - standardRedemptionQuota: BfusdStandardRedemptionQuota; +export interface GetMarginCapitalFlowParams { + asset?: string; + symbol?: string; + type?: string; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface MarginCapitalFlow { + id: number; + tranId: number; + timestamp: number; + asset: string; + symbol: string; + type: string; + amount: string; +} +⋮---- +export interface MarginDelistSchedule { + delistTime: number; + crossMarginAssets: string[]; + isolatedMarginSymbols: string[]; + updateTime: number; } ⋮---- -export interface BfusdSubscribeParams { - asset: string; - amount: number; +export interface MarginAvailableInventoryResponse { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any; + updateTime: number; } ⋮---- -export interface BfusdSubscribeResponse { - success: boolean; - bfusdAmount: string; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface ManualLiquidationParams { + type: string; + symbol?: string; } ⋮---- -export interface BfusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; +export interface ManualLiquidationResponse { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; } ⋮---- -export interface BfusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; +export interface LeverageBracket { + leverage: number; + maxDebt: number; + maintenanceMarginRate: number; + initialMarginRate: number; + fastNum: number; } ⋮---- -export interface GetBfusdSubscriptionHistoryParams { +export interface LiabilityCoinLeverageBracket { + assetNames: string[]; + rank: number; + brackets: LeverageBracket[]; +} +export interface GetFlexibleSubscriptionRecordParams { + productId?: string; + purchaseId?: string; asset?: string; startTime?: number; endTime?: number; @@ -19239,4417 +17637,5028 @@ export interface GetBfusdSubscriptionHistoryParams { size?: number; } ⋮---- -export interface BfusdSubscriptionHistoryRow { - time: number; - asset: string; +export interface GetFlexibleSubscriptionRecordResponse { amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; + asset: string; + time: number; + purchaseId: number; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; } ⋮---- -export interface GetBfusdRedemptionHistoryParams { +export interface GetLockedSubscriptionRecordParams { + purchaseId?: string; + asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- -export interface BfusdRedemptionHistoryRow { +export interface LockedSubscriptionRecord { + positionId: string; + purchaseId: number; time: number; asset: string; amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; + lockPeriod: string; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; } ⋮---- -export interface GetBfusdRewardsHistoryParams { +export interface GetFlexibleRedemptionRecordParams { + productId?: string; + redeemId?: string; + asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- -export interface BfusdRewardsHistoryRow { +export interface FlexibleRedemptionRecord { + amount: string; + asset: string; time: number; - rewardsAmount: string; - annualPercentageRate: string; - rewardAsset?: string; - /** API may return this casing per Binance docs. */ - BFUSDPosition?: string; + productId: string; + redeemId: number; + destAccount: string; + status: string; } ⋮---- -/** API may return this casing per Binance docs. */ -⋮---- -export interface GetBfusdRateHistoryParams { +export interface GetLockedRedemptionRecordParams { + positionId?: string; + redeemId?: string; + asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- -export interface BfusdRateHistoryRow { - annualPercentageRate: string; +export interface LockedRedemptionRecord { + positionId: string; + redeemId: number; time: number; -} -⋮---- -/** - * RWUSD (sapi/v1/rwusd/*) - */ -⋮---- -export interface RwusdAccountResponse { - rwusdAmount: string; - totalProfit: string; -} -⋮---- -export interface RwusdSubscriptionQuota { - assets: string[]; - leftQuota: string; - minimum: string; -} -⋮---- -export interface RwusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; -} -⋮---- -export interface RwusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; -} -⋮---- -export interface RwusdQuotaResponse { - subscriptionQuota: RwusdSubscriptionQuota; - fastRedemptionQuota: RwusdFastRedemptionQuota; - standardRedemptionQuota: RwusdStandardRedemptionQuota; - subscribeEnable: boolean; - redeemEnable: boolean; -} -⋮---- -export interface RwusdSubscribeParams { asset: string; - amount: number; -} -⋮---- -export interface RwusdSubscribeResponse { - success: boolean; - rwusdAmount: string; -} -⋮---- -export interface RwusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; -} -⋮---- -export interface RwusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; + lockPeriod: string; + amount: string; + type: string; + deliverDate: string; + status: string; } ⋮---- -export interface GetRwusdSubscriptionHistoryParams { +export interface GetFlexibleRewardsHistoryParams { + productId?: string; asset?: string; startTime?: number; endTime?: number; + type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; current?: number; size?: number; } ⋮---- -export interface RwusdSubscriptionHistoryRow { - time: number; +export interface FlexibleRewardsHistory { asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; + rewards: string; + projectId: string; + type: string; + time: number; } ⋮---- -export interface GetRwusdRedemptionHistoryParams { +export interface GetLockedRewardsHistoryParams { + positionId?: string; + asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- -export interface RwusdRedemptionHistoryRow { +export interface GetLockedRewardsHistory { + positionId: string; time: number; asset: string; + lockPeriod: string; amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetRwusdRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; + type: string; } ⋮---- -export interface RwusdRewardsHistoryRow { - time: number; - rewardsAmount: string; - rwusdPosition: string; - annualPercentageRate: string; +export interface SetAutoSubscribeParams { + productId: string; + autoSubscribe: boolean; } ⋮---- -export interface GetRwusdRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface GetFlexibleSubscriptionPreviewParams { + productId: string; + amount: number; } ⋮---- -export interface RwusdRateHistoryRow { - annualPercentageRate: string; - time: number; +export interface FlexibleSubscriptionPreview { + totalAmount: string; + rewardAsset: string; + airDropAsset: string; + estDailyBonusRewards: string; + estDailyRealTimeRewards: string; + estDailyAirdropRewards: string; } ⋮---- -export interface GetMiningAlgoListResponse { - algoName: string; // Algorithm name - algoId: number; // Algorithm ID - poolIndex: number; // Sequence - unit: string; // Unit +export interface GetLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; } ⋮---- -algoName: string; // Algorithm name -algoId: number; // Algorithm ID -poolIndex: number; // Sequence -unit: string; // Unit -⋮---- -export interface GetMiningCoinListResponse { - coinName: string; // Coin name - coinId: number; // Coin ID - poolIndex: number; // Sequence - unit: string; // Unit +export interface LockedSubscriptionPreview { + rewardAsset: string; + totalRewardAmt: string; + extraRewardAsset: string; + estTotalExtraRewardAmt: string; + nextPay: string; + nextPayDate: string; + valueDate: string; + rewardsEndDate: string; + deliverDate: string; + nextSubscriptionDate: string; + boostRewardAsset: string; + estDailyRewardAmt: string; } ⋮---- -coinName: string; // Coin name -coinId: number; // Coin ID -poolIndex: number; // Sequence -unit: string; // Unit -⋮---- -export interface GetMinerDetailsParams { - algo: string; - userName: string; - workerName: string; +export interface GetRateHistoryParams { + productId: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface HashrateData { +export interface GetRateHistory { + productId: string; + asset: string; + annualPercentageRate: string; time: number; - hashrate: string; - reject: number; } ⋮---- -export interface MinerDetail { - workerName: string; - type: string; - hashrateDatas: HashrateData[]; +export interface GetCollateralRecordParams { + productId?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface GetMinerDetailsResponse { - code: number; - msg: string; - data: MinerDetail[]; +export interface CollateralRecord { + amount: string; + productId: string; + asset: string; + createTime: number; + type: string; + productName: string; + orderId: number; } ⋮---- -export interface GetMinerListParams { - algo: string; - userName: string; +export interface GetDualInvestmentProductListParams { + optionType: string; + exercisedCoin: string; + investCoin: string; + pageSize?: number; pageIndex?: number; - sort?: number; - sortColumn?: number; - workerStatus?: number; } ⋮---- -export interface WorkerData { - workerId: string; - workerName: string; - status: number; - hashRate: number; - dayHashRate: number; - rejectRate: number; - lastShareTime: number; +export interface DualInvestmentProduct { + id: string; + investCoin: string; + exercisedCoin: string; + strikePrice: string; + duration: number; + settleDate: number; + purchaseDecimal: number; + purchaseEndTime: number; + canPurchase: boolean; + apr: string; + orderId: number; + minAmount: string; + maxAmount: string; + createTimestamp: number; + optionType: string; + isAutoCompoundEnable: boolean; + autoCompoundPlanList: string[]; } ⋮---- -export interface GetMinerListResponse { - code: number; - msg: string; - data: { - workerDatas: WorkerData[]; - totalNum: number; - pageSize: number; - }; +export interface SubscribeDualInvestmentProductParams { + id: string; + orderId: string; + depositAmount: number; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; } ⋮---- -export interface GetEarningsListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; +export interface SubscribeDualInvestmentProductResponse { + positionId: number; + investCoin: string; + exercisedCoin: string; + subscriptionAmount: string; + duration: number; + autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; + strikePrice: string; + settleDate: number; + purchaseStatus: string; + apr: string; + orderId: number; + purchaseTime: number; + optionType: string; } ⋮---- -export interface AccountEarningsProfit { - time: number; - type: number; - hashTransfer: number | null; - transferAmount: number | null; - dayHashRate: number; - profitAmount: number; - coinName: string; - status: number; +export interface GetDualInvestmentPositionsParams { + status?: + | 'PENDING' + | 'PURCHASE_SUCCESS' + | 'SETTLED' + | 'PURCHASE_FAIL' + | 'REFUNDING' + | 'REFUND_SUCCESS' + | 'SETTLING'; + pageSize?: number; + pageIndex?: number; } ⋮---- -export interface GetEarningsListResponse { - code: number; - msg: string; - data: { - accountProfits: AccountEarningsProfit[]; - totalNum: number; - pageSize: number; - }; +export interface DualInvestmentPosition { + id: string; + investCoin: string; + exercisedCoin: string; + subscriptionAmount: string; + strikePrice: string; + duration: number; + settleDate: number; + purchaseStatus: string; + apr: string; + orderId: number; + purchaseEndTime: number; + optionType: string; + autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; + settlePrice?: string; + isExercised?: boolean; + settleAsset?: string; + settleAmount?: string; + subscriptionTime?: number; } ⋮---- -export interface GetExtraBonusListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; +export interface CheckDualInvestmentAccountsResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; } ⋮---- -export interface OtherProfit { - time: number; - coinName: string; - type: number; - profitAmount: number; - status: number; +export interface ChangeAutoCompoundStatusParams { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; } ⋮---- -export interface GetExtraBonusListResponse { - code: number; - msg: string; - data: { - otherProfits: OtherProfit[]; - totalNum: number; - pageSize: number; - }; +export interface ChangeAutoCompoundStatusResponse { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; } ⋮---- -export interface GetHashrateResaleListParams { - pageIndex?: number; - pageSize?: number; +export interface GetTargetAssetListParams { + targetAsset?: string; + size?: number; + current?: number; } ⋮---- -export interface ConfigDetail { - configId: number; - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - startDay: number; - endDay: number; - status: number; +export interface RoiAndDimensionType { + simulateRoi: string; + dimensionValue: string; + dimensionUnit: string; } ⋮---- -export interface GetHashrateResaleListResponse { - code: number; - msg: string; - data: { - configDetails: ConfigDetail[]; - totalNum: number; - pageSize: number; - }; +export interface AutoInvestAsset { + targetAsset: string; + roiAndDimensionTypeList: RoiAndDimensionType[]; } ⋮---- -export interface GetHashrateResaleDetailParams { - configId: number; - userName: string; - pageIndex?: number; - pageSize?: number; +export interface GetTargetAssetListResponse { + targetAssets: string[]; + autoInvestAssetList: AutoInvestAsset[]; } ⋮---- -export interface ProfitTransferDetail { - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - day: number; - amount: number; - coinName: string; +export interface GetTargetAssetROIParams { + targetAsset: string; + hisRoiType: + | 'FIVE_YEAR' + | 'THREE_YEAR' + | 'ONE_YEAR' + | 'SIX_MONTH' + | 'THREE_MONTH' + | 'SEVEN_DAY'; } ⋮---- -export interface GetHashrateResaleDetailResponse { - code: number; - msg: string; - data: { - profitTransferDetails: ProfitTransferDetail[]; - totalNum: number; - pageSize: number; - }; +export interface TargetAssetROI { + date: string; + simulateRoi: string; } -export interface SubmitHashrateResaleParams { - userName: string; - algo: string; - endDate: number; - startDate: number; - toPoolUser: string; - hashRate: number; +⋮---- +export interface GetSourceAssetListParams { + targetAsset?: string[]; + indexId?: number; + usageType: 'RECURRING' | 'ONE_TIME'; + flexibleAllowedToUse?: boolean; + sourceType?: 'MAIN_SITE' | 'TR'; } ⋮---- -export interface CancelHashrateResaleConfigParams { - configId: number; - userName: string; +export interface SourceAsset { + sourceAsset: string; + assetMinAmount: string; + assetMaxAmount: string; + scale: string; + flexibleAmount: string; } ⋮---- -export interface GetStatisticListParams { - algo: string; - userName: string; +export interface GetSourceAssetListResponse { + feeRate: string; + taxRate: string; + sourceAssets: SourceAsset[]; } ⋮---- -export interface Profit { - BTC: string; - BSV: string; - BCH: string; +export interface AutoInvestPortfolioDetail { + targetAsset: string; + percentage: number; } ⋮---- -export interface GetStatisticListResponse { - code: number; - msg: string; - data: { - fifteenMinHashRate: string; - dayHashRate: string; - validNum: number; - invalidNum: number; - profitToday: Profit; - profitYesterday: Profit; - userName: string; - unit: string; - algo: string; - }; +export interface CreateInvestmentPlanParams { + UID: string; + sourceType: 'MAIN_SITE' | 'TR'; + requestId?: string; + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; + indexId?: number; + subscriptionAmount: number; + subscriptionCycle: + | 'H1' + | 'H4' + | 'H8' + | 'H12' + | 'WEEKLY' + | 'DAILY' + | 'MONTHLY' + | 'BI_WEEKLY'; + subscriptionStartDay?: number; + subscriptionStartWeekday?: + | 'MON' + | 'TUE' + | 'WED' + | 'THU' + | 'FRI' + | 'SAT' + | 'SUN'; + subscriptionStartTime: number; + sourceAsset: string; + flexibleAllowedToUse: boolean; + details: AutoInvestPortfolioDetail[]; } ⋮---- -export interface getMiningAccountsListParams { - algo: string; - userName: string; +export interface CreateInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; } ⋮---- -export interface MiningHashrateData { - time: number; - hashrate: string; - reject: string; +export interface EditInvestmentPlanParams { + planId: number; + subscriptionAmount: number; + subscriptionCycle: + | 'H1' + | 'H4' + | 'H8' + | 'H12' + | 'WEEKLY' + | 'DAILY' + | 'MONTHLY' + | 'BI_WEEKLY'; + subscriptionStartDay?: number; + subscriptionStartWeekday?: + | 'MON' + | 'TUE' + | 'WED' + | 'THU' + | 'FRI' + | 'SAT' + | 'SUN'; + subscriptionStartTime: number; + sourceAsset: string; + flexibleAllowedToUse?: boolean; + details: AutoInvestPortfolioDetail[]; } ⋮---- -export interface MiningAccountData { - type: string; - userName: string; - list: MiningHashrateData[]; +export interface EditInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; } ⋮---- -export interface getMiningAccountsListResponse { - code: number; - msg: string; - data: MiningAccountData[]; +export interface ChangePlanStatusParams { + planId: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; } ⋮---- -export interface GetMiningAccountEarningParams { - algo: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; +export interface ChangePlanStatusResponse { + planId: number; + nextExecutionDateTime: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; } ⋮---- -export interface AccountMiningProfit { - time: number; - coinName: string; - type: number; - puid: number; - subName: string; - amount: number; +export interface GetPlanDetailsParams { + planId?: number; + requestId?: string; } ⋮---- -export interface GetMiningAccountEarningResponse { - code: number; - msg: string; - data: { - accountProfits: AccountMiningProfit[]; - totalNum: number; - pageSize: number; - }; +export interface GetSubscriptionTransactionHistoryParams { + planId?: number; + startTime?: number; + endTime?: number; + targetAsset?: string; + planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; + size?: number; + current?: number; } ⋮---- -export interface GetFutureTickLevelOrderbookDataLinkParams { - symbol: string; - dataType: 'T_DEPTH' | 'S_DEPTH'; - startTime: number; - endTime: number; +export interface AssetAllocation { + targetAsset: string; + allocation: string; } ⋮---- -export interface HistoricalDataLink { - day: string; - url: string; +export interface GetIndexDetailsResponse { + indexId: number; + indexName: string; + status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; + assetAllocation: AssetAllocation[]; } ⋮---- -export interface SubmitVpNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - quantity: number; - urgency: 'LOW' | 'MEDIUM' | 'HIGH'; - clientAlgoId?: string; - reduceOnly?: boolean; - limitPrice?: number; +export interface IndexLinkedPlanDetail { + targetAsset: string; + averagePriceInUSD: string; + totalInvestedInUSD: string; + currentInvestedInUSD: string; + purchasedAmount: string; + pnlInUSD: string; + roi: string; + percentage: string; + availableAmount: string; + redeemedAmount: string; + assetValueInUSD: string; } ⋮---- -export interface SubmitVpNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; +export interface GetIndexLinkedPlanPositionDetailsResponse { + indexId: number; + totalInvestedInUSD: string; + currentInvestedInUSD: string; + pnlInUSD: string; + roi: string; + assetAllocation: { targetAsset: string; allocation: string }[]; + details: IndexLinkedPlanDetail[]; } ⋮---- -export interface SubmitTwapNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - quantity: number; - duration: number; - clientAlgoId?: string; - reduceOnly?: boolean; - limitPrice?: number; +export interface SubmitOneTimeTransactionParams { + sourceType: 'MAIN_SITE' | 'TR'; + requestId?: string; + subscriptionAmount: number; + sourceAsset: string; + flexibleAllowedToUse?: boolean; + planId?: number; + indexId?: number; + details: AutoInvestPortfolioDetail[]; } ⋮---- -export interface SubmitTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; +export interface SubmitOneTimeTransactionResponse { + transactionId: number; + waitSecond: number; } ⋮---- -export interface CancelAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: string; +export interface GetOneTimeTransactionStatusParams { + transactionId: number; + requestId?: string; } ⋮---- -export interface AlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; +export interface GetOneTimeTransactionStatusResponse { + transactionId: number; + status: 'SUCCESS' | 'CONVERTING'; } ⋮---- -export interface GetAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; +export interface SubmitIndexLinkedPlanRedemptionParams { + indexId: number; + requestId?: string; + redemptionPercentage: number; +} +⋮---- +export interface GetIndexLinkedPlanRedemptionHistoryParams { + requestId: number; startTime?: number; endTime?: number; - page?: number; - pageSize?: number; + current?: number; + asset?: string; + size?: number; } ⋮---- -export interface HistoricalAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; +export interface IndexLinkedPlanRedemptionRecord { + indexId: number; + indexName: string; + redemptionId: number; + status: 'SUCCESS' | 'FAILED'; + asset: string; + amount: string; + redemptionDateTime: number; + transactionFee: string; + transactionFeeUnit: string; } ⋮---- -export interface GetAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: number; +export interface GetIndexLinkedPlanRebalanceHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface SubOrder { - algoId: number; - orderId: number; - orderStatus: string; - executedQty: string; - executedAmt: string; - feeAmt: string; - feeAsset: string; - bookTime: number; - avgPrice: string; - side: 'BUY' | 'SELL'; - symbol: string; - subId: number; - timeInForce: string; - origQty: string; +export interface RebalanceTransactionDetail { + asset: string; + transactionDateTime: number; + rebalanceDirection: 'BUY' | 'SELL'; + rebalanceAmount: string; } ⋮---- -export interface GetAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SubOrder[]; +export interface IndexLinkedPlanRebalanceRecord { + indexId: number; + indexName: string; + rebalanceId: number; + status: 'SUCCESS' | 'INIT'; + rebalanceFee: string; + rebalanceFeeUnit: string; + transactionDetails: RebalanceTransactionDetail[]; } ⋮---- -export interface SubmitSpotTwapNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: number; - duration: number; - clientAlgoId?: string; - limitPrice?: number; - stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; +export interface SubscribeEthStakingV2Response { + success: boolean; + wbethAmount: string; + conversionRatio: string; } ⋮---- -export interface SubmitSpotTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; +export interface RedeemEthParams { + asset?: string; + amount: number; } ⋮---- -export interface CancelSpotAlgoOrderResponse { - algoId: number; +export interface RedeemEthResponse { success: boolean; - code: number; - msg: string; + arrivalTime: number; + ethAmount: string; + conversionRatio: string; } ⋮---- -export interface SpotAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; +export interface GetEthStakingHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface GetSpotAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; +export interface EthStakingHistory { + time: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAmount: string; + conversionRatio: string; +} +⋮---- +export interface GetEthRedemptionHistoryParams { startTime?: number; endTime?: number; - page?: number; - pageSize?: number; + current?: number; + size?: number; } ⋮---- -export interface HistoricalSpotAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; +export interface EthRedemptionHistory { + time: number; + arrivalTime: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAsset: string; + distributeAmount: string; + conversionRatio: string; } ⋮---- -export interface GetSpotAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: number; +export interface GetBethRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface SpotSubOrder { - algoId: number; - orderId: number; - orderStatus: string; - executedQty: string; - executedAmt: string; - feeAmt: string; - feeAsset: string; - bookTime: number; - avgPrice: string; - side: 'BUY' | 'SELL'; - symbol: string; - subId: number; - timeInForce: string; - origQty: string; +export interface BethRewardsHistory { + time: number; + asset: string; + holding: string; + amount: string; + annualPercentageRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; } ⋮---- -export interface GetSpotAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SpotSubOrder[]; +export interface GetEthStakingQuotaResponse { + leftStakingPersonalQuota: string; + leftRedemptionPersonalQuota: string; } ⋮---- -export interface GetPortfolioMarginProAccountInfoResponse { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - accountStatus: string; - accountType: string; +export interface GetETHRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface ETHRateHistory { + annualPercentageRate: string; + exchangeRate: string; + time: number; +} +⋮---- +export interface GetEthStakingAccountResponse { + cumulativeProfitInBETH: string; + lastDayProfitInBETH: string; } ⋮---- -export interface GetPortfolioMarginProCollateralRateResponse { - asset: string; - collateralRate: string; +export interface GetEthStakingAccountV2Response { + holdingInETH: string; + holdings: { + wbethAmount: string; + bethAmount: string; + }; + thirtyDaysProfitInETH: string; + profit: { + amountFromWBETH: string; + amountFromBETH: string; + }; } ⋮---- -export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { - asset: string; - amount: string; +export interface WrapBethResponse { + success: boolean; + wbethAmount: string; + exchangeRate: string; } ⋮---- -export interface GetPortfolioMarginProInterestHistoryParams { - asset?: string; +export interface GetWrapHistoryParams { startTime?: number; endTime?: number; + current?: number; size?: number; } ⋮---- -export interface GetPortfolioMarginProInterestHistoryResponse { - asset: string; - interest: string; - interestAccruedTime: number; - interestRate: string; - principal: string; +export interface WrapHistory { + time: number; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + exchangeRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; } ⋮---- -export interface GetPortfolioMarginAssetIndexPriceResponse { - asset: string; - assetIndexPrice: string; +export interface WbethRewardsHistory { time: number; + amountInETH: string; + holding: string; + holdingInETH: string; + annualPercentageRate: string; } ⋮---- -export interface BnbTransferParams { - amount: number; - transferSide: 'TO_UM' | 'FROM_UM'; +export interface GetWbethRewardsHistoryResponse { + estRewardsInETH: string; + rows: WbethRewardsHistory[]; + total: number; } ⋮---- -export interface GetPortfolioMarginAssetLeverageResponse { - asset: string; - leverage: number; +/** + * BFUSD (sapi/v1/bfusd/*) + */ +⋮---- +export interface BfusdAccountResponse { + bfusdAmount: string; + usdtProfit: string; + bfusdProfit: string; } ⋮---- -export interface SetPortfolioMarginMarginCallLevelParams { - marginCallLevel: number; +export interface BfusdSubscriptionQuota { + leftQuota: string; } ⋮---- -export interface PortfolioMarginMarginCallLevelResponse { - marginCallLevel: string; +export interface BfusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; } ⋮---- -export type PortfolioMarginMarginCallLevelGetResponse = - | PortfolioMarginMarginCallLevelResponse - | Record; +export interface BfusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; +} ⋮---- -export interface PortfolioMarginMarginCallLevelDeleteResponse { - msg: string; +export interface BfusdQuotaResponse { + subscriptionQuota: BfusdSubscriptionQuota; + fastRedemptionQuota: BfusdFastRedemptionQuota; + standardRedemptionQuota: BfusdStandardRedemptionQuota; } ⋮---- -export interface SubscribeBlvtParams { - tokenName: string; - cost: number; +export interface BfusdSubscribeParams { + asset: string; + amount: number; } ⋮---- -export interface SubscribeBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - amount: string; - cost: string; - timestamp: number; +export interface BfusdSubscribeResponse { + success: boolean; + bfusdAmount: string; } ⋮---- -export interface GetBlvtSubscriptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; +export interface BfusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; } ⋮---- -export interface BlvtSubscriptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; +export interface BfusdRedeemResponse { + success: boolean; + receiveAmount: string; fee: string; - totalCharge: string; - timestamp: number; + arrivalTime: number; } ⋮---- -export interface RedeemBlvtParams { - tokenName: string; - amount: number; +export interface GetBfusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface RedeemBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - redeemAmount: string; +export interface BfusdSubscriptionHistoryRow { + time: number; + asset: string; amount: string; - timestamp: number; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; } ⋮---- -export interface GetBlvtRedemptionRecordParams { - tokenName?: string; - id?: number; +export interface GetBfusdRedemptionHistoryParams { startTime?: number; endTime?: number; - limit?: number; + current?: number; + size?: number; } ⋮---- -export interface BlvtRedemptionRecord { - id: number; - tokenName: string; +export interface BfusdRedemptionHistoryRow { + time: number; + asset: string; amount: string; - nav: string; + receiveAsset: string; + receiveAmount: string; fee: string; - netProceed: string; - timestamp: number; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; } ⋮---- -export interface BlvtUserLimitInfo { - tokenName: string; - userDailyTotalPurchaseLimit: string; - userDailyTotalRedeemLimit: string; +export interface GetBfusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface GetFiatOrderHistoryParams { - transactionType: string; - beginTime?: number; +export interface BfusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + annualPercentageRate: string; + rewardAsset?: string; + /** API may return this casing per Binance docs. */ + BFUSDPosition?: string; +} +⋮---- +/** API may return this casing per Binance docs. */ +⋮---- +export interface GetBfusdRateHistoryParams { + startTime?: number; endTime?: number; - page?: number; - rows?: number; + current?: number; + size?: number; } ⋮---- -export interface GetFiatOrderHistoryResponse { - code: string; - message: string; - data: { - orderNo: string; - fiatCurrency: string; - indicatedAmount: string; - amount: string; - totalFee: string; - method: string; - status: string; - createTime: number; - updateTime: number; - }[]; - total: number; - success: boolean; +export interface BfusdRateHistoryRow { + annualPercentageRate: string; + time: number; } ⋮---- -export interface GetFiatPaymentsHistoryResponse { - code: string; - message: string; - data: { - orderNo: string; - sourceAmount: string; - fiatCurrency: string; - obtainAmount: string; - cryptoCurrency: string; - totalFee: string; - price: string; - status: string; - paymentMethod?: string; - createTime: number; - updateTime: number; - }[]; - total: number; - success: boolean; +/** + * RWUSD (sapi/v1/rwusd/*) + */ +⋮---- +export interface RwusdAccountResponse { + rwusdAmount: string; + totalProfit: string; +} +⋮---- +export interface RwusdSubscriptionQuota { + assets: string[]; + leftQuota: string; + minimum: string; +} +⋮---- +export interface RwusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; } ⋮---- -export interface WithdrawFiatAccountInfo { - accountNumber: string; - agency: string; - bankCodeForPix: string; - accountType: string; +export interface RwusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; } ⋮---- -export interface WithdrawFiatParams { - currency: string; - apiPaymentMethod: string; - amount: number; - accountInfo?: WithdrawFiatAccountInfo; +export interface RwusdQuotaResponse { + subscriptionQuota: RwusdSubscriptionQuota; + fastRedemptionQuota: RwusdFastRedemptionQuota; + standardRedemptionQuota: RwusdStandardRedemptionQuota; + subscribeEnable: boolean; + redeemEnable: boolean; } ⋮---- -export interface FiatDepositParams { - currency: string; - apiPaymentMethod: string; +export interface RwusdSubscribeParams { + asset: string; amount: number; - ext?: object; - recvWindow?: number; - timestamp?: number; } ⋮---- -export interface FiatDepositResponse { - code: string; - message: string; - data: { - orderId: string; - }; +export interface RwusdSubscribeResponse { + success: boolean; + rwusdAmount: string; } ⋮---- -export interface GetFiatOrderDetailParams { - orderNo: string; - recvWindow?: number; - timestamp?: number; +export interface RwusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; } ⋮---- -export interface GetFiatOrderDetailResponse { - code: string; - message: string; - data: { - orderId: string; - orderStatus: string; - amount: string; - fee: string; - fiatCurrency: string; - errorCode: string; - errorMessage: string; - ext: object; - }; +export interface RwusdRedeemResponse { + success: boolean; + receiveAmount: string; + fee: string; + arrivalTime: number; } ⋮---- -export interface GetC2CTradeHistoryParams { - tradeType: string; - startTimestamp?: number; - endTimestamp?: number; - page?: number; - rows?: number; +export interface GetRwusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface c2cTradeData { - orderNumber: string; - advNo: string; - tradeType: string; +export interface RwusdSubscriptionHistoryRow { + time: number; asset: string; - fiat: string; - fiatSymbol: string; amount: string; - totalPrice: string; - unitPrice: string; - orderStatus: string; - createTime: number; - commission: string; - counterPartNickName: string; - advertisementRole: string; -} -export interface GetC2CTradeHistoryResponse { - code: string; - message: string; - data: c2cTradeData[]; - total: number; - success: boolean; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; } ⋮---- -export interface GetVipLoanOngoingOrdersParams { - orderId?: number; - collateralAccountId?: number; - loanCoin?: string; - collateralCoin?: string; +export interface GetRwusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; current?: number; - limit?: number; + size?: number; } ⋮---- -export interface VipOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - loanRate: string; - residualInterest: string; - collateralAccountId: string; - collateralCoin: string; - totalCollateralValueAfterHaircut: string; - lockedCollateralValue: string; - currentLTV: string; - expirationTime: number; - loanDate: string; - loanTerm: string; - initialLtv: string; - marginCallLtv: string; - liquidationLtv: string; +export interface RwusdRedemptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + fee: string; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; } ⋮---- -export interface VipLoanRepayParams { - orderId: number; - amount: number; +export interface GetRwusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface VipLoanRepayResponse { - loanCoin: string; - repayAmount: string; - remainingPrincipal: string; - remainingInterest: string; - collateralCoin: string; - currentLTV: string; - repayStatus: string; +export interface RwusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + rwusdPosition: string; + annualPercentageRate: string; } ⋮---- -export interface GetVipLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; +export interface GetRwusdRateHistoryParams { startTime?: number; endTime?: number; current?: number; - limit?: number; + size?: number; } ⋮---- -export interface VipLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - repayStatus: string; - loanDate: string; - repayTime: string; - orderId: string; +export interface RwusdRateHistoryRow { + annualPercentageRate: string; + time: number; } ⋮---- -export interface VipLoanRenewParams { - orderId: number; - loanTerm?: number; +export interface GetMiningAlgoListResponse { + algoName: string; // Algorithm name + algoId: number; // Algorithm ID + poolIndex: number; // Sequence + unit: string; // Unit } ⋮---- -export interface VipLoanRenewResponse { - loanAccountId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; +algoName: string; // Algorithm name +algoId: number; // Algorithm ID +poolIndex: number; // Sequence +unit: string; // Unit +⋮---- +export interface GetMiningCoinListResponse { + coinName: string; // Coin name + coinId: number; // Coin ID + poolIndex: number; // Sequence + unit: string; // Unit } ⋮---- -export interface CheckVipCollateralAccountParams { - orderId?: number; - collateralAccountId?: number; +coinName: string; // Coin name +coinId: number; // Coin ID +poolIndex: number; // Sequence +unit: string; // Unit +⋮---- +export interface GetMinerDetailsParams { + algo: string; + userName: string; + workerName: string; } ⋮---- -export interface VipCollateralAccount { - collateralAccountId: string; - collateralCoin: string; +export interface HashrateData { + time: number; + hashrate: string; + reject: number; } ⋮---- -export interface VipLoanBorrowParams { - loanAccountId: number; - loanCoin: string; - loanAmount: number; - collateralAccountId: string; - collateralCoin: string; - isFlexibleRate: boolean; - loanTerm?: number; +export interface MinerDetail { + workerName: string; + type: string; + hashrateDatas: HashrateData[]; } ⋮---- -export interface VipLoanBorrowResponse { - loanAccountId: string; - requestId: string; - loanCoin: string; - isFlexibleRate: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm?: string; +export interface GetMinerDetailsResponse { + code: number; + msg: string; + data: MinerDetail[]; } ⋮---- -export interface GetLoanableAssetsDataParams { - loanCoin?: string; - vipLevel?: number; +export interface GetMinerListParams { + algo: string; + userName: string; + pageIndex?: number; + sort?: number; + sortColumn?: number; + workerStatus?: number; +} +⋮---- +export interface WorkerData { + workerId: string; + workerName: string; + status: number; + hashRate: number; + dayHashRate: number; + rejectRate: number; + lastShareTime: number; } ⋮---- -export interface GetApplicationStatusParams { - current?: number; - limit?: number; +export interface GetMinerListResponse { + code: number; + msg: string; + data: { + workerDatas: WorkerData[]; + totalNum: number; + pageSize: number; + }; } ⋮---- -export interface ApplicationStatus { - loanAccountId: string; - orderId: string; - requestId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; - status: string; - loanDate: string; +export interface GetEarningsListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; } ⋮---- -export interface BorrowInterestRate { - asset: string; - flexibleDailyInterestRate: string; - flexibleYearlyInterestRate: string; +export interface AccountEarningsProfit { time: number; + type: number; + hashTransfer: number | null; + transferAmount: number | null; + dayHashRate: number; + profitAmount: number; + coinName: string; + status: number; } ⋮---- -export interface GetCryptoLoansIncomeHistoryParams { - asset?: string; - type?: string; - startTime?: number; - endTime?: number; - limit?: number; +export interface GetEarningsListResponse { + code: number; + msg: string; + data: { + accountProfits: AccountEarningsProfit[]; + totalNum: number; + pageSize: number; + }; } ⋮---- -export interface GetCryptoLoansIncomeHistoryResponse { - asset: string; - type: string; - amount: string; - timestamp: number; - tranId: string; +export interface GetExtraBonusListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; } ⋮---- -export interface BorrowCryptoLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; - loanTerm: number; +export interface OtherProfit { + time: number; + coinName: string; + type: number; + profitAmount: number; + status: number; } ⋮---- -export interface BorrowCryptoLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - hourlyInterestRate: string; - orderId: string; +export interface GetExtraBonusListResponse { + code: number; + msg: string; + data: { + otherProfits: OtherProfit[]; + totalNum: number; + pageSize: number; + }; } ⋮---- -export interface GetLoanBorrowHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; +export interface GetHashrateResaleListParams { + pageIndex?: number; + pageSize?: number; } ⋮---- -export interface LoanBorrowHistory { - orderId: number; - loanCoin: string; - initialLoanAmount: string; - hourlyInterestRate: string; - loanTerm: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: string; +export interface ConfigDetail { + configId: number; + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + startDay: number; + endDay: number; + status: number; } ⋮---- -export interface GetLoanOngoingOrdersParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; +export interface GetHashrateResaleListResponse { + code: number; + msg: string; + data: { + configDetails: ConfigDetail[]; + totalNum: number; + pageSize: number; + }; } ⋮---- -export interface LoanOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - residualInterest: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; - expirationTime: number; +export interface GetHashrateResaleDetailParams { + configId: number; + userName: string; + pageIndex?: number; + pageSize?: number; } ⋮---- -export interface RepayCryptoLoanParams { - orderId: number; +export interface ProfitTransferDetail { + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + day: number; amount: number; - type?: number; - collateralReturn?: boolean; + coinName: string; } ⋮---- -export interface RepayCryptoLoanResponse { - loanCoin: string; - remainingPrincipal?: string; - remainingInterest?: string; - collateralCoin: string; - remainingCollateral?: string; - currentLTV?: string; - repayStatus: string; +export interface GetHashrateResaleDetailResponse { + code: number; + msg: string; + data: { + profitTransferDetails: ProfitTransferDetail[]; + totalNum: number; + pageSize: number; + }; } -⋮---- -export interface GetLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; +export interface SubmitHashrateResaleParams { + userName: string; + algo: string; + endDate: number; + startDate: number; + toPoolUser: string; + hashRate: number; } ⋮---- -export interface LoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralUsed: string; - collateralReturn: string; - repayType: string; - repayStatus: string; - repayTime: number; - orderId: number; +export interface CancelHashrateResaleConfigParams { + configId: number; + userName: string; } ⋮---- -export interface AdjustCryptoLoanLTVParams { - orderId: number; - amount: number; - direction: 'ADDITIONAL' | 'REDUCED'; +export interface GetStatisticListParams { + algo: string; + userName: string; } ⋮---- -export interface AdjustCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - currentLTV: string; +export interface Profit { + BTC: string; + BSV: string; + BCH: string; } ⋮---- -export interface GetLoanLTVAdjustmentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; +export interface GetStatisticListResponse { + code: number; + msg: string; + data: { + fifteenMinHashRate: string; + dayHashRate: string; + validNum: number; + invalidNum: number; + profitToday: Profit; + profitYesterday: Profit; + userName: string; + unit: string; + algo: string; + }; } ⋮---- -export interface LoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; - orderId: number; +export interface getMiningAccountsListParams { + algo: string; + userName: string; } ⋮---- -export interface LoanableAssetData { - loanCoin: string; - _7dHourlyInterestRate: string; - _7dDailyInterestRate: string; - _14dHourlyInterestRate: string; - _14dDailyInterestRate: string; - _30dHourlyInterestRate: string; - _30dDailyInterestRate: string; - _90dHourlyInterestRate: string; - _90dDailyInterestRate: string; - _180dHourlyInterestRate: string; - _180dDailyInterestRate: string; - minLimit: string; - maxLimit: string; - vipLevel: number; +export interface MiningHashrateData { + time: number; + hashrate: string; + reject: string; } ⋮---- -export interface GetCollateralAssetDataParams { - collateralCoin?: string; - vipLevel?: number; +export interface MiningAccountData { + type: string; + userName: string; + list: MiningHashrateData[]; } ⋮---- -export interface CollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; - vipLevel: number; +export interface getMiningAccountsListResponse { + code: number; + msg: string; + data: MiningAccountData[]; } ⋮---- -export interface CheckCollateralRepayRateParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; +export interface GetMiningAccountEarningParams { + algo: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; } ⋮---- -export interface CheckCollateralRepayRateResponse { - loanCoin: string; - collateralCoin: string; - repayAmount: string; - rate: string; +export interface AccountMiningProfit { + time: number; + coinName: string; + type: number; + puid: number; + subName: string; + amount: number; } ⋮---- -export interface CustomizeMarginCallParams { - orderId?: number; - collateralCoin?: string; - marginCall: number; +export interface GetMiningAccountEarningResponse { + code: number; + msg: string; + data: { + accountProfits: AccountMiningProfit[]; + totalNum: number; + pageSize: number; + }; } ⋮---- -export interface CustomizeMarginCall { - orderId: string; - collateralCoin: string; - preMarginCall: string; - afterMarginCall: string; - customizeTime: number; +export interface GetFutureTickLevelOrderbookDataLinkParams { + symbol: string; + dataType: 'T_DEPTH' | 'S_DEPTH'; + startTime: number; + endTime: number; } ⋮---- -export interface BorrowFlexibleLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; +export interface HistoricalDataLink { + day: string; + url: string; } ⋮---- -export interface BorrowFlexibleLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - status: 'Succeeds' | 'Failed' | 'Processing'; +export interface SubmitVpNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + quantity: number; + urgency: 'LOW' | 'MEDIUM' | 'HIGH'; + clientAlgoId?: string; + reduceOnly?: boolean; + limitPrice?: number; } ⋮---- -export interface GetFlexibleLoanOngoingOrdersParams { - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; +export interface SubmitVpNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; } ⋮---- -export interface FlexibleLoanOngoingOrder { - loanCoin: string; - totalDebt: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; +export interface SubmitTwapNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + quantity: number; + duration: number; + clientAlgoId?: string; + reduceOnly?: boolean; + limitPrice?: number; } ⋮---- -export interface GetFlexibleLoanLiquidationHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; // Default: 1, max: 1000 - limit?: number; // Default: 10, max: 100 - recvWindow?: number; +export interface SubmitTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; } ⋮---- -current?: number; // Default: 1, max: 1000 -limit?: number; // Default: 10, max: 100 +export interface CancelAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: string; +} ⋮---- -export interface FlexibleLoanLiquidationHistoryRecord { - loanCoin: string; - liquidationDebt: string; - collateralCoin: string; - liquidationCollateralAmount: string; - returnCollateralAmount: string; - liquidationFee: string; - liquidationStartingPrice: string; - liquidationStartingTime: number; - status: 'Liquidated' | 'Liquidating'; +export interface AlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; } ⋮---- -export interface GetFlexibleCryptoLoanBorrowHistoryParams { - loanCoin?: string; - collateralCoin?: string; +export interface GetAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; startTime?: number; endTime?: number; - current?: number; - limit?: number; + page?: number; + pageSize?: number; } ⋮---- -export interface FlexibleCryptoLoanBorrowHistory { - loanCoin: string; - initialLoanAmount: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: 'Succeeds' | 'Failed' | 'Processing'; +export interface HistoricalAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; } ⋮---- -export interface RepayCryptoFlexibleLoanParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; - collateralReturn?: boolean; - fullRepayment?: boolean; +export interface GetAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: number; } ⋮---- -export interface RepayCryptoFlexibleLoanResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +export interface SubOrder { + algoId: number; + orderId: number; + orderStatus: string; + executedQty: string; + executedAmt: string; + feeAmt: string; + feeAsset: string; + bookTime: number; + avgPrice: string; + side: 'BUY' | 'SELL'; + symbol: string; + subId: number; + timeInForce: string; + origQty: string; } ⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; // Amount of loan to repay - fullRepayment?: boolean; // Default: FALSE +export interface GetAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SubOrder[]; } ⋮---- -repayAmount: number; // Amount of loan to repay -fullRepayment?: boolean; // Default: FALSE -⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; -} -export interface GetFlexibleCryptoLoanRepaymentHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; +export interface SubmitSpotTwapNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: number; + duration: number; + clientAlgoId?: string; + limitPrice?: number; + stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; } ⋮---- -export interface FlexibleCryptoLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralReturn: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; - repayTime: number; +export interface SubmitSpotTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; } ⋮---- -export interface AdjustFlexibleCryptoLoanLTVParams { - loanCoin: string; - collateralCoin: string; - adjustmentAmount: number; - direction: 'ADDITIONAL' | 'REDUCED'; +export interface CancelSpotAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: string; } ⋮---- -export interface AdjustFlexibleCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - adjustmentAmount: string; - currentLTV: string; +export interface SpotAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; } ⋮---- -export interface GetFlexibleLoanLTVAdjustmentHistoryParams { - loanCoin?: string; - collateralCoin?: string; +export interface GetSpotAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; startTime?: number; endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleLoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - collateralAmount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; -} -⋮---- -export interface FlexibleLoanAssetData { - loanCoin: string; - flexibleInterestRate: string; - flexibleMinLimit: string; - flexibleMaxLimit: string; + page?: number; + pageSize?: number; } ⋮---- -export interface FlexibleLoanCollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; +export interface HistoricalSpotAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; } ⋮---- -export interface GetFuturesLeadTraderStatusResponse { - code: string; - message: string; - data: { - isLeadTrader: boolean; - time: number; - }; - success: boolean; +export interface GetSpotAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: number; } ⋮---- -export interface GetFuturesLeadTradingSymbolWhitelistResponse { - code: string; - message: string; - data: { - symbol: string; - baseAsset: string; - quoteAsset: string; - }[]; +export interface SpotSubOrder { + algoId: number; + orderId: number; + orderStatus: string; + executedQty: string; + executedAmt: string; + feeAmt: string; + feeAsset: string; + bookTime: number; + avgPrice: string; + side: 'BUY' | 'SELL'; + symbol: string; + subId: number; + timeInForce: string; + origQty: string; } ⋮---- -export interface GetPayTradeHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; +export interface GetSpotAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SpotSubOrder[]; } ⋮---- -export interface GetAllConvertPairsParams { - fromAsset?: string; - toAsset?: string; +export interface GetPortfolioMarginProAccountInfoResponse { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + accountStatus: string; + accountType: string; } ⋮---- -export interface SubmitConvertLimitOrderParams { - baseAsset: string; - quoteAsset: string; - limitPrice: number; - baseAmount?: number; - quoteAmount?: number; - side: 'BUY' | 'SELL'; - walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; - expiredType: '1_D' | '3_D' | '7_D' | '30_D'; +export interface GetPortfolioMarginProCollateralRateResponse { + asset: string; + collateralRate: string; } ⋮---- -export interface ConvertLimitOpenOrder { - quoteId: string; - orderId: number; - orderStatus: string; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - ratio: string; - inverseRatio: string; - createTime: number; - expiredTimestamp: number; +export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { + asset: string; + amount: string; } ⋮---- -export interface GetSpotRebateHistoryRecordsParams { +export interface GetPortfolioMarginProInterestHistoryParams { + asset?: string; startTime?: number; endTime?: number; - page?: number; + size?: number; } ⋮---- -export interface SpotRebateHistoryRecord { +export interface GetPortfolioMarginProInterestHistoryResponse { asset: string; - type: number; - amount: string; - updateTime: number; + interest: string; + interestAccruedTime: number; + interestRate: string; + principal: string; } ⋮---- -export interface GetSpotRebateHistoryRecordsResponse { - status: string; - type: string; - code: string; - data: { - page: number; - totalRecords: number; - totalPageNum: number; - data: SpotRebateHistoryRecord[]; - }; +export interface GetPortfolioMarginAssetIndexPriceResponse { + asset: string; + assetIndexPrice: string; + time: number; } ⋮---- -export interface GetNftTransactionHistoryParams { - orderType: number; - startTime?: number; - endTime?: number; - limit?: number; - page?: number; +export interface BnbTransferParams { + amount: number; + transferSide: 'TO_UM' | 'FROM_UM'; } ⋮---- -export interface NftToken { - network: string; - tokenId: string; - contractAddress: string; +export interface GetPortfolioMarginAssetLeverageResponse { + asset: string; + leverage: number; +} +⋮---- +export interface SetPortfolioMarginMarginCallLevelParams { + marginCallLevel: number; +} +⋮---- +export interface PortfolioMarginMarginCallLevelResponse { + marginCallLevel: string; } ⋮---- -export interface NftTransaction { - orderNo: string; - tokens: NftToken[]; - tradeTime: number; - tradeAmount: string; - tradeCurrency: string; +export type PortfolioMarginMarginCallLevelGetResponse = + | PortfolioMarginMarginCallLevelResponse + | Record; +⋮---- +export interface PortfolioMarginMarginCallLevelDeleteResponse { + msg: string; } ⋮---- -export interface GetNftDepositHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; +export interface SubscribeBlvtParams { + tokenName: string; + cost: number; } ⋮---- -export interface NftDeposit { - network: string; - txID: string | null; - contractAdrress: string; - tokenId: string; +export interface SubscribeBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + amount: string; + cost: string; timestamp: number; } ⋮---- -export interface GetNftWithdrawHistoryParams { +export interface GetBlvtSubscriptionRecordParams { + tokenName?: string; + id?: number; startTime?: number; endTime?: number; limit?: number; - page?: number; } ⋮---- -export interface NftWithdraw { - network: string; - txID: string; - contractAdrress: string; - tokenId: string; +export interface BlvtSubscriptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + totalCharge: string; timestamp: number; - fee: number; - feeAsset: string; -} -⋮---- -export interface GetNftAssetParams { - limit?: number; - page?: number; -} -⋮---- -export interface NftAsset { - network: string; - contractAddress: string; - tokenId: string; } ⋮---- -export interface CreateGiftCardParams { - token: string; +export interface RedeemBlvtParams { + tokenName: string; amount: number; } ⋮---- -export interface CreateDualTokenGiftCardParams { - baseToken: string; - faceToken: string; - baseTokenAmount: number; - discount?: number; -} -⋮---- -export interface RedeemGiftCardParams { - code: string; - externalUid?: string; -} -⋮---- -export interface SimpleEarnProductListParams { - asset?: string; - current?: number; - size?: number; +export interface RedeemBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + redeemAmount: string; + amount: string; + timestamp: number; } ⋮---- -export interface SimpleEarnFlexibleProduct { - asset: string; - latestAnnualInterestRate: string; - tierAnnualPercentageRate: Record; - airDropPercentageRate: string; - canPurchase: boolean; - canRedeem: boolean; - isSoldOut: boolean; - hot: boolean; - minPurchaseAmount: string; - productId: string; - subscriptionStartTime: number; - status: string; +export interface GetBlvtRedemptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface SimpleEarnLockedProduct { - projectId: string; - detail: { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: string; - subscriptionStartTime: number; - extraRewardAsset: string; - extraRewardAPR: string; - boostRewardAsset: string; - boostApr: string; - boostEndTime: string; - }; - quota: { - totalPersonalQuota: string; - minimum: string; - }; +export interface BlvtRedemptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + netProceed: string; + timestamp: number; } ⋮---- -export interface SimpleEarnSubscribeProductParams { - productId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; +export interface BlvtUserLimitInfo { + tokenName: string; + userDailyTotalPurchaseLimit: string; + userDailyTotalRedeemLimit: string; } ⋮---- -export interface SimpleEarnSubscribeFlexibleProductResponse { - purchaseId: string; - success: boolean; +export interface GetFiatOrderHistoryParams { + transactionType: string; + beginTime?: number; + endTime?: number; + page?: number; + rows?: number; } ⋮---- -export interface SimpleEarnSubscribeLockedProductResponse { - purchaseId: string; - positionId: string; +export interface GetFiatOrderHistoryResponse { + code: string; + message: string; + data: { + orderNo: string; + fiatCurrency: string; + indicatedAmount: string; + amount: string; + totalFee: string; + method: string; + status: string; + createTime: number; + updateTime: number; + }[]; + total: number; success: boolean; } ⋮---- -export interface SimpleEarnRedeemFlexibleProductParams { - productId: string; - redeemAll?: boolean; - amount?: number; - destAccount?: 'SPOT' | 'FUND'; -} -⋮---- -export interface SimpleEarnRedeemResponse { +export interface GetFiatPaymentsHistoryResponse { + code: string; + message: string; + data: { + orderNo: string; + sourceAmount: string; + fiatCurrency: string; + obtainAmount: string; + cryptoCurrency: string; + totalFee: string; + price: string; + status: string; + paymentMethod?: string; + createTime: number; + updateTime: number; + }[]; + total: number; success: boolean; - redeemId: string; } ⋮---- -export interface SimpleEarnFlexibleProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; +export interface WithdrawFiatAccountInfo { + accountNumber: string; + agency: string; + bankCodeForPix: string; + accountType: string; } ⋮---- -export interface SimpleEarnLockedProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; - positionId?: string; +export interface WithdrawFiatParams { + currency: string; + apiPaymentMethod: string; + amount: number; + accountInfo?: WithdrawFiatAccountInfo; } ⋮---- -export interface SimpleEarnLockedProductPosition { - positionId: string; - projectId: string; - asset: string; - amount: string; - purchaseTime: string; - duration: string; - accrualDays: string; - rewardAsset: string; - APY: string; - isRenewable: boolean; - isAutoRenew: boolean; - redeemDate: string; - boostRewardAsset: string; - boostApr: string; - totalBoostRewardAmt: string; +export interface FiatDepositParams { + currency: string; + apiPaymentMethod: string; + amount: number; + ext?: object; + recvWindow?: number; + timestamp?: number; } ⋮---- -export interface SimpleEarnAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedinBTC: string; - totalLockedinUSDT: string; +export interface FiatDepositResponse { + code: string; + message: string; + data: { + orderId: string; + }; } ⋮---- -export interface GetSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; +export interface GetFiatOrderDetailParams { + orderNo: string; + recvWindow?: number; + timestamp?: number; } ⋮---- -export interface SubAccountDeposit { - depositId: number; - subAccountId: string; - address: string; - addressTag: string; - amount: string; - coin: string; - insertTime: number; - transferType: number; - network: string; - status: number; - txId: string; - sourceAddress: string; - confirmTimes: string; - selfReturnStatus: number; +export interface GetFiatOrderDetailResponse { + code: string; + message: string; + data: { + orderId: string; + orderStatus: string; + amount: string; + fee: string; + fiatCurrency: string; + errorCode: string; + errorMessage: string; + ext: object; + }; } ⋮---- -// Request interface for querying sub account spot asset info -export interface QuerySubAccountSpotMarginAssetInfoParams { - subAccountId?: string; +export interface GetC2CTradeHistoryParams { + tradeType: string; + startTimestamp?: number; + endTimestamp?: number; page?: number; - size?: number; + rows?: number; } ⋮---- -export interface SubaccountBrokerSpotAsset { - subAccountId: string; - totalBalanceOfBtc: string; +export interface c2cTradeData { + orderNumber: string; + advNo: string; + tradeType: string; + asset: string; + fiat: string; + fiatSymbol: string; + amount: string; + totalPrice: string; + unitPrice: string; + orderStatus: string; + createTime: number; + commission: string; + counterPartNickName: string; + advertisementRole: string; } -⋮---- -export interface SubAccountBrokerMarginAsset { - marginEnable: boolean; - subAccountId: string; - totalAssetOfBtc?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - marginLevel?: string; +export interface GetC2CTradeHistoryResponse { + code: string; + message: string; + data: c2cTradeData[]; + total: number; + success: boolean; } ⋮---- -// Request interface for querying sub account futures asset info -export interface QuerySubAccountFuturesAssetInfoParams { - subAccountId?: string; - futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures - page?: number; - size?: number; +export interface GetVipLoanOngoingOrdersParams { + orderId?: number; + collateralAccountId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; } ⋮---- -futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures +export interface VipOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + loanRate: string; + residualInterest: string; + collateralAccountId: string; + collateralCoin: string; + totalCollateralValueAfterHaircut: string; + lockedCollateralValue: string; + currentLTV: string; + expirationTime: number; + loanDate: string; + loanTerm: string; + initialLtv: string; + marginCallLtv: string; + liquidationLtv: string; +} ⋮---- -// Response interface for querying sub account futures asset info (USD Margined Futures) -export interface UsdtMarginedFuturesResponse { - subAccountId: string; - totalInitialMargin: string; - totalMaintenanceMargin: string; - totalWalletBalance: string; - totalUnrealizedProfit: string; - totalMarginBalance: string; - totalPositionInitialMargin: string; - totalOpenOrderInitialMargin: string; - futuresEnable: boolean; - asset: string; +export interface VipLoanRepayParams { + orderId: number; + amount: number; } ⋮---- -// Response interface for querying sub account futures asset info (COIN Margined Futures) -export interface CoinMarginedFuturesResponse { - subAccountId: string; - totalWalletBalanceOfUsdt: string; - totalUnrealizedProfitOfUsdt: string; - totalMarginBalanceOfUsdt: string; - futuresEnable: boolean; +export interface VipLoanRepayResponse { + loanCoin: string; + repayAmount: string; + remainingPrincipal: string; + remainingInterest: string; + collateralCoin: string; + currentLTV: string; + repayStatus: string; } ⋮---- -// Combined response interface for querying sub account futures asset info -export interface BrokerFuturesSubAccountAssets { - data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; - timestamp: number; +export interface GetVipLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -export interface BrokerUniversalTransfer { - toId: string; - asset: string; - qty: string; - time: number; - status: string; - txnId: string; - clientTranId: string; - fromAccountType: string; - toAccountType: string; +export interface VipLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + repayStatus: string; + loanDate: string; + repayTime: string; + orderId: string; } ⋮---- -// Request interface for changing sub account commission -export interface ChangeSubAccountCommissionParams { - subAccountId: string; - makerCommission: number; - takerCommission: number; - marginMakerCommission?: number; - marginTakerCommission?: number; +export interface VipLoanRenewParams { + orderId: number; + loanTerm?: number; } ⋮---- -// Response interface for changing sub account commission -export interface ChangeSubAccountCommissionResponse { - subAccountId: string; - makerCommission: number; - takerCommission: number; - marginMakerCommission: number; - marginTakerCommission: number; +export interface VipLoanRenewResponse { + loanAccountId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; } ⋮---- -// Request interface for changing sub account USDT-Ⓜ futures commission adjustment -export interface ChangeSubAccountFuturesCommissionParams { - subAccountId: string; - symbol: string; - makerAdjustment: number; - takerAdjustment: number; +export interface CheckVipCollateralAccountParams { + orderId?: number; + collateralAccountId?: number; } ⋮---- -// Response interface for changing sub account USDT-Ⓜ futures commission adjustment -export interface ChangeSubAccountFuturesCommissionResponse { - subAccountId: string; - symbol: string; - makerAdjustment: number; - takerAdjustment: number; - makerCommission: number; - takerCommission: number; +export interface VipCollateralAccount { + collateralAccountId: string; + collateralCoin: string; } ⋮---- -// Request interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface QuerySubAccountFuturesCommissionParams { - subAccountId: string; - symbol?: string; +export interface VipLoanBorrowParams { + loanAccountId: number; + loanCoin: string; + loanAmount: number; + collateralAccountId: string; + collateralCoin: string; + isFlexibleRate: boolean; + loanTerm?: number; } ⋮---- -// Response interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface BrokerSubAccountFuturesCommission { - subAccountId: string; - symbol: string; - makerCommission: number; - takerCommission: number; +export interface VipLoanBorrowResponse { + loanAccountId: string; + requestId: string; + loanCoin: string; + isFlexibleRate: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm?: string; } ⋮---- -export interface ChangeSubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair: string; - makerAdjustment: number; - takerAdjustment: number; - recvWindow?: number; - timestamp: number; +export interface GetLoanableAssetsDataParams { + loanCoin?: string; + vipLevel?: number; +} +⋮---- +export interface GetApplicationStatusParams { + current?: number; + limit?: number; } ⋮---- -export interface QuerySubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair?: string; - recvWindow?: number; - timestamp: number; +export interface ApplicationStatus { + loanAccountId: string; + orderId: string; + requestId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; + status: string; + loanDate: string; } ⋮---- -// Response interface for querying sub account COIN-Ⓜ futures commission adjustment -export interface BrokerSubAccountCoinFuturesCommission { - subAccountId: string; - pair: string; - makerCommission: number; - takerCommission: number; +export interface BorrowInterestRate { + asset: string; + flexibleDailyInterestRate: string; + flexibleYearlyInterestRate: string; + time: number; } ⋮---- -export interface QueryBrokerSpotCommissionRebateParams { - subAccountId?: string; +export interface GetCryptoLoansIncomeHistoryParams { + asset?: string; + type?: string; startTime?: number; endTime?: number; - page?: number; - size?: number; - recvWindow?: number; - timestamp: number; + limit?: number; } ⋮---- -// Response interface for querying spot commission rebate recent record -export interface BrokerCommissionRebate { - subaccountId: string; - income: string; +export interface GetCryptoLoansIncomeHistoryResponse { asset: string; - symbol: string; - tradeId: number; - time: number; - status: number; -} -⋮---- -export interface QueryBrokerFuturesCommissionRebateParams { - futuresType: number; // 1: USDT Futures, 2: Coin Futures - startTime: number; - endTime: number; - page?: number; - size?: number; - filterResult?: boolean; - recvWindow?: number; + type: string; + amount: string; timestamp: number; + tranId: string; } ⋮---- -futuresType: number; // 1: USDT Futures, 2: Coin Futures +export interface BorrowCryptoLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; + loanTerm: number; +} ⋮---- -export interface SubmitMarginOTOOrderParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - sideEffectType?: SideEffects; - selfTradePreventionMode?: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - autoRepayAtCancel?: boolean; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: number; - workingQuantity: number; - workingIcebergQty?: number; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingType: OrderType; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: number; - pendingStopPrice?: number; - pendingTrailingDelta?: number; - pendingQuantity: number; - pendingIcebergQty?: number; - pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; +export interface BorrowCryptoLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + hourlyInterestRate: string; + orderId: string; } ⋮---- -export interface MarginOTOOrder { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - selfTradePreventionMode: string; - }[]; +export interface GetLoanBorrowHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -export interface SubmitMarginOTOCOOrderParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - sideEffectType?: SideEffects; - autoRepayAtCancel?: boolean; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: string; - pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; +export interface LoanBorrowHistory { + orderId: number; + loanCoin: string; + initialLoanAmount: string; + hourlyInterestRate: string; + loanTerm: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: string; } ⋮---- -export interface MarginOTOCOOrder { - orderListId: number; - contingencyType: 'OTO'; - listStatusType: 'EXEC_STARTED'; - listOrderStatus: 'EXECUTING'; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: - | 'NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED' - | 'PENDING_NEW'; - timeInForce: 'GTC' | 'IOC' | 'FOK'; - type: - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - side: 'BUY' | 'SELL'; - stopPrice?: string; - selfTradePreventionMode: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - }[]; +export interface GetLoanOngoingOrdersParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; } ⋮---- -export interface CreateSpecialLowLatencyKeyParams { - apiName: string; - symbol?: string; - ip?: string; - publicKey?: string; +export interface LoanOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + residualInterest: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; + expirationTime: number; } ⋮---- -export interface SpecialLowLatencyKeyResponse { - apiKey: string; - secretKey: string | null; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +export interface RepayCryptoLoanParams { + orderId: number; + amount: number; + type?: number; + collateralReturn?: boolean; } ⋮---- -export interface SpecialLowLatencyKeyInfo { - apiName: string; - apiKey: string; - ip: string; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +export interface RepayCryptoLoanResponse { + loanCoin: string; + remainingPrincipal?: string; + remainingInterest?: string; + collateralCoin: string; + remainingCollateral?: string; + currentLTV?: string; + repayStatus: string; } ⋮---- -export interface MarginLiquidationLoan { - asset: string; - amount: string; - repaidAmount: string; - remainingAmount: string; +export interface GetLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -export interface RepayMarginLiquidationLoanParams { - asset: string; - amount: string; +export interface LoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralUsed: string; + collateralReturn: string; + repayType: string; + repayStatus: string; + repayTime: number; + orderId: number; } ⋮---- -export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; +export interface AdjustCryptoLoanLTVParams { + orderId: number; + amount: number; + direction: 'ADDITIONAL' | 'REDUCED'; +} ⋮---- -export interface MarginLiquidationLoanRepayResponse { - repayId: number; - asset: string; +export interface AdjustCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; + currentLTV: string; } ⋮---- -export interface GetMarginLiquidationLoanRepayHistoryParams { +export interface GetLoanLTVAdjustmentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; startTime?: number; endTime?: number; current?: number; - size?: number; + limit?: number; } ⋮---- -export interface MarginLiquidationLoanRepayHistoryRecord { - repayId: number; - asset: string; +export interface LoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; + preLTV: string; + afterLTV: string; + adjustTime: number; + orderId: number; } ⋮---- -export interface MarginLiquidationLoanRepayHistoryResponse { - total: number; - rows: MarginLiquidationLoanRepayHistoryRecord[]; +export interface LoanableAssetData { + loanCoin: string; + _7dHourlyInterestRate: string; + _7dDailyInterestRate: string; + _14dHourlyInterestRate: string; + _14dDailyInterestRate: string; + _30dHourlyInterestRate: string; + _30dDailyInterestRate: string; + _90dHourlyInterestRate: string; + _90dDailyInterestRate: string; + _180dHourlyInterestRate: string; + _180dDailyInterestRate: string; + minLimit: string; + maxLimit: string; + vipLevel: number; } ⋮---- -export interface SolStakingAccount { - bnsolAmount: string; // Amount in bNSOL - holdingInSOL: string; // Holding in SOL - thirtyDaysProfitInSOL: string; // 30 days profit in SOL +export interface GetCollateralAssetDataParams { + collateralCoin?: string; + vipLevel?: number; } ⋮---- -bnsolAmount: string; // Amount in bNSOL -holdingInSOL: string; // Holding in SOL -thirtyDaysProfitInSOL: string; // 30 days profit in SOL +export interface CollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; + vipLevel: number; +} ⋮---- -export interface SolStakingQuota { - leftStakingPersonalQuota: string; // Remaining personal staking quota - leftRedemptionPersonalQuota: string; // Remaining personal redemption quota - minStakeAmount: string; // Minimum stake amount - minRedeemAmount: string; // Minimum redeem amount - redeemPeriod: number; // Redemption period in days - stakeable: boolean; // Whether staking is possible - redeemable: boolean; // Whether redemption is possible - soldOut: boolean; // Whether the staking is sold out - commissionFee: string; // Commission fee - nextEpochTime: number; // Time for the next epoch - calculating: boolean; // Whether calculations are ongoing +export interface CheckCollateralRepayRateParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; } ⋮---- -leftStakingPersonalQuota: string; // Remaining personal staking quota -leftRedemptionPersonalQuota: string; // Remaining personal redemption quota -minStakeAmount: string; // Minimum stake amount -minRedeemAmount: string; // Minimum redeem amount -redeemPeriod: number; // Redemption period in days -stakeable: boolean; // Whether staking is possible -redeemable: boolean; // Whether redemption is possible -soldOut: boolean; // Whether the staking is sold out -commissionFee: string; // Commission fee -nextEpochTime: number; // Time for the next epoch -calculating: boolean; // Whether calculations are ongoing +export interface CheckCollateralRepayRateResponse { + loanCoin: string; + collateralCoin: string; + repayAmount: string; + rate: string; +} ⋮---- -export interface SubscribeSolStakingResponse { - success: boolean; // Indicates if the subscription was successful - bnsolAmount: string; // Amount in bNSOL received - exchangeRate: string; // SOL amount per 1 BNSOL +export interface CustomizeMarginCallParams { + orderId?: number; + collateralCoin?: string; + marginCall: number; } ⋮---- -success: boolean; // Indicates if the subscription was successful -bnsolAmount: string; // Amount in bNSOL received -exchangeRate: string; // SOL amount per 1 BNSOL +export interface CustomizeMarginCall { + orderId: string; + collateralCoin: string; + preMarginCall: string; + afterMarginCall: string; + customizeTime: number; +} ⋮---- -export interface RedeemSolResponse { - success: boolean; // Indicates if the redemption was successful - solAmount: string; // Amount in SOL received - exchangeRate: string; // SOL amount per 1 BNSOL - arrivalTime: number; // Time of arrival for the redeemed SOL +export interface BorrowFlexibleLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; } ⋮---- -success: boolean; // Indicates if the redemption was successful -solAmount: string; // Amount in SOL received -exchangeRate: string; // SOL amount per 1 BNSOL -arrivalTime: number; // Time of arrival for the redeemed SOL +export interface BorrowFlexibleLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + status: 'Succeeds' | 'Failed' | 'Processing'; +} ⋮---- -export interface GetSolStakingHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory +export interface GetFlexibleLoanOngoingOrdersParams { + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; } ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +export interface FlexibleLoanOngoingOrder { + loanCoin: string; + totalDebt: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; +} ⋮---- -export interface SolStakingHistoryRecord { - time: number; // Time of the staking event - asset: string; // Asset involved, e.g., SOL - amount: string; // Amount staked - distributeAsset: string; // Asset distributed, e.g., BNSOL - distributeAmount: string; // Amount distributed - exchangeRate: string; // Exchange rate at the time - status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +export interface GetFlexibleLoanLiquidationHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; // Default: 1, max: 1000 + limit?: number; // Default: 10, max: 100 + recvWindow?: number; } ⋮---- -time: number; // Time of the staking event -asset: string; // Asset involved, e.g., SOL -amount: string; // Amount staked -distributeAsset: string; // Asset distributed, e.g., BNSOL -distributeAmount: string; // Amount distributed -exchangeRate: string; // Exchange rate at the time -status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +current?: number; // Default: 1, max: 1000 +limit?: number; // Default: 10, max: 100 +⋮---- +export interface FlexibleLoanLiquidationHistoryRecord { + loanCoin: string; + liquidationDebt: string; + collateralCoin: string; + liquidationCollateralAmount: string; + returnCollateralAmount: string; + liquidationFee: string; + liquidationStartingPrice: string; + liquidationStartingTime: number; + status: 'Liquidated' | 'Liquidating'; +} ⋮---- -export interface GetSolRedemptionHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory +export interface GetFlexibleCryptoLoanBorrowHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +export interface FlexibleCryptoLoanBorrowHistory { + loanCoin: string; + initialLoanAmount: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: 'Succeeds' | 'Failed' | 'Processing'; +} ⋮---- -export interface SolRedemptionHistoryRecord { - time: number; // Time of the redemption event - arrivalTime: number; // Time of arrival for the redeemed SOL - asset: string; // Asset redeemed, e.g., BNSOL - amount: string; // Amount redeemed - distributeAsset: string; // Asset distributed, e.g., SOL - distributeAmount: string; // Amount distributed - exchangeRate: string; // Exchange rate at the time - status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event +export interface RepayCryptoFlexibleLoanParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; + collateralReturn?: boolean; + fullRepayment?: boolean; } ⋮---- -time: number; // Time of the redemption event -arrivalTime: number; // Time of arrival for the redeemed SOL -asset: string; // Asset redeemed, e.g., BNSOL -amount: string; // Amount redeemed -distributeAsset: string; // Asset distributed, e.g., SOL -distributeAmount: string; // Amount distributed -exchangeRate: string; // Exchange rate at the time -status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event +export interface RepayCryptoFlexibleLoanResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +} ⋮---- -export interface GetBnsolRewardsHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory +export interface RepayCryptoLoanFlexibleWithCollateralParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; // Amount of loan to repay + fullRepayment?: boolean; // Default: FALSE } ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +repayAmount: number; // Amount of loan to repay +fullRepayment?: boolean; // Default: FALSE ⋮---- -export interface BnsolRewardHistoryRecord { - time: number; // Time of the reward event - amountInSOL: string; // Reward amount in SOL - holding: string; // BNSOL holding balance - holdingInSOL: string; // BNSOL holding balance in SOL - annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) +export interface RepayCryptoLoanFlexibleWithCollateralResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +} +export interface GetFlexibleCryptoLoanRepaymentHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -time: number; // Time of the reward event -amountInSOL: string; // Reward amount in SOL -holding: string; // BNSOL holding balance -holdingInSOL: string; // BNSOL holding balance in SOL -annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) +export interface FlexibleCryptoLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralReturn: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; + repayTime: number; +} ⋮---- -export interface GetBnsolRateHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory +export interface AdjustFlexibleCryptoLoanLTVParams { + loanCoin: string; + collateralCoin: string; + adjustmentAmount: number; + direction: 'ADDITIONAL' | 'REDUCED'; } ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +export interface AdjustFlexibleCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + adjustmentAmount: string; + currentLTV: string; +} ⋮---- -export interface SolBoostRewardsHistoryReq { - type: 'CLAIM' | 'DISTRIBUTE'; +export interface GetFlexibleLoanLTVAdjustmentHistoryParams { + loanCoin?: string; + collateralCoin?: string; startTime?: number; endTime?: number; current?: number; - size?: number; + limit?: number; } ⋮---- -export interface SolBoostRewardsHistoryRecord { - time: number; - token: string; - amount: string; - bnsolHolding?: string; // Only present if type is "DISTRIBUTE" - status?: string; // Only present if type is "CLAIM" +export interface FlexibleLoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + collateralAmount: string; + preLTV: string; + afterLTV: string; + adjustTime: number; } ⋮---- -bnsolHolding?: string; // Only present if type is "DISTRIBUTE" -status?: string; // Only present if type is "CLAIM" -⋮---- -export interface BnsolRateHistoryRecord { - annualPercentageRate: string; // BNSOL APR - exchangeRate: string; // SOL amount per 1 BNSOL - time: number; // Time of the rate record +export interface FlexibleLoanAssetData { + loanCoin: string; + flexibleInterestRate: string; + flexibleMinLimit: string; + flexibleMaxLimit: string; } ⋮---- -annualPercentageRate: string; // BNSOL APR -exchangeRate: string; // SOL amount per 1 BNSOL -time: number; // Time of the rate record -⋮---- -export interface RiskUnitMM { - asset: string; - uniMaintainUsd: string; +export interface FlexibleLoanCollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; } ⋮---- -export interface PortfolioMarginProSpanAccountInfo { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - riskUnitMMList: RiskUnitMM[]; - marginMM: string; - otherMM: string; - accountStatus: - | 'NORMAL' - | 'MARGIN_CALL' - | 'SUPPLY_MARGIN' - | 'REDUCE_ONLY' - | 'ACTIVE_LIQUIDATION' - | 'FORCE_LIQUIDATION' - | 'BANKRUPTED'; - accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) +export interface GetFuturesLeadTraderStatusResponse { + code: string; + message: string; + data: { + isLeadTrader: boolean; + time: number; + }; + success: boolean; } ⋮---- -accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) +export interface GetFuturesLeadTradingSymbolWhitelistResponse { + code: string; + message: string; + data: { + symbol: string; + baseAsset: string; + quoteAsset: string; + }[]; +} ⋮---- -export interface PortfolioMarginProAccountBalance { - asset: string; - totalWalletBalance: string; - crossMarginAsset: string; - crossMarginBorrowed: string; - crossMarginFree: string; - crossMarginInterest: string; - crossMarginLocked: string; - umWalletBalance: string; - umUnrealizedPNL: string; - cmWalletBalance: string; - cmUnrealizedPNL: string; - updateTime: number; - negativeBalance: string; - optionWalletBalance: string; // only for PM PRO SPAN - optionEquity: string; // only for PM PRO SPAN +export interface GetPayTradeHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -optionWalletBalance: string; // only for PM PRO SPAN -optionEquity: string; // only for PM PRO SPAN +export interface GetAllConvertPairsParams { + fromAsset?: string; + toAsset?: string; +} ⋮---- -export interface PMProMintBFUSDParams { - fromAsset: string; // USDT only - targetAsset: string; // BFUSD only - amount: number; +export interface SubmitConvertLimitOrderParams { + baseAsset: string; + quoteAsset: string; + limitPrice: number; + baseAmount?: number; + quoteAmount?: number; + side: 'BUY' | 'SELL'; + walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; + expiredType: '1_D' | '3_D' | '7_D' | '30_D'; } ⋮---- -fromAsset: string; // USDT only -targetAsset: string; // BFUSD only -⋮---- -export interface PMProMintBFUSDResponse { +export interface ConvertLimitOpenOrder { + quoteId: string; + orderId: number; + orderStatus: string; fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; + expiredTimestamp: number; } ⋮---- -export interface PMProRedeemBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; +export interface GetSpotRebateHistoryRecordsParams { + startTime?: number; + endTime?: number; + page?: number; } ⋮---- -export interface PMProBankruptcyLoanRepaymentHistory { +export interface SpotRebateHistoryRecord { asset: string; + type: number; amount: string; - repayTime: number; + updateTime: number; } ⋮---- -export interface VipLoanInterestRateHistoryParams { - coin: string; +export interface GetSpotRebateHistoryRecordsResponse { + status: string; + type: string; + code: string; + data: { + page: number; + totalRecords: number; + totalPageNum: number; + data: SpotRebateHistoryRecord[]; + }; +} +⋮---- +export interface GetNftTransactionHistoryParams { + orderType: number; startTime?: number; endTime?: number; - current?: number; limit?: number; + page?: number; } ⋮---- -export interface VipLoanInterestRateRecord { - coin: string; - annualizedInterestRate: string; - time: number; +export interface NftToken { + network: string; + tokenId: string; + contractAddress: string; } ⋮---- -export interface VipLoanAccruedInterestParams { - orderId?: number; - loanCoin?: string; +export interface NftTransaction { + orderNo: string; + tokens: NftToken[]; + tradeTime: number; + tradeAmount: string; + tradeCurrency: string; +} +⋮---- +export interface GetNftDepositHistoryParams { startTime?: number; endTime?: number; - current?: number; limit?: number; + page?: number; } ⋮---- -export interface VipLoanAccruedInterestRecord { - loanCoin: string; - principalAmount: string; - interestAmount: string; - annualInterestRate: string; - accrualTime: number; - orderId: number; -} -⋮---- -export interface WithdrawTravelRuleParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; - questionnaire: string; +export interface NftDeposit { + network: string; + txID: string | null; + contractAdrress: string; + tokenId: string; + timestamp: number; } ⋮---- -export interface GetTravelRuleWithdrawHistoryParams { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; - limit?: number; +export interface GetNftWithdrawHistoryParams { startTime?: number; endTime?: number; + limit?: number; + page?: number; } ⋮---- -export interface GetTravelRuleWithdrawHistoryV2Params { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; +export interface NftWithdraw { + network: string; + txID: string; + contractAdrress: string; + tokenId: string; + timestamp: number; + fee: number; + feeAsset: string; +} +⋮---- +export interface GetNftAssetParams { limit?: number; - startTime?: number; - endTime?: number; + page?: number; } ⋮---- -export interface SubmitTravelRuleDepositQuestionnaireParams { - tranId: number; - questionnaire: string; +export interface NftAsset { + network: string; + contractAddress: string; + tokenId: string; } ⋮---- -export interface GetTravelRuleDepositHistoryParams { - trId?: string; - txId?: string; - tranId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - pendingQuestionnaire?: boolean; - startTime?: number; - endTime?: number; - offset?: number; - limit?: number; +export interface CreateGiftCardParams { + token: string; + amount: number; } ⋮---- -export interface TravelRuleWithdrawHistoryRecord { - id: string; - trId: number; - amount: string; - transactionFee: string; - coin: string; - withdrawalStatus: number; - travelRuleStatus: number; - address: string; - addressTag?: string; - txId: string; - applyTime: string; - network?: string; - transferType: number; - withdrawOrderId?: string; - info: string; - confirmNo: number; - walletType: number; - txKey: string; - questionnaire: string; - completeTime?: string; +export interface CreateDualTokenGiftCardParams { + baseToken: string; + faceToken: string; + baseTokenAmount: number; + discount?: number; } ⋮---- -export interface SubmitTravelRuleDepositQuestionnaireResponse { - trId: number; - accepted: boolean; - info: string; +export interface RedeemGiftCardParams { + code: string; + externalUid?: string; } ⋮---- -export interface TravelRuleDepositHistoryRecord { - trId: number; - tranId: number; - amount: string; - coin: string; - network: string; - depositStatus: number; - travelRuleStatus: number; - address: string; - addressTag?: string; - txId: string; - insertTime: number; - transferType: number; - confirmTimes: string; - unlockConfirm: number; - walletType: number; - requireQuestionnaire: boolean; - questionnaire: string | null; +export interface SimpleEarnProductListParams { + asset?: string; + current?: number; + size?: number; } ⋮---- -export interface VASPInfo { - vaspName: string; - vaspCode?: string; - /** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ - identifier?: string; +export interface SimpleEarnFlexibleProduct { + asset: string; + latestAnnualInterestRate: string; + tierAnnualPercentageRate: Record; + airDropPercentageRate: string; + canPurchase: boolean; + canRedeem: boolean; + isSoldOut: boolean; + hot: boolean; + minPurchaseAmount: string; + productId: string; + subscriptionStartTime: number; + status: string; +} +⋮---- +export interface SimpleEarnLockedProduct { + projectId: string; + detail: { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: string; + subscriptionStartTime: number; + extraRewardAsset: string; + extraRewardAPR: string; + boostRewardAsset: string; + boostApr: string; + boostEndTime: string; + }; + quota: { + totalPersonalQuota: string; + minimum: string; + }; } ⋮---- -/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ +export interface SimpleEarnSubscribeProductParams { + productId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; +} ⋮---- -// Institutional Loan types -export interface InstitutionalLoanLiability { - assetName: string; - principal: string; - interest: string; +export interface SimpleEarnSubscribeFlexibleProductResponse { + purchaseId: string; + success: boolean; } ⋮---- -export interface InstitutionalLoanWallet { - accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; +export interface SimpleEarnSubscribeLockedProductResponse { + purchaseId: string; + positionId: string; + success: boolean; } ⋮---- -export interface InstitutionalLoanCollateralAccount { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - wallets: InstitutionalLoanWallet[]; +export interface SimpleEarnRedeemFlexibleProductParams { + productId: string; + redeemAll?: boolean; + amount?: number; + destAccount?: 'SPOT' | 'FUND'; } ⋮---- -export interface InstitutionalLoanRiskUnitDetails { - groupId: number; - parentEmail: string; - creditEmail: string; - updateTime: number; - ltv: string; - totalNetEquity: string; - totalMaintenanceMargin: string; - totalLiability: string; - liabilities: InstitutionalLoanLiability[]; - collateralAccounts: InstitutionalLoanCollateralAccount[]; +export interface SimpleEarnRedeemResponse { + success: boolean; + redeemId: string; } ⋮---- -export interface GetInstitutionalLoanRiskUnitDetailsParams { - groupId?: number; +export interface SimpleEarnFlexibleProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; } ⋮---- -export interface CloseInstitutionalLoanRiskUnitResponse { - groupId: number; - status: 'CLOSED'; +export interface SimpleEarnLockedProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; + positionId?: string; } ⋮---- -export interface AddInstitutionalLoanCollateralAccountParams { - groupId: number; - subEmail: string; - enableSpot: boolean; - enableMargin: boolean; +export interface SimpleEarnLockedProductPosition { + positionId: string; + projectId: string; + asset: string; + amount: string; + purchaseTime: string; + duration: string; + accrualDays: string; + rewardAsset: string; + APY: string; + isRenewable: boolean; + isAutoRenew: boolean; + redeemDate: string; + boostRewardAsset: string; + boostApr: string; + totalBoostRewardAmt: string; } ⋮---- -export interface InstitutionalLoanRiskUnitMember { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - enableMargin: boolean; - enableSpot: boolean; +export interface SimpleEarnAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedinBTC: string; + totalLockedinUSDT: string; } ⋮---- -export interface ActiveInstitutionalLoanRiskUnit { - groupId: number; - members: InstitutionalLoanRiskUnitMember[]; - createTime: number; +export interface GetSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; } -export interface ClosedInstitutionalLoanRiskUnit { - groupId: number; - parentEmail: string; - creditEmail: string; - enabled: boolean; - createTime: number; - closeTime: number; +⋮---- +export interface SubAccountDeposit { + depositId: number; + subAccountId: string; + address: string; + addressTag: string; + amount: string; + coin: string; + insertTime: number; + transferType: number; + network: string; + status: number; + txId: string; + sourceAddress: string; + confirmTimes: string; + selfReturnStatus: number; } ⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsParams { - current?: number; +// Request interface for querying sub account spot asset info +export interface QuerySubAccountSpotMarginAssetInfoParams { + subAccountId?: string; + page?: number; size?: number; } ⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsResponse { - total: number; - rows: ClosedInstitutionalLoanRiskUnit[]; +export interface SubaccountBrokerSpotAsset { + subAccountId: string; + totalBalanceOfBtc: string; } ⋮---- -// Institutional Loan Force Liquidation interfaces -export interface InstitutionalLoanLiquidationSnapshot { - subEmail: string; - memberType: 'CREDIT' | 'COLLATERAL'; - walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; +export interface SubAccountBrokerMarginAsset { + marginEnable: boolean; + subAccountId: string; + totalAssetOfBtc?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + marginLevel?: string; } ⋮---- -export interface InstitutionalLoanLiquidationSnapshotData { - snapshots: InstitutionalLoanLiquidationSnapshot[]; - liabilities: InstitutionalLoanLiability[]; +// Request interface for querying sub account futures asset info +export interface QuerySubAccountFuturesAssetInfoParams { + subAccountId?: string; + futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures + page?: number; + size?: number; } ⋮---- -export interface InstitutionalLoanForceLiquidationRecord { - groupId: number; - startLtv: number; - endLtv: number; - liquidationStartTime: number; - liquidationEndTime: number; - totalNetEquity: string; +futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures +⋮---- +// Response interface for querying sub account futures asset info (USD Margined Futures) +export interface UsdtMarginedFuturesResponse { + subAccountId: string; + totalInitialMargin: string; totalMaintenanceMargin: string; - totalLiability: string; - liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; + totalWalletBalance: string; + totalUnrealizedProfit: string; + totalMarginBalance: string; + totalPositionInitialMargin: string; + totalOpenOrderInitialMargin: string; + futuresEnable: boolean; + asset: string; } ⋮---- -export interface GetInstitutionalLoanForceLiquidationParams { - groupId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; +// Response interface for querying sub account futures asset info (COIN Margined Futures) +export interface CoinMarginedFuturesResponse { + subAccountId: string; + totalWalletBalanceOfUsdt: string; + totalUnrealizedProfitOfUsdt: string; + totalMarginBalanceOfUsdt: string; + futuresEnable: boolean; +} +⋮---- +// Combined response interface for querying sub account futures asset info +export interface BrokerFuturesSubAccountAssets { + data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; timestamp: number; } ⋮---- -export interface GetInstitutionalLoanForceLiquidationResponse { - total: number; - rows: InstitutionalLoanForceLiquidationRecord[]; +export interface BrokerUniversalTransfer { + toId: string; + asset: string; + qty: string; + time: number; + status: string; + txnId: string; + clientTranId: string; + fromAccountType: string; + toAccountType: string; } ⋮---- -// Risk Unit Transfer interfaces -export interface InstitutionalLoanRiskUnitTransferParams { - subEmail?: string; // Optional: subEmail can be credit account or collateral account - asset: string; // Asset Name - amount: number; // Transfer amount of the asset +// Request interface for changing sub account commission +export interface ChangeSubAccountCommissionParams { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission?: number; + marginTakerCommission?: number; +} +⋮---- +// Response interface for changing sub account commission +export interface ChangeSubAccountCommissionResponse { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission: number; + marginTakerCommission: number; +} +⋮---- +// Request interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionParams { + subAccountId: string; + symbol: string; + makerAdjustment: number; + takerAdjustment: number; +} +⋮---- +// Response interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionResponse { + subAccountId: string; + symbol: string; + makerAdjustment: number; + takerAdjustment: number; + makerCommission: number; + takerCommission: number; } ⋮---- -subEmail?: string; // Optional: subEmail can be credit account or collateral account -asset: string; // Asset Name -amount: number; // Transfer amount of the asset +// Request interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface QuerySubAccountFuturesCommissionParams { + subAccountId: string; + symbol?: string; +} ⋮---- -// Additional institutional loan types for borrow, repay, and interest history -export interface InstitutionalLoanBorrowParams { - groupId: number; - assetName: string; - amount: number; +// Response interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface BrokerSubAccountFuturesCommission { + subAccountId: string; + symbol: string; + makerCommission: number; + takerCommission: number; } ⋮---- -export interface InstitutionalLoanBorrowResponse { - transactionId: string; - amount: number; - status: string; +export interface ChangeSubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair: string; + makerAdjustment: number; + takerAdjustment: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface InstitutionalLoanRepayParams { - groupId: number; - assetName: string; - amount: number; +export interface QuerySubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface InstitutionalLoanRepayResponse { - transactionId: string; - amount: number; +// Response interface for querying sub account COIN-Ⓜ futures commission adjustment +export interface BrokerSubAccountCoinFuturesCommission { + subAccountId: string; + pair: string; + makerCommission: number; + takerCommission: number; } ⋮---- -export interface GetInstitutionalLoanInterestHistoryParams { - groupId?: number; - asset?: string; +export interface QueryBrokerSpotCommissionRebateParams { + subAccountId?: string; startTime?: number; endTime?: number; - current?: number; + page?: number; size?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface InstitutionalLoanInterestHistoryRecord { - groupId: number; - assetName: string; - principal: string; - interestRate: string; - interest: string; - interestTimestamp: number; +// Response interface for querying spot commission rebate recent record +export interface BrokerCommissionRebate { + subaccountId: string; + income: string; + asset: string; + symbol: string; + tradeId: number; + time: number; + status: number; } ⋮---- -export interface InstitutionalLoanInterestHistoryResponse { - total: number; - rows: InstitutionalLoanInterestHistoryRecord[]; +export interface QueryBrokerFuturesCommissionRebateParams { + futuresType: number; // 1: USDT Futures, 2: Coin Futures + startTime: number; + endTime: number; + page?: number; + size?: number; + filterResult?: boolean; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface GetInstitutionalLoanBorrowRepayRecordsParams { - groupId?: number; // Optional: Risk unit unique identifier - type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY - asset?: string; // Optional: Asset name - startTime?: number; // Optional: Start time - endTime?: number; // Optional: End time - current?: number; // Optional: The currently querying page. Start from 1. Default:1 - size?: number; // Optional: Default:10 Max:100 - recvWindow?: number; // Optional: The value cannot be greater than 60000 - timestamp: number; // Required +futuresType: number; // 1: USDT Futures, 2: Coin Futures +⋮---- +export interface SubmitMarginOTOOrderParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + sideEffectType?: SideEffects; + selfTradePreventionMode?: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + autoRepayAtCancel?: boolean; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: number; + workingQuantity: number; + workingIcebergQty?: number; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingType: OrderType; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: number; + pendingStopPrice?: number; + pendingTrailingDelta?: number; + pendingQuantity: number; + pendingIcebergQty?: number; + pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; } ⋮---- -groupId?: number; // Optional: Risk unit unique identifier -type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY -asset?: string; // Optional: Asset name -startTime?: number; // Optional: Start time -endTime?: number; // Optional: End time -current?: number; // Optional: The currently querying page. Start from 1. Default:1 -size?: number; // Optional: Default:10 Max:100 -recvWindow?: number; // Optional: The value cannot be greater than 60000 -timestamp: number; // Required +export interface MarginOTOOrder { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + selfTradePreventionMode: string; + }[]; +} +⋮---- +export interface SubmitMarginOTOCOOrderParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + sideEffectType?: SideEffects; + autoRepayAtCancel?: boolean; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: string; + pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; +} +⋮---- +export interface MarginOTOCOOrder { + orderListId: number; + contingencyType: 'OTO'; + listStatusType: 'EXEC_STARTED'; + listOrderStatus: 'EXECUTING'; + listClientOrderId: string; + transactionTime: number; + symbol: string; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: + | 'NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'PENDING_NEW'; + timeInForce: 'GTC' | 'IOC' | 'FOK'; + type: + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + side: 'BUY' | 'SELL'; + stopPrice?: string; + selfTradePreventionMode: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + }[]; +} ⋮---- -export interface InstitutionalLoanBorrowRepayRecord { - tranId: number; // Transaction ID - assetName: string; // Asset name - amount: number; // Amount - status: 'CONFIRM' | 'FAILED'; // Status - type: 'BORROW' | 'REPAY'; // Type - timestamp: number; // Create Time - principal?: number; // Only present for REPAY type - interest?: number; // Only present for REPAY type +export interface CreateSpecialLowLatencyKeyParams { + apiName: string; + symbol?: string; + ip?: string; + publicKey?: string; } ⋮---- -tranId: number; // Transaction ID -assetName: string; // Asset name -amount: number; // Amount -status: 'CONFIRM' | 'FAILED'; // Status -type: 'BORROW' | 'REPAY'; // Type -timestamp: number; // Create Time -principal?: number; // Only present for REPAY type -interest?: number; // Only present for REPAY type +export interface SpecialLowLatencyKeyResponse { + apiKey: string; + secretKey: string | null; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +} ⋮---- -export interface GetInstitutionalLoanBorrowRepayRecordsResponse { - total: number; - rows: InstitutionalLoanBorrowRepayRecord[]; +export interface SpecialLowLatencyKeyInfo { + apiName: string; + apiKey: string; + ip: string; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; } ⋮---- -export interface MarginInterestRebateBalanceResponse { +export interface MarginLiquidationLoan { asset: string; - balance: string; - totalGranted: string; - totalConsumed: string; + amount: string; + repaidAmount: string; + remainingAmount: string; } ⋮---- -export interface GetMarginInterestRebateBalanceRecordsParams { - type?: 0 | 1 | 2; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface RepayMarginLiquidationLoanParams { + asset: string; + amount: string; } ⋮---- -export interface MarginInterestRebateBalanceRecord { - type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; - rebateAsset: string; - delta: string; - createTime: number; - groupId?: number; - liabilityAsset?: string; - deductedInterest?: string; - exchangeRate?: string; -} +export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; ⋮---- -export interface MarginInterestRebateBalanceRecordsResponse { - total: number; - rows: MarginInterestRebateBalanceRecord[]; +export interface MarginLiquidationLoanRepayResponse { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; } ⋮---- -// On-chain Yields types -⋮---- -export interface OnchainYieldsLockedProductListParams { - asset?: string; +export interface GetMarginLiquidationLoanRepayHistoryParams { + startTime?: number; + endTime?: number; current?: number; size?: number; } ⋮---- -export interface OnchainYieldsLockedProductDetail { +export interface MarginLiquidationLoanRepayHistoryRecord { + repayId: number; asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: 'PREHEATING' | 'PURCHASING'; - subscriptionStartTime: string; - canRedeemToFlex: boolean; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; } ⋮---- -export interface OnchainYieldsLockedProductQuota { - totalPersonalQuota: string; - minimum: string; +export interface MarginLiquidationLoanRepayHistoryResponse { + total: number; + rows: MarginLiquidationLoanRepayHistoryRecord[]; } ⋮---- -export interface OnchainYieldsLockedProduct { - projectId: string; - detail: OnchainYieldsLockedProductDetail; - quota: OnchainYieldsLockedProductQuota; +export interface SolStakingAccount { + bnsolAmount: string; // Amount in bNSOL + holdingInSOL: string; // Holding in SOL + thirtyDaysProfitInSOL: string; // 30 days profit in SOL } ⋮---- -export interface OnchainYieldsLockedProductListResponse { - rows: OnchainYieldsLockedProduct[]; - total: number; -} +bnsolAmount: string; // Amount in bNSOL +holdingInSOL: string; // Holding in SOL +thirtyDaysProfitInSOL: string; // 30 days profit in SOL ⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaParams { - projectId: string; +export interface SolStakingQuota { + leftStakingPersonalQuota: string; // Remaining personal staking quota + leftRedemptionPersonalQuota: string; // Remaining personal redemption quota + minStakeAmount: string; // Minimum stake amount + minRedeemAmount: string; // Minimum redeem amount + redeemPeriod: number; // Redemption period in days + stakeable: boolean; // Whether staking is possible + redeemable: boolean; // Whether redemption is possible + soldOut: boolean; // Whether the staking is sold out + commissionFee: string; // Commission fee + nextEpochTime: number; // Time for the next epoch + calculating: boolean; // Whether calculations are ongoing } ⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaResponse { - leftPersonalQuota: string; -} +leftStakingPersonalQuota: string; // Remaining personal staking quota +leftRedemptionPersonalQuota: string; // Remaining personal redemption quota +minStakeAmount: string; // Minimum stake amount +minRedeemAmount: string; // Minimum redeem amount +redeemPeriod: number; // Redemption period in days +stakeable: boolean; // Whether staking is possible +redeemable: boolean; // Whether redemption is possible +soldOut: boolean; // Whether the staking is sold out +commissionFee: string; // Commission fee +nextEpochTime: number; // Time for the next epoch +calculating: boolean; // Whether calculations are ongoing ⋮---- -export interface OnchainYieldsLockedPositionParams { - asset?: string; - positionId?: number; - projectId?: string; - current?: number; - size?: number; +export interface SubscribeSolStakingResponse { + success: boolean; // Indicates if the subscription was successful + bnsolAmount: string; // Amount in bNSOL received + exchangeRate: string; // SOL amount per 1 BNSOL } ⋮---- -export interface OnchainYieldsLockedPosition { - positionId: string; - projectId: string; - asset: string; - amount: string; - purchaseTime: string; - duration: string; - accrualDays: string; - rewardAsset: string; - APY: string; - rewardAmt: string; - nextPay?: string; - nextPayDate?: string; - payPeriod?: string; - rewardsPayDate?: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; - redeemingAmt?: string; - redeemTo?: 'FLEXIBLE' | 'SPOT'; - canRedeemEarly: boolean; - autoSubscribe: boolean; - type: 'AUTO' | 'NORMAL'; - status: 'HOLDING' | 'REDEEMING' | 'RENEWING' | 'NEW_TRANSFERRING'; -} +success: boolean; // Indicates if the subscription was successful +bnsolAmount: string; // Amount in bNSOL received +exchangeRate: string; // SOL amount per 1 BNSOL ⋮---- -export interface OnchainYieldsLockedPositionResponse { - rows: OnchainYieldsLockedPosition[]; - total: number; +export interface RedeemSolResponse { + success: boolean; // Indicates if the redemption was successful + solAmount: string; // Amount in SOL received + exchangeRate: string; // SOL amount per 1 BNSOL + arrivalTime: number; // Time of arrival for the redeemed SOL } ⋮---- -export interface OnchainYieldsAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedInBTC: string; - totalLockedInUSDT: string; +success: boolean; // Indicates if the redemption was successful +solAmount: string; // Amount in SOL received +exchangeRate: string; // SOL amount per 1 BNSOL +arrivalTime: number; // Time of arrival for the redeemed SOL +⋮---- +export interface GetSolStakingHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -// On-chain Yields Earn types +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory ⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; +export interface SolStakingHistoryRecord { + time: number; // Time of the staking event + asset: string; // Asset involved, e.g., SOL + amount: string; // Amount staked + distributeAsset: string; // Asset distributed, e.g., BNSOL + distributeAmount: string; // Amount distributed + exchangeRate: string; // Exchange rate at the time + status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event } ⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewResponse { - rewardAsset: string; - totalRewardAmt: string; - nextPay?: string; - nextPayDate?: string; - rewardsPayDate?: string; - valueDate: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; -} +time: number; // Time of the staking event +asset: string; // Asset involved, e.g., SOL +amount: string; // Amount staked +distributeAsset: string; // Asset distributed, e.g., BNSOL +distributeAmount: string; // Amount distributed +exchangeRate: string; // Exchange rate at the time +status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event ⋮---- -export interface OnchainYieldsLockedSubscribeParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; - redeemTo?: 'SPOT' | 'FLEXIBLE'; - channelId?: string; - clientId?: string; +export interface GetSolRedemptionHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -export interface OnchainYieldsLockedSubscribeResponse { - purchaseId: number; - positionId: string; - amount: string; - success: boolean; -} +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory ⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeParams { - positionId: string; - autoSubscribe: boolean; +export interface SolRedemptionHistoryRecord { + time: number; // Time of the redemption event + arrivalTime: number; // Time of arrival for the redeemed SOL + asset: string; // Asset redeemed, e.g., BNSOL + amount: string; // Amount redeemed + distributeAsset: string; // Asset distributed, e.g., SOL + distributeAmount: string; // Amount distributed + exchangeRate: string; // Exchange rate at the time + status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event } ⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeResponse { - success: boolean; -} +time: number; // Time of the redemption event +arrivalTime: number; // Time of arrival for the redeemed SOL +asset: string; // Asset redeemed, e.g., BNSOL +amount: string; // Amount redeemed +distributeAsset: string; // Asset distributed, e.g., SOL +distributeAmount: string; // Amount distributed +exchangeRate: string; // Exchange rate at the time +status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event ⋮---- -export interface OnchainYieldsLockedSetRedeemOptionParams { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; +export interface GetBnsolRewardsHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -export interface OnchainYieldsLockedSetRedeemOptionResponse { - success: boolean; -} +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory ⋮---- -export interface OnchainYieldsLockedRedeemParams { - positionId: number; - channelId?: string; +export interface BnsolRewardHistoryRecord { + time: number; // Time of the reward event + amountInSOL: string; // Reward amount in SOL + holding: string; // BNSOL holding balance + holdingInSOL: string; // BNSOL holding balance in SOL + annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) } ⋮---- -export interface OnchainYieldsLockedRedeemResponse { - redeemId: number; - success: boolean; +time: number; // Time of the reward event +amountInSOL: string; // Reward amount in SOL +holding: string; // BNSOL holding balance +holdingInSOL: string; // BNSOL holding balance in SOL +annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) +⋮---- +export interface GetBnsolRateHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -// On-chain Yields History types +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory ⋮---- -export interface OnchainYieldsLockedSubscriptionRecordParams { - purchaseId?: string; - clientId?: string; - asset?: string; +export interface SolBoostRewardsHistoryReq { + type: 'CLAIM' | 'DISTRIBUTE'; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- -export interface OnchainYieldsLockedSubscriptionRecord { - positionId: string; - purchaseId: string; - projectId: string; - clientId: string; +export interface SolBoostRewardsHistoryRecord { time: number; - asset: string; + token: string; amount: string; - lockPeriod: string; - type: 'NORMAL' | 'AUTO'; - sourceAccount: 'SPOT' | 'FUNDING' | 'SPOTANDFUNDING'; - amtFromSpot?: string; - amtFromFunding?: string; - status: 'PURCHASING' | 'SUCCESS' | 'FAILED'; + bnsolHolding?: string; // Only present if type is "DISTRIBUTE" + status?: string; // Only present if type is "CLAIM" } ⋮---- -export interface OnchainYieldsLockedSubscriptionRecordResponse { - rows: OnchainYieldsLockedSubscriptionRecord[]; - total: number; -} +bnsolHolding?: string; // Only present if type is "DISTRIBUTE" +status?: string; // Only present if type is "CLAIM" ⋮---- -export interface OnchainYieldsLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface BnsolRateHistoryRecord { + annualPercentageRate: string; // BNSOL APR + exchangeRate: string; // SOL amount per 1 BNSOL + time: number; // Time of the rate record } ⋮---- -export interface OnchainYieldsLockedRewardsRecord { - positionId: string; - time: number; +annualPercentageRate: string; // BNSOL APR +exchangeRate: string; // SOL amount per 1 BNSOL +time: number; // Time of the rate record +⋮---- +export interface RiskUnitMM { asset: string; - lockPeriod: string; - amount: string; + uniMaintainUsd: string; } ⋮---- -export interface OnchainYieldsLockedRewardsHistoryResponse { - rows: OnchainYieldsLockedRewardsRecord[]; - total: number; +export interface PortfolioMarginProSpanAccountInfo { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + riskUnitMMList: RiskUnitMM[]; + marginMM: string; + otherMM: string; + accountStatus: + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; + accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) } ⋮---- -export interface OnchainYieldsLockedRedemptionRecordParams { - positionId?: number; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) ⋮---- -export interface OnchainYieldsLockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; +export interface PortfolioMarginProAccountBalance { asset: string; - lockPeriod: string; - amount: string; - originalAmount: string; - type: 'NORMAL' | 'EARLY' | 'CONVERT'; - deliverDate: string; - lossAmount: string; - isComplete: boolean; - rewardAsset: string; - rewardAmt: string; - status: 'CREATED' | 'PAID'; -} -⋮---- -export interface OnchainYieldsLockedRedemptionRecordResponse { - rows: OnchainYieldsLockedRedemptionRecord[]; - total: number; + totalWalletBalance: string; + crossMarginAsset: string; + crossMarginBorrowed: string; + crossMarginFree: string; + crossMarginInterest: string; + crossMarginLocked: string; + umWalletBalance: string; + umUnrealizedPNL: string; + cmWalletBalance: string; + cmUnrealizedPNL: string; + updateTime: number; + negativeBalance: string; + optionWalletBalance: string; // only for PM PRO SPAN + optionEquity: string; // only for PM PRO SPAN } ⋮---- -/** - * ALPHA TRADING INTERFACES - */ +optionWalletBalance: string; // only for PM PRO SPAN +optionEquity: string; // only for PM PRO SPAN ⋮---- -export interface AlphaToken { - alphaId: number; - symbol: string; - name: string; - chainId: string; - contractAddress: string; - decimals?: number; +export interface PMProMintBFUSDParams { + fromAsset: string; // USDT only + targetAsset: string; // BFUSD only + amount: number; } ⋮---- -export interface AlphaExchangeFilter { - filterType: string; - minPrice?: string; - maxPrice?: string; - tickSize?: string; - stepSize?: string; - maxQty?: string; - minQty?: string; - limit?: number; - minNotional?: string; - maxNotional?: string; - multiplierDown?: string; - multiplierUp?: string; - bidMultiplierUp?: string; - askMultiplierUp?: string; - bidMultiplierDown?: string; - askMultiplierDown?: string; -} +fromAsset: string; // USDT only +targetAsset: string; // BFUSD only ⋮---- -export interface AlphaSymbol { - symbol: string; - status: string; - baseAsset: string; - quoteAsset: string; - pricePrecision: number; - quantityPrecision: number; - baseAssetPrecision: number; - quotePrecision: number; - filters: AlphaExchangeFilter[]; - orderTypes: string[]; +export interface PMProMintBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; } ⋮---- -export interface AlphaAsset { - asset: string; +export interface PMProRedeemBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; } ⋮---- -export interface AlphaExchangeInfo { - timezone: string; - assets: AlphaAsset[]; - symbols: AlphaSymbol[]; +export interface PMProBankruptcyLoanRepaymentHistory { + asset: string; + amount: string; + repayTime: number; } ⋮---- -export interface AlphaAggTradesParams { - symbol: string; - fromId?: number; +export interface VipLoanInterestRateHistoryParams { + coin: string; startTime?: number; endTime?: number; + current?: number; limit?: number; } ⋮---- -export interface AlphaAggTrade { - a: number; // aggregate trade ID - p: string; // price - q: string; // quantity - f: number; // first trade ID - l: number; // last trade ID - T: number; // timestamp - m: boolean; // is buyer market maker +export interface VipLoanInterestRateRecord { + coin: string; + annualizedInterestRate: string; + time: number; } ⋮---- -a: number; // aggregate trade ID -p: string; // price -q: string; // quantity -f: number; // first trade ID -l: number; // last trade ID -T: number; // timestamp -m: boolean; // is buyer market maker -⋮---- -export interface AlphaKlinesParams { - symbol: string; - interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M - limit?: number; +export interface VipLoanAccruedInterestParams { + orderId?: number; + loanCoin?: string; startTime?: number; endTime?: number; + current?: number; + limit?: number; } ⋮---- -interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M -⋮---- -export type AlphaKline = [ - string, // Open time - string, // Open price - string, // High price - string, // Low price - string, // Close price - string, // Volume - string, // Close time - string, // Quote asset volume - string, // Number of trades - string, // Taker buy base asset volume - string, // Taker buy quote asset volume - string, // Ignore (always "0") -]; +export interface VipLoanAccruedInterestRecord { + loanCoin: string; + principalAmount: string; + interestAmount: string; + annualInterestRate: string; + accrualTime: number; + orderId: number; +} ⋮---- -string, // Open time -string, // Open price -string, // High price -string, // Low price -string, // Close price -string, // Volume -string, // Close time -string, // Quote asset volume -string, // Number of trades -string, // Taker buy base asset volume -string, // Taker buy quote asset volume -string, // Ignore (always "0") +export interface WithdrawTravelRuleParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; + amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; + questionnaire: string; +} ⋮---- -export interface AlphaTickerParams { - symbol: string; +export interface GetTravelRuleWithdrawHistoryParams { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; +export interface GetTravelRuleWithdrawHistoryV2Params { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; +} ⋮---- -export interface AlphaFullDepthParams { - symbol: string; - limit?: AlphaFullDepthLimit; +export interface SubmitTravelRuleDepositQuestionnaireParams { + tranId: number; + questionnaire: string; } ⋮---- -export interface AlphaFullDepthData { - lastUpdateId: number; - symbol: string; - bids: [string, string][]; - asks: [string, string][]; - E: number; - T: number; +export interface GetTravelRuleDepositHistoryParams { + trId?: string; + txId?: string; + tranId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + pendingQuestionnaire?: boolean; + startTime?: number; + endTime?: number; + offset?: number; + limit?: number; } ⋮---- -export interface AlphaFullDepthResponse { - code: string; - message: string | null; - messageDetail: string | null; - success: boolean; - data: AlphaFullDepthData; +export interface TravelRuleWithdrawHistoryRecord { + id: string; + trId: number; + amount: string; + transactionFee: string; + coin: string; + withdrawalStatus: number; + travelRuleStatus: number; + address: string; + addressTag?: string; + txId: string; + applyTime: string; + network?: string; + transferType: number; + withdrawOrderId?: string; + info: string; + confirmNo: number; + walletType: number; + txKey: string; + questionnaire: string; + completeTime?: string; } ⋮---- -export interface AlphaTicker { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - lastPrice: string; - lastQty: string; - openPrice: string; - highPrice: string; - lowPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; +export interface SubmitTravelRuleDepositQuestionnaireResponse { + trId: number; + accepted: boolean; + info: string; } ⋮---- -/** - * Soft Staking interfaces - */ -export interface GetSoftStakingProductListParams { - asset?: string; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; +export interface TravelRuleDepositHistoryRecord { + trId: number; + tranId: number; + amount: string; + coin: string; + network: string; + depositStatus: number; + travelRuleStatus: number; + address: string; + addressTag?: string; + txId: string; + insertTime: number; + transferType: number; + confirmTimes: string; + unlockConfirm: number; + walletType: number; + requireQuestionnaire: boolean; + questionnaire: string | null; } ⋮---- -export interface SoftStakingProduct { - asset: string; - minAmount: string; - maxCap: string; - apr: string; - stakedAmount: string; - totalProfit: string; +export interface VASPInfo { + vaspName: string; + vaspCode?: string; + /** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ + identifier?: string; } ⋮---- -export interface GetSoftStakingProductListResponse { - status: boolean; - totalRewardsUsdt: string; - rows: SoftStakingProduct[]; - total: number; +/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ +⋮---- +export interface TravelRuleCountryInfo { + countryCode: string; + countryName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; + hasRegionRestrictions: boolean; } ⋮---- -export interface SetSoftStakingParams { - softStaking: boolean; - recvWindow?: number; - timestamp: number; +export interface TravelRuleCountryListResponse { + countries: TravelRuleCountryInfo[]; + lastUpdated: number; } ⋮---- -export interface SetSoftStakingResponse { - success: boolean; +export interface GetTravelRuleRegionListParams { + countryCode: string; } ⋮---- -export interface GetSoftStakingRewardsHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; +export interface TravelRuleRegionInfo { + regionName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; +} +⋮---- +export interface TravelRuleRegionListResponse { + countryCode: string; + regions: TravelRuleRegionInfo[]; + lastUpdated: number; +} +⋮---- +export interface GetVipLoanFixedRateMarketParams { + loanCoin: string; + duration?: number; current?: number; size?: number; - recvWindow?: number; - timestamp: number; } ⋮---- -export interface SoftStakingRewardsRecord { - asset: string; - rewards: string; - rewardAsset: string; - avgAmount: string; - time: number; +export interface VipLoanFixedRateMarketRecord { + requestId: number; + requestNo: number; + coin: string; + interestRate: numberInString; + duration: number; + minimumAmount: numberInString; + availableAmount: numberInString; + estimatedInterest: numberInString; } ⋮---- -export interface GetSoftStakingRewardsHistoryResponse { - rows: SoftStakingRewardsRecord[]; - total: number; +export interface VipLoanFixedRateBorrowParams { + supplyRequest: string; + borrowCoin: string; + loanTerm: number; + borrowUid: number; + collateralCoin: string; + collateralAccountId: string; + autoRepay?: boolean; } - -================ -File: src/websocket-api-client.ts -================ -import { - ExchangeInfo, - SpotAmendKeepPriorityResult, - SpotExecutionRulesResponse, - SpotReferencePriceCalculationResponse, - SpotReferencePriceResult, -} from './types/spot'; -import { - WSAPIResponse, - WSAPIUserDataListenKeyRequest, -} from './types/websockets/ws-api'; -import { - WSAPIAccountCommissionWSAPIRequest, - WSAPIAccountInformationRequest, - WSAPIAllOrderListsRequest, - WSAPIAllOrdersRequest, - WSAPIAvgPriceRequest, - WSAPIBlockTradesHistoricalRequest, - WSAPIExchangeInfoRequest, - WSAPIExecutionRulesRequest, - WSAPIFuturesAlgoOrderCancelRequest, - WSAPIFuturesOrderBookRequest, - WSAPIFuturesOrderCancelRequest, - WSAPIFuturesOrderModifyRequest, - WSAPIFuturesOrderStatusRequest, - WSAPIFuturesPositionRequest, - WSAPIFuturesPositionV2Request, - WSAPIFuturesTickerBookRequest, - WSAPIFuturesTickerPriceRequest, - WSAPIKlinesRequest, - WSAPIMyAllocationsRequest, - WSAPIMyPreventedMatchesRequest, - WSAPIMyTradesRequest, - WSAPINewFuturesAlgoOrderRequest, - WSAPINewFuturesOrderRequest, - WSAPINewSpotOrderRequest, - WSAPIOpenOrdersCancelAllRequest, - WSAPIOpenOrdersStatusRequest, - WSAPIOrderAmendKeepPriorityRequest, - WSAPIOrderBookRequest, - WSAPIOrderCancelReplaceRequest, - WSAPIOrderCancelRequest, - WSAPIOrderListCancelRequest, - WSAPIOrderListPlaceOCORequest, - WSAPIOrderListPlaceOPOCORequest, - WSAPIOrderListPlaceOPORequest, - WSAPIOrderListPlaceOTOCORequest, - WSAPIOrderListPlaceOTORequest, - WSAPIOrderListPlaceRequest, - WSAPIOrderListStatusRequest, - WSAPIOrderStatusRequest, - WSAPIOrderTestRequest, - WSAPIRecvWindowTimestamp, - WSAPIReferencePriceCalculationRequest, - WSAPIReferencePriceRequest, - WSAPISOROrderPlaceRequest, - WSAPISOROrderTestRequest, - WSAPITicker24hrRequest, - WSAPITickerBookRequest, - WSAPITickerPriceRequest, - WSAPITickerRequest, - WSAPITickerTradingDayRequest, - WSAPITradesAggregateRequest, - WSAPITradesHistoricalRequest, - WSAPITradesRecentRequest, -} from './types/websockets/ws-api-requests'; -import { - WSAPIAccountCommission, - WSAPIAccountInformation, - WSAPIAggregateTrade, - WSAPIAllocation, - WSAPIAvgPrice, - WSAPIBlockTrade, - WSAPIBookTicker, - WSAPIFullTicker, - WSAPIFuturesAccountBalanceItem, - WSAPIFuturesAccountStatus, - WSAPIFuturesAlgoOrder, - WSAPIFuturesAlgoOrderCancelResponse, - WSAPIFuturesBookTicker, - WSAPIFuturesOrder, - WSAPIFuturesOrderBook, - WSAPIFuturesPosition, - WSAPIFuturesPositionV2, - WSAPIFuturesPriceTicker, - WSAPIKline, - WSAPIMiniTicker, - WSAPIOrder, - WSAPIOrderBook, - WSAPIOrderCancel, - WSAPIOrderCancelReplaceResponse, - WSAPIOrderListCancelResponse, - WSAPIOrderListPlaceResponse, - WSAPIOrderListStatusResponse, - WSAPIOrderTestResponse, - WSAPIOrderTestWithCommission, - WSAPIPreventedMatch, - WSAPIPriceTicker, - WSAPIRateLimit, - WSAPIServerTime, - WSAPISessionStatus, - WSAPISOROrderPlaceResponse, - WSAPISOROrderTestResponse, - WSAPISOROrderTestResponseWithCommission, - WSAPISpotOrderResponse, - WSAPITrade, -} from './types/websockets/ws-api-responses'; -import { WSClientConfigurableOptions } from './types/websockets/ws-general'; -import { DefaultLogger } from './util/logger'; -import { - isWSAPIWsKey, - isWsEventStreamTerminatedRaw, - neverGuard, -} from './util/typeGuards'; -import { - getTestnetWsKey, - WS_KEY_MAP, - WS_LOGGER_CATEGORY, - WSAPIWsKey, - WSAPIWsKeyFutures, - WSAPIWsKeyMain, - WsKey, -} from './util/websockets/websocket-util'; -import { WSConnectedResult } from './util/websockets/WsStore.types'; -import { WebsocketClient } from './websocket-client'; -⋮---- -function getFuturesMarketWsKey(market: 'usdm' | 'coinm'): WSAPIWsKeyFutures ⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected - */ - resubscribeUserDataStreamAfterReconnect: boolean; - - /** - * Default: 2 seconds - * - * Delay automatic userdata resubscribe by x seconds. - */ - resubscribeUserDataStreamDelaySeconds: number; - - /** - * 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: false - * - * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. - * - * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. - */ - muteLatencyWarning: boolean; - - /** - * Default: true - * - * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. - */ - keepMarginListenTokenRefreshed: boolean; +export interface VipLoanFixedRateBorrowResponse { + borrowCoin: string; + borrowAmount: numberInString; + actualReceivedAmount: numberInString; + collateralCoin: string; + collateralAccountId: string; + borrowInterestRate: numberInString; + duration: string; + autoRepay: boolean; + orderId: number; + status: 'Succeeds' | 'Failed' | 'Processing'; } ⋮---- -/** - * Default: true - * - * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected - */ +// Institutional Loan types +export interface InstitutionalLoanLiability { + assetName: string; + principal: string; + interest: string; +} ⋮---- -/** - * Default: 2 seconds - * - * Delay automatic userdata resubscribe by x seconds. - */ +export interface InstitutionalLoanWallet { + accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; +} ⋮---- -/** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ +export interface InstitutionalLoanCollateralAccount { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + wallets: InstitutionalLoanWallet[]; +} ⋮---- -/** - * Default: false - * - * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. - * - * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. - */ +export interface InstitutionalLoanRiskUnitDetails { + groupId: number; + parentEmail: string; + creditEmail: string; + updateTime: number; + ltv: string; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + liabilities: InstitutionalLoanLiability[]; + collateralAccounts: InstitutionalLoanCollateralAccount[]; +} ⋮---- -/** - * Default: true - * - * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. - */ +export interface GetInstitutionalLoanRiskUnitDetailsParams { + groupId?: number; +} ⋮---- -/** - * Used to track that a connection had an active user data stream before it disconnected. - * - * Note: This is not the same as the "listenKey" WS API workflow (the listenKey workflow is deprecated). - * - * This does not return a listen key. This also does not require a regular "ping" on the listen key. - */ -interface ActiveUserDataStreamState { - subscribedAt: Date; - subscribeAttempt: number; - respawnTimeout?: ReturnType; - /** - * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. - */ - refreshTimeout?: ReturnType; - /** - * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream - */ - userDataStreamParameters?: unknown; +export interface CloseInstitutionalLoanRiskUnitResponse { + groupId: number; + status: 'CLOSED'; } ⋮---- -/** - * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. - */ +export interface AddInstitutionalLoanCollateralAccountParams { + groupId: number; + subEmail: string; + enableSpot: boolean; + enableMargin: boolean; +} ⋮---- -/** - * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream - */ +export interface InstitutionalLoanRiskUnitMember { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + enableMargin: boolean; + enableSpot: boolean; +} ⋮---- -/** - * This is a minimal Websocket API wrapper around the WebsocketClient. - * - * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should - * be used to transmit that message. This is only useful if you wish to use an alternative wss - * domain that is supported by the SDK. - * - * Note: To use testnet, don't set the wsKey - use `testnet: true` in - * the constructor instead. - * - * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some - * may find the below methods slightly more intuitive. - * - * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: - * https://github.com/tiagosiebler/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108 - */ -export class WebsocketAPIClient +export interface ActiveInstitutionalLoanRiskUnit { + groupId: number; + members: InstitutionalLoanRiskUnitMember[]; + createTime: number; +} +export interface ClosedInstitutionalLoanRiskUnit { + groupId: number; + parentEmail: string; + creditEmail: string; + enabled: boolean; + createTime: number; + closeTime: number; +} ⋮---- -/** - * Minimal state store around automating sticky "userDataStream.subscribe" sessions - */ +export interface GetClosedInstitutionalLoanRiskUnitsParams { + current?: number; + size?: number; +} ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +export interface GetClosedInstitutionalLoanRiskUnitsResponse { + total: number; + rows: ClosedInstitutionalLoanRiskUnit[]; +} ⋮---- -public getWSClient(): WebsocketClient +// Institutional Loan Force Liquidation interfaces +export interface InstitutionalLoanLiquidationSnapshot { + subEmail: string; + memberType: 'CREDIT' | 'COLLATERAL'; + walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; +} ⋮---- -public setTimeOffsetMs(newOffset: number): void +export interface InstitutionalLoanLiquidationSnapshotData { + snapshots: InstitutionalLoanLiquidationSnapshot[]; + liabilities: InstitutionalLoanLiability[]; +} ⋮---- -public async disconnectAll(): Promise +export interface InstitutionalLoanForceLiquidationRecord { + groupId: number; + startLtv: number; + endLtv: number; + liquidationStartTime: number; + liquidationEndTime: number; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; +} ⋮---- -/* - * - * SPOT - General requests - * - */ +export interface GetInstitutionalLoanForceLiquidationParams { + groupId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Test connectivity to the WebSocket API - */ -testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> +export interface GetInstitutionalLoanForceLiquidationResponse { + total: number; + rows: InstitutionalLoanForceLiquidationRecord[]; +} ⋮---- -/** - * Test connectivity to the WebSocket API and get the current server time - */ -getSpotServerTime( - wsKey?: WSAPIWsKeyMain, -): Promise> +// Risk Unit Transfer interfaces +export interface InstitutionalLoanRiskUnitTransferParams { + subEmail?: string; // Optional: subEmail can be credit account or collateral account + asset: string; // Asset Name + amount: number; // Transfer amount of the asset +} ⋮---- -/** - * Query current exchange trading rules, rate limits, and symbol information - */ -getSpotExchangeInfo( - params?: WSAPIExchangeInfoRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +subEmail?: string; // Optional: subEmail can be credit account or collateral account +asset: string; // Asset Name +amount: number; // Transfer amount of the asset ⋮---- -/* - * - * SPOT - Market data requests - * - */ +// Additional institutional loan types for borrow, repay, and interest history +export interface GetInstitutionalLoanMaxBorrowableParams { + groupId?: number; + assetName: string; +} ⋮---- -/** - * Get current order book - * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams - */ -getSpotOrderBook( - params: WSAPIOrderBookRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanMaxBorrowableResponse { + maxBorrowableAmount: numberInString | null; +} ⋮---- -/** - * Get recent trades - * Note: If you need access to real-time trading activity, consider using WebSocket Streams - */ -getSpotRecentTrades( - params: WSAPITradesRecentRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanBorrowParams { + groupId: number; + assetName: string; + amount: number; +} ⋮---- -/** - * Get historical trades - * Note: If fromId is not specified, the most recent trades are returned - */ -getSpotHistoricalTrades( - params: WSAPITradesHistoricalRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanBorrowResponse { + transactionId: string; + amount: number; + status: string; +} ⋮---- -/** - * Get historical block trades - */ -getSpotHistoricalBlockTrades( - params: WSAPIBlockTradesHistoricalRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanRepayParams { + groupId: number; + assetName: string; + amount: number; +} ⋮---- -/** - * Get aggregate trades - * Note: An aggregate trade represents one or more individual trades that fill at the same time - */ -getSpotAggregateTrades( - params: WSAPITradesAggregateRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanRepayResponse { + transactionId: string; + amount: number; +} ⋮---- -/** - * Get klines (candlestick bars) - * Note: If you need access to real-time kline updates, consider using WebSocket Streams - */ -getSpotKlines( - params: WSAPIKlinesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface GetInstitutionalLoanInterestHistoryParams { + groupId?: number; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface InstitutionalLoanInterestHistoryRecord { + groupId: number; + assetName: string; + principal: string; + interestRate: string; + interest: string; + interestTimestamp: number; +} ⋮---- -/** - * Get klines (candlestick bars) optimized for presentation - * Note: This request is similar to klines, having the same parameters and response - */ -getSpotUIKlines( - params: WSAPIKlinesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanInterestHistoryResponse { + total: number; + rows: InstitutionalLoanInterestHistoryRecord[]; +} ⋮---- -/** - * Get current average price for a symbol - */ -getSpotAveragePrice( - params: WSAPIAvgPriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface GetInstitutionalLoanBorrowRepayRecordsParams { + groupId?: number; // Optional: Risk unit unique identifier + type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY + asset?: string; // Optional: Asset name + startTime?: number; // Optional: Start time + endTime?: number; // Optional: End time + current?: number; // Optional: The currently querying page. Start from 1. Default:1 + size?: number; // Optional: Default:10 Max:100 + recvWindow?: number; // Optional: The value cannot be greater than 60000 + timestamp: number; // Required +} ⋮---- -/** - * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. - */ -getSpotExecutionRules( - params?: WSAPIExecutionRulesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +groupId?: number; // Optional: Risk unit unique identifier +type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY +asset?: string; // Optional: Asset name +startTime?: number; // Optional: Start time +endTime?: number; // Optional: End time +current?: number; // Optional: The currently querying page. Start from 1. Default:1 +size?: number; // Optional: Default:10 Max:100 +recvWindow?: number; // Optional: The value cannot be greater than 60000 +timestamp: number; // Required ⋮---- -/** - * Query reference price for a symbol. - */ -getSpotReferencePrice( - params: WSAPIReferencePriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface InstitutionalLoanBorrowRepayRecord { + tranId: number; // Transaction ID + assetName: string; // Asset name + amount: number; // Amount + status: 'CONFIRM' | 'FAILED'; // Status + type: 'BORROW' | 'REPAY'; // Type + timestamp: number; // Create Time + principal?: number; // Only present for REPAY type + interest?: number; // Only present for REPAY type +} ⋮---- -/** - * Query how reference price is calculated for a symbol. - */ -getSpotReferencePriceCalculation( - params: WSAPIReferencePriceCalculationRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +tranId: number; // Transaction ID +assetName: string; // Asset name +amount: number; // Amount +status: 'CONFIRM' | 'FAILED'; // Status +type: 'BORROW' | 'REPAY'; // Type +timestamp: number; // Create Time +principal?: number; // Only present for REPAY type +interest?: number; // Only present for REPAY type ⋮---- -/** - * Get 24-hour rolling window price change statistics - * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams - */ -getSpot24hrTicker( - params?: WSAPITicker24hrRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker.24hr', - params, - { authIsOptional: true }, - ); +export interface GetInstitutionalLoanBorrowRepayRecordsResponse { + total: number; + rows: InstitutionalLoanBorrowRepayRecord[]; +} ⋮---- -/** - * Get price change statistics for a trading day - */ -getSpotTradingDayTicker( - params: WSAPITickerTradingDayRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker.tradingDay', - params, - { authIsOptional: true }, - ); +export interface MarginInterestRebateBalanceResponse { + asset: string; + balance: string; + totalGranted: string; + totalConsumed: string; +} ⋮---- -/** - * Get rolling window price change statistics with a custom window - * Note: Window size precision is limited to 1 minute - */ -getSpotTicker( - params: WSAPITickerRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker', - params, - { authIsOptional: true }, - ); +export interface GetMarginInterestRebateBalanceRecordsParams { + type?: 0 | 1 | 2; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * Get the latest market price for a symbol - * Note: If you need access to real-time price updates, consider using WebSocket Streams - */ -getSpotSymbolPriceTicker( - params?: WSAPITickerPriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface MarginInterestRebateBalanceRecord { + type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; + rebateAsset: string; + delta: string; + createTime: number; + groupId?: number; + liabilityAsset?: string; + deductedInterest?: string; + exchangeRate?: string; +} ⋮---- -/** - * Get the current best price and quantity on the order book - * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams - */ -getSpotSymbolOrderBookTicker( - params?: WSAPITickerBookRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface MarginInterestRebateBalanceRecordsResponse { + total: number; + rows: MarginInterestRebateBalanceRecord[]; +} ⋮---- -/* - * - * SPOT - Session authentication requests - * - * Note: authentication is automatic - * - */ +// On-chain Yields types ⋮---- -getSpotSessionStatus( - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedProductListParams { + asset?: string; + current?: number; + size?: number; +} ⋮---- -/* - * - * SPOT - Trading requests - * - */ +export interface OnchainYieldsLockedProductDetail { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: 'PREHEATING' | 'PURCHASING'; + subscriptionStartTime: string; + canRedeemToFlex: boolean; +} ⋮---- -/** - * Submit a spot order - */ -submitNewSpotOrder( - params: WSAPINewSpotOrderRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedProductQuota { + totalPersonalQuota: string; + minimum: string; +} ⋮---- -/** - * Test order placement - * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine - */ -testSpotOrder( - params: WSAPIOrderTestRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'order.test', - params, - ); +export interface OnchainYieldsLockedProduct { + projectId: string; + detail: OnchainYieldsLockedProductDetail; + quota: OnchainYieldsLockedProductQuota; +} ⋮---- -/** - * Check execution status of an order - * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used - */ -getSpotOrderStatus( - params: WSAPIOrderStatusRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedProductListResponse { + rows: OnchainYieldsLockedProduct[]; + total: number; +} +⋮---- +export interface OnchainYieldsLockedPersonalLeftQuotaParams { + projectId: string; +} ⋮---- -/** - * Cancel an active order - * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used - */ -cancelSpotOrder( - params: WSAPIOrderCancelRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedPersonalLeftQuotaResponse { + leftPersonalQuota: string; +} ⋮---- -/** - * Cancel an existing order and immediately place a new order - * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used - */ -cancelReplaceSpotOrder( - params: WSAPIOrderCancelReplaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedPositionParams { + asset?: string; + positionId?: number; + projectId?: string; + current?: number; + size?: number; +} ⋮---- -/** - * Reduce the quantity of an existing open order. - * - * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority - */ -amendSpotOrderKeepPriority( - params: WSAPIOrderAmendKeepPriorityRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedPosition { + positionId: string; + projectId: string; + asset: string; + amount: string; + purchaseTime: string; + duration: string; + accrualDays: string; + rewardAsset: string; + APY: string; + rewardAmt: string; + nextPay?: string; + nextPayDate?: string; + payPeriod?: string; + rewardsPayDate?: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; + redeemingAmt?: string; + redeemTo?: 'FLEXIBLE' | 'SPOT'; + canRedeemEarly: boolean; + autoSubscribe: boolean; + type: 'AUTO' | 'NORMAL'; + status: 'HOLDING' | 'REDEEMING' | 'RENEWING' | 'NEW_TRANSFERRING'; +} ⋮---- -/** - * Query execution status of all open orders - * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams - */ -getSpotOpenOrders( - params: WSAPIOpenOrdersStatusRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedPositionResponse { + rows: OnchainYieldsLockedPosition[]; + total: number; +} ⋮---- -/** - * Cancel all open orders on a symbol - * Note: This includes orders that are part of an order list - */ -cancelAllSpotOpenOrders( - params: WSAPIOpenOrdersCancelAllRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]> - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'openOrders.cancelAll', - params, - ); +export interface OnchainYieldsAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedInBTC: string; + totalLockedInUSDT: string; +} ⋮---- -/** - * Place a new order list - * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead - */ -placeSpotOrderList( - params: WSAPIOrderListPlaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +// On-chain Yields Earn types ⋮---- -/** - * Place a new OCO (One-Cancels-the-Other) order list - * Note: Activation of one order immediately cancels the other - */ -placeSpotOCOOrderList( - params: WSAPIOrderListPlaceOCORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; +} ⋮---- -/** - * Place a new OTO (One-Triggers-the-Other) order list - * Note: The pending order is placed only when the working order is fully filled - */ -placeSpotOTOOrderList( - params: WSAPIOrderListPlaceOTORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSubscriptionPreviewResponse { + rewardAsset: string; + totalRewardAmt: string; + nextPay?: string; + nextPayDate?: string; + rewardsPayDate?: string; + valueDate: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; +} ⋮---- -/** - * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list - * Note: The pending orders are placed only when the working order is fully filled - */ -placeSpotOTOCOOrderList( - params: WSAPIOrderListPlaceOTOCORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSubscribeParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; + redeemTo?: 'SPOT' | 'FLEXIBLE'; + channelId?: string; + clientId?: string; +} ⋮---- -/** - * Place a new OPO (One-Pays-the-Other) order list - * Note: One order pays for the other - when the working order is filled, the pending order is placed - */ -placeSpotOPOOrderList( - params: WSAPIOrderListPlaceOPORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSubscribeResponse { + purchaseId: number; + positionId: string; + amount: string; + success: boolean; +} ⋮---- -/** - * Place a new OPOCO (One-Pays-One-Cancels-the-Other) order list - * Note: Combines OPO and OCO - working order pays for two pending orders, one cancels the other - */ -placeSpotOPOCOOrderList( - params: WSAPIOrderListPlaceOPOCORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSetAutoSubscribeParams { + positionId: string; + autoSubscribe: boolean; +} ⋮---- -/** - * Check execution status of an order list - * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used - */ -getSpotOrderListStatus( - params: WSAPIOrderListStatusRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSetAutoSubscribeResponse { + success: boolean; +} ⋮---- -/** - * Cancel an active order list - * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used - */ -cancelSpotOrderList( - params: WSAPIOrderListCancelRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSetRedeemOptionParams { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; +} ⋮---- -/** - * Query execution status of all open order lists - * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams - */ -getSpotOpenOrderLists( - params: WSAPIRecvWindowTimestamp, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSetRedeemOptionResponse { + success: boolean; +} ⋮---- -/** - * Place a new order using Smart Order Routing (SOR) - * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported - */ -placeSpotSOROrder( - params: WSAPISOROrderPlaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRedeemParams { + positionId: number; + channelId?: string; +} ⋮---- -/** - * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) - * Note: Creates and validates a new order but does not send it into the matching engine - */ -testSpotSOROrder( - params: WSAPISOROrderTestRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'sor.order.test', - params, - ); +export interface OnchainYieldsLockedRedeemResponse { + redeemId: number; + success: boolean; +} +⋮---- +// On-chain Yields History types +⋮---- +export interface OnchainYieldsLockedSubscriptionRecordParams { + purchaseId?: string; + clientId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/* - * - * SPOT - Account requests - * - */ +export interface OnchainYieldsLockedSubscriptionRecord { + positionId: string; + purchaseId: string; + projectId: string; + clientId: string; + time: number; + asset: string; + amount: string; + lockPeriod: string; + type: 'NORMAL' | 'AUTO'; + sourceAccount: 'SPOT' | 'FUNDING' | 'SPOTANDFUNDING'; + amtFromSpot?: string; + amtFromFunding?: string; + status: 'PURCHASING' | 'SUCCESS' | 'FAILED'; +} ⋮---- -/** - * Query information about your account, including balances - * Note: Weight: 20 - */ -getSpotAccountInformation( - params: WSAPIAccountInformationRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedSubscriptionRecordResponse { + rows: OnchainYieldsLockedSubscriptionRecord[]; + total: number; +} ⋮---- -/** - * Query your current unfilled order count for all intervals - * Note: Weight: 40 - */ -getSpotOrderRateLimits( - params: WSAPIRecvWindowTimestamp, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRewardsHistoryParams { + positionId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * Query information about all your orders – active, canceled, filled – filtered by time range - * Note: Weight: 20 - */ -getSpotAllOrders( - params: WSAPIAllOrdersRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRewardsRecord { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; +} ⋮---- -/** - * Query information about all your order lists, filtered by time range - * Note: Weight: 20 - */ -getSpotAllOrderLists( - params: WSAPIAllOrderListsRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRewardsHistoryResponse { + rows: OnchainYieldsLockedRewardsRecord[]; + total: number; +} ⋮---- -/** - * Query information about all your trades, filtered by time range - * Note: Weight: 20 - */ -getSpotMyTrades( - params: WSAPIMyTradesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRedemptionRecordParams { + positionId?: number; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * Displays the list of orders that were expired due to STP - * Note: Weight varies based on query type (2-20) - */ -getSpotPreventedMatches( - params: WSAPIMyPreventedMatchesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRedemptionRecord { + positionId: string; + redeemId: number; + time: number; + asset: string; + lockPeriod: string; + amount: string; + originalAmount: string; + type: 'NORMAL' | 'EARLY' | 'CONVERT'; + deliverDate: string; + lossAmount: string; + isComplete: boolean; + rewardAsset: string; + rewardAmt: string; + status: 'CREATED' | 'PAID'; +} ⋮---- -/** - * Retrieves allocations resulting from SOR order placement - * Note: Weight: 20 - */ -getSpotAllocations( - params: WSAPIMyAllocationsRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export interface OnchainYieldsLockedRedemptionRecordResponse { + rows: OnchainYieldsLockedRedemptionRecord[]; + total: number; +} ⋮---- /** - * Get current account commission rates - * Note: Weight: 20 - */ -getSpotAccountCommission( - params: WSAPIAccountCommissionWSAPIRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> + * ALPHA TRADING INTERFACES + */ ⋮---- -/* - * - * FUTURES - Market data requests - * - */ +export interface AlphaToken { + alphaId: number; + symbol: string; + name: string; + chainId: string; + contractAddress: string; + decimals?: number; +} ⋮---- -/** - * Get current order book for futures - * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams - */ -getFuturesOrderBook( - params: WSAPIFuturesOrderBookRequest, -): Promise> +export interface AlphaExchangeFilter { + filterType: string; + minPrice?: string; + maxPrice?: string; + tickSize?: string; + stepSize?: string; + maxQty?: string; + minQty?: string; + limit?: number; + minNotional?: string; + maxNotional?: string; + multiplierDown?: string; + multiplierUp?: string; + bidMultiplierUp?: string; + askMultiplierUp?: string; + bidMultiplierDown?: string; + askMultiplierDown?: string; +} ⋮---- -/** - * Get latest price for a futures symbol or symbols - * Note: If symbol is not provided, prices for all symbols will be returned - */ -getFuturesSymbolPriceTicker( - params?: WSAPIFuturesTickerPriceRequest, - ): Promise< - WSAPIResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.usdmWSAPI, - 'ticker.price', - params, - { authIsOptional: true }, - ); +export interface AlphaSymbol { + symbol: string; + status: string; + baseAsset: string; + quoteAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + filters: AlphaExchangeFilter[]; + orderTypes: string[]; +} ⋮---- -/** - * Get best price/qty on the order book for a futures symbol or symbols - * Note: If symbol is not provided, bookTickers for all symbols will be returned - */ -getFuturesSymbolOrderBookTicker( - params?: WSAPIFuturesTickerBookRequest, -): Promise> +export interface AlphaAsset { + asset: string; +} ⋮---- -/* - * - * FUTURES - Trading requests - * - */ +export interface AlphaExchangeInfo { + timezone: string; + assets: AlphaAsset[]; + symbols: AlphaSymbol[]; +} ⋮---- -/** - * Submit a futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -submitNewFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPINewFuturesOrderRequest, -): Promise> +export interface AlphaAggTradesParams { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Modify an existing futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -modifyFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderModifyRequest, -): Promise> +export interface AlphaAggTrade { + a: number; // aggregate trade ID + p: string; // price + q: string; // quantity + f: number; // first trade ID + l: number; // last trade ID + T: number; // timestamp + m: boolean; // is buyer market maker +} ⋮---- -/** - * Cancel a futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -cancelFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderCancelRequest, -): Promise> +a: number; // aggregate trade ID +p: string; // price +q: string; // quantity +f: number; // first trade ID +l: number; // last trade ID +T: number; // timestamp +m: boolean; // is buyer market maker ⋮---- -/** - * Query futures order status - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesOrderStatus( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderStatusRequest, -): Promise> +export interface AlphaKlinesParams { + symbol: string; + interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M + limit?: number; + startTime?: number; + endTime?: number; +} ⋮---- -/** - * Get current position information (V2) - * Note: Only symbols that have positions or open orders will be returned - */ -getFuturesPositionV2( - params: WSAPIFuturesPositionV2Request, -): Promise> +interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M ⋮---- -/** - * Get current position information - * Note: Only symbols that have positions or open orders will be returned - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesPosition( - market: 'usdm' | 'coinm', - params: WSAPIFuturesPositionRequest, -): Promise> +export type AlphaKline = [ + string, // Open time + string, // Open price + string, // High price + string, // Low price + string, // Close price + string, // Volume + string, // Close time + string, // Quote asset volume + string, // Number of trades + string, // Taker buy base asset volume + string, // Taker buy quote asset volume + string, // Ignore (always "0") +]; ⋮---- -/** - * Send in a new algo order - * - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/New-Algo-Order - */ -submitNewFuturesAlgoOrder( - params: WSAPINewFuturesAlgoOrderRequest, -): Promise> +string, // Open time +string, // Open price +string, // High price +string, // Low price +string, // Close price +string, // Volume +string, // Close time +string, // Quote asset volume +string, // Number of trades +string, // Taker buy base asset volume +string, // Taker buy quote asset volume +string, // Ignore (always "0") ⋮---- -/** - * Cancel an active algo order. - * - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order - * @param params - */ -cancelFuturesAlgoOrder( - params: WSAPIFuturesAlgoOrderCancelRequest, -): Promise> +export interface AlphaTickerParams { + symbol: string; +} ⋮---- -/* - * - * FUTURES - Account requests - * - */ +export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; ⋮---- -/** - * Get account balance information (V2) - * Note: Returns balance information for all assets - */ -getFuturesAccountBalanceV2( - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface AlphaFullDepthParams { + symbol: string; + limit?: AlphaFullDepthLimit; +} ⋮---- -/** - * Get account balance information - * Note: Returns balance information for all assets - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesAccountBalance( - market: 'usdm' | 'coinm', - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface AlphaFullDepthData { + lastUpdateId: number; + symbol: string; + bids: [string, string][]; + asks: [string, string][]; + E: number; + T: number; +} ⋮---- -/** - * Get account information (V2) - * Note: Returns detailed account information including positions and assets - */ -getFuturesAccountStatusV2( - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface AlphaFullDepthResponse { + code: string; + message: string | null; + messageDetail: string | null; + success: boolean; + data: AlphaFullDepthData; +} +⋮---- +export interface AlphaTicker { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + lastPrice: string; + lastQty: string; + openPrice: string; + highPrice: string; + lowPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} ⋮---- /** - * Get account information - * Note: Returns detailed account information including positions and assets - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesAccountStatus( - market: 'usdm' | 'coinm', - params: WSAPIRecvWindowTimestamp, -): Promise> + * Soft Staking interfaces + */ +export interface GetSoftStakingProductListParams { + asset?: string; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/* - * - * User data stream requests - * - */ +export interface SoftStakingProduct { + asset: string; + minAmount: string; + maxCap: string; + apr: string; + stakedAmount: string; + totalProfit: string; +} ⋮---- -/** - * Start the user data stream for an apiKey (passed as param). - * - * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. - * - * @param params - * @param wsKey - * @returns listenKey - */ -startUserDataStreamForKey( - params: { apiKey: string }, - wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> +export interface SetSoftStakingParams { + softStaking: boolean; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Stop the user data stream listen key. - * - * @param params - * @param wsKey - * @returns - */ -stopUserDataStreamForKey( - params: WSAPIUserDataListenKeyRequest, - wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> +export interface SetSoftStakingResponse { + success: boolean; +} ⋮---- -/** - * Consolidated method to clear any timers related to user data stream subscriptions for a given wsKey, if found. - * - * @param wsKey - */ -clearUserDataStreamTimers(wsKey: WSAPIWsKey) +export interface GetSoftStakingRewardsHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -// Just in case the refresh timer is still running -// Harmless given one connection, but still unnecessary +export interface SoftStakingRewardsRecord { + asset: string; + rewards: string; + rewardAsset: string; + avgAmount: string; + time: number; +} ⋮---- +export interface GetSoftStakingRewardsHistoryResponse { + rows: SoftStakingRewardsRecord[]; + total: number; +} + +================ +File: README.md +================ +# Node.js & JavaScript SDK for Binance REST APIs & WebSockets + +[![Build & Test](https://github.com/tiagosiebler/binance/actions/workflows/test.yml/badge.svg)](https://github.com/tiagosiebler/binance/actions/workflows/test.yml) +[![npm version](https://img.shields.io/npm/v/binance)][1] +[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1] +[![users count](https://dependents.info/tiagosiebler/binance/badge?label=users)](https://dependents.info/tiagosiebler/binance) +[![npm downloads](https://img.shields.io/npm/dt/binance)][1] +[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/binance)][1] +[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/binance/badge)](https://www.codefactor.io/repository/github/tiagosiebler/binance) +[![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/binance) + +

+ + + + SDK Logo + + +

+ +[1]: https://www.npmjs.com/package/binance + +> [!TIP] +> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK will soon be hosted under the [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. + +Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets: + +- Professional, robust & performant Binance SDK with leading trading volume in production (livenet). +- Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. +- Complete TypeScript support (with type declarations for all API requests & responses). +- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. + - Strongly typed requests and responses. + - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. +- Actively maintained with a modern, promise-driven interface. +- Support for all authentication mechanisms available on Binance: + - HMAC + - RSA + - Ed25519 (required for WS API login, else each request is signed). + - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication. +- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures. + - Event driven messaging. + - Smart WebSocket persistence + - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. + - Automatically handle listenKey persistence and expiration/refresh. + - Emit `reconnected` event when dropped connection is restored. + - Strongly typed on most WebSocket events, with typeguards available for TypeScript users. + - Optional: + - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers). + - Automatic beautification of REST responses (parsing numbers in strings to numbers). +- Supports WebSocket API on all available product groups, including Spot & Futures: + - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or; + - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. +- Heavy automated end-to-end testing with real API calls. + - End-to-end testing before any release. + - Real API calls in e2e tests. +- Proxy support via axios integration. +- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). +- QuickStart Guide: [Binance JavaScript QuickStart Guide](https://siebly.io/sdk/binance/javascript) +- Binance JavaScript Tutorial: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) + +## Table of Contents + +- [Installation](#installation) +- [Examples](#examples) + - [REST API Examples](./examples/REST) + - [WebSocket Examples](./examples/WebSockets) + - [WebSocket Consumers](./examples/WebSockets/) + - [WebSocket API](./examples/WebSockets/ws-api-client.ts) +- [Issues & Discussion](#issues--discussion) +- [Related Projects](#related-projects) +- [Documentation Links](#documentation) +- [Usage](#usage) + - [Demo Trading vs Testnet](#demo-trading-vs-testnet) + - [REST API Clients](#rest-api-clients) + - [REST Main Client](#rest-main-client) + - [REST USD-M Futures](#rest-usd-m-futures) + - [REST COIN-M Futures](#rest-coin-m-futures) + - [REST Portfolio Margin](#rest-portfolio-margin) + - [WebSockets](#websockets) + - [WebSocket Consumers](#websocket-consumers) + - [WebSocket API](#websocket-api) + - [Event Driven API](#event-driven-api) + - [Promise Driven API](#async-await-api) + - [Market Maker Endpoints](#market-maker-endpoints) + - [Using Market Maker Endpoints](#using-market-maker-endpoints) + - [Best practice](#best-practice) + - [Customise Logging](#customise-logging) + - [Frontend Usage](#browserfrontend-usage) + - [Import](#import) + - [Webpack](#webpack) +- [LLMs & AI](#use-with-llms--ai) +- [Contributions & Thanks](#contributions--thanks) + +## Installation + +`npm install binance --save` + +## Examples + +Refer to the [examples](./examples) folder for implementation demos. + +## Issues & Discussion + +- Issues? Check the [issues tab](https://github.com/tiagosiebler/binance/issues). +- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. +- Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. +- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) + + + +## Related Projects + +Check out my related JavaScript/TypeScript/Node.js projects: + +- Try our REST API & WebSocket SDKs published on npmjs: + - [Bybit Node.js SDK: bybit-api](https://www.npmjs.com/package/bybit-api) + - [Kraken Node.js SDK: @siebly/kraken-api](https://www.npmjs.com/package/coinbase-api) + - [OKX Node.js SDK: okx-api](https://www.npmjs.com/package/okx-api) + - [Binance Node.js SDK: binance](https://www.npmjs.com/package/binance) + - [Gate (gate.com) Node.js SDK: gateio-api](https://www.npmjs.com/package/gateio-api) + - [Bitget Node.js SDK: bitget-api](https://www.npmjs.com/package/bitget-api) + - [Kucoin Node.js SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) + - [Coinbase Node.js SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) + - [Bitmart Node.js SDK: bitmart-api](https://www.npmjs.com/package/bitmart-api) +- Try my misc utilities: + - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) + - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) +- Check out my examples: + - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) + + +## Documentation + +Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. + +- Binance API Documentation + - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) + - [ Derivatives ](https://developers.binance.com/docs/derivatives) + - [ Margin ](https://developers.binance.com/docs/margin_trading) + - [ Wallet ](https://developers.binance.com/docs/wallet) +- [Find all products here](https://developers.binance.com/en) +- [REST Endpoint Function List](./docs/endpointFunctionList.md) +- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) + +## Structure + +This project uses typescript. Resources are stored in 3 key structures: + +- [src](./src) - the whole connector written in typescript +- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. +- [dist](./dist) - the packed bundle of the project for use in browser environments. + +--- + +# Usage + +Create API credentials at Binance + +- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) +- [Testnet](https://testnet.binance.vision/). +- [Testnet Futures](testnet.binancefuture.com). +- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading. + +### Demo Trading vs Testnet + +Binance offers two testing environments: + +- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures. +- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing. + +To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information. + +## REST API Clients + +There are several REST API modules as there are some differences in each API group. + +1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management. +2. `USDMClient` for USD-M futures APIs. +3. `CoinMClient` for COIN-M futures APIs. +4. `PortfolioClient` for Portfolio Margin APIs. + +Vanilla Options is not yet available. Please get in touch if you're looking for this. + +### REST Main Client + +The MainClient covers all endpoints under the main "api\*.binance.com" subdomains, including but not limited to endpoints in the following product groups: + +- Spot +- Cross & isolated margin +- Convert +- Wallet +- Futures management (transfers & history) +- Sub account management +- Misc transfers +- Auto & dual invest +- Staking +- Mining +- Loans & VIP loans +- Simple Earn +- NFTs +- C2C +- Exchange Link +- Alpha trading + +Refer to the following links for a complete list of available endpoints: + +- [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/tiagosiebler/binance/blob/master/docs/endpointFunctionList.md) +- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) + +Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. + +```javascript +import { MainClient } from 'binance'; + +// or, if you prefer `require()`: +// const { MainClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new MainClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getAccountTradeList({ symbol: 'BTCUSDT' }) + .then((result) => { + console.log('getAccountTradeList result: ', result); + }) + .catch((err) => { + console.error('getAccountTradeList error: ', err); + }); + +client + .getExchangeInfo() + .then((result) => { + console.log('getExchangeInfo inverse result: ', result); + }) + .catch((err) => { + console.error('getExchangeInfo inverse error: ', err); + }); +``` + +See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. + +### REST USD-M Futures + +Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. + +```javascript +import { USDMClient } from 'binance'; + +// or, if you prefer `require()`: +// const { USDMClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getBalance() + .then((result) => { + console.log('getBalance result: ', result); + }) + .catch((err) => { + console.error('getBalance error: ', err); + }); + +client + .submitNewOrder({ + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + }) + .then((result) => { + console.log('submitNewOrder result: ', result); + }) + .catch((err) => { + console.error('submitNewOrder error: ', err); + }); +``` + +See [usdm-client.ts](./src/usdm-client.ts) for further information. + +### REST COIN-M Futures + +Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. + +```javascript +import { CoinMClient } from 'binance'; + +// or, if you prefer `require()`: +// const { CoinMClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new CoinMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getSymbolOrderBookTicker() + .then((result) => { + console.log('getSymbolOrderBookTicker result: ', result); + }) + .catch((err) => { + console.error('getSymbolOrderBookTicker error: ', err); + }); +``` + +See [coinm-client.ts](./src/coinm-client.ts) for further information. + +### REST Portfolio Margin + +Start by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. + +```javascript +import { PortfolioClient } from 'binance'; + +// or, if you prefer `require()`: +// const { PortfolioClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new PortfolioClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getBalance() + .then((result) => { + console.log('getBalance result: ', result); + }) + .catch((err) => { + console.error('getBalance error: ', err); + }); + +client + .submitNewUMOrder({ + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + }) + .then((result) => { + console.log('submitNewUMOrder result: ', result); + }) + .catch((err) => { + console.error('submitNewUMOrder error: ', err); + }); +``` + +See [portfolio-client.ts](./src/portfolio-client.ts) for further information. + +## WebSockets + +### WebSocket Consumers + +All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. + +The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: + +```javascript +import { WebsocketClient } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + /** - * Request user data stream subscription on the currently authenticated connection. - * - * If reconnected, this will automatically resubscribe unless you unsubscribe manually. - */ -async subscribeUserDataStream( - wsKey: WSAPIWsKey, - isRefreshingToken: boolean = false, -): Promise | WSConnectedResult | undefined> -⋮---- -// User data stream works differently for margin, since Feb 2026, via a listen token mechanic -⋮---- -// validity: 30 * 1000, // milliseconds (30 secs) -// validity: 5 * 60 * 1000, // milliseconds (5 mins ) -⋮---- -// Set respawn timer, to automatically fetch and sub to new token before expiry. Should be seamless on existing connection. -⋮---- -// try to respawn 30 seconds before expiration -⋮---- -// for Ed25519 keys, no signature is needed, we should already be authenticated in session -⋮---- -// for HMAC & RSA keys, request will be signed and sent to a dedicated topic -⋮---- -// Used to track whether this connection had the general "userDataStream.subscribe" called. -// Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub. -⋮---- + * The WebsocketClient will manage individual connections for you, under the hood. + * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. + */ +const wsClient = new WebsocketClient({ + api_key: key, + api_secret: secret, + // Optional: when enabled, the SDK will try to format incoming data into more readable objects. + // Beautified data is emitted via the "formattedMessage" event + beautify: true, + // Disable ping/pong ws heartbeat mechanism (not recommended) + // disableHeartbeat: true, + // Connect to testnet environment + // testnet: true, +}); + +// receive raw events +wsClient.on('message', (data) => { + console.log('raw message received ', JSON.stringify(data, null, 2)); +}); + +// notification when a connection is opened +wsClient.on('open', (data) => { + console.log('connection opened open:', data.wsKey, data.wsUrl); +}); + +// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. +wsClient.on('formattedMessage', (data) => { + console.log('formattedMessage: ', data); +}); + +// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +wsClient.on('response', (data) => { + console.log('log response: ', JSON.stringify(data, null, 2)); +}); + +// receive notification when a ws connection is reconnecting automatically +wsClient.on('reconnecting', (data) => { + console.log('ws automatically reconnecting.... ', data?.wsKey); +}); + +// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) +wsClient.on('reconnected', (data) => { + console.log('ws has reconnected ', data?.wsKey); +}); + +// Recommended: receive error events (e.g. first reconnection failed) +wsClient.on('exception', (data) => { + console.log('ws saw error ', data?.wsKey); +}); + /** - * Unsubscribe from the user data stream subscription on the currently authenticated connection. - * - * If reconnected, this will also stop it from automatically resubscribing after reconnect. - */ -unsubscribeUserDataStream( - wsKey: WSAPIWsKey, -): Promise { + // return JSON.parse(rawEvent); + // }, + + // Or, pre-process the raw event using RegEx, before using the same workflow: + customParseJSONFn: (rawEvent) => { + return JSON.parse( + rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), + ); + }, + + // Or, use a 3rd party library such as json-bigint: + // customParseJSONFn: (rawEvent) => { + // return JSONbig({ storeAsString: true }).parse(rawEvent); + // }, +}); + +ws.on('message', (msg) => { + console.log(msg); +}); + +// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values. +// Use a custom replacer or JSONbig.stringify if you need to log/serialize: +// const replacer = (_k: string, v: unknown) => typeof v === 'bigint' ? v.toString() : v; +// console.log(JSON.stringify(msg, replacer)); +``` + +### WebSocket API + +Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. + +#### Authentication + +HMAC, RSA and Ed25519 keys are supported for the WebSocket API. However, only Ed25519 keys support WebSocket API login. When using HMAC or RSA keys, each WebSocket API command will need to be individually signed. + +This is no issue for most use cases, but if you are latency sensitive, you should consider using Ed25519 keys. This will allow the WebSocket API client to authenticate once after the connection opens, and all commands can then be sent without additional request signatures. + +#### Event Driven API + +The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method. + +Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. + +#### Async Await API + +The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient). + +It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. + +Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. + +```typescript +import { WebsocketAPIClient } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketAPIClient } = require('binance'); + /** - * Required event handlers for handling automatic resubscribe to user data stream after reconnect, etc - */ -⋮---- -// Handle notification that user data stream has been terminated (e.g. due to expired listen token) and attempt to automatically resubscribe with new token -// Designed around margin mode mechanics: https://developers.binance.com/docs/margin_trading/trade-data-stream#response-example-1 -⋮---- -// console.log(new Date(), 'ws message received: ', data); -⋮---- -private setupSignMechanic() -⋮---- -private async tryResubscribeUserDataStream( - wsKey: WSAPIWsKey, - isRefreshingToken: boolean, -) -⋮---- -// Just in case the refresh timer is still running -⋮---- -private getSubscribedUserDataStreamState(wsKey: WSAPIWsKey) -⋮---- -private handleWSCloseEvent(params: -⋮---- -// Not a WS API connection -⋮---- -// If connection closes and we have a record of subscribing to user data stream on this connection, then we can assume it was likely an unintentional disconnect and we should attempt to resubscribe when it reconnects -⋮---- -private handleWSReconnectedEvent(params: -⋮---- -// Not a WS API connection -⋮---- -// No record of ever subscribing to user data stream on this connection, so no need to resubscribe -⋮---- -// Clear token refresh timer, just in case. No need on a dead & potentially respawning connection -⋮---- -// Feature enabled -⋮---- -// Delay existing timer, if exists -⋮---- -// Queue resubscribe workflow + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. + */ + +const publicKey = `-----BEGIN PUBLIC KEY----- +MCexampleQTxwLU9o= +-----END PUBLIC KEY----- +`; + +const privateKey = `-----BEGIN PRIVATE KEY----- +MC4CAQAexamplewqj5CzUuTy1 +-----END PRIVATE KEY----- +`; + +// API Key returned by binance, generated using the publicKey (above) via Binance's website +const apiKey = 'TQpJexamplerobdG'; + +// Make an instance of the WS API Client +const wsClient = new WebsocketAPIClient({ + api_key: apiKey, + api_secret: privateKey, + beautify: true, + + // Enforce testnet ws connections, regardless of supplied wsKey + // testnet: true, +}); + +// 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, see above. Can be used to prepare a connection before sending commands +// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); + +// Make WebSocket API calls, very similar to a REST API: + +wsClient + .getFuturesAccountBalanceV2({ + timestamp: Date.now(), + recvWindow: 5000, + }) + .then((result) => { + console.log('getFuturesAccountBalanceV2 result: ', result); + }) + .catch((err) => { + console.error('getFuturesAccountBalanceV2 error: ', err); + }); + +wsClient + .submitNewFuturesOrder('usdm', { + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + timestamp: Date.now(), + // recvWindow: 5000, + }) + .then((result) => { + console.log('getFuturesAccountBalanceV2 result: ', result); + }) + .catch((err) => { + console.error('getFuturesAccountBalanceV2 error: ', err); + }); +``` + +--- + +## Market Maker Endpoints + +Binance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program. + +These endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + +### Using Market Maker Endpoints + +To use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients): + +#### Market Maker REST API Clients + +```javascript +import { USDMClient, CoinMClient } from 'binance'; + +// USD-M Futures with MM endpoints +const usdmClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); + +// COIN-M Futures with MM endpoints +const coinmClient = new CoinMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); +``` + +#### Market Maker WebSocket Clients + +```javascript +import { WebsocketClient, WebsocketAPIClient } from 'binance'; + +// WebSocket consumer with MM endpoints +const wsClient = new WebsocketClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); + +// WebSocket API client with MM endpoints +const wsApiClient = new WebsocketAPIClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); +``` + +**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments. + +### Best practice + +Since market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints. + +```javascript +import { USDMClient } from 'binance'; + +// MM client for USD-M futures +const futuresMMClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMEndpoints: true, // Use MM endpoints for futures +}); + +// Regular client for USD-M futures +const futuresRegularClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMEndpoints: false, // Use regular endpoints for futures +}); +``` + +## Customise Logging + +Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. + +```javascript +import { WebsocketClient, DefaultLogger } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketClient, DefaultLogger } = require('binance'); + +// Enable all logging on the trace level (disabled by default) +DefaultLogger.trace = (...params) => { + console.trace('trace: ', params); +}; + +// Pass the updated logger as the 2nd parameter +const ws = new WebsocketClient( + { + api_key: key, + api_secret: secret, + beautify: true, + }, + DefaultLogger +); + +// Or, create a completely custom logger with the 3 available functions +const customLogger = { + trace: (...params: LogParams): void => { + console.trace(new Date(), params); + }, + info: (...params: LogParams): void => { + console.info(new Date(), params); + }, + error: (...params: LogParams): void => { + console.error(new Date(), params); + }, +} + +// Pass the custom logger as the 2nd parameter +const ws = new WebsocketClient( + { + api_key: key, + api_secret: secret, + beautify: true, + }, + customLogger +); +``` + +## Browser/Frontend Usage + +### Import + +This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. + +1. Install these dependencies + ```sh + npm install crypto-browserify stream-browserify + ``` +2. Add this to your `tsconfig.json` + ```json + { + "compilerOptions": { + "paths": { + "crypto": [ + "./node_modules/crypto-browserify" + ], + "stream": [ + "./node_modules/stream-browserify" + ] + } + ``` +3. Declare this in the global context of your application (ex: in polyfills for angular) + ```js + (window as any).global = window; + ``` + +### Webpack + +This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. + +Build a bundle using webpack: + +- `npm install` +- `npm build` +- `npm pack` + +The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. + +## Use with LLMs & AI + +This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. + +This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. + +--- + + + +### Contributions & Thanks + +Have my projects helped you? Share the love, there are many ways you can show your thanks: + +- Star & share my projects. +- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler +- Have an interesting project? Get in touch & invite me to it. +- Or buy me all the coffee: + - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` +- Sign up with my referral links: + - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 + - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ + - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SDK + - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 + + + + +### Contributions & Pull Requests + +Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. + +## Used By + +[![Repository Users Preview Image](https://dependents.info/tiagosiebler/binance/image)](https://github.com/tiagosiebler/binance/network/dependents) + + + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) + + ================ File: src/main-client.ts @@ -23931,6 +22940,7 @@ import { GetInstitutionalLoanForceLiquidationParams, GetInstitutionalLoanForceLiquidationResponse, GetInstitutionalLoanInterestHistoryParams, + GetInstitutionalLoanMaxBorrowableParams, GetInstitutionalLoanRiskUnitDetailsParams, GetLoanableAssetsDataParams, GetLoanBorrowHistoryParams, @@ -24004,9 +23014,11 @@ import { GetTargetAssetListResponse, GetTargetAssetROIParams, GetTravelRuleDepositHistoryParams, + GetTravelRuleRegionListParams, GetTravelRuleWithdrawHistoryParams, GetTravelRuleWithdrawHistoryV2Params, GetUniversalTransferBrokerParams, + GetVipLoanFixedRateMarketParams, GetVipLoanOngoingOrdersParams, GetVipLoanRepaymentHistoryParams, GetWbethRewardsHistoryResponse, @@ -24019,6 +23031,7 @@ import { InstitutionalLoanBorrowParams, InstitutionalLoanBorrowResponse, InstitutionalLoanInterestHistoryResponse, + InstitutionalLoanMaxBorrowableResponse, InstitutionalLoanRepayParams, InstitutionalLoanRepayResponse, InstitutionalLoanRiskUnitDetails, @@ -24302,7 +23315,9 @@ import { TradingDayTickerSingle, TransferBrokerSubAccount, TransferBrokerSubAccountParams, + TravelRuleCountryListResponse, TravelRuleDepositHistoryRecord, + TravelRuleRegionListResponse, TravelRuleWithdrawHistoryRecord, UniversalTransferBrokerParams, UniversalTransferHistoryParams, @@ -24316,6 +23331,9 @@ import { VipLoanAccruedInterestRecord, VipLoanBorrowParams, VipLoanBorrowResponse, + VipLoanFixedRateBorrowParams, + VipLoanFixedRateBorrowResponse, + VipLoanFixedRateMarketRecord, VipLoanInterestRateHistoryParams, VipLoanInterestRateRecord, VipLoanRenewParams, @@ -24346,2584 +23364,3693 @@ import { serialiseParams, } from './util/requestUtils'; ⋮---- -export class MainClient extends BaseRestClient +export class MainClient extends BaseRestClient +⋮---- +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) +⋮---- +/** + * This method is used to get the latency and time sync between the client and the server. + * This is not official API endpoint and is only used for internal testing purposes. + * Use this method to check the latency and time sync between the client and the server. + * Final values might vary slightly, but it should be within few ms difference. + * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. + */ +async fetchLatencySummary(): Promise +⋮---- +// Adjust server time by adding estimated one-way latency +⋮---- +// Calculate time difference between adjusted server time and local time +⋮---- +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - General endpoints + * + **/ +⋮---- +testConnectivity(): Promise +⋮---- +getExchangeInfo(params?: ExchangeInfoParams): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - Market endpoints + * + **/ +⋮---- +getOrderBook(params: OrderBookParams): Promise +⋮---- +getRecentTrades(params: RecentTradesParams): Promise +⋮---- +getHistoricalTrades(params: HistoricalTradesParams): Promise +⋮---- +getHistoricalBlockTrades( + params: HistoricalBlockTradesParams, +): Promise +⋮---- +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise +⋮---- +getKlines(params: KlinesParams): Promise +⋮---- +getUIKlines(params: KlinesParams): Promise +⋮---- +getAvgPrice(params: +⋮---- +getExecutionRules( + params?: SpotExecutionRulesParams, +): Promise +⋮---- +getReferencePrice(params: { + symbol: string; +}): Promise +⋮---- +getReferencePriceCalculation(params: { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +}): Promise +⋮---- +get24hrChangeStatistics(params?: { + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; +⋮---- +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL +⋮---- +get24hrChangeStatistics(params: { + symbol: string; // use for single symbol + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; +⋮---- +symbol: string; // use for single symbol +type?: 'FULL' | 'MINI'; // default is FULL +⋮---- +get24hrChangeStatistics(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; +}): Promise +⋮---- +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL +⋮---- +getTradingDayTicker( + params: TradingDayTickerParams, +): Promise +⋮---- +getSymbolPriceTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; +}): Promise +⋮---- +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +⋮---- +getSymbolOrderBookTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; +}): Promise +⋮---- +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +⋮---- +getRollingWindowTicker( + params: RollingWindowTickerParams, +): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - Trading endpoints + * + **/ +⋮---- +submitNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise> +⋮---- +testNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise +⋮---- +getOrder(params: GetOrderParams): Promise +⋮---- +cancelOrder(params: CancelOrderParams): Promise +⋮---- +cancelAllSymbolOrders(params: { + symbol: string; +}): Promise +⋮---- +replaceOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >( + params: ReplaceSpotOrderParams, +): Promise> +⋮---- +/** + * Reduce the quantity of an existing open order while keeping its priority in the order book. + * The new quantity must be less than the current quantity. + * https://binance-docs.github.io/apidocs/futures/en/#order-amend-keep-priority-trade + */ +amendOrderKeepPriority( + params: AmendKeepPriorityParams, +): Promise +⋮---- +getOpenOrders(params?: +⋮---- +getAllOrders(params: GetAllOrdersParams): Promise +⋮---- +/** + * @deprecated + */ +submitNewOCO(params: NewOCOParams): Promise +⋮---- +submitNewOrderList( + params: NewOrderListParams, +): Promise> +⋮---- +submitNewOrderListOTO( + params: NewOrderListOTOParams, +): Promise +⋮---- +submitNewOrderListOTOCO( + params: NewOrderListOTOCOParams, +): Promise +⋮---- +submitNewOrderListOPO( + params: NewOrderListOPOParams, +): Promise +⋮---- +submitNewOrderListOPOCO( + params: NewOrderListOPOCOParams, +): Promise +⋮---- +cancelOCO(params: CancelOCOParams): Promise +⋮---- +getOCO(params?: GetOCOParams): Promise +⋮---- +getAllOCO(params?: BasicFromPaginatedParams): Promise +⋮---- +/** + * Query open OCO + */ +getAllOpenOCO(): Promise +⋮---- +/** + * Places an order using smart order routing (SOR). + */ +submitNewSOROrder( + params: NewSpotSOROrderParams, +): Promise +⋮---- +/** + * Test new order creation and signature/recvWindow using smart order routing (SOR). + * Creates and validates a new order but does not send it into the matching engine. + */ +testNewSOROrder( + params: NewSpotSOROrderParams & { computeCommissionRates?: boolean }, +): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - Account endpoints + * + **/ +⋮---- +/** + * Get current account information + */ +getAccountInformation(params?: { + omitZeroBalances?: boolean; +}): Promise +⋮---- +getAccountTradeList( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, +): Promise +⋮---- +getOrderRateLimit(): Promise +⋮---- +getPreventedMatches( + params: PreventedMatchesParams, +): Promise +⋮---- +getAllocations(params: AllocationsParams): Promise +⋮---- +getCommissionRates(params: +⋮---- +/** + * + * MARGIN TRADING Endpoints - Market Data endpoints + * + **/ +⋮---- +getCrossMarginCollateralRatio(): Promise< + { + collaterals: Collateral[]; + assetNames: string[]; + }[] + > { + return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); +⋮---- +getAllCrossMarginPairs(): Promise +⋮---- +getIsolatedMarginAllSymbols(params?: { + symbol?: string; +}): Promise +⋮---- +getAllMarginAssets(): Promise +⋮---- +getMarginDelistSchedule(): Promise +⋮---- +getIsolatedMarginTierData( + params: QueryIsolatedMarginTierDataParams, +): Promise +⋮---- +queryMarginPriceIndex( + params: BasicSymbolParam, +): Promise +⋮---- +getMarginAvailableInventory(params: { + type: string; +}): Promise +⋮---- +getLeverageBracket(): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Borrow and Repay endpoints + * + **/ +⋮---- +getNextHourlyInterestRate( + params: GetNextHourlyInterestRateParams, +): Promise +⋮---- +getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< +⋮---- +submitMarginAccountBorrowRepay( + params: MarginAccountLoanParams, +): Promise +⋮---- +getMarginAccountBorrowRepayRecords( + params: GetMarginAccountBorrowRepayRecordsParams, +): Promise< ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +getMarginInterestRateHistory( + params: QueryMarginInterestRateHistoryParams, +): Promise +⋮---- +queryMaxBorrow( + params: BasicMarginAssetParams, +): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Trade endpoints + * + **/ +⋮---- +getMarginForceLiquidationRecord( + params: GetForceLiquidationRecordParams, +): Promise< +⋮---- +getSmallLiabilityExchangeCoins(): Promise +⋮---- +getSmallLiabilityExchangeHistory( + params: GetSmallLiabilityExchangeHistoryParams, +): Promise< +⋮---- +marginAccountCancelOpenOrders( + params: BasicSymbolParam, +): Promise +⋮---- +marginAccountCancelOCO(params: CancelOCOParams): Promise +⋮---- +marginAccountCancelOrder( + params: CancelOrderParams, +): Promise +⋮---- +marginAccountNewOCO(params: NewOCOParams): Promise +⋮---- +marginAccountNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise> +⋮---- +getMarginOrderCountUsage( + params: GetMarginOrderCountUsageParams, +): Promise +⋮---- +queryMarginAccountAllOCO( + params: QueryMarginAccountAllOCOParams, +): Promise +⋮---- +queryMarginAccountAllOrders( + params: GetAllOrdersParams, +): Promise +⋮---- +queryMarginAccountOCO(params: GetOCOParams): Promise +⋮---- +queryMarginAccountOpenOCO(params: { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; +}): Promise +⋮---- +queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise +⋮---- +queryMarginAccountOrder(params: GetOrderParams): Promise +⋮---- +queryMarginAccountTradeList( + params: QueryMarginAccountTradeListParams, +): Promise +⋮---- +submitSmallLiabilityExchange(params: +⋮---- +submitManualLiquidation( + params: ManualLiquidationParams, +): Promise +⋮---- +/** + * Post a new OTO order for margin account + */ +submitMarginOTOOrder( + params: SubmitMarginOTOOrderParams, +): Promise +⋮---- +/** + * Submit a new OTOCO order for margin account + */ +submitMarginOTOCOOrder( + params: SubmitMarginOTOCOOrderParams, +): Promise +⋮---- +/** + * Create a special key for low-latency trading (VIP 4+ only) + */ +createMarginSpecialLowLatencyKey( + params: CreateSpecialLowLatencyKeyParams, +): Promise +⋮---- +deleteMarginSpecialLowLatencyKey(params?: { + apiKey?: string; + apiName?: string; + symbol?: string; +}): Promise +⋮---- +updateMarginIPForSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; + ip: string; +}): Promise +⋮---- +/** + * Query the list of special keys for low-latency trading + */ +getMarginSpecialLowLatencyKeys(params: { + symbol?: string; +}): Promise +⋮---- +/** + * Query information for a specific special key used in low-latency trading + */ +getMarginSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; +}): Promise +⋮---- +/** + * Query the current cross-margin liquidation loan status (bankruptcy deficit). + */ +getMarginLiquidationLoan(): Promise +⋮---- +/** + * Repay an outstanding cross-margin liquidation loan from the spot wallet. + */ +repayMarginLiquidationLoan( + params: RepayMarginLiquidationLoanParams, +): Promise +⋮---- +/** + * Query cross-margin liquidation loan repayment history. + */ +getMarginLiquidationLoanRepayHistory( + params?: GetMarginLiquidationLoanRepayHistoryParams, +): Promise +⋮---- +/** + * Exit Margin Special Key mode for Cross Margin Classic accounts. + */ +exitMarginSpecialKeyMode(): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Transfer endpoints + * + **/ +⋮---- +getCrossMarginTransferHistory( + params: GetCrossMarginTransferHistoryParams, +): Promise> +⋮---- +queryMaxTransferOutAmount( + params: BasicMarginAssetParams, +): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Account endpoints + * + **/ +⋮---- +updateCrossMarginMaxLeverage(params: +⋮---- +disableIsolatedMarginAccount(params: +⋮---- +enableIsolatedMarginAccount(params: +⋮---- +getBNBBurn(): Promise +⋮---- +getMarginSummary(): Promise +⋮---- +queryCrossMarginAccountDetails(): Promise +⋮---- +getCrossMarginFeeData( + params: QueryCrossMarginFeeDataParams, +): Promise +⋮---- +getIsolatedMarginAccountLimit(): Promise< +⋮---- +getIsolatedMarginAccountInfo(params?: { + symbols?: string; +}): Promise +⋮---- +getIsolatedMarginFeeData( + params: QueryCrossMarginFeeDataParams, +): Promise +⋮---- +toggleBNBBurn(params: ToggleBNBBurnParams): Promise +⋮---- +/** + * Possibly @deprecated + * Only existing in old documentation, not in new documentation + */ +getMarginCapitalFlow( + params: GetMarginCapitalFlowParams, +): Promise +⋮---- +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryLoanRecord( + params: QueryMarginRecordParams, +): Promise< +⋮---- +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryRepayRecord( + params: QueryMarginRecordParams, +): Promise< +⋮---- +/** + * @deprecated on 2024-01-09, use submitUniversalTransfer() instead + */ +isolatedMarginAccountTransfer( + params: IsolatedMarginAccountTransferParams, +): Promise +⋮---- +/** + * + * WALLET Endpoints - Capital endpoints + * + **/ +⋮---- +getBalances(): Promise +⋮---- +withdraw(params: WithdrawParams): Promise< +⋮---- +getWithdrawHistory( + params?: WithdrawHistoryParams, +): Promise +⋮---- +getWithdrawAddresses(): Promise +⋮---- +getWithdrawQuota(): Promise< +⋮---- +getDepositHistory(params?: DepositHistoryParams): Promise +⋮---- +getDepositAddress( + params: DepositAddressParams, +): Promise +⋮---- +getDepositAddresses( + params: DepositAddressListParams, +): Promise +⋮---- +submitDepositCredit( + params: SubmitDepositCreditParams, +): Promise ⋮---- /** - * This method is used to get the latency and time sync between the client and the server. - * This is not official API endpoint and is only used for internal testing purposes. - * Use this method to check the latency and time sync between the client and the server. - * Final values might vary slightly, but it should be within few ms difference. - * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. + * @deprecated - deleted as of 2024-11-21 */ -async fetchLatencySummary(): Promise -⋮---- -// Adjust server time by adding estimated one-way latency -⋮---- -// Calculate time difference between adjusted server time and local time +getAutoConvertStablecoins(): Promise ⋮---- /** - * Abstraction required by each client to aid with time sync / drift handling + * @deprecated - deleted as of 2024-11-21 */ -async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise +setConvertibleCoins(params: ConvertibleCoinsParams): Promise ⋮---- /** * - * SPOT TRADING Endpoints - General endpoints + * WALLET Endpoints - Asset endpoints * **/ ⋮---- -testConnectivity(): Promise +getAssetDetail( + params?: Partial, +): Promise> ⋮---- -getExchangeInfo(params?: ExchangeInfoParams): Promise +getWalletBalances(params?: { + quoteAsset?: string; +}): Promise +⋮---- +getUserAsset(params: GetAssetParams): Promise +⋮---- +submitUniversalTransfer( + params: UniversalTransferParams, +): Promise< +⋮---- +getUniversalTransferHistory( + params: UniversalTransferHistoryParams, +): Promise +⋮---- +getDust(params: +⋮---- +convertDustToBnb(params: ConvertDustParams): Promise +⋮---- +/** + * Convert dust assets to a target asset (e.g. BNB, USDT). + */ +convertDustAssets(params: DustConvertParams): Promise +⋮---- +/** + * Query assets eligible for dust conversion. + */ +queryDustConvertibleAssets( + params: DustConvertibleAssetsParams, +): Promise +⋮---- +getDustLog(params?: BasicTimeRangeParam): Promise +⋮---- +getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise +⋮---- +getTradeFee(params?: +⋮---- +getFundingAsset(params: GetAssetParams): Promise +⋮---- +getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< +⋮---- +getDelegationHistory( + params: DelegationHistoryParams, +): Promise> ⋮---- /** * - * SPOT TRADING Endpoints - Market endpoints + * Futures Management Endpoints: + * https://binance-docs.github.io/apidocs/spot/en/#futures + * + * Note: to trade futures use the usdm-client or coinm-client. + * MainClient only has the futures endpoints listed in the "spot" docs category, primarily used for transfers. * **/ ⋮---- -getOrderBook(params: OrderBookParams): Promise +/** + * Execute transfer between spot account and futures account. + * + * Type: + * - 1: transfer from spot account to USDT-Ⓜ futures account. + * - 2: transfer from USDT-Ⓜ futures account to spot account. + * - 3: transfer from spot account to COIN-Ⓜ futures account. + * - 4: transfer from COIN-Ⓜ futures account to spot account. + */ ⋮---- -getRecentTrades(params: RecentTradesParams): Promise +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +submitNewFutureAccountTransfer( + params: NewFutureAccountTransferParams, +): Promise< ⋮---- -getHistoricalTrades(params: HistoricalTradesParams): Promise +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +getFutureAccountTransferHistory( + params: GetFutureAccountTransferHistoryParams, +): Promise> ⋮---- -getHistoricalBlockTrades( - params: HistoricalBlockTradesParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise ⋮---- -getKlines(params: KlinesParams): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralWalletV2(): Promise ⋮---- -getUIKlines(params: KlinesParams): Promise +/** + * @deprecated as of 2023-09-25 + */ +getAdjustCrossCollateralLTVHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -getAvgPrice(params: +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralLiquidationHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -getExecutionRules( - params?: SpotExecutionRulesParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralInterestHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -getReferencePrice(params: { - symbol: string; -}): Promise +/** + * + * WALLET Endpoints - Account endpoints + * + **/ ⋮---- -getReferencePriceCalculation(params: { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -}): Promise +getAccountInfo(): Promise ⋮---- -get24hrChangeStatistics(params?: { - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; - }): Promise; +getDailyAccountSnapshot( + params: DailyAccountSnapshotParams, +): Promise ⋮---- -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL +disableFastWithdrawSwitch(): Promise ⋮---- -get24hrChangeStatistics(params: { - symbol: string; // use for single symbol - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; - }): Promise; +enableFastWithdrawSwitch(): Promise ⋮---- -symbol: string; // use for single symbol -type?: 'FULL' | 'MINI'; // default is FULL +getAccountStatus(): Promise< ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; -}): Promise +getApiTradingStatus(): Promise ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL +getApiKeyPermissions(): Promise ⋮---- -getTradingDayTicker( - params: TradingDayTickerParams, -): Promise +/** + * + * WALLET Endpoints - Travel Rule endpoints + * + **/ ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise +/** + * Submit a withdrawal request for local entities that require travel rule + * + * For questionaire format, please refer to the docs: + * https://developers.binance.com/docs/wallet/travel-rule/withdraw-questionnaire + */ +withdrawTravelRule(params: WithdrawTravelRuleParams): Promise< ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistory( + params?: GetTravelRuleWithdrawHistoryParams, +): Promise ⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistoryV2( + params?: GetTravelRuleWithdrawHistoryV2Params, +): Promise ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols +/** + * Submit questionnaire for local entities that require travel rule + * + * for questionaire format, please refer to the docs: + * https://developers.binance.com/docs/wallet/travel-rule/deposit-questionnaire + */ +submitTravelRuleDepositQuestionnaire( + params: SubmitTravelRuleDepositQuestionnaireParams, +): Promise ⋮---- -getRollingWindowTicker( - params: RollingWindowTickerParams, -): Promise +/** + * Fetch deposit history for local entities that require travel rule + */ +getTravelRuleDepositHistory( + params?: GetTravelRuleDepositHistoryParams, +): Promise +⋮---- +/** + * Fetch the onboarded VASP list for local entities that require travel rule. + * Use the `identifier` field (not vaspCode) for the `vasp` param in deposit/withdrawal questionnaires. + * Both vaspCode and identifier accepted until 28 May 2026. + */ +getOnboardedVASPList(): Promise +⋮---- +getTravelRuleCountryList(): Promise +⋮---- +getTravelRuleRegionList( + params: GetTravelRuleRegionListParams, +): Promise ⋮---- /** * - * SPOT TRADING Endpoints - Trading endpoints + * WALLET Endpoints - Other endpoints * **/ ⋮---- -submitNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> +getSystemStatus(): Promise ⋮---- -testNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise +getDelistSchedule(): Promise ⋮---- -getOrder(params: GetOrderParams): Promise +/** + * + * SUB ACCOUNT Endpoints - Account management + * + **/ ⋮---- -cancelOrder(params: CancelOrderParams): Promise +createVirtualSubAccount( + params: CreateSubAccountParams, +): Promise ⋮---- -cancelAllSymbolOrders(params: { - symbol: string; -}): Promise +getSubAccountList( + params?: SubAccountListParams, +): Promise ⋮---- -replaceOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, - >( - params: ReplaceSpotOrderParams, -): Promise> +subAccountEnableFutures(email: string): Promise ⋮---- /** - * Reduce the quantity of an existing open order while keeping its priority in the order book. - * The new quantity must be less than the current quantity. - * https://binance-docs.github.io/apidocs/futures/en/#order-amend-keep-priority-trade + * @deprecated as of 2025-06-03 + * User now should make the initial transfer in the Margin account to enable it. */ -amendOrderKeepPriority( - params: AmendKeepPriorityParams, -): Promise -⋮---- -getOpenOrders(params?: +subAccountEnableMargin(email: string): Promise ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +enableOptionsForSubAccount(params: { + email: string; +}): Promise ⋮---- /** - * @deprecated + * @deprecated as of 2025-06-03 + * User now should make the initial transfer in the Margin account to enable it. */ -submitNewOCO(params: NewOCOParams): Promise -⋮---- -submitNewOrderList( - params: NewOrderListParams, -): Promise> +subAccountEnableLeverageToken( + params: SubAccountEnableLeverageToken, +): Promise ⋮---- -submitNewOrderListOTO( - params: NewOrderListOTOParams, -): Promise +getSubAccountStatusOnMarginOrFutures(params?: { + email?: string; +}): Promise ⋮---- -submitNewOrderListOTOCO( - params: NewOrderListOTOCOParams, -): Promise +getSubAccountFuturesPositionRisk( + email: string, +): Promise ⋮---- -submitNewOrderListOPO( - params: NewOrderListOPOParams, -): Promise +getSubAccountFuturesPositionRiskV2( + params: BasicFuturesSubAccountParams, +): Promise ⋮---- -submitNewOrderListOPOCO( - params: NewOrderListOPOCOParams, -): Promise +getSubAccountTransactionStatistics(params: { + email: string; +}): Promise ⋮---- -cancelOCO(params: CancelOCOParams): Promise +/** + * + * SUB ACCOUNT Endpoints - API management + * + **/ ⋮---- -getOCO(params?: GetOCOParams): Promise +getSubAccountIPRestriction( + params: BasicSubAccount, +): Promise ⋮---- -getAllOCO(params?: BasicFromPaginatedParams): Promise +subAccountDeleteIPList( + params: SubAccountAddOrDeleteIPList, +): Promise ⋮---- -/** - * Query open OCO - */ -getAllOpenOCO(): Promise +subAccountAddIPRestriction( + params: AddIpRestriction, +): Promise ⋮---- /** - * Places an order using smart order routing (SOR). - */ -submitNewSOROrder( - params: NewSpotSOROrderParams, -): Promise + * @deprecated + * Use subAccountAddIPRestriction instead + **/ +subAccountAddIPList( + params: SubAccountEnableOrDisableIPRestriction, +): Promise ⋮---- /** - * Test new order creation and signature/recvWindow using smart order routing (SOR). - * Creates and validates a new order but does not send it into the matching engine. - */ -testNewSOROrder( - params: NewSpotSOROrderParams & { computeCommissionRates?: boolean }, -): Promise + * @deprecated + * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList + **/ +subAccountEnableOrDisableIPRestriction( + params: EnableOrDisableIPRestrictionForSubAccountParams, +): Promise ⋮---- /** * - * SPOT TRADING Endpoints - Account endpoints + * SUB ACCOUNT Endpoints - Asset management * **/ ⋮---- -/** - * Get current account information - */ -getAccountInformation(params?: { - omitZeroBalances?: boolean; -}): Promise +subAccountFuturesTransfer( + params: SubAccountTransferParams, +): Promise ⋮---- -getAccountTradeList( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise +getSubAccountFuturesAccountDetail( + email: string, +): Promise ⋮---- -getOrderRateLimit(): Promise +getSubAccountDetailOnFuturesAccountV2( + params: BasicFuturesSubAccountParams, +): Promise ⋮---- -getPreventedMatches( - params: PreventedMatchesParams, -): Promise +getSubAccountDetailOnMarginAccount( + email: string, +): Promise ⋮---- -getAllocations(params: AllocationsParams): Promise +getSubAccountDepositAddress( + params: SubAccountDepositAddressParams, +): Promise ⋮---- -getCommissionRates(params: +getSubAccountDepositHistory( + params: SubAccountDepositHistoryParams, +): Promise +⋮---- +getSubAccountFuturesAccountSummary(): Promise +⋮---- +getSubAccountSummaryOnFuturesAccountV2( + params: SubAccountSummaryOnFuturesAccountV2Params, +): Promise +⋮---- +getSubAccountsSummaryOfMarginAccount(): Promise +⋮---- +subAccountMarginTransfer( + params: SubAccountTransferParams, +): Promise +⋮---- +getSubAccountAssets( + params: SubAccountAssetsParams, +): Promise +⋮---- +getSubAccountAssetsMaster(params: +⋮---- +getSubAccountFuturesAssetTransferHistory( + params: SubAccountFuturesAssetTransferHistoryParams, +): Promise +⋮---- +getSubAccountSpotAssetTransferHistory( + params?: SubAccountSpotAssetTransferHistoryParams, +): Promise +⋮---- +getSubAccountSpotAssetsSummary( + params?: SubAccountSpotAssetsSummaryParams, +): Promise +⋮---- +getSubAccountUniversalTransferHistory( + params?: SubAccountUniversalTransferHistoryParams, +): Promise +⋮---- +subAccountFuturesAssetTransfer( + params: SubAccountFuturesAssetTransferParams, +): Promise +⋮---- +subAccountTransferHistory( + params?: SubAccountTransferHistoryParams, +): Promise +⋮---- +subAccountTransferToMaster( + params: SubAccountTransferToMasterParams, +): Promise +⋮---- +subAccountTransferToSameMaster( + params: SubAccountTransferToSameMasterParams, +): Promise +⋮---- +subAccountUniversalTransfer( + params: SubAccountUniversalTransferParams, +): Promise +⋮---- +subAccountMovePosition( + params: SubAccountMovePositionParams, +): Promise< +⋮---- +getSubAccountFuturesPositionMoveHistory( + params: SubAccountMovePositionHistoryParams, +): Promise< ⋮---- /** * - * MARGIN TRADING Endpoints - Market Data endpoints + * SUB ACCOUNT Endpoints - Managed Sub Account * **/ ⋮---- -getCrossMarginCollateralRatio(): Promise< - { - collaterals: Collateral[]; - assetNames: string[]; - }[] - > { - return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); +depositAssetsIntoManagedSubAccount( + params: SubAccountTransferToSameMasterParams, +): Promise ⋮---- -getAllCrossMarginPairs(): Promise +getManagedSubAccountDepositAddress( + params: ManagedSubAccountDepositAddressParams, +): Promise ⋮---- -getIsolatedMarginAllSymbols(params?: { - symbol?: string; -}): Promise +withdrawAssetsFromManagedSubAccount( + params: WithdrawAssetsFromManagedSubAccountParams, +): Promise +⋮---- +getManagedSubAccountTransfersParent( + params: ManagedSubAccountTransferLogParams, +): Promise< +⋮---- +getManagedSubAccountTransferLog( + params: ManagedSubAccountTransferTTLogParams, +): Promise< ⋮---- -getAllMarginAssets(): Promise +getManagedSubAccountTransfersInvestor( + params: ManagedSubAccountTransferLogParams, +): Promise< ⋮---- -getMarginDelistSchedule(): Promise +getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< ⋮---- -getIsolatedMarginTierData( - params: QueryIsolatedMarginTierDataParams, -): Promise +getManagedSubAccountSnapshot( + params: ManagedSubAccountSnapshotParams, +): Promise ⋮---- -queryMarginPriceIndex( - params: BasicSymbolParam, -): Promise +getManagedSubAccountAssetDetails( + email: string, +): Promise ⋮---- -getMarginAvailableInventory(params: { - type: string; -}): Promise +getManagedSubAccountMarginAssets(params: { + email: string; + accountType?: string; +}): Promise ⋮---- -getLeverageBracket(): Promise +getManagedSubAccountFuturesAssets(params: { + email: string; + accountType?: string; +}): Promise ⋮---- /** * - * MARGIN TRADING Endpoints - Borrow and Repay endpoints + * AUTO INVEST Endpoints - Market data * **/ ⋮---- -getNextHourlyInterestRate( - params: GetNextHourlyInterestRateParams, -): Promise +getAutoInvestAssets(): Promise< ⋮---- -getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< +getAutoInvestSourceAssets( + params: GetSourceAssetListParams, +): Promise ⋮---- -submitMarginAccountBorrowRepay( - params: MarginAccountLoanParams, -): Promise +getAutoInvestTargetAssets( + params: GetTargetAssetListParams, +): Promise ⋮---- -getMarginAccountBorrowRepayRecords( - params: GetMarginAccountBorrowRepayRecordsParams, -): Promise< +getAutoInvestTargetAssetsROI( + params: GetTargetAssetROIParams, +): Promise ⋮---- -getMarginInterestRateHistory( - params: QueryMarginInterestRateHistoryParams, -): Promise +getAutoInvestIndex(params: { + indexId: number; +}): Promise ⋮---- -queryMaxBorrow( - params: BasicMarginAssetParams, -): Promise +getAutoInvestPlans(params: { + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; +}): Promise ⋮---- /** * - * MARGIN TRADING Endpoints - Trade endpoints + * AUTO INVEST Endpoints - Trade * **/ ⋮---- -getMarginForceLiquidationRecord( - params: GetForceLiquidationRecordParams, -): Promise< +/** + * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction + * + * @param params + * @returns + */ +submitAutoInvestOneTimeTransaction( + params: SubmitOneTimeTransactionParams, +): Promise ⋮---- -getSmallLiabilityExchangeCoins(): Promise +updateAutoInvestPlanStatus( + params: ChangePlanStatusParams, +): Promise ⋮---- -getSmallLiabilityExchangeHistory( - params: GetSmallLiabilityExchangeHistoryParams, +updateAutoInvestmentPlan( + params: EditInvestmentPlanParams, +): Promise +⋮---- +submitAutoInvestRedemption( + params: SubmitIndexLinkedPlanRedemptionParams, ): Promise< ⋮---- -marginAccountCancelOpenOrders( - params: BasicSymbolParam, -): Promise +getAutoInvestSubscriptionTransactions( + params: GetSubscriptionTransactionHistoryParams, +): Promise ⋮---- -marginAccountCancelOCO(params: CancelOCOParams): Promise +getOneTimeTransactionStatus( + params: GetOneTimeTransactionStatusParams, +): Promise ⋮---- -marginAccountCancelOrder( - params: CancelOrderParams, -): Promise +submitAutoInvestmentPlan( + params: CreateInvestmentPlanParams, +): Promise ⋮---- -marginAccountNewOCO(params: NewOCOParams): Promise +getAutoInvestRedemptionHistory( + params: GetIndexLinkedPlanRedemptionHistoryParams, +): Promise ⋮---- -marginAccountNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> +getAutoInvestPlan(params: GetPlanDetailsParams): Promise ⋮---- -getMarginOrderCountUsage( - params: GetMarginOrderCountUsageParams, -): Promise +getAutoInvestUserIndex(params: { + indexId: number; +}): Promise ⋮---- -queryMarginAccountAllOCO( - params: QueryMarginAccountAllOCOParams, -): Promise +getAutoInvestRebalanceHistory( + params: GetIndexLinkedPlanRebalanceHistoryParams, +): Promise ⋮---- -queryMarginAccountAllOrders( - params: GetAllOrdersParams, -): Promise +/** + * + * CONVERT Endpoints - Market Data + * + **/ ⋮---- -queryMarginAccountOCO(params: GetOCOParams): Promise +getConvertPairs(params: GetAllConvertPairsParams): Promise ⋮---- -queryMarginAccountOpenOCO(params: { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; -}): Promise +getConvertAssetInfo(): Promise ⋮---- -queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise +/** + * + * CONVERT Endpoints - Trade + * + **/ ⋮---- -queryMarginAccountOrder(params: GetOrderParams): Promise +convertQuoteRequest(params: ConvertQuoteRequestParams): Promise ⋮---- -queryMarginAccountTradeList( - params: QueryMarginAccountTradeListParams, -): Promise +acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise ⋮---- -submitSmallLiabilityExchange(params: +getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise ⋮---- -submitManualLiquidation( - params: ManualLiquidationParams, -): Promise +getOrderStatus(params: GetOrderStatusParams): Promise ⋮---- -/** - * Post a new OTO order for margin account - */ -submitMarginOTOOrder( - params: SubmitMarginOTOOrderParams, -): Promise +submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise +⋮---- +cancelConvertLimitOrder(params: +⋮---- +getConvertLimitOpenOrders(): Promise< ⋮---- /** - * Submit a new OTOCO order for margin account - */ -submitMarginOTOCOOrder( - params: SubmitMarginOTOCOOrderParams, -): Promise + * + * STAKING Endpoints - ETH Staking - Account + * + **/ ⋮---- /** - * Create a special key for low-latency trading (VIP 4+ only) - */ -createMarginSpecialLowLatencyKey( - params: CreateSpecialLowLatencyKeyParams, -): Promise + * @deprecated use getEthStakingAccountV2 instead + **/ +getEthStakingAccount(): Promise ⋮---- -deleteMarginSpecialLowLatencyKey(params?: { - apiKey?: string; - apiName?: string; - symbol?: string; -}): Promise +getEthStakingAccountV2(): Promise ⋮---- -updateMarginIPForSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; - ip: string; -}): Promise +getEthStakingQuota(): Promise ⋮---- /** - * Query the list of special keys for low-latency trading - */ -getMarginSpecialLowLatencyKeys(params: { - symbol?: string; -}): Promise + * + * STAKING Endpoints - ETH Staking- Staking + * + **/ ⋮---- /** - * Query information for a specific special key used in low-latency trading - */ -getMarginSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; -}): Promise + * @deprecated use subscribeEthStakingV2 instead + **/ +subscribeEthStakingV1(params: ⋮---- -/** - * Query the current cross-margin liquidation loan status (bankruptcy deficit). - */ -getMarginLiquidationLoan(): Promise +subscribeEthStakingV2(params: { + amount: number; +}): Promise ⋮---- -/** - * Repay an outstanding cross-margin liquidation loan from the spot wallet. - */ -repayMarginLiquidationLoan( - params: RepayMarginLiquidationLoanParams, -): Promise +redeemEth(params: RedeemEthParams): Promise +⋮---- +wrapBeth(params: ⋮---- /** - * Query cross-margin liquidation loan repayment history. - */ -getMarginLiquidationLoanRepayHistory( - params?: GetMarginLiquidationLoanRepayHistoryParams, -): Promise + * + * STAKING Endpoints - ETH Staking - History + * + **/ +⋮---- +getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< +⋮---- +getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< +⋮---- +getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< +⋮---- +getWbethRewardsHistory( + params: GetWrapHistoryParams, +): Promise +⋮---- +getEthRateHistory(params: GetETHRateHistoryParams): Promise< ⋮---- -/** - * Exit Margin Special Key mode for Cross Margin Classic accounts. - */ -exitMarginSpecialKeyMode(): Promise +getBethWrapHistory(params: GetWrapHistoryParams): Promise< +⋮---- +getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< ⋮---- /** * - * MARGIN TRADING Endpoints - Transfer endpoints + * BFUSD (sapi/v1/bfusd) * **/ ⋮---- -getCrossMarginTransferHistory( - params: GetCrossMarginTransferHistoryParams, -): Promise> +getBfusdAccount(): Promise ⋮---- -queryMaxTransferOutAmount( - params: BasicMarginAssetParams, -): Promise +getBfusdQuota(): Promise +⋮---- +subscribeBfusd( + params: BfusdSubscribeParams, +): Promise +⋮---- +redeemBfusd(params: BfusdRedeemParams): Promise +⋮---- +getBfusdSubscriptionHistory( + params: GetBfusdSubscriptionHistoryParams, +): Promise< +⋮---- +getBfusdRedemptionHistory( + params: GetBfusdRedemptionHistoryParams, +): Promise< +⋮---- +getBfusdRewardsHistory( + params: GetBfusdRewardsHistoryParams, +): Promise< +⋮---- +getBfusdRateHistory( + params: GetBfusdRateHistoryParams, +): Promise< ⋮---- /** * - * MARGIN TRADING Endpoints - Account endpoints + * RWUSD (sapi/v1/rwusd) * **/ ⋮---- -updateCrossMarginMaxLeverage(params: -⋮---- -disableIsolatedMarginAccount(params: -⋮---- -enableIsolatedMarginAccount(params: -⋮---- -getBNBBurn(): Promise +getRwusdAccount(): Promise ⋮---- -getMarginSummary(): Promise +getRwusdQuota(): Promise ⋮---- -queryCrossMarginAccountDetails(): Promise +subscribeRwusd( + params: RwusdSubscribeParams, +): Promise ⋮---- -getCrossMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise +redeemRwusd(params: RwusdRedeemParams): Promise ⋮---- -getIsolatedMarginAccountLimit(): Promise< +getRwusdSubscriptionHistory( + params: GetRwusdSubscriptionHistoryParams, +): Promise< ⋮---- -getIsolatedMarginAccountInfo(params?: { - symbols?: string; -}): Promise +getRwusdRedemptionHistory( + params: GetRwusdRedemptionHistoryParams, +): Promise< ⋮---- -getIsolatedMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise +getRwusdRewardsHistory( + params: GetRwusdRewardsHistoryParams, +): Promise< ⋮---- -toggleBNBBurn(params: ToggleBNBBurnParams): Promise +getRwusdRateHistory( + params: GetRwusdRateHistoryParams, +): Promise< ⋮---- /** - * Possibly @deprecated - * Only existing in old documentation, not in new documentation + * @deprecated as of 2024-01-19 */ -getMarginCapitalFlow( - params: GetMarginCapitalFlowParams, -): Promise +getStakingProducts( + params: StakingBasicParams & { + asset?: string; + }, +): Promise ⋮---- /** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + * @deprecated as of 2024-01-19 */ -queryLoanRecord( - params: QueryMarginRecordParams, -): Promise< +getStakingProductPosition( + params: StakingBasicParams & { + productId?: string; + asset?: string; + }, +): Promise ⋮---- /** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + * @deprecated as of 2024-01-19 */ -queryRepayRecord( - params: QueryMarginRecordParams, -): Promise< +getStakingHistory(params: StakingHistoryParams): Promise ⋮---- /** - * @deprecated on 2024-01-09, use submitUniversalTransfer() instead + * @deprecated as of 2024-01-19 */ -isolatedMarginAccountTransfer( - params: IsolatedMarginAccountTransferParams, -): Promise +getPersonalLeftQuotaOfStakingProduct(params: { + product: StakingProductType; + productId: string; +}): Promise ⋮---- /** * - * WALLET Endpoints - Capital endpoints + * STAKING Endpoints - SOL Staking- Account * **/ ⋮---- -getBalances(): Promise +getSolStakingAccount(): Promise ⋮---- -withdraw(params: WithdrawParams): Promise< +getSolStakingQuota(): Promise ⋮---- -getWithdrawHistory( - params?: WithdrawHistoryParams, -): Promise +/** + * + * STAKING Endpoints - SOL Staking - Staking + * + **/ ⋮---- -getWithdrawAddresses(): Promise +subscribeSolStaking(params: { + amount: number; +}): Promise ⋮---- -getWithdrawQuota(): Promise< +redeemSol(params: ⋮---- -getDepositHistory(params?: DepositHistoryParams): Promise +claimSolBoostRewards(): Promise< ⋮---- -getDepositAddress( - params: DepositAddressParams, -): Promise +/** + * + * STAKING Endpoints - SOL Staking- History + * + **/ ⋮---- -getDepositAddresses( - params: DepositAddressListParams, -): Promise +getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< ⋮---- -submitDepositCredit( - params: SubmitDepositCreditParams, -): Promise +getSolRedemptionHistory(params?: { + rows: SolRedemptionHistoryRecord[]; + total: number; +}): Promise ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - */ -getAutoConvertStablecoins(): Promise +getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - */ -setConvertibleCoins(params: ConvertibleCoinsParams): Promise +getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< +⋮---- +getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< +⋮---- +getSolUnclaimedRewards(): Promise< + { + amount: string; + rewardsAsset: string; + }[] + > { + return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); ⋮---- /** * - * WALLET Endpoints - Asset endpoints + * STAKING - Onchain Yields - Account * **/ ⋮---- -getAssetDetail( - params?: Partial, -): Promise> +getOnchainYieldsLockedProducts( + params?: OnchainYieldsLockedProductListParams, +): Promise ⋮---- -getWalletBalances(params?: { - quoteAsset?: string; -}): Promise +getOnchainYieldsLockedPersonalLeftQuota( + params: OnchainYieldsLockedPersonalLeftQuotaParams, +): Promise ⋮---- -getUserAsset(params: GetAssetParams): Promise +getOnchainYieldsLockedPosition( + params?: OnchainYieldsLockedPositionParams, +): Promise ⋮---- -submitUniversalTransfer( - params: UniversalTransferParams, -): Promise< +getOnchainYieldsAccount(): Promise ⋮---- -getUniversalTransferHistory( - params: UniversalTransferHistoryParams, -): Promise +/** + * + * STAKING - Onchain Yields - Earn + * + **/ ⋮---- -getDust(params: +getOnchainYieldsLockedSubscriptionPreview( + params: OnchainYieldsLockedSubscriptionPreviewParams, +): Promise ⋮---- -convertDustToBnb(params: ConvertDustParams): Promise +subscribeOnchainYieldsLockedProduct( + params: OnchainYieldsLockedSubscribeParams, +): Promise +⋮---- +setOnchainYieldsLockedAutoSubscribe( + params: OnchainYieldsLockedSetAutoSubscribeParams, +): Promise +⋮---- +setOnchainYieldsLockedRedeemOption( + params: OnchainYieldsLockedSetRedeemOptionParams, +): Promise +⋮---- +redeemOnchainYieldsLockedProduct( + params: OnchainYieldsLockedRedeemParams, +): Promise ⋮---- /** - * Convert dust assets to a target asset (e.g. BNB, USDT). - */ -convertDustAssets(params: DustConvertParams): Promise + * + * STAKING - Onchain Yields - History + * + **/ +⋮---- +getOnchainYieldsLockedSubscriptionRecord( + params?: OnchainYieldsLockedSubscriptionRecordParams, +): Promise +⋮---- +getOnchainYieldsLockedRewardsHistory( + params?: OnchainYieldsLockedRewardsHistoryParams, +): Promise +⋮---- +getOnchainYieldsLockedRedemptionRecord( + params?: OnchainYieldsLockedRedemptionRecordParams, +): Promise ⋮---- /** - * Query assets eligible for dust conversion. - */ -queryDustConvertibleAssets( - params: DustConvertibleAssetsParams, -): Promise + * + * STAKING - Soft staking + * + **/ ⋮---- -getDustLog(params?: BasicTimeRangeParam): Promise +getSoftStakingProductList( + params?: GetSoftStakingProductListParams, +): Promise ⋮---- -getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise +setSoftStaking( + params: SetSoftStakingParams, +): Promise ⋮---- -getTradeFee(params?: +getSoftStakingRewardsHistory( + params?: GetSoftStakingRewardsHistoryParams, +): Promise ⋮---- -getFundingAsset(params: GetAssetParams): Promise +/** + * + * COPY TRADING Endpoints - Future copy trading + * + **/ ⋮---- -getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< +getFuturesLeadTraderStatus(): Promise ⋮---- -getDelegationHistory( - params: DelegationHistoryParams, -): Promise> +getFuturesLeadTradingSymbolWhitelist(): Promise< + GetFuturesLeadTradingSymbolWhitelistResponse[] + > { + return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); ⋮---- /** * - * Futures Management Endpoints: - * https://binance-docs.github.io/apidocs/spot/en/#futures - * - * Note: to trade futures use the usdm-client or coinm-client. - * MainClient only has the futures endpoints listed in the "spot" docs category, primarily used for transfers. + * MINING Endpoints - rest api * **/ ⋮---- -/** - * Execute transfer between spot account and futures account. - * - * Type: - * - 1: transfer from spot account to USDT-Ⓜ futures account. - * - 2: transfer from USDT-Ⓜ futures account to spot account. - * - 3: transfer from spot account to COIN-Ⓜ futures account. - * - 4: transfer from COIN-Ⓜ futures account to spot account. - */ +getMiningAlgos(): Promise ⋮---- -/** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead - */ -submitNewFutureAccountTransfer( - params: NewFutureAccountTransferParams, -): Promise< +getMiningCoins(): Promise ⋮---- -/** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead - */ -getFutureAccountTransferHistory( - params: GetFutureAccountTransferHistoryParams, -): Promise> +getHashrateResales( + params: GetHashrateResaleListParams, +): Promise ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise +getMiners(params: GetMinerListParams): Promise ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise +getMinerDetails( + params: GetMinerDetailsParams, +): Promise ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralWalletV2(): Promise +getExtraBonuses( + params: GetExtraBonusListParams, +): Promise ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getAdjustCrossCollateralLTVHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +getMiningEarnings( + params: GetEarningsListParams, +): Promise ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralLiquidationHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +cancelHashrateResaleConfig( + params: CancelHashrateResaleConfigParams, +): Promise ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralInterestHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +getHashrateResale( + params: GetHashrateResaleDetailParams, +): Promise +⋮---- +getMiningAccountEarnings( + params: GetMiningAccountEarningParams, +): Promise +⋮---- +getMiningStatistics( + params: GetStatisticListParams, +): Promise +⋮---- +submitHashrateResale(params: SubmitHashrateResaleParams): Promise +⋮---- +getMiningAccounts( + params: getMiningAccountsListParams, +): Promise ⋮---- /** * - * WALLET Endpoints - Account endpoints + * ALGO TRADING Endpoints - Future algo * **/ ⋮---- -getAccountInfo(): Promise -⋮---- -getDailyAccountSnapshot( - params: DailyAccountSnapshotParams, -): Promise +submitVpNewOrder( + params: SubmitVpNewOrderParams, +): Promise ⋮---- -disableFastWithdrawSwitch(): Promise +submitTwapNewOrder( + params: SubmitTwapNewOrderParams, +): Promise ⋮---- -enableFastWithdrawSwitch(): Promise +cancelAlgoOrder(params: { + algoId: number; +}): Promise ⋮---- -getAccountStatus(): Promise< +getAlgoSubOrders( + params: GetAlgoSubOrdersParams, +): Promise ⋮---- -getApiTradingStatus(): Promise +getAlgoOpenOrders(): Promise< ⋮---- -getApiKeyPermissions(): Promise +getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< ⋮---- /** * - * WALLET Endpoints - Travel Rule endpoints + * ALGO TRADING Endpoints - Spot algo * **/ ⋮---- -/** - * Submit a withdrawal request for local entities that require travel rule - * - * For questionaire format, please refer to the docs: - * https://developers.binance.com/docs/wallet/travel-rule/withdraw-questionnaire - */ -withdrawTravelRule(params: WithdrawTravelRuleParams): Promise< +submitSpotAlgoTwapOrder( + params: SubmitSpotTwapNewOrderParams, +): Promise ⋮---- -/** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistory( - params?: GetTravelRuleWithdrawHistoryParams, -): Promise +cancelSpotAlgoOrder(params: { + algoId: number; +}): Promise ⋮---- -/** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistoryV2( - params?: GetTravelRuleWithdrawHistoryV2Params, -): Promise +getSpotAlgoSubOrders( + params: GetSpotAlgoSubOrdersParams, +): Promise +⋮---- +getSpotAlgoOpenOrders(): Promise< +⋮---- +getSpotAlgoHistoricalOrders( + params: GetSpotAlgoHistoricalOrdersParams, +): Promise< ⋮---- /** - * Submit questionnaire for local entities that require travel rule * - * for questionaire format, please refer to the docs: - * https://developers.binance.com/docs/wallet/travel-rule/deposit-questionnaire - */ -submitTravelRuleDepositQuestionnaire( - params: SubmitTravelRuleDepositQuestionnaireParams, -): Promise + * CRYPTO LOAN Endpoints - Flexible rate - Market data + * + **/ ⋮---- -/** - * Fetch deposit history for local entities that require travel rule - */ -getTravelRuleDepositHistory( - params?: GetTravelRuleDepositHistoryParams, -): Promise +getCryptoLoanFlexibleCollateralAssets(params: { + collateralCoin?: string; +}): Promise< ⋮---- -/** - * Fetch the onboarded VASP list for local entities that require travel rule. - * Use the `identifier` field (not vaspCode) for the `vasp` param in deposit/withdrawal questionnaires. - * Both vaspCode and identifier accepted until 28 May 2026. - */ -getOnboardedVASPList(): Promise +getCryptoLoanFlexibleAssets(params: ⋮---- /** * - * WALLET Endpoints - Other endpoints + * CRYPTO LOAN Endpoints - Flexible rate - Trade * **/ ⋮---- -getSystemStatus(): Promise +borrowCryptoLoanFlexible( + params: BorrowFlexibleLoanParams, +): Promise ⋮---- -getDelistSchedule(): Promise +repayCryptoLoanFlexible( + params: RepayCryptoFlexibleLoanParams, +): Promise +⋮---- +repayCryptoLoanFlexibleWithCollateral( + params: RepayCryptoLoanFlexibleWithCollateralParams, +): Promise +⋮---- +adjustCryptoLoanFlexibleLTV( + params: AdjustFlexibleCryptoLoanLTVParams, +): Promise ⋮---- /** * - * SUB ACCOUNT Endpoints - Account management + * CRYPTO LOAN Endpoints - Flexible rate - User info * **/ ⋮---- -createVirtualSubAccount( - params: CreateSubAccountParams, -): Promise +getCryptoLoanFlexibleLTVAdjustmentHistory( + params: GetFlexibleLoanLTVAdjustmentHistoryParams, +): Promise< ⋮---- -getSubAccountList( - params?: SubAccountListParams, -): Promise +getFlexibleLoanCollateralRepayRate(params: { + loanCoin: string; + collateralCoin: string; +}): Promise< +⋮---- +getLoanFlexibleBorrowHistory( + params: GetFlexibleCryptoLoanBorrowHistoryParams, +): Promise< +⋮---- +getCryptoLoanFlexibleOngoingOrders( + params: GetFlexibleLoanOngoingOrdersParams, +): Promise< +⋮---- +getFlexibleLoanLiquidationHistory( + params?: GetFlexibleLoanLiquidationHistoryParams, +): Promise< +⋮---- +getLoanFlexibleRepaymentHistory( + params: GetLoanRepaymentHistoryParams, +): Promise< ⋮---- -subAccountEnableFutures(email: string): Promise +/** + * + * CRYPTO LOAN Endpoints - Stable rate - Market data + * + **/ ⋮---- /** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. + * @deprecated */ -subAccountEnableMargin(email: string): Promise +getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< ⋮---- -enableOptionsForSubAccount(params: { - email: string; -}): Promise +getCryptoLoanCollateralRepayRate( + params: CheckCollateralRepayRateParams, +): Promise ⋮---- /** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. + * @deprecated */ -subAccountEnableLeverageToken( - params: SubAccountEnableLeverageToken, -): Promise -⋮---- -getSubAccountStatusOnMarginOrFutures(params?: { - email?: string; -}): Promise -⋮---- -getSubAccountFuturesPositionRisk( - email: string, -): Promise -⋮---- -getSubAccountFuturesPositionRiskV2( - params: BasicFuturesSubAccountParams, -): Promise +getCryptoLoanCollateralAssetsData( + params: GetCollateralAssetDataParams, +): Promise< ⋮---- -getSubAccountTransactionStatistics(params: { - email: string; -}): Promise +getCryptoLoansIncomeHistory( + params: GetCryptoLoansIncomeHistoryParams, +): Promise ⋮---- /** * - * SUB ACCOUNT Endpoints - API management + * CRYPTO LOAN Endpoints - Stable rate - Trade * **/ ⋮---- -getSubAccountIPRestriction( - params: BasicSubAccount, -): Promise -⋮---- -subAccountDeleteIPList( - params: SubAccountAddOrDeleteIPList, -): Promise +/** + * @deprecated + */ +borrowCryptoLoan( + params: BorrowCryptoLoanParams, +): Promise ⋮---- -subAccountAddIPRestriction( - params: AddIpRestriction, -): Promise +/** + * @deprecated + */ +repayCryptoLoan( + params: RepayCryptoLoanParams, +): Promise ⋮---- /** * @deprecated - * Use subAccountAddIPRestriction instead - **/ -subAccountAddIPList( - params: SubAccountEnableOrDisableIPRestriction, -): Promise + */ +adjustCryptoLoanLTV( + params: AdjustCryptoLoanLTVParams, +): Promise ⋮---- /** * @deprecated - * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList - **/ -subAccountEnableOrDisableIPRestriction( - params: EnableOrDisableIPRestrictionForSubAccountParams, -): Promise + */ +customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< ⋮---- /** * - * SUB ACCOUNT Endpoints - Asset management + * CRYPTO LOAN Endpoints - Stable rate - User info * **/ ⋮---- -subAccountFuturesTransfer( - params: SubAccountTransferParams, -): Promise -⋮---- -getSubAccountFuturesAccountDetail( - email: string, -): Promise +/** + * @deprecated + */ +getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< ⋮---- -getSubAccountDetailOnFuturesAccountV2( - params: BasicFuturesSubAccountParams, -): Promise +getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< ⋮---- -getSubAccountDetailOnMarginAccount( - email: string, -): Promise +getCryptoLoanLTVAdjustmentHistory( + params: GetLoanLTVAdjustmentHistoryParams, +): Promise< ⋮---- -getSubAccountDepositAddress( - params: SubAccountDepositAddressParams, -): Promise +getCryptoLoanRepaymentHistory( + params: GetLoanRepaymentHistoryParams, +): Promise ⋮---- -getSubAccountDepositHistory( - params: SubAccountDepositHistoryParams, -): Promise +/** + * + * SIMPLE EARN Endpoints - Account + * + **/ ⋮---- -getSubAccountFuturesAccountSummary(): Promise +getSimpleEarnAccount(): Promise ⋮---- -getSubAccountSummaryOnFuturesAccountV2( - params: SubAccountSummaryOnFuturesAccountV2Params, -): Promise +getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< ⋮---- -getSubAccountsSummaryOfMarginAccount(): Promise +getSimpleEarnLockedProductList( + params?: SimpleEarnProductListParams, +): Promise< ⋮---- -subAccountMarginTransfer( - params: SubAccountTransferParams, -): Promise +getFlexibleProductPosition( + params?: SimpleEarnFlexibleProductPositionParams, +): Promise< ⋮---- -getSubAccountAssets( - params: SubAccountAssetsParams, -): Promise +getLockedProductPosition( + params?: SimpleEarnLockedProductPositionParams, +): Promise< ⋮---- -getSubAccountAssetsMaster(params: +getFlexiblePersonalLeftQuota(params: ⋮---- -getSubAccountFuturesAssetTransferHistory( - params: SubAccountFuturesAssetTransferHistoryParams, -): Promise +getLockedPersonalLeftQuota(params: ⋮---- -getSubAccountSpotAssetTransferHistory( - params?: SubAccountSpotAssetTransferHistoryParams, -): Promise +/** + * + * SIMPLE EARN Endpoints - Earn + * + **/ ⋮---- -getSubAccountSpotAssetsSummary( - params?: SubAccountSpotAssetsSummaryParams, -): Promise +purchaseFlexibleProduct( + params: SimpleEarnSubscribeProductParams, +): Promise ⋮---- -getSubAccountUniversalTransferHistory( - params?: SubAccountUniversalTransferHistoryParams, -): Promise +subscribeSimpleEarnLockedProduct( + params: SimpleEarnSubscribeProductParams, +): Promise ⋮---- -subAccountFuturesAssetTransfer( - params: SubAccountFuturesAssetTransferParams, -): Promise +redeemFlexibleProduct( + params: SimpleEarnRedeemFlexibleProductParams, +): Promise ⋮---- -subAccountTransferHistory( - params?: SubAccountTransferHistoryParams, -): Promise +redeemLockedProduct(params: { + positionId: string; +}): Promise ⋮---- -subAccountTransferToMaster( - params: SubAccountTransferToMasterParams, -): Promise +setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< ⋮---- -subAccountTransferToSameMaster( - params: SubAccountTransferToSameMasterParams, -): Promise +setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< ⋮---- -subAccountUniversalTransfer( - params: SubAccountUniversalTransferParams, -): Promise +getFlexibleSubscriptionPreview( + params: GetFlexibleSubscriptionPreviewParams, +): Promise ⋮---- -subAccountMovePosition( - params: SubAccountMovePositionParams, -): Promise< +getLockedSubscriptionPreview( + params: GetLockedSubscriptionPreviewParams, +): Promise ⋮---- -getSubAccountFuturesPositionMoveHistory( - params: SubAccountMovePositionHistoryParams, -): Promise< +setLockedProductRedeemOption(params: { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; +}): Promise< ⋮---- /** * - * SUB ACCOUNT Endpoints - Managed Sub Account + * SIMPLE EARN Endpoints - History * **/ ⋮---- -depositAssetsIntoManagedSubAccount( - params: SubAccountTransferToSameMasterParams, -): Promise -⋮---- -getManagedSubAccountDepositAddress( - params: ManagedSubAccountDepositAddressParams, -): Promise -⋮---- -withdrawAssetsFromManagedSubAccount( - params: WithdrawAssetsFromManagedSubAccountParams, -): Promise -⋮---- -getManagedSubAccountTransfersParent( - params: ManagedSubAccountTransferLogParams, +getFlexibleSubscriptionRecord( + params: GetFlexibleSubscriptionRecordParams, ): Promise< ⋮---- -getManagedSubAccountTransferLog( - params: ManagedSubAccountTransferTTLogParams, +getLockedSubscriptionRecord( + params: GetLockedSubscriptionRecordParams, ): Promise< ⋮---- -getManagedSubAccountTransfersInvestor( - params: ManagedSubAccountTransferLogParams, +getFlexibleRedemptionRecord( + params: GetFlexibleRedemptionRecordParams, ): Promise< ⋮---- -getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< +getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< ⋮---- -getManagedSubAccountSnapshot( - params: ManagedSubAccountSnapshotParams, -): Promise +getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< ⋮---- -getManagedSubAccountAssetDetails( - email: string, -): Promise +getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< ⋮---- -getManagedSubAccountMarginAssets(params: { - email: string; - accountType?: string; -}): Promise +getCollateralRecord(params: GetCollateralRecordParams): Promise< ⋮---- -getManagedSubAccountFuturesAssets(params: { - email: string; - accountType?: string; -}): Promise +getRateHistory(params: GetRateHistoryParams): Promise< ⋮---- /** * - * AUTO INVEST Endpoints - Market data + * VIP LOAN Endpoints - Market Data * **/ ⋮---- -getAutoInvestAssets(): Promise< -⋮---- -getAutoInvestSourceAssets( - params: GetSourceAssetListParams, -): Promise -⋮---- -getAutoInvestTargetAssets( - params: GetTargetAssetListParams, -): Promise +getVipBorrowInterestRate(params: { + loanCoin: string; +}): Promise ⋮---- -getAutoInvestTargetAssetsROI( - params: GetTargetAssetROIParams, -): Promise +getVipLoanInterestRateHistory( + params: VipLoanInterestRateHistoryParams, +): Promise< ⋮---- -getAutoInvestIndex(params: { - indexId: number; -}): Promise +getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< ⋮---- -getAutoInvestPlans(params: { - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; -}): Promise +getVipCollateralAssets(params: ⋮---- /** * - * AUTO INVEST Endpoints - Trade + * VIP LOAN Endpoints - User Info * **/ ⋮---- -/** - * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction - * - * @param params - * @returns - */ -submitAutoInvestOneTimeTransaction( - params: SubmitOneTimeTransactionParams, -): Promise -⋮---- -updateAutoInvestPlanStatus( - params: ChangePlanStatusParams, -): Promise -⋮---- -updateAutoInvestmentPlan( - params: EditInvestmentPlanParams, -): Promise +getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< ⋮---- -submitAutoInvestRedemption( - params: SubmitIndexLinkedPlanRedemptionParams, +getVipLoanRepaymentHistory( + params: GetVipLoanRepaymentHistoryParams, ): Promise< ⋮---- -getAutoInvestSubscriptionTransactions( - params: GetSubscriptionTransactionHistoryParams, -): Promise +checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< ⋮---- -getOneTimeTransactionStatus( - params: GetOneTimeTransactionStatusParams, -): Promise +getVipApplicationStatus(params: GetApplicationStatusParams): Promise< ⋮---- -submitAutoInvestmentPlan( - params: CreateInvestmentPlanParams, -): Promise +/** + * + * VIP LOAN Endpoints - Trade + * + **/ ⋮---- -getAutoInvestRedemptionHistory( - params: GetIndexLinkedPlanRedemptionHistoryParams, -): Promise +renewVipLoan(params: VipLoanRenewParams): Promise ⋮---- -getAutoInvestPlan(params: GetPlanDetailsParams): Promise +repayVipLoan(params: VipLoanRepayParams): Promise ⋮---- -getAutoInvestUserIndex(params: { - indexId: number; -}): Promise +borrowVipLoan(params: VipLoanBorrowParams): Promise ⋮---- -getAutoInvestRebalanceHistory( - params: GetIndexLinkedPlanRebalanceHistoryParams, -): Promise +getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise< +⋮---- +borrowVipLoanFixedRate( + params: VipLoanFixedRateBorrowParams, +): Promise ⋮---- /** * - * CONVERT Endpoints - Market Data + * DUAL INVESTMENT Endpoints - Market Data * **/ ⋮---- -getConvertPairs(params: GetAllConvertPairsParams): Promise -⋮---- -getConvertAssetInfo(): Promise +getDualInvestmentProducts( + params: GetDualInvestmentProductListParams, +): Promise< ⋮---- /** * - * CONVERT Endpoints - Trade + * DUAL INVESTMENT Endpoints - Trade * **/ ⋮---- -convertQuoteRequest(params: ConvertQuoteRequestParams): Promise -⋮---- -acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise -⋮---- -getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise +subscribeDualInvestmentProduct( + params: SubscribeDualInvestmentProductParams, +): Promise ⋮---- -getOrderStatus(params: GetOrderStatusParams): Promise +getDualInvestmentPositions( + params: GetDualInvestmentPositionsParams, +): Promise< ⋮---- -submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise +getDualInvestmentAccounts(): Promise ⋮---- -cancelConvertLimitOrder(params: +getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< ⋮---- -getConvertLimitOpenOrders(): Promise< +updateAutoCompoundStatus( + params: ChangeAutoCompoundStatusParams, +): Promise ⋮---- /** * - * STAKING Endpoints - ETH Staking - Account + * GIFT CARD Endpoints - Market Data * **/ ⋮---- -/** - * @deprecated use getEthStakingAccountV2 instead - **/ -getEthStakingAccount(): Promise +createGiftCard(params: CreateGiftCardParams): Promise ⋮---- -getEthStakingAccountV2(): Promise +createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise ⋮---- -getEthStakingQuota(): Promise +redeemGiftCard(params: RedeemGiftCardParams): Promise +⋮---- +verifyGiftCard(params: +⋮---- +getTokenLimit(params: +⋮---- +getRsaPublicKey(): Promise ⋮---- /** * - * STAKING Endpoints - ETH Staking- Staking + * NFT Endpoints - REST api * **/ ⋮---- -/** - * @deprecated use subscribeEthStakingV2 instead - **/ -subscribeEthStakingV1(params: +getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< ⋮---- -subscribeEthStakingV2(params: { - amount: number; -}): Promise +getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< ⋮---- -redeemEth(params: RedeemEthParams): Promise +getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< ⋮---- -wrapBeth(params: +getNftAsset(params: GetNftAssetParams): Promise< ⋮---- /** * - * STAKING Endpoints - ETH Staking - History + * C2C Endpoints * **/ ⋮---- -getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< +getC2CTradeHistory( + params: GetC2CTradeHistoryParams, +): Promise ⋮---- -getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< +/** + * + * FIAT Endpoints - REST api + * + **/ ⋮---- -getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< +getFiatOrderHistory( + params: GetFiatOrderHistoryParams, +): Promise ⋮---- -getWbethRewardsHistory( - params: GetWrapHistoryParams, -): Promise +getFiatPaymentsHistory( + params: GetFiatOrderHistoryParams, +): Promise ⋮---- -getEthRateHistory(params: GetETHRateHistoryParams): Promise< +fiatWithdraw(params: WithdrawFiatParams): Promise< ⋮---- -getBethWrapHistory(params: GetWrapHistoryParams): Promise< +fiatDeposit(params: FiatDepositParams): Promise ⋮---- -getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< +getFiatOrderDetail( + params: GetFiatOrderDetailParams, +): Promise ⋮---- /** * - * BFUSD (sapi/v1/bfusd) + * Rebate Endpoints * **/ ⋮---- -getBfusdAccount(): Promise -⋮---- -getBfusdQuota(): Promise -⋮---- -subscribeBfusd( - params: BfusdSubscribeParams, -): Promise +getSpotRebateHistoryRecords( + params: GetSpotRebateHistoryRecordsParams, +): Promise ⋮---- -redeemBfusd(params: BfusdRedeemParams): Promise +/** + * + * DERIVATIVES - Portfolio Margin Pro - Market Data + * This is in mainclient because it shares the same base url + * + **/ ⋮---- -getBfusdSubscriptionHistory( - params: GetBfusdSubscriptionHistoryParams, -): Promise< +getPortfolioMarginIndexPrice(params?: { + asset?: string; +}): Promise ⋮---- -getBfusdRedemptionHistory( - params: GetBfusdRedemptionHistoryParams, -): Promise< +getPortfolioMarginAssetLeverage(): Promise< + GetPortfolioMarginAssetLeverageResponse[] + > { + return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); ⋮---- -getBfusdRewardsHistory( - params: GetBfusdRewardsHistoryParams, -): Promise< +getPortfolioMarginProCollateralRate(): Promise< + GetPortfolioMarginProCollateralRateResponse[] + > { + return this.get('sapi/v1/portfolio/collateralRate'); ⋮---- -getBfusdRateHistory( - params: GetBfusdRateHistoryParams, -): Promise< +getPortfolioMarginProTieredCollateralRate(): Promise ⋮---- /** * - * RWUSD (sapi/v1/rwusd) + * DERIVATIVES - Portfolio Margin Pro - Account + * This is in mainclient because it shares the same base url * **/ ⋮---- -getRwusdAccount(): Promise +getPortfolioMarginProAccountInfo(): Promise ⋮---- -getRwusdQuota(): Promise +setPortfolioMarginMarginCallLevel( + params: SetPortfolioMarginMarginCallLevelParams, +): Promise ⋮---- -subscribeRwusd( - params: RwusdSubscribeParams, -): Promise +getPortfolioMarginMarginCallLevel(): Promise ⋮---- -redeemRwusd(params: RwusdRedeemParams): Promise +deletePortfolioMarginMarginCallLevel(): Promise ⋮---- -getRwusdSubscriptionHistory( - params: GetRwusdSubscriptionHistoryParams, -): Promise< +bnbTransfer(params: BnbTransferParams): Promise< ⋮---- -getRwusdRedemptionHistory( - params: GetRwusdRedemptionHistoryParams, -): Promise< +submitPortfolioMarginProFullTransfer(): Promise< +⋮---- +submitPortfolioMarginProSpecificTransfer(params: +⋮---- +repayPortfolioMarginProBankruptcyLoan(params: { + from?: 'SPOT' | 'MARGIN'; +}): Promise< +⋮---- +getPortfolioMarginProBankruptcyLoanAmount(): Promise +⋮---- +repayFuturesNegativeBalance(): Promise< +⋮---- +updateAutoRepayFuturesStatus(params: +⋮---- +getAutoRepayFuturesStatus(): Promise< +⋮---- +getPortfolioMarginProInterestHistory( + params: GetPortfolioMarginProInterestHistoryParams, +): Promise ⋮---- -getRwusdRewardsHistory( - params: GetRwusdRewardsHistoryParams, -): Promise< +getPortfolioMarginProSpanAccountInfo(): Promise ⋮---- -getRwusdRateHistory( - params: GetRwusdRateHistoryParams, -): Promise< +getPortfolioMarginProAccountBalance(params?: { + asset?: string; +}): Promise ⋮---- /** - * @deprecated as of 2024-01-19 + * @deprecated + * Check Simple Earn endpoints for new way of doing it */ -getStakingProducts( - params: StakingBasicParams & { - asset?: string; - }, -): Promise +mintPortfolioMarginBFUSD( + params: PMProMintBFUSDParams, +): Promise ⋮---- /** - * @deprecated as of 2024-01-19 + * @deprecated + * Check Simple Earn endpointsfor new way of doing it */ -getStakingProductPosition( - params: StakingBasicParams & { - productId?: string; - asset?: string; - }, -): Promise +redeemPortfolioMarginBFUSD(params: { + fromAsset: string; // BFUSD only + targetAsset: string; // USDT only + amount: number; +}): Promise ⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingHistory(params: StakingHistoryParams): Promise +fromAsset: string; // BFUSD only +targetAsset: string; // USDT only +⋮---- +getPortfolioMarginBankruptcyLoanRepayHistory(params?: { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +}): Promise< ⋮---- /** - * @deprecated as of 2024-01-19 + * Transfer LDUSDT as collateral for all types of Portfolio Margin account */ -getPersonalLeftQuotaOfStakingProduct(params: { - product: StakingProductType; - productId: string; -}): Promise +transferLDUSDTPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; + amount: number; +}): Promise< ⋮---- /** - * - * STAKING Endpoints - SOL Staking- Account - * - **/ -⋮---- -getSolStakingAccount(): Promise -⋮---- -getSolStakingQuota(): Promise + * Get transferable earn asset balance for all types of Portfolio Margin account + */ +getTransferableEarnAssetBalanceForPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; +}): Promise< ⋮---- /** * - * STAKING Endpoints - SOL Staking - Staking + * DERIVATIVES - Futures Data - Market + * This is in mainclient because it shares the same base url * **/ ⋮---- -subscribeSolStaking(params: { - amount: number; -}): Promise -⋮---- -redeemSol(params: -⋮---- -claimSolBoostRewards(): Promise< +getFuturesTickLevelOrderbookDataLink( + params: GetFutureTickLevelOrderbookDataLinkParams, +): Promise< ⋮---- /** * - * STAKING Endpoints - SOL Staking- History - * + * BLVT Endpoints + * BLVT category is possibly @deprecated, found only in old docs **/ ⋮---- -getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< +getBlvtInfo(params?: ⋮---- -getSolRedemptionHistory(params?: { - rows: SolRedemptionHistoryRecord[]; - total: number; -}): Promise +subscribeBlvt(params: SubscribeBlvtParams): Promise ⋮---- -getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< +getBlvtSubscriptionRecord( + params: GetBlvtSubscriptionRecordParams, +): Promise ⋮---- -getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< +redeemBlvt(params: RedeemBlvtParams): Promise ⋮---- -getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< +getBlvtRedemptionRecord( + params: GetBlvtRedemptionRecordParams, +): Promise ⋮---- -getSolUnclaimedRewards(): Promise< - { - amount: string; - rewardsAsset: string; - }[] - > { - return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); +getBlvtUserLimitInfo(params: { + tokenName?: string; +}): Promise ⋮---- /** * - * STAKING - Onchain Yields - Account - * + * Pay endpoints + * Found only in old docs, possibly @deprecated **/ -⋮---- -getOnchainYieldsLockedProducts( - params?: OnchainYieldsLockedProductListParams, -): Promise -⋮---- -getOnchainYieldsLockedPersonalLeftQuota( - params: OnchainYieldsLockedPersonalLeftQuotaParams, -): Promise -⋮---- -getOnchainYieldsLockedPosition( - params?: OnchainYieldsLockedPositionParams, -): Promise -⋮---- -getOnchainYieldsAccount(): Promise +getPayTransactions(params: GetPayTradeHistoryParams): Promise ⋮---- /** * - * STAKING - Onchain Yields - Earn + * INSTITUTIONAL LOAN - Account Endpoints * **/ ⋮---- -getOnchainYieldsLockedSubscriptionPreview( - params: OnchainYieldsLockedSubscriptionPreviewParams, -): Promise -⋮---- -subscribeOnchainYieldsLockedProduct( - params: OnchainYieldsLockedSubscribeParams, -): Promise -⋮---- -setOnchainYieldsLockedAutoSubscribe( - params: OnchainYieldsLockedSetAutoSubscribeParams, -): Promise -⋮---- -setOnchainYieldsLockedRedeemOption( - params: OnchainYieldsLockedSetRedeemOptionParams, -): Promise -⋮---- -redeemOnchainYieldsLockedProduct( - params: OnchainYieldsLockedRedeemParams, -): Promise +getInstLoanRiskUnit( + params?: GetInstitutionalLoanRiskUnitDetailsParams, +): Promise ⋮---- -/** - * - * STAKING - Onchain Yields - History - * - **/ +closeInstLoanRiskUnit(): Promise ⋮---- -getOnchainYieldsLockedSubscriptionRecord( - params?: OnchainYieldsLockedSubscriptionRecordParams, -): Promise +addInstLoanCollateralAccount( + params: AddInstitutionalLoanCollateralAccountParams, +): Promise ⋮---- -getOnchainYieldsLockedRewardsHistory( - params?: OnchainYieldsLockedRewardsHistoryParams, -): Promise +getActiveInstLoanRiskUnits(): Promise ⋮---- -getOnchainYieldsLockedRedemptionRecord( - params?: OnchainYieldsLockedRedemptionRecordParams, -): Promise +getClosedInstLoanRiskUnits( + params?: GetClosedInstitutionalLoanRiskUnitsParams, +): Promise ⋮---- /** * - * STAKING - Soft staking + * INSTITUTIONAL LOAN - Trade Endpoints * **/ ⋮---- -getSoftStakingProductList( - params?: GetSoftStakingProductListParams, -): Promise -⋮---- -setSoftStaking( - params: SetSoftStakingParams, -): Promise -⋮---- -getSoftStakingRewardsHistory( - params?: GetSoftStakingRewardsHistoryParams, -): Promise -⋮---- +getInstLoanForceLiquidationRecord( + params: GetInstitutionalLoanForceLiquidationParams, +): Promise /** * - * COPY TRADING Endpoints - Future copy trading + * INSTITUTIONAL LOAN - TransferEndpoints * **/ ⋮---- -getFuturesLeadTraderStatus(): Promise -⋮---- -getFuturesLeadTradingSymbolWhitelist(): Promise< - GetFuturesLeadTradingSymbolWhitelistResponse[] - > { - return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); +transferInstLoanRiskUnit( + params: InstitutionalLoanRiskUnitTransferParams, +): Promise ⋮---- /** * - * MINING Endpoints - rest api + * INSTITUTIONAL LOAN - Borrow/Repay Endpoints * **/ ⋮---- -getMiningAlgos(): Promise -⋮---- -getMiningCoins(): Promise -⋮---- -getHashrateResales( - params: GetHashrateResaleListParams, -): Promise -⋮---- -getMiners(params: GetMinerListParams): Promise -⋮---- -getMinerDetails( - params: GetMinerDetailsParams, -): Promise -⋮---- -getExtraBonuses( - params: GetExtraBonusListParams, -): Promise -⋮---- -getMiningEarnings( - params: GetEarningsListParams, -): Promise +getInstitutionalLoanMaxBorrowable( + params: GetInstitutionalLoanMaxBorrowableParams, +): Promise ⋮---- -cancelHashrateResaleConfig( - params: CancelHashrateResaleConfigParams, -): Promise +borrowInstitutionalLoan( + params: InstitutionalLoanBorrowParams, +): Promise ⋮---- -getHashrateResale( - params: GetHashrateResaleDetailParams, -): Promise +getInstLoanInterestHistory( + params?: GetInstitutionalLoanInterestHistoryParams, +): Promise ⋮---- -getMiningAccountEarnings( - params: GetMiningAccountEarningParams, -): Promise +repayInstitutionalLoan( + params: InstitutionalLoanRepayParams, +): Promise ⋮---- -getMiningStatistics( - params: GetStatisticListParams, -): Promise +getInstLoanBorrowRepayRecords( + params: GetInstitutionalLoanBorrowRepayRecordsParams, +): Promise ⋮---- -submitHashrateResale(params: SubmitHashrateResaleParams): Promise +getMarginInterestRebateBalance(): Promise ⋮---- -getMiningAccounts( - params: getMiningAccountsListParams, -): Promise +getMarginInterestRebateBalanceRecords( + params?: GetMarginInterestRebateBalanceRecordsParams, +): Promise ⋮---- /** * - * ALGO TRADING Endpoints - Future algo - * - **/ + * ALPHA TRADING - Market Data + * https://developers.binance.com/docs/alpha + */ ⋮---- -submitVpNewOrder( - params: SubmitVpNewOrderParams, -): Promise +getAlphaTokenList(): Promise ⋮---- -submitTwapNewOrder( - params: SubmitTwapNewOrderParams, -): Promise +getAlphaExchangeInfo(): Promise ⋮---- -cancelAlgoOrder(params: { - algoId: number; -}): Promise +getAlphaAggTrades(params: AlphaAggTradesParams): Promise ⋮---- -getAlgoSubOrders( - params: GetAlgoSubOrdersParams, -): Promise +getAlphaKlines(params: AlphaKlinesParams): Promise ⋮---- -getAlgoOpenOrders(): Promise< +getAlphaTicker(params: ⋮---- -getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< +getAlphaFullDepth( + params: AlphaFullDepthParams, +): Promise ⋮---- /** * - * ALGO TRADING Endpoints - Spot algo - * - **/ + * EXCHANGE LINK - Account Endpoints + * https://developers.binance.com/docs/binance_link + */ ⋮---- -submitSpotAlgoTwapOrder( - params: SubmitSpotTwapNewOrderParams, -): Promise +createBrokerSubAccount( + params: CreateBrokerSubAccountParams, +): Promise ⋮---- -cancelSpotAlgoOrder(params: { - algoId: number; -}): Promise +getBrokerSubAccount( + params: GetBrokerSubAccountParams, +): Promise ⋮---- -getSpotAlgoSubOrders( - params: GetSpotAlgoSubOrdersParams, -): Promise +enableMarginBrokerSubAccount( + params: EnableMarginBrokerSubAccountParams, +): Promise ⋮---- -getSpotAlgoOpenOrders(): Promise< +createApiKeyBrokerSubAccount( + params: CreateApiKeyBrokerSubAccountParams, +): Promise ⋮---- -getSpotAlgoHistoricalOrders( - params: GetSpotAlgoHistoricalOrdersParams, +changePermissionApiKeyBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, +): Promise +⋮---- +changeComissionBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, +): Promise +⋮---- +enableUniversalTransferApiKeyBrokerSubAccount( + params: EnableUniversalTransferApiKeyBrokerSubAccountParams, +): Promise +⋮---- +updateIpRestrictionForSubAccountApiKey( + params: UpdateIpRestrictionForSubApiKey, ): Promise< ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - Market data - * - **/ +deleteIPRestrictionForSubAccountApiKey(params: { + subAccountId: string; + subAccountApiKey: string; + ipAddress?: string; +}): Promise< ⋮---- -getCryptoLoanFlexibleCollateralAssets(params: { - collateralCoin?: string; +deleteApiKeyBrokerSubAccount( + params: DeleteApiKeyBrokerSubAccountParams, +): Promise +⋮---- +getSubAccountBrokerIpRestriction(params: { + subAccountId: string; + subAccountApiKey: string; }): Promise< ⋮---- -getCryptoLoanFlexibleAssets(params: +getApiKeyBrokerSubAccount( + params: GetApiKeyBrokerSubAccountParams, +): Promise ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - Trade - * - **/ +getBrokerInfo(): Promise ⋮---- -borrowCryptoLoanFlexible( - params: BorrowFlexibleLoanParams, -): Promise +updateSubAccountBNBBurn(params: { + subAccountId: string; + spotBNBBurn: 'true' | 'false'; +}): Promise< ⋮---- -repayCryptoLoanFlexible( - params: RepayCryptoFlexibleLoanParams, -): Promise +updateSubAccountMarginInterestBNBBurn(params: { + subAccountId: string; + interestBNBBurn: 'true' | 'false'; +}): Promise< ⋮---- -repayCryptoLoanFlexibleWithCollateral( - params: RepayCryptoLoanFlexibleWithCollateralParams, -): Promise +getSubAccountBNBBurnStatus(params: ⋮---- -adjustCryptoLoanFlexibleLTV( - params: AdjustFlexibleCryptoLoanLTVParams, -): Promise +/** + * Caution: + * The operation will delete a sub account under your brokerage master account. + * Please transfer out all funds from the sub account and delete API key of the sub account before deleting it. + * The deleted sub account CANNOT be reverted. + * The daily deletion limit for a broker Master is 20 sub accounts. + * You need to enable "trade" option for the api key which requests this endpoint. + */ +deleteBrokerSubAccount(params: ⋮---- /** * - * CRYPTO LOAN Endpoints - Flexible rate - User info - * - **/ + * EXCHANGE LINK - Asset Endpoints + * https://developers.binance.com/docs/binance_link + */ ⋮---- -getCryptoLoanFlexibleLTVAdjustmentHistory( - params: GetFlexibleLoanLTVAdjustmentHistoryParams, -): Promise< +transferBrokerSubAccount( + params: TransferBrokerSubAccountParams, +): Promise ⋮---- -getFlexibleLoanCollateralRepayRate(params: { - loanCoin: string; - collateralCoin: string; +getBrokerSubAccountHistory( + params: GetBrokerSubAccountHistoryParams, +): Promise +⋮---- +submitBrokerSubFuturesTransfer(params: { + fromId?: string; + toId?: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + asset: string; + amount: number; + clientTranId?: string; // The max length is 32 characters }): Promise< ⋮---- -getLoanFlexibleBorrowHistory( - params: GetFlexibleCryptoLoanBorrowHistoryParams, -): Promise< +futuresType: number; // 1: USDT Futures, 2: COIN Futures ⋮---- -getCryptoLoanFlexibleOngoingOrders( - params: GetFlexibleLoanOngoingOrdersParams, +clientTranId?: string; // The max length is 32 characters +⋮---- +getSubAccountFuturesTransferHistory(params: { + subAccountId: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +}): Promise +⋮---- +futuresType: number; // 1: USDT Futures, 2: COIN Futures +⋮---- +getBrokerSubDepositHistory( + params: GetSubAccountDepositHistoryParams, +): Promise +⋮---- +getBrokerSubAccountSpotAssets( + params: QuerySubAccountSpotMarginAssetInfoParams, ): Promise< ⋮---- -getFlexibleLoanLiquidationHistory( - params?: GetFlexibleLoanLiquidationHistoryParams, +getSubAccountMarginAssetInfo( + params: QuerySubAccountSpotMarginAssetInfoParams, ): Promise< ⋮---- -getLoanFlexibleRepaymentHistory( - params: GetLoanRepaymentHistoryParams, +querySubAccountFuturesAssetInfo( + params: QuerySubAccountFuturesAssetInfoParams, ): Promise< ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - Market data - * - **/ +universalTransferBroker(params: UniversalTransferBrokerParams): Promise< +⋮---- +getUniversalTransferBroker( + params: GetUniversalTransferBrokerParams, +): Promise ⋮---- /** - * @deprecated + * + * EXCHANGE LINK - Fee Endpoints + * https://developers.binance.com/docs/binance_link */ -getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< ⋮---- -getCryptoLoanCollateralRepayRate( - params: CheckCollateralRepayRateParams, -): Promise +updateBrokerSubAccountCommission( + params: ChangeSubAccountCommissionParams, +): Promise ⋮---- -/** - * @deprecated - */ -getCryptoLoanCollateralAssetsData( - params: GetCollateralAssetDataParams, -): Promise< +updateBrokerSubAccountFuturesCommission( + params: ChangeSubAccountFuturesCommissionParams, +): Promise ⋮---- -getCryptoLoansIncomeHistory( - params: GetCryptoLoansIncomeHistoryParams, -): Promise +getBrokerSubAccountFuturesCommission( + params: QuerySubAccountFuturesCommissionParams, +): Promise ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - Trade - * - **/ +updateBrokerSubAccountCoinFuturesCommission( + params: ChangeSubAccountCoinFuturesCommissionParams, +): Promise +⋮---- +getBrokerSubAccountCoinFuturesCommission( + params: QuerySubAccountCoinFuturesCommissionParams, +): Promise +⋮---- +getBrokerSpotCommissionRebate( + params: QueryBrokerSpotCommissionRebateParams, +): Promise +⋮---- +getBrokerFuturesCommissionRebate( + params: QueryBrokerFuturesCommissionRebateParams, +): Promise ⋮---- /** + * * @deprecated */ -borrowCryptoLoan( - params: BorrowCryptoLoanParams, -): Promise +// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) +getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) ⋮---- /** - * @deprecated + * Broker Endpoints - only on old docs + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link */ -repayCryptoLoan( - params: RepayCryptoLoanParams, -): Promise ⋮---- /** - * @deprecated - */ -adjustCryptoLoanLTV( - params: AdjustCryptoLoanLTVParams, -): Promise + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerIfNewSpotUser(): Promise< ⋮---- /** - * @deprecated - */ -customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerSubAccountDepositHistory( + params?: GetBrokerSubAccountDepositHistoryParams, +): Promise ⋮---- /** - * - * CRYPTO LOAN Endpoints - Stable rate - User info - * + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead **/ +getBrokerUserCustomisedId(market: 'spot' | 'futures') ⋮---- /** - * @deprecated - */ -getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< -⋮---- -getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableFuturesBrokerSubAccount( + params: EnableFuturesBrokerSubAccountParams, +): Promise ⋮---- -getCryptoLoanLTVAdjustmentHistory( - params: GetLoanLTVAdjustmentHistoryParams, -): Promise< +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableMarginApiKeyBrokerSubAccount( + params: EnableMarginApiKeyBrokerSubAccountParams, +): Promise ⋮---- -getCryptoLoanRepaymentHistory( - params: GetLoanRepaymentHistoryParams, -): Promise +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewSpotOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams + | NewOrderListParams, + orderIdProperty: OrderIdProperty, +): void ⋮---- /** * - * SIMPLE EARN Endpoints - Account + * User Data Stream Endpoints * **/ ⋮---- -getSimpleEarnAccount(): Promise -⋮---- -getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< -⋮---- -getSimpleEarnLockedProductList( - params?: SimpleEarnProductListParams, -): Promise< -⋮---- -getFlexibleProductPosition( - params?: SimpleEarnFlexibleProductPositionParams, -): Promise< -⋮---- -getLockedProductPosition( - params?: SimpleEarnLockedProductPositionParams, -): Promise< +// spot +getSpotUserDataListenKey(): Promise< ⋮---- -getFlexiblePersonalLeftQuota(params: +keepAliveSpotUserDataListenKey(listenKey: string): Promise ⋮---- -getLockedPersonalLeftQuota(params: +closeSpotUserDataListenKey(listenKey: string): Promise ⋮---- /** - * - * SIMPLE EARN Endpoints - Earn - * - **/ + * Get a cross margin user data listen key + */ +getMarginUserDataListenKey(): Promise< ⋮---- -purchaseFlexibleProduct( - params: SimpleEarnSubscribeProductParams, -): Promise +keepAliveMarginUserDataListenKey(listenKey: string): Promise ⋮---- -subscribeSimpleEarnLockedProduct( - params: SimpleEarnSubscribeProductParams, -): Promise +closeMarginUserDataListenKey(listenKey: string): Promise ⋮---- -redeemFlexibleProduct( - params: SimpleEarnRedeemFlexibleProductParams, -): Promise +// isolated margin +getIsolatedMarginUserDataListenKey(params: { + symbol: string; +}): Promise< ⋮---- -redeemLockedProduct(params: { - positionId: string; -}): Promise +keepAliveIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; +}): Promise ⋮---- -setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< +closeIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; +}): Promise ⋮---- -setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< +/** + * Get a cross margin risk data listen key + */ +getMarginRiskUserDataListenKey(): Promise< ⋮---- -getFlexibleSubscriptionPreview( - params: GetFlexibleSubscriptionPreviewParams, -): Promise +keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise ⋮---- -getLockedSubscriptionPreview( - params: GetLockedSubscriptionPreviewParams, -): Promise +closeMarginRiskUserDataListenKey(): Promise ⋮---- -setLockedProductRedeemOption(params: { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; +/** + * Get/create margin account listenToken for the user data stream + * https://developers.binance.com/docs/margin_trading/trade-data-stream + */ +getMarginListenToken(params?: { + symbol?: string; + isIsolated?: boolean; + validity?: number; }): Promise< ⋮---- /** * - * SIMPLE EARN Endpoints - History + * DEPRECATED ENDPOINTS * **/ -⋮---- -getFlexibleSubscriptionRecord( - params: GetFlexibleSubscriptionRecordParams, -): Promise< -⋮---- -getLockedSubscriptionRecord( - params: GetLockedSubscriptionRecordParams, -): Promise< -⋮---- -getFlexibleRedemptionRecord( - params: GetFlexibleRedemptionRecordParams, -): Promise< -⋮---- -getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< -⋮---- -getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< -⋮---- -getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< -⋮---- -getCollateralRecord(params: GetCollateralRecordParams): Promise< -⋮---- -getRateHistory(params: GetRateHistoryParams): Promise< -⋮---- /** * - * VIP LOAN Endpoints - Market Data - * + * BSwap Endpoints + * @deprecated as of 2024-01-19 **/ ⋮---- -getVipBorrowInterestRate(params: { - loanCoin: string; -}): Promise +/** + * @deprecated as of 2024-01-19 + **/ +getBSwapLiquidity(params?: ⋮---- -getVipLoanInterestRateHistory( - params: VipLoanInterestRateHistoryParams, -): Promise< +/** + * @deprecated as of 2024-01-19 + **/ +addBSwapLiquidity(params: AddBSwapLiquidityParams): Promise< ⋮---- -getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +/** + * @deprecated as of 2024-01-19 + **/ +removeBSwapLiquidity(params: RemoveBSwapLiquidityParams): Promise< ⋮---- -getVipCollateralAssets(params: +/** + * @deprecated as of 2024-01-19 + **/ +getBSwapOperations( + params?: BSwapOperationsParams, +): Promise ⋮---- /** * - * VIP LOAN Endpoints - User Info - * + * Savings Endpoints + * @deprecated as of 2023-06-22, now Simple Earn **/ ⋮---- -getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyPurchaseQuotaFlexibleProduct(params: { + productId: string; +}): Promise ⋮---- -getVipLoanRepaymentHistory( - params: GetVipLoanRepaymentHistoryParams, -): Promise< +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyRedemptionQuotaFlexibleProduct(params: { + productId: string; + }): Promise< + LeftDailyPurchaseQuotaFlexibleProductResponse & { + dailyQuota: string; + minRedemptionAmount: string; + } + > { + return this.getPrivate('sapi/v1/lending/daily/userRedemptionQuota', params); ⋮---- -checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +purchaseFixedAndActivityProject(params: { + projectId: string; + lot: number; +}): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProjects( + params: FixedAndActivityProjectParams, +): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProductPosition( + params: FixedAndActivityProjectPositionParams, +): Promise ⋮---- -getVipApplicationStatus(params: GetApplicationStatusParams): Promise< +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLendingAccount(): Promise ⋮---- /** - * - * VIP LOAN Endpoints - Trade - * - **/ + * @deprecated as of 2023-06-22, now Simple Earn + */ +getPurchaseRecord(params: PurchaseRecordParams): Promise ⋮---- -renewVipLoan(params: VipLoanRenewParams): Promise +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getRedemptionRecord(params: PurchaseRecordParams): Promise ⋮---- -repayVipLoan(params: VipLoanRepayParams): Promise +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getInterestHistory(params: PurchaseRecordParams): Promise ⋮---- -borrowVipLoan(params: VipLoanBorrowParams): Promise +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +changeFixedAndActivityPositionToDailyPosition(params: { + projectId: string; + lot: number; + positionId?: number; +}): Promise ⋮---- /** * - * DUAL INVESTMENT Endpoints - Market Data - * + * Wallet Endpoints + * @deprecated **/ ⋮---- -getDualInvestmentProducts( - params: GetDualInvestmentProductListParams, -): Promise< +/** + * @deprecated + */ +enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise ⋮---- /** + * @deprecated - deleted as of 2024-11-21 * - * DUAL INVESTMENT Endpoints - Trade - * - **/ -⋮---- -subscribeDualInvestmentProduct( - params: SubscribeDualInvestmentProductParams, -): Promise -⋮---- -getDualInvestmentPositions( - params: GetDualInvestmentPositionsParams, -): Promise< -⋮---- -getDualInvestmentAccounts(): Promise + */ +convertBUSD(params: ConvertTransfer): Promise ⋮---- -getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< +/** + * @deprecated + */ +getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise< + +================ +File: src/websocket-api-client.ts +================ +import { + ExchangeInfo, + SpotAmendKeepPriorityResult, + SpotExecutionRulesResponse, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, +} from './types/spot'; +import { + WSAPIResponse, + WSAPIUserDataListenKeyRequest, +} from './types/websockets/ws-api'; +import { + WSAPIAccountCommissionWSAPIRequest, + WSAPIAccountInformationRequest, + WSAPIAllOrderListsRequest, + WSAPIAllOrdersRequest, + WSAPIAvgPriceRequest, + WSAPIBlockTradesHistoricalRequest, + WSAPIExchangeInfoRequest, + WSAPIExecutionRulesRequest, + WSAPIFuturesAlgoOrderCancelRequest, + WSAPIFuturesOrderBookRequest, + WSAPIFuturesOrderCancelRequest, + WSAPIFuturesOrderModifyRequest, + WSAPIFuturesOrderStatusRequest, + WSAPIFuturesPositionRequest, + WSAPIFuturesPositionV2Request, + WSAPIFuturesTickerBookRequest, + WSAPIFuturesTickerPriceRequest, + WSAPIKlinesRequest, + WSAPIMyAllocationsRequest, + WSAPIMyPreventedMatchesRequest, + WSAPIMyTradesRequest, + WSAPINewFuturesAlgoOrderRequest, + WSAPINewFuturesOrderRequest, + WSAPINewSpotOrderRequest, + WSAPIOpenOrdersCancelAllRequest, + WSAPIOpenOrdersStatusRequest, + WSAPIOrderAmendKeepPriorityRequest, + WSAPIOrderBookRequest, + WSAPIOrderCancelReplaceRequest, + WSAPIOrderCancelRequest, + WSAPIOrderListCancelRequest, + WSAPIOrderListPlaceOCORequest, + WSAPIOrderListPlaceOPOCORequest, + WSAPIOrderListPlaceOPORequest, + WSAPIOrderListPlaceOTOCORequest, + WSAPIOrderListPlaceOTORequest, + WSAPIOrderListPlaceRequest, + WSAPIOrderListStatusRequest, + WSAPIOrderStatusRequest, + WSAPIOrderTestRequest, + WSAPIRecvWindowTimestamp, + WSAPIReferencePriceCalculationRequest, + WSAPIReferencePriceRequest, + WSAPISOROrderPlaceRequest, + WSAPISOROrderTestRequest, + WSAPITicker24hrRequest, + WSAPITickerBookRequest, + WSAPITickerPriceRequest, + WSAPITickerRequest, + WSAPITickerTradingDayRequest, + WSAPITradesAggregateRequest, + WSAPITradesHistoricalRequest, + WSAPITradesRecentRequest, +} from './types/websockets/ws-api-requests'; +import { + WSAPIAccountCommission, + WSAPIAccountInformation, + WSAPIAggregateTrade, + WSAPIAllocation, + WSAPIAvgPrice, + WSAPIBlockTrade, + WSAPIBookTicker, + WSAPIFullTicker, + WSAPIFuturesAccountBalanceItem, + WSAPIFuturesAccountStatus, + WSAPIFuturesAlgoOrder, + WSAPIFuturesAlgoOrderCancelResponse, + WSAPIFuturesBookTicker, + WSAPIFuturesOrder, + WSAPIFuturesOrderBook, + WSAPIFuturesPosition, + WSAPIFuturesPositionV2, + WSAPIFuturesPriceTicker, + WSAPIKline, + WSAPIMiniTicker, + WSAPIOrder, + WSAPIOrderBook, + WSAPIOrderCancel, + WSAPIOrderCancelReplaceResponse, + WSAPIOrderListCancelResponse, + WSAPIOrderListPlaceResponse, + WSAPIOrderListStatusResponse, + WSAPIOrderTestResponse, + WSAPIOrderTestWithCommission, + WSAPIPreventedMatch, + WSAPIPriceTicker, + WSAPIRateLimit, + WSAPIServerTime, + WSAPISessionStatus, + WSAPISOROrderPlaceResponse, + WSAPISOROrderTestResponse, + WSAPISOROrderTestResponseWithCommission, + WSAPISpotOrderResponse, + WSAPITrade, +} from './types/websockets/ws-api-responses'; +import { WSClientConfigurableOptions } from './types/websockets/ws-general'; +import { DefaultLogger } from './util/logger'; +import { + isWSAPIWsKey, + isWsEventStreamTerminatedRaw, + neverGuard, +} from './util/typeGuards'; +import { + getTestnetWsKey, + WS_KEY_MAP, + WS_LOGGER_CATEGORY, + WSAPIWsKey, + WSAPIWsKeyFutures, + WSAPIWsKeyMain, + WsKey, +} from './util/websockets/websocket-util'; +import { WSConnectedResult } from './util/websockets/WsStore.types'; +import { WebsocketClient } from './websocket-client'; ⋮---- -updateAutoCompoundStatus( - params: ChangeAutoCompoundStatusParams, -): Promise +function getFuturesMarketWsKey(market: 'usdm' | 'coinm'): WSAPIWsKeyFutures ⋮---- /** + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true * - * GIFT CARD Endpoints - Market Data + * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected + */ + resubscribeUserDataStreamAfterReconnect: boolean; + + /** + * Default: 2 seconds * - **/ -⋮---- -createGiftCard(params: CreateGiftCardParams): Promise -⋮---- -createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise -⋮---- -redeemGiftCard(params: RedeemGiftCardParams): Promise -⋮---- -verifyGiftCard(params: -⋮---- -getTokenLimit(params: + * Delay automatic userdata resubscribe by x seconds. + */ + resubscribeUserDataStreamDelaySeconds: number; + + /** + * 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: false + * + * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. + * + * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. + */ + muteLatencyWarning: boolean; + + /** + * Default: true + * + * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. + */ + keepMarginListenTokenRefreshed: boolean; +} ⋮---- -getRsaPublicKey(): Promise +/** + * Default: true + * + * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected + */ ⋮---- /** + * Default: 2 seconds * - * NFT Endpoints - REST api - * - **/ -⋮---- -getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< -⋮---- -getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< -⋮---- -getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< -⋮---- -getNftAsset(params: GetNftAssetParams): Promise< + * Delay automatic userdata resubscribe by x seconds. + */ ⋮---- /** + * Default: true * - * C2C Endpoints + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). * - **/ -⋮---- -getC2CTradeHistory( - params: GetC2CTradeHistoryParams, -): Promise + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ ⋮---- /** + * Default: false * - * FIAT Endpoints - REST api + * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. * - **/ -⋮---- -getFiatOrderHistory( - params: GetFiatOrderHistoryParams, -): Promise -⋮---- -getFiatPaymentsHistory( - params: GetFiatOrderHistoryParams, -): Promise + * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. + */ ⋮---- -fiatWithdraw(params: WithdrawFiatParams): Promise< +/** + * Default: true + * + * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. + */ ⋮---- -fiatDeposit(params: FiatDepositParams): Promise +/** + * Used to track that a connection had an active user data stream before it disconnected. + * + * Note: This is not the same as the "listenKey" WS API workflow (the listenKey workflow is deprecated). + * + * This does not return a listen key. This also does not require a regular "ping" on the listen key. + */ +interface ActiveUserDataStreamState { + subscribedAt: Date; + subscribeAttempt: number; + respawnTimeout?: ReturnType; + /** + * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. + */ + refreshTimeout?: ReturnType; + /** + * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream + */ + userDataStreamParameters?: unknown; +} ⋮---- -getFiatOrderDetail( - params: GetFiatOrderDetailParams, -): Promise +/** + * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. + */ ⋮---- /** - * - * Rebate Endpoints - * - **/ + * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream + */ ⋮---- -getSpotRebateHistoryRecords( - params: GetSpotRebateHistoryRecordsParams, -): Promise +/** + * 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/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108 + */ +export class WebsocketAPIClient ⋮---- /** - * - * DERIVATIVES - Portfolio Margin Pro - Market Data - * This is in mainclient because it shares the same base url - * - **/ + * Minimal state store around automating sticky "userDataStream.subscribe" sessions + */ ⋮---- -getPortfolioMarginIndexPrice(params?: { - asset?: string; -}): Promise +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -getPortfolioMarginAssetLeverage(): Promise< - GetPortfolioMarginAssetLeverageResponse[] - > { - return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); +public getWSClient(): WebsocketClient ⋮---- -getPortfolioMarginProCollateralRate(): Promise< - GetPortfolioMarginProCollateralRateResponse[] - > { - return this.get('sapi/v1/portfolio/collateralRate'); +public setTimeOffsetMs(newOffset: number): void ⋮---- -getPortfolioMarginProTieredCollateralRate(): Promise +public async disconnectAll(): Promise ⋮---- -/** +/* * - * DERIVATIVES - Portfolio Margin Pro - Account - * This is in mainclient because it shares the same base url + * SPOT - General requests * - **/ -⋮---- -getPortfolioMarginProAccountInfo(): Promise + */ ⋮---- -setPortfolioMarginMarginCallLevel( - params: SetPortfolioMarginMarginCallLevelParams, -): Promise +/** + * Test connectivity to the WebSocket API + */ +testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> ⋮---- -getPortfolioMarginMarginCallLevel(): Promise +/** + * Test connectivity to the WebSocket API and get the current server time + */ +getSpotServerTime( + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -deletePortfolioMarginMarginCallLevel(): Promise +/** + * Query current exchange trading rules, rate limits, and symbol information + */ +getSpotExchangeInfo( + params?: WSAPIExchangeInfoRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -bnbTransfer(params: BnbTransferParams): Promise< +/* + * + * SPOT - Market data requests + * + */ ⋮---- -submitPortfolioMarginProFullTransfer(): Promise< +/** + * Get current order book + * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + */ +getSpotOrderBook( + params: WSAPIOrderBookRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -submitPortfolioMarginProSpecificTransfer(params: +/** + * Get recent trades + * Note: If you need access to real-time trading activity, consider using WebSocket Streams + */ +getSpotRecentTrades( + params: WSAPITradesRecentRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -repayPortfolioMarginProBankruptcyLoan(params: { - from?: 'SPOT' | 'MARGIN'; -}): Promise< +/** + * Get historical trades + * Note: If fromId is not specified, the most recent trades are returned + */ +getSpotHistoricalTrades( + params: WSAPITradesHistoricalRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getPortfolioMarginProBankruptcyLoanAmount(): Promise +/** + * Get historical block trades + */ +getSpotHistoricalBlockTrades( + params: WSAPIBlockTradesHistoricalRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -repayFuturesNegativeBalance(): Promise< +/** + * Get aggregate trades + * Note: An aggregate trade represents one or more individual trades that fill at the same time + */ +getSpotAggregateTrades( + params: WSAPITradesAggregateRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -updateAutoRepayFuturesStatus(params: +/** + * Get klines (candlestick bars) + * Note: If you need access to real-time kline updates, consider using WebSocket Streams + */ +getSpotKlines( + params: WSAPIKlinesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getAutoRepayFuturesStatus(): Promise< +/** + * Get klines (candlestick bars) optimized for presentation + * Note: This request is similar to klines, having the same parameters and response + */ +getSpotUIKlines( + params: WSAPIKlinesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getPortfolioMarginProInterestHistory( - params: GetPortfolioMarginProInterestHistoryParams, -): Promise +/** + * Get current average price for a symbol + */ +getSpotAveragePrice( + params: WSAPIAvgPriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getPortfolioMarginProSpanAccountInfo(): Promise +/** + * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. + */ +getSpotExecutionRules( + params?: WSAPIExecutionRulesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getPortfolioMarginProAccountBalance(params?: { - asset?: string; -}): Promise +/** + * Query reference price for a symbol. + */ +getSpotReferencePrice( + params: WSAPIReferencePriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** - * @deprecated - * Check Simple Earn endpoints for new way of doing it + * Query how reference price is calculated for a symbol. */ -mintPortfolioMarginBFUSD( - params: PMProMintBFUSDParams, -): Promise +getSpotReferencePriceCalculation( + params: WSAPIReferencePriceCalculationRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** - * @deprecated - * Check Simple Earn endpointsfor new way of doing it + * Get 24-hour rolling window price change statistics + * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams */ -redeemPortfolioMarginBFUSD(params: { - fromAsset: string; // BFUSD only - targetAsset: string; // USDT only - amount: number; -}): Promise -⋮---- -fromAsset: string; // BFUSD only -targetAsset: string; // USDT only -⋮---- -getPortfolioMarginBankruptcyLoanRepayHistory(params?: { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -}): Promise< +getSpot24hrTicker( + params?: WSAPITicker24hrRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'ticker.24hr', + params, + { authIsOptional: true }, + ); ⋮---- /** - * Transfer LDUSDT as collateral for all types of Portfolio Margin account + * Get price change statistics for a trading day */ -transferLDUSDTPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; - amount: number; -}): Promise< +getSpotTradingDayTicker( + params: WSAPITickerTradingDayRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'ticker.tradingDay', + params, + { authIsOptional: true }, + ); ⋮---- /** - * Get transferable earn asset balance for all types of Portfolio Margin account + * Get rolling window price change statistics with a custom window + * Note: Window size precision is limited to 1 minute */ -getTransferableEarnAssetBalanceForPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; -}): Promise< +getSpotTicker( + params: WSAPITickerRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'ticker', + params, + { authIsOptional: true }, + ); ⋮---- /** - * - * DERIVATIVES - Futures Data - Market - * This is in mainclient because it shares the same base url - * - **/ -⋮---- -getFuturesTickLevelOrderbookDataLink( - params: GetFutureTickLevelOrderbookDataLinkParams, -): Promise< + * Get the latest market price for a symbol + * Note: If you need access to real-time price updates, consider using WebSocket Streams + */ +getSpotSymbolPriceTicker( + params?: WSAPITickerPriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** - * - * BLVT Endpoints - * BLVT category is possibly @deprecated, found only in old docs - **/ -⋮---- -getBlvtInfo(params?: -⋮---- -subscribeBlvt(params: SubscribeBlvtParams): Promise -⋮---- -getBlvtSubscriptionRecord( - params: GetBlvtSubscriptionRecordParams, -): Promise -⋮---- -redeemBlvt(params: RedeemBlvtParams): Promise -⋮---- -getBlvtRedemptionRecord( - params: GetBlvtRedemptionRecordParams, -): Promise -⋮---- -getBlvtUserLimitInfo(params: { - tokenName?: string; -}): Promise + * Get the current best price and quantity on the order book + * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams + */ +getSpotSymbolOrderBookTicker( + params?: WSAPITickerBookRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -/** +/* * - * Pay endpoints - * Found only in old docs, possibly @deprecated - **/ -getPayTransactions(params: GetPayTradeHistoryParams): Promise -⋮---- -/** + * SPOT - Session authentication requests * - * INSTITUTIONAL LOAN - Account Endpoints + * Note: authentication is automatic * - **/ -⋮---- -getInstLoanRiskUnit( - params?: GetInstitutionalLoanRiskUnitDetailsParams, -): Promise -⋮---- -closeInstLoanRiskUnit(): Promise -⋮---- -addInstLoanCollateralAccount( - params: AddInstitutionalLoanCollateralAccountParams, -): Promise -⋮---- -getActiveInstLoanRiskUnits(): Promise + */ ⋮---- -getClosedInstLoanRiskUnits( - params?: GetClosedInstitutionalLoanRiskUnitsParams, -): Promise +getSpotSessionStatus( + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -/** +/* * - * INSTITUTIONAL LOAN - Trade Endpoints + * SPOT - Trading requests * - **/ + */ ⋮---- -getInstLoanForceLiquidationRecord( - params: GetInstitutionalLoanForceLiquidationParams, -): Promise /** - * - * INSTITUTIONAL LOAN - TransferEndpoints - * - **/ -⋮---- -transferInstLoanRiskUnit( - params: InstitutionalLoanRiskUnitTransferParams, -): Promise + * Submit a spot order + */ +submitNewSpotOrder( + params: WSAPINewSpotOrderRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** - * - * INSTITUTIONAL LOAN - Borrow/Repay Endpoints - * - **/ -⋮---- -borrowInstitutionalLoan( - params: InstitutionalLoanBorrowParams, -): Promise -⋮---- -getInstLoanInterestHistory( - params?: GetInstitutionalLoanInterestHistoryParams, -): Promise -⋮---- -repayInstitutionalLoan( - params: InstitutionalLoanRepayParams, -): Promise -⋮---- -getInstLoanBorrowRepayRecords( - params: GetInstitutionalLoanBorrowRepayRecordsParams, -): Promise -⋮---- -getMarginInterestRebateBalance(): Promise -⋮---- -getMarginInterestRebateBalanceRecords( - params?: GetMarginInterestRebateBalanceRecordsParams, -): Promise + * Test order placement + * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine + */ +testSpotOrder( + params: WSAPIOrderTestRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'order.test', + params, + ); ⋮---- /** - * - * ALPHA TRADING - Market Data - * https://developers.binance.com/docs/alpha + * Check execution status of an order + * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used */ +getSpotOrderStatus( + params: WSAPIOrderStatusRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getAlphaTokenList(): Promise -⋮---- -getAlphaExchangeInfo(): Promise -⋮---- -getAlphaAggTrades(params: AlphaAggTradesParams): Promise -⋮---- -getAlphaKlines(params: AlphaKlinesParams): Promise -⋮---- -getAlphaTicker(params: +/** + * Cancel an active order + * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used + */ +cancelSpotOrder( + params: WSAPIOrderCancelRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getAlphaFullDepth( - params: AlphaFullDepthParams, -): Promise +/** + * Cancel an existing order and immediately place a new order + * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used + */ +cancelReplaceSpotOrder( + params: WSAPIOrderCancelReplaceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** + * Reduce the quantity of an existing open order. * - * EXCHANGE LINK - Account Endpoints - * https://developers.binance.com/docs/binance_link + * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority */ +amendSpotOrderKeepPriority( + params: WSAPIOrderAmendKeepPriorityRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -createBrokerSubAccount( - params: CreateBrokerSubAccountParams, -): Promise -⋮---- -getBrokerSubAccount( - params: GetBrokerSubAccountParams, -): Promise -⋮---- -enableMarginBrokerSubAccount( - params: EnableMarginBrokerSubAccountParams, -): Promise -⋮---- -createApiKeyBrokerSubAccount( - params: CreateApiKeyBrokerSubAccountParams, -): Promise -⋮---- -changePermissionApiKeyBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise -⋮---- -changeComissionBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise -⋮---- -enableUniversalTransferApiKeyBrokerSubAccount( - params: EnableUniversalTransferApiKeyBrokerSubAccountParams, -): Promise +/** + * Query execution status of all open orders + * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams + */ +getSpotOpenOrders( + params: WSAPIOpenOrdersStatusRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -updateIpRestrictionForSubAccountApiKey( - params: UpdateIpRestrictionForSubApiKey, -): Promise< +/** + * Cancel all open orders on a symbol + * Note: This includes orders that are part of an order list + */ +cancelAllSpotOpenOrders( + params: WSAPIOpenOrdersCancelAllRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]> + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'openOrders.cancelAll', + params, + ); ⋮---- -deleteIPRestrictionForSubAccountApiKey(params: { - subAccountId: string; - subAccountApiKey: string; - ipAddress?: string; -}): Promise< +/** + * Place a new order list + * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead + */ +placeSpotOrderList( + params: WSAPIOrderListPlaceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -deleteApiKeyBrokerSubAccount( - params: DeleteApiKeyBrokerSubAccountParams, -): Promise +/** + * Place a new OCO (One-Cancels-the-Other) order list + * Note: Activation of one order immediately cancels the other + */ +placeSpotOCOOrderList( + params: WSAPIOrderListPlaceOCORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getSubAccountBrokerIpRestriction(params: { - subAccountId: string; - subAccountApiKey: string; -}): Promise< +/** + * Place a new OTO (One-Triggers-the-Other) order list + * Note: The pending order is placed only when the working order is fully filled + */ +placeSpotOTOOrderList( + params: WSAPIOrderListPlaceOTORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getApiKeyBrokerSubAccount( - params: GetApiKeyBrokerSubAccountParams, -): Promise +/** + * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list + * Note: The pending orders are placed only when the working order is fully filled + */ +placeSpotOTOCOOrderList( + params: WSAPIOrderListPlaceOTOCORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getBrokerInfo(): Promise +/** + * Place a new OPO (One-Pays-the-Other) order list + * Note: One order pays for the other - when the working order is filled, the pending order is placed + */ +placeSpotOPOOrderList( + params: WSAPIOrderListPlaceOPORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -updateSubAccountBNBBurn(params: { - subAccountId: string; - spotBNBBurn: 'true' | 'false'; -}): Promise< +/** + * Place a new OPOCO (One-Pays-One-Cancels-the-Other) order list + * Note: Combines OPO and OCO - working order pays for two pending orders, one cancels the other + */ +placeSpotOPOCOOrderList( + params: WSAPIOrderListPlaceOPOCORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -updateSubAccountMarginInterestBNBBurn(params: { - subAccountId: string; - interestBNBBurn: 'true' | 'false'; -}): Promise< +/** + * Check execution status of an order list + * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used + */ +getSpotOrderListStatus( + params: WSAPIOrderListStatusRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getSubAccountBNBBurnStatus(params: +/** + * Cancel an active order list + * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used + */ +cancelSpotOrderList( + params: WSAPIOrderListCancelRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** - * Caution: - * The operation will delete a sub account under your brokerage master account. - * Please transfer out all funds from the sub account and delete API key of the sub account before deleting it. - * The deleted sub account CANNOT be reverted. - * The daily deletion limit for a broker Master is 20 sub accounts. - * You need to enable "trade" option for the api key which requests this endpoint. + * Query execution status of all open order lists + * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams */ -deleteBrokerSubAccount(params: +getSpotOpenOrderLists( + params: WSAPIRecvWindowTimestamp, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- /** - * - * EXCHANGE LINK - Asset Endpoints - * https://developers.binance.com/docs/binance_link + * Place a new order using Smart Order Routing (SOR) + * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported */ +placeSpotSOROrder( + params: WSAPISOROrderPlaceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -transferBrokerSubAccount( - params: TransferBrokerSubAccountParams, -): Promise +/** + * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) + * Note: Creates and validates a new order but does not send it into the matching engine + */ +testSpotSOROrder( + params: WSAPISOROrderTestRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'sor.order.test', + params, + ); ⋮---- -getBrokerSubAccountHistory( - params: GetBrokerSubAccountHistoryParams, -): Promise +/* + * + * SPOT - Account requests + * + */ ⋮---- -submitBrokerSubFuturesTransfer(params: { - fromId?: string; - toId?: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - asset: string; - amount: number; - clientTranId?: string; // The max length is 32 characters -}): Promise< +/** + * Query information about your account, including balances + * Note: Weight: 20 + */ +getSpotAccountInformation( + params: WSAPIAccountInformationRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures +/** + * Query your current unfilled order count for all intervals + * Note: Weight: 40 + */ +getSpotOrderRateLimits( + params: WSAPIRecvWindowTimestamp, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -clientTranId?: string; // The max length is 32 characters +/** + * Query information about all your orders – active, canceled, filled – filtered by time range + * Note: Weight: 20 + */ +getSpotAllOrders( + params: WSAPIAllOrdersRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getSubAccountFuturesTransferHistory(params: { - subAccountId: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -}): Promise +/** + * Query information about all your order lists, filtered by time range + * Note: Weight: 20 + */ +getSpotAllOrderLists( + params: WSAPIAllOrderListsRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures +/** + * Query information about all your trades, filtered by time range + * Note: Weight: 20 + */ +getSpotMyTrades( + params: WSAPIMyTradesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getBrokerSubDepositHistory( - params: GetSubAccountDepositHistoryParams, -): Promise +/** + * Displays the list of orders that were expired due to STP + * Note: Weight varies based on query type (2-20) + */ +getSpotPreventedMatches( + params: WSAPIMyPreventedMatchesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getBrokerSubAccountSpotAssets( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< +/** + * Retrieves allocations resulting from SOR order placement + * Note: Weight: 20 + */ +getSpotAllocations( + params: WSAPIMyAllocationsRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -getSubAccountMarginAssetInfo( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< +/** + * Get current account commission rates + * Note: Weight: 20 + */ +getSpotAccountCommission( + params: WSAPIAccountCommissionWSAPIRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -querySubAccountFuturesAssetInfo( - params: QuerySubAccountFuturesAssetInfoParams, -): Promise< +/* + * + * FUTURES - Market data requests + * + */ ⋮---- -universalTransferBroker(params: UniversalTransferBrokerParams): Promise< +/** + * Get current order book for futures + * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + */ +getFuturesOrderBook( + params: WSAPIFuturesOrderBookRequest, +): Promise> ⋮---- -getUniversalTransferBroker( - params: GetUniversalTransferBrokerParams, -): Promise +/** + * Get latest price for a futures symbol or symbols + * Note: If symbol is not provided, prices for all symbols will be returned + */ +getFuturesSymbolPriceTicker( + params?: WSAPIFuturesTickerPriceRequest, + ): Promise< + WSAPIResponse + > { + return this.wsClient.sendWSAPIRequest( + WS_KEY_MAP.usdmWSAPI, + 'ticker.price', + params, + { authIsOptional: true }, + ); ⋮---- /** + * Get best price/qty on the order book for a futures symbol or symbols + * Note: If symbol is not provided, bookTickers for all symbols will be returned + */ +getFuturesSymbolOrderBookTicker( + params?: WSAPIFuturesTickerBookRequest, +): Promise> +⋮---- +/* + * + * FUTURES - Trading requests * - * EXCHANGE LINK - Fee Endpoints - * https://developers.binance.com/docs/binance_link */ ⋮---- -updateBrokerSubAccountCommission( - params: ChangeSubAccountCommissionParams, -): Promise +/** + * Submit a futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +submitNewFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPINewFuturesOrderRequest, +): Promise> ⋮---- -updateBrokerSubAccountFuturesCommission( - params: ChangeSubAccountFuturesCommissionParams, -): Promise +/** + * Modify an existing futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +modifyFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderModifyRequest, +): Promise> ⋮---- -getBrokerSubAccountFuturesCommission( - params: QuerySubAccountFuturesCommissionParams, -): Promise +/** + * Cancel a futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +cancelFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderCancelRequest, +): Promise> ⋮---- -updateBrokerSubAccountCoinFuturesCommission( - params: ChangeSubAccountCoinFuturesCommissionParams, -): Promise +/** + * Query futures order status + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesOrderStatus( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderStatusRequest, +): Promise> ⋮---- -getBrokerSubAccountCoinFuturesCommission( - params: QuerySubAccountCoinFuturesCommissionParams, -): Promise +/** + * Get current position information (V2) + * Note: Only symbols that have positions or open orders will be returned + */ +getFuturesPositionV2( + params: WSAPIFuturesPositionV2Request, +): Promise> ⋮---- -getBrokerSpotCommissionRebate( - params: QueryBrokerSpotCommissionRebateParams, -): Promise +/** + * Get current position information + * Note: Only symbols that have positions or open orders will be returned + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesPosition( + market: 'usdm' | 'coinm', + params: WSAPIFuturesPositionRequest, +): Promise> ⋮---- -getBrokerFuturesCommissionRebate( - params: QueryBrokerFuturesCommissionRebateParams, -): Promise +/** + * Send in a new algo order + * + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/New-Algo-Order + */ +submitNewFuturesAlgoOrder( + params: WSAPINewFuturesAlgoOrderRequest, +): Promise> ⋮---- /** + * Cancel an active algo order. + * + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order + * @param params + */ +cancelFuturesAlgoOrder( + params: WSAPIFuturesAlgoOrderCancelRequest, +): Promise> +⋮---- +/* + * + * FUTURES - Account requests * - * @deprecated */ -// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) -getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) ⋮---- /** - * Broker Endpoints - only on old docs - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link + * Get account balance information (V2) + * Note: Returns balance information for all assets */ +getFuturesAccountBalanceV2( + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerIfNewSpotUser(): Promise< + * Get account balance information + * Note: Returns balance information for all assets + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesAccountBalance( + market: 'usdm' | 'coinm', + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerSubAccountDepositHistory( - params?: GetBrokerSubAccountDepositHistoryParams, -): Promise + * Get account information (V2) + * Note: Returns detailed account information including positions and assets + */ +getFuturesAccountStatusV2( + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerUserCustomisedId(market: 'spot' | 'futures') + * Get account information + * Note: Returns detailed account information including positions and assets + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesAccountStatus( + market: 'usdm' | 'coinm', + params: WSAPIRecvWindowTimestamp, +): Promise> +⋮---- +/* + * + * User data stream requests + * + */ ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableFuturesBrokerSubAccount( - params: EnableFuturesBrokerSubAccountParams, -): Promise + * Start the user data stream for an apiKey (passed as param). + * + * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. + * + * @param params + * @param wsKey + * @returns listenKey + */ +startUserDataStreamForKey( + params: { apiKey: string }, + wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, +): Promise + * Attempt to "ping" a listen key. + * + * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. + * + * @param params + * @param wsKey + * @returns + */ +pingUserDataStreamForKey( + params: WSAPIUserDataListenKeyRequest, + wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, +): Promise> ⋮---- /** - * Validate syntax meets requirements set by binance. Log warning if not. + * Stop the user data stream listen key. + * + * @param params + * @param wsKey + * @returns */ -private validateOrderId( - params: - | NewSpotOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams - | NewOrderListParams, - orderIdProperty: OrderIdProperty, -): void +stopUserDataStreamForKey( + params: WSAPIUserDataListenKeyRequest, + wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, +): Promise> ⋮---- /** + * Consolidated method to clear any timers related to user data stream subscriptions for a given wsKey, if found. * - * User Data Stream Endpoints - * - **/ -⋮---- -// spot -getSpotUserDataListenKey(): Promise< -⋮---- -keepAliveSpotUserDataListenKey(listenKey: string): Promise + * @param wsKey + */ +clearUserDataStreamTimers(wsKey: WSAPIWsKey) ⋮---- -closeSpotUserDataListenKey(listenKey: string): Promise +// Just in case the refresh timer is still running +// Harmless given one connection, but still unnecessary ⋮---- /** - * Get a cross margin user data listen key + * Request user data stream subscription on the currently authenticated connection. + * + * If reconnected, this will automatically resubscribe unless you unsubscribe manually. */ -getMarginUserDataListenKey(): Promise< -⋮---- -keepAliveMarginUserDataListenKey(listenKey: string): Promise +async subscribeUserDataStream( + wsKey: WSAPIWsKey, + isRefreshingToken: boolean = false, +): Promise | WSConnectedResult | undefined> ⋮---- -closeMarginUserDataListenKey(listenKey: string): Promise +// User data stream works differently for margin, since Feb 2026, via a listen token mechanic ⋮---- -// isolated margin -getIsolatedMarginUserDataListenKey(params: { - symbol: string; -}): Promise< +// validity: 30 * 1000, // milliseconds (30 secs) +// validity: 5 * 60 * 1000, // milliseconds (5 mins ) ⋮---- -keepAliveIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise +// Set respawn timer, to automatically fetch and sub to new token before expiry. Should be seamless on existing connection. ⋮---- -closeIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise +// try to respawn 30 seconds before expiration ⋮---- -/** - * Get a cross margin risk data listen key - */ -getMarginRiskUserDataListenKey(): Promise< +// for Ed25519 keys, no signature is needed, we should already be authenticated in session ⋮---- -keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise +// for HMAC & RSA keys, request will be signed and sent to a dedicated topic ⋮---- -closeMarginRiskUserDataListenKey(): Promise +// Used to track whether this connection had the general "userDataStream.subscribe" called. +// Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub. ⋮---- /** - * Get/create margin account listenToken for the user data stream - * https://developers.binance.com/docs/margin_trading/trade-data-stream + * Unsubscribe from the user data stream subscription on the currently authenticated connection. + * + * If reconnected, this will also stop it from automatically resubscribing after reconnect. */ -getMarginListenToken(params?: { - symbol?: string; - isIsolated?: boolean; - validity?: number; -}): Promise< +unsubscribeUserDataStream( + wsKey: WSAPIWsKey, +): Promise +// JSON.stringify({ ...data, target: 'WebSocket' }), ⋮---- -/** - * - * Savings Endpoints - * @deprecated as of 2023-06-22, now Simple Earn - **/ +private setupRequiredEventListeners() ⋮---- /** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyPurchaseQuotaFlexibleProduct(params: { - productId: string; -}): Promise + * Required event handlers for handling automatic resubscribe to user data stream after reconnect, etc + */ ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyRedemptionQuotaFlexibleProduct(params: { - productId: string; - }): Promise< - LeftDailyPurchaseQuotaFlexibleProductResponse & { - dailyQuota: string; - minRedemptionAmount: string; - } - > { - return this.getPrivate('sapi/v1/lending/daily/userRedemptionQuota', params); +// Handle notification that user data stream has been terminated (e.g. due to expired listen token) and attempt to automatically resubscribe with new token +// Designed around margin mode mechanics: https://developers.binance.com/docs/margin_trading/trade-data-stream#response-example-1 ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -purchaseFixedAndActivityProject(params: { - projectId: string; - lot: number; -}): Promise +// console.log(new Date(), 'ws message received: ', data); ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProjects( - params: FixedAndActivityProjectParams, -): Promise +private setupSignMechanic() ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProductPosition( - params: FixedAndActivityProjectPositionParams, -): Promise +private async tryResubscribeUserDataStream( + wsKey: WSAPIWsKey, + isRefreshingToken: boolean, +) ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLendingAccount(): Promise +// Just in case the refresh timer is still running ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getPurchaseRecord(params: PurchaseRecordParams): Promise +private getSubscribedUserDataStreamState(wsKey: WSAPIWsKey) ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getRedemptionRecord(params: PurchaseRecordParams): Promise +private handleWSCloseEvent(params: ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getInterestHistory(params: PurchaseRecordParams): Promise +// Not a WS API connection ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -changeFixedAndActivityPositionToDailyPosition(params: { - projectId: string; - lot: number; - positionId?: number; -}): Promise +// If connection closes and we have a record of subscribing to user data stream on this connection, then we can assume it was likely an unintentional disconnect and we should attempt to resubscribe when it reconnects ⋮---- -/** - * - * Wallet Endpoints - * @deprecated - **/ +private handleWSReconnectedEvent(params: ⋮---- -/** - * @deprecated - */ -enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise +// Not a WS API connection ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - * - */ -convertBUSD(params: ConvertTransfer): Promise +// No record of ever subscribing to user data stream on this connection, so no need to resubscribe ⋮---- -/** - * @deprecated - */ -getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise< +// Clear token refresh timer, just in case. No need on a dead & potentially respawning connection +⋮---- +// Feature enabled +⋮---- +// Delay existing timer, if exists +⋮---- +// Queue resubscribe workflow ================ File: src/websocket-client.ts @@ -28057,7 +28184,7 @@ File: package.json ================ { "name": "binance", - "version": "3.5.9", + "version": "3.5.11", "description": "Professional Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", @@ -28116,9 +28243,7 @@ File: package.json "rimraf": "^6.1.3", "ts-jest": "^29.4.6", "ts-node": "^10.9.2", - "typescript": "^5.7.3" - }, - "optionalDependencies": { + "typescript": "^5.7.3", "source-map-loader": "^2.0.2", "ts-loader": "^8.0.11", "webpack": "^5.102.1", diff --git a/package-lock.json b/package-lock.json index 25a80815..7e634b58 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "binance", - "version": "3.5.10", + "version": "3.5.11", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "binance", - "version": "3.5.10", + "version": "3.5.11", "license": "MIT", "dependencies": { "axios": "^1.13.2", diff --git a/package.json b/package.json index 7f9f749a..f81fc517 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "binance", - "version": "3.5.10", + "version": "3.5.11", "description": "Professional Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", diff --git a/src/coinm-client.ts b/src/coinm-client.ts index ce77d132..4c7b506b 100644 --- a/src/coinm-client.ts +++ b/src/coinm-client.ts @@ -23,13 +23,18 @@ import { ContinuousContractKlinesParams, ForceOrderResult, FundingRateHistory, + FuturesAlgoOrderResponse, + FuturesCancelAlgoOrderParams, + FuturesCancelAlgoOrderResponse, FuturesCoinMAccountBalance, FuturesCoinMAccountInformation, FuturesCoinMBasisParams, FuturesCoinMTakerBuySellVolumeParams, FuturesDataPaginatedParams, FuturesExchangeInfo, + FuturesNewAlgoOrderParams, FuturesOrderBook, + FuturesQueryOpenAlgoOrdersParams, GetForceOrdersParams, GetIncomeHistoryParams, GetPositionMarginChangeHistoryParams, @@ -379,6 +384,32 @@ export class CoinMClient extends BaseRestClient { return this.getPrivate('dapi/v1/openOrder', params); } + /** + * + * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) + * Conditional orders migrate to Algo Service on COIN-M + * + **/ + + submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, + ): Promise { + this.validateOrderId(params, 'clientAlgoId'); + return this.postPrivate('dapi/v1/algoOrder', params); + } + + cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, + ): Promise { + return this.deletePrivate('dapi/v1/algoOrder', params); + } + + getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, + ): Promise { + return this.getPrivate('dapi/v1/openAlgoOrders', params); + } + getForceOrders(params?: GetForceOrdersParams): Promise { return this.getPrivate('dapi/v1/forceOrders', params); } @@ -678,6 +709,7 @@ export class CoinMClient extends BaseRestClient { private validateOrderId( params: | NewFuturesOrderParams + | FuturesNewAlgoOrderParams | CancelOrderParams | NewOCOParams | CancelOCOParams, diff --git a/src/main-client.ts b/src/main-client.ts index f6f96f6f..657f2faf 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -275,6 +275,7 @@ import { GetInstitutionalLoanForceLiquidationParams, GetInstitutionalLoanForceLiquidationResponse, GetInstitutionalLoanInterestHistoryParams, + GetInstitutionalLoanMaxBorrowableParams, GetInstitutionalLoanRiskUnitDetailsParams, GetLoanableAssetsDataParams, GetLoanBorrowHistoryParams, @@ -348,9 +349,11 @@ import { GetTargetAssetListResponse, GetTargetAssetROIParams, GetTravelRuleDepositHistoryParams, + GetTravelRuleRegionListParams, GetTravelRuleWithdrawHistoryParams, GetTravelRuleWithdrawHistoryV2Params, GetUniversalTransferBrokerParams, + GetVipLoanFixedRateMarketParams, GetVipLoanOngoingOrdersParams, GetVipLoanRepaymentHistoryParams, GetWbethRewardsHistoryResponse, @@ -363,6 +366,7 @@ import { InstitutionalLoanBorrowParams, InstitutionalLoanBorrowResponse, InstitutionalLoanInterestHistoryResponse, + InstitutionalLoanMaxBorrowableResponse, InstitutionalLoanRepayParams, InstitutionalLoanRepayResponse, InstitutionalLoanRiskUnitDetails, @@ -646,7 +650,9 @@ import { TradingDayTickerSingle, TransferBrokerSubAccount, TransferBrokerSubAccountParams, + TravelRuleCountryListResponse, TravelRuleDepositHistoryRecord, + TravelRuleRegionListResponse, TravelRuleWithdrawHistoryRecord, UniversalTransferBrokerParams, UniversalTransferHistoryParams, @@ -660,6 +666,9 @@ import { VipLoanAccruedInterestRecord, VipLoanBorrowParams, VipLoanBorrowResponse, + VipLoanFixedRateBorrowParams, + VipLoanFixedRateBorrowResponse, + VipLoanFixedRateMarketRecord, VipLoanInterestRateHistoryParams, VipLoanInterestRateRecord, VipLoanRenewParams, @@ -1958,6 +1967,16 @@ export class MainClient extends BaseRestClient { return this.getPrivate('sapi/v1/localentity/vasp'); } + getTravelRuleCountryList(): Promise { + return this.getPrivate('sapi/v1/localentity/country/list'); + } + + getTravelRuleRegionList( + params: GetTravelRuleRegionListParams, + ): Promise { + return this.getPrivate('sapi/v1/localentity/region/list', params); + } + /** * * WALLET Endpoints - Other endpoints @@ -3837,6 +3856,19 @@ export class MainClient extends BaseRestClient { return this.postPrivate('sapi/v1/loan/vip/borrow', params); } + getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise<{ + total: number; + rows: VipLoanFixedRateMarketRecord[]; + }> { + return this.getPrivate('sapi/v1/loan/vip/fixed/market', params); + } + + borrowVipLoanFixedRate( + params: VipLoanFixedRateBorrowParams, + ): Promise { + return this.postPrivate('sapi/v1/loan/vip/fixed/borrow', params); + } + /** * * DUAL INVESTMENT Endpoints - Market Data @@ -4318,6 +4350,12 @@ export class MainClient extends BaseRestClient { * **/ + getInstitutionalLoanMaxBorrowable( + params: GetInstitutionalLoanMaxBorrowableParams, + ): Promise { + return this.getPrivate('sapi/v1/margin/loan-group/max-borrowable', params); + } + borrowInstitutionalLoan( params: InstitutionalLoanBorrowParams, ): Promise { diff --git a/src/types/spot.ts b/src/types/spot.ts index 62bb84d9..ecd3386d 100644 --- a/src/types/spot.ts +++ b/src/types/spot.ts @@ -37,7 +37,8 @@ export type SymbolStatus = | 'END_OF_DAY' | 'HALT' | 'AUCTION_MATCH' - | 'BREAK'; + | 'BREAK' + | 'CANCEL_ONLY'; export interface SystemStatusResponse { status: 0 | 1; @@ -6498,6 +6499,78 @@ export interface VASPInfo { identifier?: string; } +export interface TravelRuleCountryInfo { + countryCode: string; + countryName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; + hasRegionRestrictions: boolean; +} + +export interface TravelRuleCountryListResponse { + countries: TravelRuleCountryInfo[]; + lastUpdated: number; +} + +export interface GetTravelRuleRegionListParams { + countryCode: string; +} + +export interface TravelRuleRegionInfo { + regionName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; +} + +export interface TravelRuleRegionListResponse { + countryCode: string; + regions: TravelRuleRegionInfo[]; + lastUpdated: number; +} + +export interface GetVipLoanFixedRateMarketParams { + loanCoin: string; + duration?: number; + current?: number; + size?: number; +} + +export interface VipLoanFixedRateMarketRecord { + requestId: number; + requestNo: number; + coin: string; + interestRate: numberInString; + duration: number; + minimumAmount: numberInString; + availableAmount: numberInString; + estimatedInterest: numberInString; +} + +export interface VipLoanFixedRateBorrowParams { + supplyRequest: string; + borrowCoin: string; + loanTerm: number; + borrowUid: number; + collateralCoin: string; + collateralAccountId: string; + autoRepay?: boolean; +} + +export interface VipLoanFixedRateBorrowResponse { + borrowCoin: string; + borrowAmount: numberInString; + actualReceivedAmount: numberInString; + collateralCoin: string; + collateralAccountId: string; + borrowInterestRate: numberInString; + duration: string; + autoRepay: boolean; + orderId: number; + status: 'Succeeds' | 'Failed' | 'Processing'; +} + // Institutional Loan types export interface InstitutionalLoanLiability { assetName: string; @@ -6626,6 +6699,15 @@ export interface InstitutionalLoanRiskUnitTransferParams { } // Additional institutional loan types for borrow, repay, and interest history +export interface GetInstitutionalLoanMaxBorrowableParams { + groupId?: number; + assetName: string; +} + +export interface InstitutionalLoanMaxBorrowableResponse { + maxBorrowableAmount: numberInString | null; +} + export interface InstitutionalLoanBorrowParams { groupId: number; assetName: string; diff --git a/src/types/websockets/ws-events-raw.ts b/src/types/websockets/ws-events-raw.ts index 2a747ed6..45dab9c0 100644 --- a/src/types/websockets/ws-events-raw.ts +++ b/src/types/websockets/ws-events-raw.ts @@ -476,7 +476,8 @@ export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { e: 'indexPriceUpdate'; E: number; - i: string; + i?: string; + s?: string; p: numberInString; } diff --git a/src/util/beautifier-maps.ts b/src/util/beautifier-maps.ts index bcd3888f..04967763 100644 --- a/src/util/beautifier-maps.ts +++ b/src/util/beautifier-maps.ts @@ -219,6 +219,7 @@ export const BEAUTIFIER_EVENT_MAP = { e: 'eventType', E: 'eventTime', i: 'symbol', + s: 'symbol', p: 'indexPrice', }, indexOptionsEvent: {