diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index ca842290..d0240d10 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -4,8 +4,8 @@

- - SDK Logo + + SDK Logo

@@ -14,7 +14,7 @@ Each REST client is a JavaScript class, which provides functions individually ma The following table shows all methods available in each REST client, whether the method requires authentication (automatically handled if API keys are provided), as well as the exact endpoint each method is connected to. -This can be used to easily find which method to call, once you have [found which endpoint you're looking to use](https://github.com/tiagosiebler/awesome-crypto-examples/wiki/How-to-find-SDK-functions-that-match-API-docs-endpoint). +This can be used to easily find which method to call, once you have [found which endpoint you're looking to use](https://github.com/sieblyio/awesome-crypto-examples/wiki/How-to-find-SDK-functions-that-match-API-docs-endpoint). All REST clients are in the [src](/src) folder. For usage examples, make sure to check the [examples](/examples) folder. @@ -52,528 +52,531 @@ 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#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` | +| [testConnectivity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L788) | | GET | `api/v3/ping` | +| [getExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L792) | | GET | `api/v3/exchangeInfo` | +| [getOrderBook()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L812) | | GET | `api/v3/depth` | +| [getRecentTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L816) | | GET | `api/v3/trades` | +| [getHistoricalTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L820) | | GET | `api/v3/historicalTrades` | +| [getHistoricalBlockTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L824) | | GET | `api/v3/historicalBlockTrades` | +| [getAggregateTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L830) | | GET | `api/v3/aggTrades` | +| [getKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L836) | | GET | `api/v3/klines` | +| [getUIKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L840) | | GET | `api/v3/uiKlines` | +| [getAvgPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L844) | | GET | `api/v3/avgPrice` | +| [getExecutionRules()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L848) | | GET | `api/v3/executionRules?symbols=` | +| [getReferencePrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L863) | | GET | `api/v3/referencePrice` | +| [getReferencePriceCalculation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L869) | | GET | `api/v3/referencePrice/calculation` | +| [get24hrChangeStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L876) | | GET | `api/v3/ticker/24hr?symbols=` | +| [getTradingDayTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L906) | | GET | `api/v3/ticker/tradingDay?symbols=` | +| [getSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L921) | | GET | `api/v3/ticker/price?symbols=` | +| [getSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L938) | | GET | `api/v3/ticker/bookTicker?symbols=` | +| [getRollingWindowTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L955) | | GET | `api/v3/ticker?symbols=` | +| [submitNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L977) | :closed_lock_with_key: | POST | `api/v3/order` | +| [testNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L985) | :closed_lock_with_key: | POST | `api/v3/order/test` | +| [getOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L993) | :closed_lock_with_key: | GET | `api/v3/order` | +| [cancelOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L997) | :closed_lock_with_key: | DELETE | `api/v3/order` | +| [cancelAllSymbolOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1001) | :closed_lock_with_key: | DELETE | `api/v3/openOrders` | +| [replaceOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1007) | :closed_lock_with_key: | POST | `api/v3/order/cancelReplace` | +| [amendOrderKeepPriority()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1021) | :closed_lock_with_key: | PUT | `fapi/v1/order/amend/keepPriority` | +| [getOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1028) | :closed_lock_with_key: | GET | `api/v3/openOrders` | +| [getAllOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1032) | :closed_lock_with_key: | GET | `api/v3/allOrders` | +| [submitNewOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1039) | :closed_lock_with_key: | POST | `api/v3/order/oco` | +| [submitNewOrderList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1046) | :closed_lock_with_key: | POST | `api/v3/orderList/oco` | +| [submitNewOrderListOTO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1055) | :closed_lock_with_key: | POST | `api/v3/orderList/oto` | +| [submitNewOrderListOTOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1064) | :closed_lock_with_key: | POST | `api/v3/orderList/otoco` | +| [submitNewOrderListOPO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1074) | :closed_lock_with_key: | POST | `api/v3/orderList/opo` | +| [submitNewOrderListOPOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1083) | :closed_lock_with_key: | POST | `api/v3/orderList/opoco` | +| [cancelOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1093) | :closed_lock_with_key: | DELETE | `api/v3/orderList` | +| [getOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1098) | :closed_lock_with_key: | GET | `api/v3/orderList` | +| [getAllOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1102) | :closed_lock_with_key: | GET | `api/v3/allOrderList` | +| [getAllOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1109) | :closed_lock_with_key: | GET | `api/v3/openOrderList` | +| [submitNewSOROrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1116) | :closed_lock_with_key: | POST | `api/v3/sor/order` | +| [testNewSOROrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1127) | :closed_lock_with_key: | POST | `api/v3/sor/order/test` | +| [getAccountInformation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1143) | :closed_lock_with_key: | GET | `api/v3/account` | +| [getAccountTradeList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1149) | :closed_lock_with_key: | GET | `api/v3/myTrades` | +| [getOrderRateLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1155) | :closed_lock_with_key: | GET | `api/v3/rateLimit/order` | +| [getPreventedMatches()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1159) | :closed_lock_with_key: | GET | `api/v3/myPreventedMatches` | +| [getAllocations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1165) | :closed_lock_with_key: | GET | `api/v3/myAllocations` | +| [getCommissionRates()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1169) | :closed_lock_with_key: | GET | `api/v3/account/commission` | +| [getCrossMarginCollateralRatio()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1179) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginCollateralRatio` | +| [getAllCrossMarginPairs()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1188) | | GET | `sapi/v1/margin/allPairs` | +| [getIsolatedMarginAllSymbols()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1192) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/allPairs` | +| [getAllMarginAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1198) | | GET | `sapi/v1/margin/allAssets` | +| [getMarginDelistSchedule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1202) | :closed_lock_with_key: | GET | `sapi/v1/margin/delist-schedule` | +| [getIsolatedMarginTierData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1206) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginTier` | +| [queryMarginPriceIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1212) | | GET | `sapi/v1/margin/priceIndex` | +| [getMarginAvailableInventory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1218) | :closed_lock_with_key: | GET | `sapi/v1/margin/available-inventory` | +| [getLeverageBracket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1224) | :closed_lock_with_key: | GET | `sapi/v1/margin/leverageBracket` | +| [getNextHourlyInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1234) | :closed_lock_with_key: | GET | `sapi/v1/margin/next-hourly-interest-rate` | +| [getMarginInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1240) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestHistory` | +| [submitMarginAccountBorrowRepay()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1247) | :closed_lock_with_key: | POST | `sapi/v1/margin/borrow-repay` | +| [getMarginAccountBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1253) | :closed_lock_with_key: | GET | `sapi/v1/margin/borrow-repay` | +| [getMarginInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1259) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestRateHistory` | +| [queryMaxBorrow()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1265) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxBorrowable` | +| [getMarginForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1277) | :closed_lock_with_key: | GET | `sapi/v1/margin/forceLiquidationRec` | +| [getSmallLiabilityExchangeCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1286) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability` | +| [getSmallLiabilityExchangeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1290) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability-history` | +| [marginAccountCancelOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1302) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/openOrders` | +| [marginAccountCancelOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1308) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/orderList` | +| [marginAccountCancelOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1313) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/order` | +| [marginAccountNewOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1319) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oco` | +| [marginAccountNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1326) | :closed_lock_with_key: | POST | `sapi/v1/margin/order` | +| [getMarginOrderCountUsage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1334) | :closed_lock_with_key: | GET | `sapi/v1/margin/rateLimit/order` | +| [queryMarginAccountAllOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1340) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrderList` | +| [queryMarginAccountAllOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1346) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrders` | +| [queryMarginAccountOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1352) | :closed_lock_with_key: | GET | `sapi/v1/margin/orderList` | +| [queryMarginAccountOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1356) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrderList` | +| [queryMarginAccountOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1363) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrders` | +| [queryMarginAccountOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1367) | :closed_lock_with_key: | GET | `sapi/v1/margin/order` | +| [queryMarginAccountTradeList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1371) | :closed_lock_with_key: | GET | `sapi/v1/margin/myTrades` | +| [submitSmallLiabilityExchange()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1377) | :closed_lock_with_key: | POST | `sapi/v1/margin/exchange-small-liability` | +| [submitManualLiquidation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1384) | :closed_lock_with_key: | POST | `sapi/v1/margin/manual-liquidation` | +| [submitMarginOTOOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1393) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oto` | +| [submitMarginOTOCOOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1405) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/otoco` | +| [createMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1418) | :closed_lock_with_key: | POST | `sapi/v1/margin/apiKey` | +| [deleteMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1424) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/apiKey` | +| [updateMarginIPForSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1432) | :closed_lock_with_key: | PUT | `sapi/v1/margin/apiKey/ip` | +| [getMarginSpecialLowLatencyKeys()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1443) | :closed_lock_with_key: | GET | `sapi/v1/margin/api-key-list` | +| [getMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1452) | :closed_lock_with_key: | GET | `sapi/v1/margin/apiKey` | +| [getMarginLiquidationLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1462) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan` | +| [repayMarginLiquidationLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1469) | :closed_lock_with_key: | POST | `sapi/v1/margin/liquidation-loan/repay` | +| [getMarginLiquidationLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1478) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan/repay-history` | +| [exitMarginSpecialKeyMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1490) | :closed_lock_with_key: | POST | `sapi/v1/margin/exit-special-key-mode` | +| [getCrossMarginTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1500) | :closed_lock_with_key: | GET | `sapi/v1/margin/transfer` | +| [queryMaxTransferOutAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1506) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxTransferable` | +| [updateCrossMarginMaxLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1518) | :closed_lock_with_key: | POST | `sapi/v1/margin/max-leverage` | +| [disableIsolatedMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1524) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/isolated/account` | +| [enableIsolatedMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1531) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/account` | +| [getBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1538) | :closed_lock_with_key: | GET | `sapi/v1/bnbBurn` | +| [getMarginSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1542) | :closed_lock_with_key: | GET | `sapi/v1/margin/tradeCoeff` | +| [queryCrossMarginAccountDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1546) | :closed_lock_with_key: | GET | `sapi/v1/margin/account` | +| [getCrossMarginFeeData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1550) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginData` | +| [getIsolatedMarginAccountLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1556) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/accountLimit` | +| [getIsolatedMarginAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1563) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/account` | +| [getIsolatedMarginFeeData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1569) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginData` | +| [toggleBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1575) | :closed_lock_with_key: | POST | `sapi/v1/bnbBurn` | +| [getMarginCapitalFlow()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1583) | :closed_lock_with_key: | GET | `sapi/v1/margin/capital-flow` | +| [queryLoanRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1592) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan` | +| [queryRepayRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1601) | :closed_lock_with_key: | GET | `sapi/v1/margin/repay` | +| [isolatedMarginAccountTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1610) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/transfer` | +| [getBalances()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1622) | :closed_lock_with_key: | GET | `sapi/v1/capital/config/getall` | +| [withdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1626) | :closed_lock_with_key: | POST | `sapi/v1/capital/withdraw/apply` | +| [getWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1630) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/history` | +| [getWithdrawAddresses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1636) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/address/list` | +| [getWithdrawQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1640) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/quota` | +| [getDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1647) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/hisrec` | +| [getDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1651) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address` | +| [getDepositAddresses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1657) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address/list` | +| [submitDepositCredit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1663) | :closed_lock_with_key: | POST | `sapi/v1/capital/deposit/credit-apply` | +| [getAutoConvertStablecoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1672) | :closed_lock_with_key: | GET | `sapi/v1/capital/contract/convertible-coins` | +| [setConvertibleCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1679) | :closed_lock_with_key: | POST | `sapi/v1/capital/contract/convertible-coins` | +| [getAssetDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1692) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDetail` | +| [getWalletBalances()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1698) | :closed_lock_with_key: | GET | `sapi/v1/asset/wallet/balance` | +| [getUserAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1704) | :closed_lock_with_key: | POST | `sapi/v3/asset/getUserAsset` | +| [getSpotAssetTags()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1708) | | GET | `sapi/v1/spot/asset/tags` | +| [submitUniversalTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1712) | :closed_lock_with_key: | POST | `sapi/v1/asset/transfer` | +| [getUniversalTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1718) | :closed_lock_with_key: | GET | `sapi/v1/asset/transfer` | +| [getDust()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1724) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-btc` | +| [convertDustToBnb()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1728) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust` | +| [convertDustAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1735) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/convert` | +| [queryDustConvertibleAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1742) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/query-convertible-assets` | +| [getDustLog()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1751) | :closed_lock_with_key: | GET | `sapi/v1/asset/dribblet` | +| [getAssetDividendRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1755) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDividend` | +| [getTradeFee()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1759) | :closed_lock_with_key: | GET | `sapi/v1/asset/tradeFee` | +| [getFundingAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1763) | :closed_lock_with_key: | POST | `sapi/v1/asset/get-funding-asset` | +| [getCloudMiningHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1767) | :closed_lock_with_key: | GET | `sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage` | +| [getDelegationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1777) | :closed_lock_with_key: | GET | `sapi/v1/asset/custody/transfer-history` | +| [submitNewFutureAccountTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1807) | :closed_lock_with_key: | POST | `sapi/v1/futures/transfer` | +| [getFutureAccountTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1817) | :closed_lock_with_key: | GET | `sapi/v1/futures/transfer` | +| [getCrossCollateralBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1826) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/borrow/history` | +| [getCrossCollateralRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1833) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/repay/history` | +| [getCrossCollateralWalletV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1840) | :closed_lock_with_key: | GET | `sapi/v2/futures/loan/wallet` | +| [getAdjustCrossCollateralLTVHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1847) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/adjustCollateral/history` | +| [getCrossCollateralLiquidationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1859) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/liquidationHistory` | +| [getCrossCollateralInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1868) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/interestHistory` | +| [getAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1880) | :closed_lock_with_key: | GET | `sapi/v1/account/info` | +| [getDailyAccountSnapshot()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1884) | :closed_lock_with_key: | GET | `sapi/v1/accountSnapshot` | +| [disableFastWithdrawSwitch()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1890) | :closed_lock_with_key: | POST | `sapi/v1/account/disableFastWithdrawSwitch` | +| [enableFastWithdrawSwitch()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1894) | :closed_lock_with_key: | POST | `sapi/v1/account/enableFastWithdrawSwitch` | +| [getAccountStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1898) | :closed_lock_with_key: | GET | `sapi/v1/account/status` | +| [getApiTradingStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1902) | :closed_lock_with_key: | GET | `sapi/v1/account/apiTradingStatus` | +| [getApiKeyPermissions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1906) | :closed_lock_with_key: | GET | `sapi/v1/account/apiRestrictions` | +| [withdrawTravelRule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1922) | :closed_lock_with_key: | POST | `sapi/v1/localentity/withdraw/apply` | +| [getTravelRuleWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1933) | :closed_lock_with_key: | GET | `sapi/v1/localentity/withdraw/history` | +| [getTravelRuleWithdrawHistoryV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1942) | :closed_lock_with_key: | GET | `sapi/v2/localentity/withdraw/history` | +| [submitTravelRuleDepositQuestionnaire()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1954) | :closed_lock_with_key: | PUT | `sapi/v1/localentity/deposit/provide-info` | +| [getTravelRuleDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1963) | :closed_lock_with_key: | GET | `sapi/v1/localentity/deposit/history` | +| [getOnboardedVASPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1974) | :closed_lock_with_key: | GET | `sapi/v1/localentity/vasp` | +| [getTravelRuleCountryList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1978) | :closed_lock_with_key: | GET | `sapi/v1/localentity/country/list` | +| [getTravelRuleRegionList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1982) | :closed_lock_with_key: | GET | `sapi/v1/localentity/region/list` | +| [getSystemStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1994) | | GET | `sapi/v1/system/status` | +| [getDelistSchedule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1998) | :closed_lock_with_key: | GET | `sapi/v1/spot/delist-schedule` | +| [createVirtualSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2008) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/virtualSubAccount` | +| [getSubAccountList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2014) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/list` | +| [subAccountEnableFutures()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2020) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/enable` | +| [subAccountEnableMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2028) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/enable` | +| [enableOptionsForSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2032) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/eoptions/enable` | +| [subAccountEnableLeverageToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2042) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/blvt/enable` | +| [getSubAccountStatusOnMarginOrFutures()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2048) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/status` | +| [getSubAccountFuturesPositionRisk()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2054) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/positionRisk` | +| [getSubAccountFuturesPositionRiskV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2062) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/positionRisk` | +| [getSubAccountTransactionStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2068) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transaction-statistics` | +| [getSubAccountIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2083) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/subAccountApi/ipRestriction` | +| [subAccountDeleteIPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2092) | :closed_lock_with_key: | DELETE | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | +| [subAccountAddIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2101) | :closed_lock_with_key: | POST | `sapi/v2/sub-account/subAccountApi/ipRestriction` | +| [subAccountAddIPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2114) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | +| [subAccountEnableOrDisableIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2127) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction` | +| [subAccountFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2142) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/transfer` | +| [getSubAccountFuturesAccountDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2148) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/account` | +| [getSubAccountDetailOnFuturesAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2154) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/account` | +| [getSubAccountDetailOnMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2160) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/account` | +| [getSubAccountDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2166) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subAddress` | +| [getSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2172) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subHisrec` | +| [getSubAccountFuturesAccountSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2178) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/accountSummary` | +| [getSubAccountSummaryOnFuturesAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2182) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/accountSummary` | +| [getSubAccountsSummaryOfMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2191) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/accountSummary` | +| [subAccountMarginTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2195) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/transfer` | +| [getSubAccountAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2201) | :closed_lock_with_key: | GET | `sapi/v3/sub-account/assets` | +| [getSubAccountAssetsMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2207) | :closed_lock_with_key: | GET | `sapi/v4/sub-account/assets` | +| [getSubAccountFuturesAssetTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2213) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/internalTransfer` | +| [getSubAccountSpotAssetTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2222) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/sub/transfer/history` | +| [getSubAccountSpotAssetsSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2228) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/spotSummary` | +| [getSubAccountUniversalTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2234) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/universalTransfer` | +| [subAccountFuturesAssetTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2240) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/internalTransfer` | +| [subAccountTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2249) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transfer/subUserHistory` | +| [subAccountTransferToMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2258) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToMaster` | +| [subAccountTransferToSameMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2264) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToSub` | +| [subAccountUniversalTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2270) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/universalTransfer` | +| [subAccountMovePosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2276) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/move-position` | +| [getSubAccountFuturesPositionMoveHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2285) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/move-position` | +| [depositAssetsIntoManagedSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2300) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/deposit` | +| [getManagedSubAccountDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2306) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/deposit/address` | +| [withdrawAssetsFromManagedSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2315) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/withdraw` | +| [getManagedSubAccountTransfersParent()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2321) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForTradeParent` | +| [getManagedSubAccountTransferLog()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2333) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/query-trans-log` | +| [getManagedSubAccountTransfersInvestor()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2345) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForInvestor` | +| [getManagedSubAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2357) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/info` | +| [getManagedSubAccountSnapshot()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2364) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/accountSnapshot` | +| [getManagedSubAccountAssetDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2373) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/asset` | +| [getManagedSubAccountMarginAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2379) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/marginAsset` | +| [getManagedSubAccountFuturesAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2386) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/fetch-future-asset` | +| [getAutoInvestAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2402) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/all/asset` | +| [getAutoInvestSourceAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2409) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/source-asset/list` | +| [getAutoInvestTargetAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2418) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/list` | +| [getAutoInvestTargetAssetsROI()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2427) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/roi/list` | +| [getAutoInvestIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2436) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/info` | +| [getAutoInvestPlans()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2442) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/list` | +| [submitAutoInvestOneTimeTransaction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2460) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/one-off` | +| [updateAutoInvestPlanStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2476) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit-status` | +| [updateAutoInvestmentPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2485) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit` | +| [submitAutoInvestRedemption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2502) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/redeem` | +| [getAutoInvestSubscriptionTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2510) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/history/list` | +| [getOneTimeTransactionStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2516) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/one-off/status` | +| [submitAutoInvestmentPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2525) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/add` | +| [getAutoInvestRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2540) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/redeem/history` | +| [getAutoInvestPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2549) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/id` | +| [getAutoInvestUserIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2553) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/user-summary` | +| [getAutoInvestRebalanceHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2562) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/rebalance/history` | +| [getConvertPairs()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2577) | :closed_lock_with_key: | GET | `sapi/v1/convert/exchangeInfo` | +| [getConvertAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2581) | :closed_lock_with_key: | GET | `sapi/v1/convert/assetInfo` | +| [convertQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2591) | :closed_lock_with_key: | POST | `sapi/v1/convert/getQuote` | +| [acceptQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2595) | :closed_lock_with_key: | POST | `sapi/v1/convert/acceptQuote` | +| [getConvertTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2599) | :closed_lock_with_key: | GET | `sapi/v1/convert/tradeFlow` | +| [getOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2603) | :closed_lock_with_key: | GET | `sapi/v1/convert/orderStatus` | +| [submitConvertLimitOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2607) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/placeOrder` | +| [cancelConvertLimitOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2611) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/cancelOrder` | +| [getConvertLimitOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2615) | :closed_lock_with_key: | GET | `sapi/v1/convert/limit/queryOpenOrders` | +| [getEthStakingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2630) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/account` | +| [getEthStakingAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2634) | :closed_lock_with_key: | GET | `sapi/v2/eth-staking/account` | +| [getEthStakingQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2638) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/quota` | +| [subscribeEthStakingV1()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2651) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/stake` | +| [subscribeEthStakingV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2657) | :closed_lock_with_key: | POST | `sapi/v2/eth-staking/eth/stake` | +| [redeemEth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2663) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/redeem` | +| [wrapBeth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2667) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/wbeth/wrap` | +| [getEthStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2677) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/stakingHistory` | +| [getEthRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2687) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/redemptionHistory` | +| [getBethRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2697) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rewardsHistory` | +| [getWbethRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2707) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/wbethRewardsHistory` | +| [getEthRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2716) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rateHistory` | +| [getBethWrapHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2726) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/wrapHistory` | +| [getBethUnwrapHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2736) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/unwrapHistory` | +| [getBfusdAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2752) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/account` | +| [getBfusdQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2756) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/quota` | +| [subscribeBfusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2760) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/subscribe` | +| [redeemBfusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2766) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/redeem` | +| [getBfusdSubscriptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2770) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/subscriptionHistory` | +| [getBfusdRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2776) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/redemptionHistory` | +| [getBfusdRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2782) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rewardsHistory` | +| [getBfusdRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2788) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rateHistory` | +| [getRwusdAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2800) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/account` | +| [getRwusdQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2804) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/quota` | +| [subscribeRwusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2808) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/subscribe` | +| [redeemRwusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2814) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/redeem` | +| [getRwusdSubscriptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2818) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/subscriptionHistory` | +| [getRwusdRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2824) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/redemptionHistory` | +| [getRwusdRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2830) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rewardsHistory` | +| [getRwusdRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2836) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rateHistory` | +| [getStakingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2845) | :closed_lock_with_key: | GET | `sapi/v1/staking/productList` | +| [getStakingProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2856) | :closed_lock_with_key: | GET | `sapi/v1/staking/position` | +| [getStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2868) | :closed_lock_with_key: | GET | `sapi/v1/staking/stakingRecord` | +| [getPersonalLeftQuotaOfStakingProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2875) | :closed_lock_with_key: | GET | `sapi/v1/staking/personalLeftQuota` | +| [getSolStakingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2888) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/account` | +| [getSolStakingQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2892) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/quota` | +| [subscribeSolStaking()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2902) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/stake` | +| [redeemSol()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2908) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/redeem` | +| [claimSolBoostRewards()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2912) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/claim` | +| [getSolStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2924) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/stakingHistory` | +| [getSolRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2934) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/redemptionHistory` | +| [getBnsolRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2944) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/bnsolRewardsHistory` | +| [getBnsolRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2955) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/rateHistory` | +| [getSolBoostRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2965) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/boostRewardsHistory` | +| [getSolUnclaimedRewards()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2975) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/unclaimedRewards` | +| [getOnchainYieldsLockedProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2990) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/list` | +| [getOnchainYieldsLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2996) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/personalLeftQuota` | +| [getOnchainYieldsLockedPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3005) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/position` | +| [getOnchainYieldsAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3011) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/account` | +| [getOnchainYieldsLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3021) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/subscriptionPreview` | +| [subscribeOnchainYieldsLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3030) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/subscribe` | +| [setOnchainYieldsLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3036) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setAutoSubscribe` | +| [setOnchainYieldsLockedRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3045) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setRedeemOption` | +| [redeemOnchainYieldsLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3054) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/redeem` | +| [getOnchainYieldsLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3066) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/subscriptionRecord` | +| [getOnchainYieldsLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3075) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/rewardsRecord` | +| [getOnchainYieldsLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3084) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/redemptionRecord` | +| [getSoftStakingProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3099) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/list` | +| [setSoftStaking()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3105) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/set` | +| [getSoftStakingRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3111) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/history/rewardsRecord` | +| [getFuturesLeadTraderStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3126) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/userStatus` | +| [getFuturesLeadTradingSymbolWhitelist()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3130) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/leadSymbol` | +| [getMiningAlgos()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3142) | | GET | `sapi/v1/mining/pub/algoList` | +| [getMiningCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3146) | | GET | `sapi/v1/mining/pub/coinList` | +| [getHashrateResales()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3150) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/config/details/list` | +| [getMiners()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3159) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/list` | +| [getMinerDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3163) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/detail` | +| [getExtraBonuses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3169) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/other` | +| [getMiningEarnings()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3175) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/list` | +| [cancelHashrateResaleConfig()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3181) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config/cancel` | +| [getHashrateResale()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3190) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/profit/details` | +| [getMiningAccountEarnings()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3199) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/uid` | +| [getMiningStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3205) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/status` | +| [submitHashrateResale()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3211) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config` | +| [getMiningAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3215) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/list` | +| [submitVpNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3227) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderVp` | +| [submitTwapNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3234) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderTwap` | +| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3241) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/futures/order` | +| [getAlgoSubOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3247) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/subOrders` | +| [getAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3253) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/openOrders` | +| [getAlgoHistoricalOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3260) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/historicalOrders` | +| [submitSpotAlgoTwapOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3273) | :closed_lock_with_key: | POST | `sapi/v1/algo/spot/newOrderTwap` | +| [cancelSpotAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3280) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/spot/order` | +| [getSpotAlgoSubOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3286) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/subOrders` | +| [getSpotAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3292) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/openOrders` | +| [getSpotAlgoHistoricalOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3299) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/historicalOrders` | +| [getCryptoLoanFlexibleCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3314) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/collateral/data` | +| [getCryptoLoanFlexibleAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3323) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/loanable/data` | +| [borrowCryptoLoanFlexible()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3336) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/borrow` | +| [repayCryptoLoanFlexible()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3342) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay` | +| [repayCryptoLoanFlexibleWithCollateral()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3348) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay/collateral` | +| [adjustCryptoLoanFlexibleLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3354) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/adjust/ltv` | +| [getCryptoLoanFlexibleLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3366) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ltv/adjustment/history` | +| [getFlexibleLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3378) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/rate` | +| [getLoanFlexibleBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3389) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/borrow/history` | +| [getCryptoLoanFlexibleOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3398) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ongoing/orders` | +| [getFlexibleLoanLiquidationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3407) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/liquidation/history` | +| [getLoanFlexibleRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3416) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/history` | +| [getCryptoLoanLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3434) | :closed_lock_with_key: | GET | `sapi/v1/loan/loanable/data` | +| [getCryptoLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3441) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/collateral/rate` | +| [getCryptoLoanCollateralAssetsData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3450) | :closed_lock_with_key: | GET | `sapi/v1/loan/collateral/data` | +| [getCryptoLoansIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3459) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | +| [borrowCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3474) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | +| [repayCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3483) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | +| [adjustCryptoLoanLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3492) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | +| [customizeCryptoLoanMarginCall()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3501) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | +| [getCryptoLoanOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3517) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | +| [getCryptoLoanBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3524) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | +| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3531) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | +| [getCryptoLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3540) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | +| [getSimpleEarnAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3552) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | +| [getFlexibleSavingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3556) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | +| [getSimpleEarnLockedProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3563) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | +| [getFlexibleProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3572) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | +| [getLockedProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3581) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | +| [getFlexiblePersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3590) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | +| [getLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3599) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | +| [purchaseFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3614) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | +| [subscribeSimpleEarnLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3620) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | +| [redeemFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3626) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | +| [redeemLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3632) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | +| [setFlexibleAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3638) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | +| [setLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3647) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | +| [getFlexibleSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3656) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | +| [getLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3665) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | +| [setLockedProductRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3674) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | +| [getFlexibleSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3692) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | +| [getLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3704) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | +| [getFlexibleRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3716) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | +| [getLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3728) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | +| [getFlexibleRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3738) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | +| [getLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3748) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | +| [getCollateralRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3758) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | +| [getRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3768) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | +| [getVipBorrowInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3784) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | +| [getVipLoanInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3790) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | +| [getVipLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3799) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | +| [getVipCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3806) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | +| [getVipLoanOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3819) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | +| [getVipLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3826) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | +| [checkVipCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3835) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | +| [getVipApplicationStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3842) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | +| [renewVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3855) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | +| [repayVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3859) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | +| [borrowVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3863) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | +| [getVipLoanFixedRateMarket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3867) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/fixed/market` | +| [borrowVipLoanFixedRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3874) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/fixed/borrow` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3886) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | +| [subscribeDualInvestmentProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3901) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | +| [getDualInvestmentPositions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3907) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | +| [getDualInvestmentAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3916) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | +| [getVipLoanAccruedInterest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3920) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | +| [updateAutoCompoundStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3927) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | +| [createGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3942) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | +| [createDualTokenGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3946) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | +| [redeemGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3950) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | +| [verifyGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3954) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | +| [getTokenLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3958) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | +| [getRsaPublicKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3962) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | +| [getNftTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3972) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | +| [getNftDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3979) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | +| [getNftWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3986) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | +| [getNftAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3993) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | +| [getC2CTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4006) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | +| [getFiatOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4021) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | +| [getFiatPaymentsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4027) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | +| [fiatWithdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4033) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | +| [fiatDeposit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4037) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | +| [getFiatOrderDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4041) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | +| [getSpotRebateHistoryRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4053) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | +| [getPortfolioMarginIndexPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4066) | | GET | `sapi/v1/portfolio/asset-index-price` | +| [getPortfolioMarginAssetLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4072) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | +| [getPortfolioMarginProCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4078) | | GET | `sapi/v1/portfolio/collateralRate` | +| [getPortfolioMarginProTieredCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4084) | | GET | `sapi/v2/portfolio/collateralRate` | +| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4095) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | +| [getPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4099) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/delta-mode` | +| [switchPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4103) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/delta-mode` | +| [setPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4109) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | +| [getPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4115) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | +| [deletePortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4119) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | +| [bnbTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4123) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | +| [submitPortfolioMarginProFullTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4129) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | +| [submitPortfolioMarginProSpecificTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4135) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | +| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4141) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | +| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4149) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | +| [repayFuturesNegativeBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4153) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | +| [updateAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4159) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | +| [getAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4165) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | +| [getPortfolioMarginProInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4171) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | +| [getPortfolioMarginProSpanAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4177) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | +| [getPortfolioMarginProAccountBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4181) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | +| [mintPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4191) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | +| [redeemPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4201) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | +| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4209) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | +| [transferLDUSDTPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4224) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | +| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4237) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | +| [getFuturesTickLevelOrderbookDataLink()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4254) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | +| [getBlvtInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4268) | | GET | `sapi/v1/blvt/tokenInfo` | +| [subscribeBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4272) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | +| [getBlvtSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4276) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | +| [redeemBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4282) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | +| [getBlvtRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4286) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | +| [getBlvtUserLimitInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4292) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | +| [getPayTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4303) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | +| [getInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4313) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | +| [closeInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4319) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | +| [addInstLoanCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4323) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | +| [getActiveInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4329) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | +| [getClosedInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4333) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | +| [getInstLoanForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4345) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | +| [transferInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4359) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | +| [getInstitutionalLoanMaxBorrowable()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4371) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/max-borrowable` | +| [borrowInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4377) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | +| [getInstLoanInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4383) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | +| [repayInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4392) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | +| [getInstLoanBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4398) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | +| [getMarginInterestRebateBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4404) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | +| [getMarginInterestRebateBalanceRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4408) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | +| [getAlphaTokenList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4423) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | +| [getAlphaExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4430) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | +| [getAlphaAggTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4437) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | +| [getAlphaKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4445) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | +| [getAlphaTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4453) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | +| [getAlphaFullDepth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4461) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | +| [createBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4477) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [getBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4483) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | +| [enableMarginBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4489) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | +| [createApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4495) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | +| [changePermissionApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4501) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [changeComissionBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4507) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4513) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | +| [updateIpRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4522) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | +| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4536) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | +| [deleteApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4552) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | +| [getSubAccountBrokerIpRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4558) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | +| [getApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4574) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | +| [getBrokerInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4580) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | +| [updateSubAccountBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4584) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | +| [updateSubAccountMarginInterestBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4594) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | +| [getSubAccountBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4607) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | +| [deleteBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4623) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | +| [transferBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4633) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | +| [getBrokerSubAccountHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4639) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | +| [submitBrokerSubFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4645) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | +| [getSubAccountFuturesTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4660) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | +| [getBrokerSubDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4672) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | +| [getBrokerSubAccountSpotAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4678) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | +| [getSubAccountMarginAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4687) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | +| [querySubAccountFuturesAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4696) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | +| [universalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4705) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | +| [getUniversalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4712) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | +| [updateBrokerSubAccountCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4724) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | +| [updateBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4730) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | +| [getBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4739) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | +| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4748) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4757) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4766) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | +| [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4772) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | +| [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4809) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | +| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4820) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | +| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4839) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4849) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | +| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4890) | | POST | `api/v3/userDataStream` | +| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4894) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | +| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4898) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | +| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4905) | | POST | `sapi/v1/userDataStream` | +| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4909) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4913) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4918) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4926) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4935) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4947) | | POST | `sapi/v1/margin/listen-key` | +| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4951) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4955) | | DELETE | `sapi/v1/margin/listen-key` | +| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4963) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | +| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4985) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | +| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4992) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | +| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5001) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | +| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5010) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | +| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5025) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | +| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5034) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | +| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5048) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | +| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5058) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | +| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5067) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | +| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5076) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | +| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5083) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | +| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5090) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | +| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5097) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | +| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5104) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | +| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5121) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | +| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5129) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | +| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5136) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | # usdm-client.ts @@ -581,109 +584,109 @@ 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/usdm-client.ts#L142) | | GET | `fapi/v1/ping` | -| [getExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L146) | | GET | `fapi/v1/exchangeInfo` | -| [getOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L150) | | GET | `fapi/v1/depth` | -| [getRpiOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L154) | | GET | `fapi/v1/rpiDepth` | -| [getRecentTrades()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L161) | | GET | `fapi/v1/trades` | -| [getHistoricalTrades()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L165) | | GET | `fapi/v1/historicalTrades` | -| [getAggregateTrades()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L171) | | GET | `fapi/v1/aggTrades` | -| [getKlines()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L177) | | GET | `fapi/v1/klines` | -| [getContinuousContractKlines()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L181) | | GET | `fapi/v1/continuousKlines` | -| [getIndexPriceKlines()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L187) | | GET | `fapi/v1/indexPriceKlines` | -| [getMarkPriceKlines()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L191) | | GET | `fapi/v1/markPriceKlines` | -| [getPremiumIndexKlines()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L195) | | GET | `fapi/v1/premiumIndexKlines` | -| [getMarkPrice()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L199) | | GET | `fapi/v1/premiumIndex` | -| [getFundingRateHistory()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L207) | | GET | `fapi/v1/fundingRate` | -| [getFundingRates()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L213) | | GET | `fapi/v1/fundingInfo` | -| [get24hrChangeStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L217) | | GET | `fapi/v1/ticker/24hr` | -| [getSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L227) | | GET | `fapi/v1/ticker/price` | -| [getSymbolPriceTickerV2()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L237) | | GET | `fapi/v2/ticker/price` | -| [getSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L247) | | GET | `fapi/v1/ticker/bookTicker` | -| [getQuarterlyContractSettlementPrices()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L259) | | GET | `futures/data/delivery-price` | -| [getOpenInterest()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L265) | | GET | `fapi/v1/openInterest` | -| [getOpenInterestStatistics()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L269) | | GET | `futures/data/openInterestHist` | -| [getTopTradersLongShortPositionRatio()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L275) | | GET | `futures/data/topLongShortPositionRatio` | -| [getTopTradersLongShortAccountRatio()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L281) | | GET | `futures/data/topLongShortAccountRatio` | -| [getGlobalLongShortAccountRatio()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L287) | | GET | `futures/data/globalLongShortAccountRatio` | -| [getTakerBuySellVolume()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L293) | | GET | `futures/data/takerlongshortRatio` | -| [getHistoricalBlvtNavKlines()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L297) | | GET | `fapi/v1/lvtKlines` | -| [getCompositeSymbolIndex()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L301) | | GET | `fapi/v1/indexInfo` | -| [getMultiAssetsModeAssetIndex()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L305) | | GET | `fapi/v1/assetIndex` | -| [getBasis()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L312) | | GET | `futures/data/basis` | -| [getIndexPriceConstituents()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L316) | | GET | `fapi/v1/constituents` | -| [getInsuranceFundBalance()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L322) | | GET | `fapi/v1/insuranceBalance` | -| [getTradingSchedule()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L328) | | GET | `fapi/v1/tradingSchedule` | -| [submitNewOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L338) | :closed_lock_with_key: | POST | `fapi/v1/order` | -| [submitMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L350) | :closed_lock_with_key: | POST | `fapi/v1/batchOrders` | -| [modifyOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L379) | :closed_lock_with_key: | PUT | `fapi/v1/order` | -| [modifyMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L385) | :closed_lock_with_key: | PUT | `fapi/v1/batchOrders` | -| [getOrderModifyHistory()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L393) | :closed_lock_with_key: | GET | `fapi/v1/orderAmendment` | -| [cancelOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L399) | :closed_lock_with_key: | DELETE | `fapi/v1/order` | -| [cancelMultipleOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L403) | :closed_lock_with_key: | DELETE | `fapi/v1/batchOrders` | -| [cancelAllOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L423) | :closed_lock_with_key: | DELETE | `fapi/v1/allOpenOrders` | -| [setCancelOrdersOnTimeout()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L430) | :closed_lock_with_key: | POST | `fapi/v1/countdownCancelAll` | -| [getOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L436) | :closed_lock_with_key: | GET | `fapi/v1/order` | -| [getAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L440) | :closed_lock_with_key: | GET | `fapi/v1/allOrders` | -| [getAllOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L444) | :closed_lock_with_key: | GET | `fapi/v1/openOrders` | -| [getCurrentOpenOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L448) | :closed_lock_with_key: | GET | `fapi/v1/openOrder` | -| [getForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L452) | :closed_lock_with_key: | GET | `fapi/v1/forceOrders` | -| [getAccountTrades()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L456) | :closed_lock_with_key: | GET | `fapi/v1/userTrades` | -| [setMarginType()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L462) | :closed_lock_with_key: | POST | `fapi/v1/marginType` | -| [setPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L466) | :closed_lock_with_key: | POST | `fapi/v1/positionSide/dual` | -| [setLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L470) | :closed_lock_with_key: | POST | `fapi/v1/leverage` | -| [setMultiAssetsMode()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L474) | :closed_lock_with_key: | POST | `fapi/v1/multiAssetsMargin` | -| [setIsolatedPositionMargin()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L480) | :closed_lock_with_key: | POST | `fapi/v1/positionMargin` | -| [getPositions()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L490) | :closed_lock_with_key: | GET | `fapi/v2/positionRisk` | -| [getPositionsV3()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L494) | :closed_lock_with_key: | GET | `fapi/v3/positionRisk` | -| [getADLQuantileEstimation()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L498) | :closed_lock_with_key: | GET | `fapi/v1/adlQuantile` | -| [getSymbolAdlRisk()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L502) | | GET | `fapi/v1/symbolAdlRisk` | -| [getPositionMarginChangeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L512) | :closed_lock_with_key: | GET | `fapi/v1/positionMargin/history` | -| [getBalanceV3()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L524) | :closed_lock_with_key: | GET | `fapi/v3/balance` | -| [getBalance()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L532) | :closed_lock_with_key: | GET | `fapi/v2/balance` | -| [getAccountInformationV3()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L536) | :closed_lock_with_key: | GET | `fapi/v3/account` | -| [getAccountInformation()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L544) | :closed_lock_with_key: | GET | `fapi/v2/account` | -| [getAccountCommissionRate()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L548) | :closed_lock_with_key: | GET | `fapi/v1/commissionRate` | -| [getFuturesAccountConfig()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L554) | :closed_lock_with_key: | GET | `fapi/v1/accountConfig` | -| [getFuturesSymbolConfig()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L558) | :closed_lock_with_key: | GET | `fapi/v1/symbolConfig` | -| [getUserForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L562) | :closed_lock_with_key: | GET | `fapi/v1/rateLimit/order` | -| [getNotionalAndLeverageBrackets()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L569) | :closed_lock_with_key: | GET | `fapi/v1/leverageBracket` | -| [getMultiAssetsMode()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L575) | :closed_lock_with_key: | GET | `fapi/v1/multiAssetsMargin` | -| [getCurrentPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L579) | :closed_lock_with_key: | GET | `fapi/v1/positionSide/dual` | -| [getIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L583) | :closed_lock_with_key: | GET | `fapi/v1/income` | -| [getApiQuantitativeRulesIndicators()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L587) | :closed_lock_with_key: | GET | `fapi/v1/apiTradingStatus` | -| [getFuturesTransactionHistoryDownloadId()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L593) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn` | -| [getFuturesTransactionHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L600) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn/id` | -| [getFuturesOrderHistoryDownloadId()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L606) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn` | -| [getFuturesOrderHistoryDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L613) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn/id` | -| [getFuturesTradeHistoryDownloadId()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L619) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn` | -| [getFuturesTradeDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L626) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn/id` | -| [setBNBBurnEnabled()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L632) | :closed_lock_with_key: | POST | `fapi/v1/feeBurn` | -| [getBNBBurnStatus()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L638) | :closed_lock_with_key: | GET | `fapi/v1/feeBurn` | -| [signTradFiPerpsAgreement()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L644) | :closed_lock_with_key: | POST | `fapi/v1/stock/contract` | -| [testOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L648) | :closed_lock_with_key: | POST | `fapi/v1/order/test` | -| [submitNewAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L660) | :closed_lock_with_key: | POST | `fapi/v1/algoOrder` | -| [cancelAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L667) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOrder` | -| [cancelAllAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L673) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOpenOrders` | -| [getAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L679) | :closed_lock_with_key: | GET | `fapi/v1/algoOrder` | -| [getOpenAlgoOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L685) | :closed_lock_with_key: | GET | `fapi/v1/openAlgoOrders` | -| [getAllAlgoOrders()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L691) | :closed_lock_with_key: | GET | `fapi/v1/allAlgoOrders` | -| [getAllConvertPairs()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L703) | | GET | `fapi/v1/convert/exchangeInfo` | -| [submitConvertQuoteRequest()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L710) | :closed_lock_with_key: | POST | `fapi/v1/convert/getQuote` | -| [acceptConvertQuote()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L716) | :closed_lock_with_key: | POST | `fapi/v1/convert/acceptQuote` | -| [getConvertOrderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L724) | :closed_lock_with_key: | GET | `fapi/v1/convert/orderStatus` | -| [getPortfolioMarginProAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L737) | :closed_lock_with_key: | GET | `fapi/v1/pmAccountInfo` | -| [getBrokerIfNewFuturesUser()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L754) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/ifNewUser` | -| [setBrokerCustomIdForClient()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L767) | :closed_lock_with_key: | POST | `fapi/v1/apiReferral/customization` | -| [getBrokerClientCustomIds()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L780) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/customization` | -| [getBrokerUserCustomId()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L797) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/userCustomization` | -| [getBrokerRebateDataOverview()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L806) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/overview` | -| [getBrokerUserTradeVolume()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L815) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/tradeVol` | -| [getBrokerRebateVolume()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L832) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/rebateVol` | -| [getBrokerTradeDetail()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L849) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/traderSummary` | -| [getFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L871) | | POST | `fapi/v1/listenKey` | -| [keepAliveFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L875) | | PUT | `fapi/v1/listenKey` | -| [closeFuturesUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/usdm-client.ts#L879) | | DELETE | `fapi/v1/listenKey` | +| [testConnectivity()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L142) | | GET | `fapi/v1/ping` | +| [getExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L146) | | GET | `fapi/v1/exchangeInfo` | +| [getOrderBook()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L150) | | GET | `fapi/v1/depth` | +| [getRpiOrderBook()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L154) | | GET | `fapi/v1/rpiDepth` | +| [getRecentTrades()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L161) | | GET | `fapi/v1/trades` | +| [getHistoricalTrades()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L165) | | GET | `fapi/v1/historicalTrades` | +| [getAggregateTrades()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L171) | | GET | `fapi/v1/aggTrades` | +| [getKlines()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L177) | | GET | `fapi/v1/klines` | +| [getContinuousContractKlines()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L181) | | GET | `fapi/v1/continuousKlines` | +| [getIndexPriceKlines()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L187) | | GET | `fapi/v1/indexPriceKlines` | +| [getMarkPriceKlines()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L191) | | GET | `fapi/v1/markPriceKlines` | +| [getPremiumIndexKlines()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L195) | | GET | `fapi/v1/premiumIndexKlines` | +| [getMarkPrice()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L199) | | GET | `fapi/v1/premiumIndex` | +| [getFundingRateHistory()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L207) | | GET | `fapi/v1/fundingRate` | +| [getFundingRates()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L213) | | GET | `fapi/v1/fundingInfo` | +| [get24hrChangeStatistics()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L217) | | GET | `fapi/v1/ticker/24hr` | +| [getSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L227) | | GET | `fapi/v1/ticker/price` | +| [getSymbolPriceTickerV2()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L237) | | GET | `fapi/v2/ticker/price` | +| [getSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L247) | | GET | `fapi/v1/ticker/bookTicker` | +| [getQuarterlyContractSettlementPrices()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L259) | | GET | `futures/data/delivery-price` | +| [getOpenInterest()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L265) | | GET | `fapi/v1/openInterest` | +| [getOpenInterestStatistics()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L269) | | GET | `futures/data/openInterestHist` | +| [getTopTradersLongShortPositionRatio()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L275) | | GET | `futures/data/topLongShortPositionRatio` | +| [getTopTradersLongShortAccountRatio()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L281) | | GET | `futures/data/topLongShortAccountRatio` | +| [getGlobalLongShortAccountRatio()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L287) | | GET | `futures/data/globalLongShortAccountRatio` | +| [getTakerBuySellVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L293) | | GET | `futures/data/takerlongshortRatio` | +| [getHistoricalBlvtNavKlines()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L297) | | GET | `fapi/v1/lvtKlines` | +| [getCompositeSymbolIndex()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L301) | | GET | `fapi/v1/indexInfo` | +| [getMultiAssetsModeAssetIndex()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L305) | | GET | `fapi/v1/assetIndex` | +| [getBasis()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L312) | | GET | `futures/data/basis` | +| [getIndexPriceConstituents()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L316) | | GET | `fapi/v1/constituents` | +| [getInsuranceFundBalance()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L322) | | GET | `fapi/v1/insuranceBalance` | +| [getTradingSchedule()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L328) | | GET | `fapi/v1/tradingSchedule` | +| [submitNewOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L338) | :closed_lock_with_key: | POST | `fapi/v1/order` | +| [submitMultipleOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L350) | :closed_lock_with_key: | POST | `fapi/v1/batchOrders` | +| [modifyOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L379) | :closed_lock_with_key: | PUT | `fapi/v1/order` | +| [modifyMultipleOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L385) | :closed_lock_with_key: | PUT | `fapi/v1/batchOrders` | +| [getOrderModifyHistory()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L393) | :closed_lock_with_key: | GET | `fapi/v1/orderAmendment` | +| [cancelOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L399) | :closed_lock_with_key: | DELETE | `fapi/v1/order` | +| [cancelMultipleOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L403) | :closed_lock_with_key: | DELETE | `fapi/v1/batchOrders` | +| [cancelAllOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L423) | :closed_lock_with_key: | DELETE | `fapi/v1/allOpenOrders` | +| [setCancelOrdersOnTimeout()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L430) | :closed_lock_with_key: | POST | `fapi/v1/countdownCancelAll` | +| [getOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L436) | :closed_lock_with_key: | GET | `fapi/v1/order` | +| [getAllOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L440) | :closed_lock_with_key: | GET | `fapi/v1/allOrders` | +| [getAllOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L444) | :closed_lock_with_key: | GET | `fapi/v1/openOrders` | +| [getCurrentOpenOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L448) | :closed_lock_with_key: | GET | `fapi/v1/openOrder` | +| [getForceOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L452) | :closed_lock_with_key: | GET | `fapi/v1/forceOrders` | +| [getAccountTrades()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L456) | :closed_lock_with_key: | GET | `fapi/v1/userTrades` | +| [setMarginType()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L462) | :closed_lock_with_key: | POST | `fapi/v1/marginType` | +| [setPositionMode()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L466) | :closed_lock_with_key: | POST | `fapi/v1/positionSide/dual` | +| [setLeverage()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L470) | :closed_lock_with_key: | POST | `fapi/v1/leverage` | +| [setMultiAssetsMode()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L474) | :closed_lock_with_key: | POST | `fapi/v1/multiAssetsMargin` | +| [setIsolatedPositionMargin()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L480) | :closed_lock_with_key: | POST | `fapi/v1/positionMargin` | +| [getPositions()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L490) | :closed_lock_with_key: | GET | `fapi/v2/positionRisk` | +| [getPositionsV3()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L494) | :closed_lock_with_key: | GET | `fapi/v3/positionRisk` | +| [getADLQuantileEstimation()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L498) | :closed_lock_with_key: | GET | `fapi/v1/adlQuantile` | +| [getSymbolAdlRisk()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L502) | | GET | `fapi/v1/symbolAdlRisk` | +| [getPositionMarginChangeHistory()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L512) | :closed_lock_with_key: | GET | `fapi/v1/positionMargin/history` | +| [getBalanceV3()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L524) | :closed_lock_with_key: | GET | `fapi/v3/balance` | +| [getBalance()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L532) | :closed_lock_with_key: | GET | `fapi/v2/balance` | +| [getAccountInformationV3()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L536) | :closed_lock_with_key: | GET | `fapi/v3/account` | +| [getAccountInformation()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L544) | :closed_lock_with_key: | GET | `fapi/v2/account` | +| [getAccountCommissionRate()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L548) | :closed_lock_with_key: | GET | `fapi/v1/commissionRate` | +| [getFuturesAccountConfig()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L554) | :closed_lock_with_key: | GET | `fapi/v1/accountConfig` | +| [getFuturesSymbolConfig()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L558) | :closed_lock_with_key: | GET | `fapi/v1/symbolConfig` | +| [getUserForceOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L562) | :closed_lock_with_key: | GET | `fapi/v1/rateLimit/order` | +| [getNotionalAndLeverageBrackets()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L569) | :closed_lock_with_key: | GET | `fapi/v1/leverageBracket` | +| [getMultiAssetsMode()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L575) | :closed_lock_with_key: | GET | `fapi/v1/multiAssetsMargin` | +| [getCurrentPositionMode()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L579) | :closed_lock_with_key: | GET | `fapi/v1/positionSide/dual` | +| [getIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L583) | :closed_lock_with_key: | GET | `fapi/v1/income` | +| [getApiQuantitativeRulesIndicators()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L587) | :closed_lock_with_key: | GET | `fapi/v1/apiTradingStatus` | +| [getFuturesTransactionHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L593) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn` | +| [getFuturesTransactionHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L600) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn/id` | +| [getFuturesOrderHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L606) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn` | +| [getFuturesOrderHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L613) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn/id` | +| [getFuturesTradeHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L619) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn` | +| [getFuturesTradeDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L626) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn/id` | +| [setBNBBurnEnabled()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L632) | :closed_lock_with_key: | POST | `fapi/v1/feeBurn` | +| [getBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L638) | :closed_lock_with_key: | GET | `fapi/v1/feeBurn` | +| [signTradFiPerpsAgreement()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L644) | :closed_lock_with_key: | POST | `fapi/v1/stock/contract` | +| [testOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L648) | :closed_lock_with_key: | POST | `fapi/v1/order/test` | +| [submitNewAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L660) | :closed_lock_with_key: | POST | `fapi/v1/algoOrder` | +| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L667) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOrder` | +| [cancelAllAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L673) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOpenOrders` | +| [getAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L679) | :closed_lock_with_key: | GET | `fapi/v1/algoOrder` | +| [getOpenAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L685) | :closed_lock_with_key: | GET | `fapi/v1/openAlgoOrders` | +| [getAllAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L691) | :closed_lock_with_key: | GET | `fapi/v1/allAlgoOrders` | +| [getAllConvertPairs()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L703) | | GET | `fapi/v1/convert/exchangeInfo` | +| [submitConvertQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L710) | :closed_lock_with_key: | POST | `fapi/v1/convert/getQuote` | +| [acceptConvertQuote()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L716) | :closed_lock_with_key: | POST | `fapi/v1/convert/acceptQuote` | +| [getConvertOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L724) | :closed_lock_with_key: | GET | `fapi/v1/convert/orderStatus` | +| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L737) | :closed_lock_with_key: | GET | `fapi/v1/pmAccountInfo` | +| [getBrokerIfNewFuturesUser()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L754) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/ifNewUser` | +| [setBrokerCustomIdForClient()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L767) | :closed_lock_with_key: | POST | `fapi/v1/apiReferral/customization` | +| [getBrokerClientCustomIds()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L780) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/customization` | +| [getBrokerUserCustomId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L797) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/userCustomization` | +| [getBrokerRebateDataOverview()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L806) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/overview` | +| [getBrokerUserTradeVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L815) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/tradeVol` | +| [getBrokerRebateVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L832) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/rebateVol` | +| [getBrokerTradeDetail()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L849) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/traderSummary` | +| [getFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L871) | | POST | `fapi/v1/listenKey` | +| [keepAliveFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L875) | | PUT | `fapi/v1/listenKey` | +| [closeFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L879) | | DELETE | `fapi/v1/listenKey` | # coinm-client.ts @@ -691,82 +694,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#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` | +| [testConnectivity()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L127) | | GET | `dapi/v1/ping` | +| [getExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L131) | | GET | `dapi/v1/exchangeInfo` | +| [getOrderBook()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L135) | | GET | `dapi/v1/depth` | +| [getRecentTrades()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L139) | | GET | `dapi/v1/trades` | +| [getHistoricalTrades()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L143) | | GET | `dapi/v1/historicalTrades` | +| [getAggregateTrades()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L149) | | GET | `dapi/v1/aggTrades` | +| [getMarkPrice()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L158) | | GET | `dapi/v1/premiumIndex` | +| [getFundingRateHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L162) | | GET | `dapi/v1/fundingRate` | +| [getFundingRate()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L168) | | GET | `dapi/v1/fundingInfo` | +| [getKlines()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L172) | | GET | `dapi/v1/klines` | +| [getContinuousContractKlines()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L176) | | GET | `dapi/v1/continuousKlines` | +| [getIndexPriceKlines()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L182) | | GET | `dapi/v1/indexPriceKlines` | +| [getMarkPriceKlines()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L186) | | GET | `dapi/v1/markPriceKlines` | +| [getPremiumIndexKlines()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L190) | | GET | `dapi/v1/premiumIndexKlines` | +| [get24hrChangeStatistics()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L194) | | GET | `dapi/v1/ticker/24hr` | +| [getSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L201) | | GET | `dapi/v1/ticker/price` | +| [getSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L208) | | GET | `dapi/v1/ticker/bookTicker` | +| [getOpenInterest()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L217) | | GET | `dapi/v1/openInterest` | +| [getOpenInterestStatistics()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L221) | | GET | `futures/data/openInterestHist` | +| [getTopTradersLongShortAccountRatio()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L225) | | GET | `futures/data/topLongShortAccountRatio` | +| [getTopTradersLongShortPositionRatio()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L231) | | GET | `futures/data/topLongShortPositionRatio` | +| [getGlobalLongShortAccountRatio()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L237) | | GET | `futures/data/globalLongShortAccountRatio` | +| [getTakerBuySellVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L243) | | GET | `futures/data/takerBuySellVol` | +| [getCompositeSymbolIndex()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L249) | | GET | `futures/data/basis` | +| [getIndexPriceConstituents()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L257) | | GET | `dapi/v1/constituents` | +| [getQuarterlyContractSettlementPrices()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L267) | | GET | `futures/data/delivery-price` | +| [submitNewOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L279) | :closed_lock_with_key: | POST | `dapi/v1/order` | +| [submitMultipleOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L289) | :closed_lock_with_key: | POST | `dapi/v1/batchOrders` | +| [modifyOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L306) | :closed_lock_with_key: | PUT | `dapi/v1/order` | +| [modifyMultipleOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L315) | :closed_lock_with_key: | PUT | `dapi/v1/batchOrders` | +| [getOrderModifyHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L328) | :closed_lock_with_key: | GET | `dapi/v1/orderAmendment` | +| [cancelOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L334) | :closed_lock_with_key: | DELETE | `dapi/v1/order` | +| [cancelMultipleOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L338) | :closed_lock_with_key: | DELETE | `dapi/v1/batchOrders` | +| [cancelAllOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L358) | :closed_lock_with_key: | DELETE | `dapi/v1/allOpenOrders` | +| [setCancelOrdersOnTimeout()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L365) | :closed_lock_with_key: | POST | `dapi/v1/countdownCancelAll` | +| [getOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L371) | :closed_lock_with_key: | GET | `dapi/v1/order` | +| [getAllOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L375) | :closed_lock_with_key: | GET | `dapi/v1/allOrders` | +| [getAllOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L379) | :closed_lock_with_key: | GET | `dapi/v1/openOrders` | +| [getCurrentOpenOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L383) | :closed_lock_with_key: | GET | `dapi/v1/openOrder` | +| [submitNewAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L394) | :closed_lock_with_key: | POST | `dapi/v1/algoOrder` | +| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L401) | :closed_lock_with_key: | DELETE | `dapi/v1/algoOrder` | +| [getOpenAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L407) | :closed_lock_with_key: | GET | `dapi/v1/openAlgoOrders` | +| [getForceOrders()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L413) | :closed_lock_with_key: | GET | `dapi/v1/forceOrders` | +| [getAccountTrades()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L417) | :closed_lock_with_key: | GET | `dapi/v1/userTrades` | +| [getPositions()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L423) | :closed_lock_with_key: | GET | `dapi/v1/positionRisk` | +| [setPositionMode()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L430) | :closed_lock_with_key: | POST | `dapi/v1/positionSide/dual` | +| [setMarginType()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L434) | :closed_lock_with_key: | POST | `dapi/v1/marginType` | +| [setLeverage()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L438) | :closed_lock_with_key: | POST | `dapi/v1/leverage` | +| [getADLQuantileEstimation()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L442) | :closed_lock_with_key: | GET | `dapi/v1/adlQuantile` | +| [setIsolatedPositionMargin()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L446) | :closed_lock_with_key: | POST | `dapi/v1/positionMargin` | +| [getPositionMarginChangeHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L452) | :closed_lock_with_key: | GET | `dapi/v1/positionMargin/history` | +| [getBalance()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L463) | :closed_lock_with_key: | GET | `dapi/v1/balance` | +| [getAccountCommissionRate()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L467) | :closed_lock_with_key: | GET | `dapi/v1/commissionRate` | +| [getAccountInformation()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L473) | :closed_lock_with_key: | GET | `dapi/v1/account` | +| [getNotionalAndLeverageBrackets()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L480) | :closed_lock_with_key: | GET | `dapi/v2/leverageBracket` | +| [getCurrentPositionMode()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L489) | :closed_lock_with_key: | GET | `dapi/v1/positionSide/dual` | +| [getIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L493) | :closed_lock_with_key: | GET | `dapi/v1/income` | +| [getDownloadIdForFuturesTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L497) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn` | +| [getFuturesTransactionHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L507) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn/id` | +| [getDownloadIdForFuturesOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L513) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn` | +| [getFuturesOrderHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L523) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn/id` | +| [getDownloadIdForFuturesTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L529) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn` | +| [getFuturesTradeHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L539) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn/id` | +| [getClassicPortfolioMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L551) | :closed_lock_with_key: | GET | `dapi/v1/pmAccountInfo` | +| [getClassicPortfolioMarginNotionalLimits()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L560) | :closed_lock_with_key: | GET | `dapi/v1/pmExchangeInfo` | +| [getBrokerIfNewFuturesUser()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L579) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/ifNewUser` | +| [setBrokerCustomIdForClient()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L592) | :closed_lock_with_key: | POST | `dapi/v1/apiReferral/customization` | +| [getBrokerClientCustomIds()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L605) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/customization` | +| [getBrokerUserCustomId()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L622) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/userCustomization` | +| [getBrokerRebateDataOverview()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L631) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/overview` | +| [getBrokerUserTradeVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L640) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/tradeVol` | +| [getBrokerRebateVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L657) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/rebateVol` | +| [getBrokerTradeDetail()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L674) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/traderSummary` | +| [getFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L694) | | POST | `dapi/v1/listenKey` | +| [keepAliveFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L698) | | PUT | `dapi/v1/listenKey` | +| [closeFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L702) | | DELETE | `dapi/v1/listenKey` | # portfolio-client.ts @@ -774,113 +777,113 @@ 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/portfolio-client.ts#L167) | | GET | `papi/v1/ping` | -| [signTradFiPerpsContract()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L171) | :closed_lock_with_key: | POST | `papi/v1/um/stock/contract` | -| [submitNewUMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L181) | :closed_lock_with_key: | POST | `papi/v1/um/order` | -| [submitNewUMConditionalOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L191) | :closed_lock_with_key: | POST | `papi/v1/um/conditional/order` | -| [submitNewUMAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L198) | :closed_lock_with_key: | POST | `papi/v1/um/algo/order` | -| [submitNewCMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L205) | :closed_lock_with_key: | POST | `papi/v1/cm/order` | -| [submitNewCMConditionalOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L212) | :closed_lock_with_key: | POST | `papi/v1/cm/conditional/order` | -| [submitNewMarginOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L219) | :closed_lock_with_key: | POST | `papi/v1/margin/order` | -| [submitMarginLoan()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L226) | :closed_lock_with_key: | POST | `papi/v1/marginLoan` | -| [submitMarginRepay()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L232) | :closed_lock_with_key: | POST | `papi/v1/repayLoan` | -| [submitNewMarginOCO()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L238) | :closed_lock_with_key: | POST | `papi/v1/margin/order/oco` | -| [cancelUMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L247) | :closed_lock_with_key: | DELETE | `papi/v1/um/order` | -| [cancelAllUMOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L253) | :closed_lock_with_key: | DELETE | `papi/v1/um/allOpenOrders` | -| [cancelUMConditionalOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L263) | :closed_lock_with_key: | DELETE | `papi/v1/um/conditional/order` | -| [cancelUMAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L269) | :closed_lock_with_key: | DELETE | `papi/v1/um/algo/order` | -| [cancelAllUMConditionalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L278) | :closed_lock_with_key: | DELETE | `papi/v1/um/conditional/allOpenOrders` | -| [cancelAllUMAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L285) | :closed_lock_with_key: | DELETE | `papi/v1/um/algo/allOpenOrders` | -| [cancelCMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L291) | :closed_lock_with_key: | DELETE | `papi/v1/cm/order` | -| [cancelAllCMOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L297) | :closed_lock_with_key: | DELETE | `papi/v1/cm/allOpenOrders` | -| [cancelCMConditionalOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L304) | :closed_lock_with_key: | DELETE | `papi/v1/cm/conditional/order` | -| [cancelAllCMConditionalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L310) | :closed_lock_with_key: | DELETE | `papi/v1/cm/conditional/allOpenOrders` | -| [cancelMarginOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L317) | :closed_lock_with_key: | DELETE | `papi/v1/margin/order` | -| [cancelMarginOCO()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L323) | :closed_lock_with_key: | DELETE | `papi/v1/margin/orderList` | -| [cancelAllMarginOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L329) | :closed_lock_with_key: | DELETE | `papi/v1/margin/allOpenOrders` | -| [modifyUMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L335) | :closed_lock_with_key: | PUT | `papi/v1/um/order` | -| [modifyCMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L341) | :closed_lock_with_key: | PUT | `papi/v1/cm/order` | -| [getUMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L347) | :closed_lock_with_key: | GET | `papi/v1/um/order` | -| [getAllUMOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L351) | :closed_lock_with_key: | GET | `papi/v1/um/allOrders` | -| [getUMOpenOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L357) | :closed_lock_with_key: | GET | `papi/v1/um/openOrder` | -| [getAllUMOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L363) | :closed_lock_with_key: | GET | `papi/v1/um/openOrders` | -| [getAllUMConditionalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L370) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/allOrders` | -| [getAllUMAlgoOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L376) | :closed_lock_with_key: | GET | `papi/v1/um/algo/allAlgoOrders` | -| [getUMOpenConditionalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L385) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/openOrders` | -| [getUMAlgoOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L391) | :closed_lock_with_key: | GET | `papi/v1/um/algo/openAlgoOrders` | -| [getUMOpenConditionalOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L400) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/openOrder` | -| [getUMAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L406) | :closed_lock_with_key: | GET | `papi/v1/um/algo/algoOrder` | -| [getUMConditionalOrderHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L415) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/orderHistory` | -| [getCMOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L421) | :closed_lock_with_key: | GET | `papi/v1/cm/order` | -| [getAllCMOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L425) | :closed_lock_with_key: | GET | `papi/v1/cm/allOrders` | -| [getCMOpenOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L431) | :closed_lock_with_key: | GET | `papi/v1/cm/openOrder` | -| [getAllCMOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L437) | :closed_lock_with_key: | GET | `papi/v1/cm/openOrders` | -| [getCMOpenConditionalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L444) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/openOrders` | -| [getCMOpenConditionalOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L450) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/openOrder` | -| [getAllCMConditionalOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L458) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/allOrders` | -| [getCMConditionalOrderHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L464) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/orderHistory` | -| [getUMForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L470) | :closed_lock_with_key: | GET | `papi/v1/um/forceOrders` | -| [getCMForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L476) | :closed_lock_with_key: | GET | `papi/v1/cm/forceOrders` | -| [getUMOrderModificationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L482) | :closed_lock_with_key: | GET | `papi/v1/um/orderAmendment` | -| [getCMOrderModificationHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L488) | :closed_lock_with_key: | GET | `papi/v1/cm/orderAmendment` | -| [getMarginForceOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L494) | :closed_lock_with_key: | GET | `papi/v1/margin/forceOrders` | -| [getUMTrades()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L501) | :closed_lock_with_key: | GET | `papi/v1/um/userTrades` | -| [getCMTrades()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L505) | :closed_lock_with_key: | GET | `papi/v1/cm/userTrades` | -| [getUMADLQuantile()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L509) | :closed_lock_with_key: | GET | `papi/v1/um/adlQuantile` | -| [getCMADLQuantile()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L518) | :closed_lock_with_key: | GET | `papi/v1/cm/adlQuantile` | -| [toggleUMFeeBurn()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L527) | :closed_lock_with_key: | POST | `papi/v1/um/feeBurn` | -| [getUMFeeBurnStatus()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L533) | :closed_lock_with_key: | GET | `papi/v1/um/feeBurn` | -| [getMarginOrder()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L537) | :closed_lock_with_key: | GET | `papi/v1/margin/order` | -| [getMarginOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L543) | :closed_lock_with_key: | GET | `papi/v1/margin/openOrders` | -| [getAllMarginOrders()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L549) | :closed_lock_with_key: | GET | `papi/v1/margin/allOrders` | -| [getMarginOCO()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L555) | :closed_lock_with_key: | GET | `papi/v1/margin/orderList` | -| [getAllMarginOCO()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L561) | :closed_lock_with_key: | GET | `papi/v1/margin/allOrderList` | -| [getMarginOpenOCO()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L567) | :closed_lock_with_key: | GET | `papi/v1/margin/openOrderList` | -| [getMarginTrades()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L571) | :closed_lock_with_key: | GET | `papi/v1/margin/myTrades` | -| [repayMarginDebt()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L577) | :closed_lock_with_key: | POST | `papi/v1/margin/repay-debt` | -| [getBalance()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L589) | :closed_lock_with_key: | GET | `papi/v1/balance` | -| [getAccountInfo()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L593) | :closed_lock_with_key: | GET | `papi/v1/account` | -| [getMarginMaxBorrow()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L597) | :closed_lock_with_key: | GET | `papi/v1/margin/maxBorrowable` | -| [getMarginMaxWithdraw()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L604) | :closed_lock_with_key: | GET | `papi/v1/margin/maxWithdraw` | -| [getUMPosition()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L610) | :closed_lock_with_key: | GET | `papi/v1/um/positionRisk` | -| [getCMPosition()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L614) | :closed_lock_with_key: | GET | `papi/v1/cm/positionRisk` | -| [updateUMLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L621) | :closed_lock_with_key: | POST | `papi/v1/um/leverage` | -| [updateCMLeverage()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L629) | :closed_lock_with_key: | POST | `papi/v1/cm/leverage` | -| [updateUMPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L637) | :closed_lock_with_key: | POST | `papi/v1/um/positionSide/dual` | -| [updateCMPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L646) | :closed_lock_with_key: | POST | `papi/v1/cm/positionSide/dual` | -| [getUMPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L655) | :closed_lock_with_key: | GET | `papi/v1/um/positionSide/dual` | -| [getCMPositionMode()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L661) | :closed_lock_with_key: | GET | `papi/v1/cm/positionSide/dual` | -| [getUMLeverageBrackets()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L667) | :closed_lock_with_key: | GET | `papi/v1/um/leverageBracket` | -| [getCMLeverageBrackets()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L677) | :closed_lock_with_key: | GET | `papi/v1/cm/leverageBracket` | -| [getUMTradingStatus()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L686) | :closed_lock_with_key: | GET | `papi/v1/um/apiTradingStatus` | -| [getUMCommissionRate()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L692) | :closed_lock_with_key: | GET | `papi/v1/um/commissionRate` | -| [getCMCommissionRate()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L700) | :closed_lock_with_key: | GET | `papi/v1/cm/commissionRate` | -| [getMarginLoanRecords()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L708) | :closed_lock_with_key: | GET | `papi/v1/margin/marginLoan` | -| [getMarginRepayRecords()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L715) | :closed_lock_with_key: | GET | `papi/v1/margin/repayLoan` | -| [getAutoRepayFuturesStatus()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L722) | :closed_lock_with_key: | GET | `papi/v1/repay-futures-switch` | -| [updateAutoRepayFuturesStatus()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L728) | :closed_lock_with_key: | POST | `papi/v1/repay-futures-switch` | -| [getMarginInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L736) | :closed_lock_with_key: | GET | `papi/v1/margin/marginInterestHistory` | -| [repayFuturesNegativeBalance()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L743) | :closed_lock_with_key: | POST | `papi/v1/repay-futures-negative-balance` | -| [getPortfolioNegativeBalanceInterestHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L749) | :closed_lock_with_key: | GET | `papi/v1/portfolio/interest-history` | -| [autoCollectFunds()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L755) | :closed_lock_with_key: | POST | `papi/v1/auto-collection` | -| [transferAssetFuturesMargin()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L761) | :closed_lock_with_key: | POST | `papi/v1/asset-collection` | -| [transferBNB()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L767) | :closed_lock_with_key: | POST | `papi/v1/bnb-transfer` | -| [getUMIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L776) | :closed_lock_with_key: | GET | `papi/v1/um/income` | -| [getCMIncomeHistory()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L782) | :closed_lock_with_key: | GET | `papi/v1/cm/income` | -| [getUMAccount()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L788) | :closed_lock_with_key: | GET | `papi/v1/um/account` | -| [getCMAccount()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L795) | :closed_lock_with_key: | GET | `papi/v1/cm/account` | -| [getUMAccountConfig()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L802) | :closed_lock_with_key: | GET | `papi/v1/um/accountConfig` | -| [getUMSymbolConfig()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L806) | :closed_lock_with_key: | GET | `papi/v1/um/symbolConfig` | -| [getUMAccountV2()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L812) | :closed_lock_with_key: | GET | `papi/v2/um/account` | -| [getUMTradeHistoryDownloadId()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L819) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn` | -| [getUMTradeDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L829) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn/id` | -| [getUMOrderHistoryDownloadId()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L835) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn` | -| [getUMOrderDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L845) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn/id` | -| [getUMTransactionHistoryDownloadId()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L851) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn` | -| [getUMTransactionDownloadLink()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L861) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn/id` | -| [getPMUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L900) | | POST | `papi/v1/listenKey` | -| [keepAlivePMUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L904) | | PUT | `papi/v1/listenKey` | -| [closePMUserDataListenKey()](https://github.com/tiagosiebler/binance/blob/master/src/portfolio-client.ts#L908) | | DELETE | `papi/v1/listenKey` | +| [testConnectivity()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L167) | | GET | `papi/v1/ping` | +| [signTradFiPerpsContract()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L171) | :closed_lock_with_key: | POST | `papi/v1/um/stock/contract` | +| [submitNewUMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L181) | :closed_lock_with_key: | POST | `papi/v1/um/order` | +| [submitNewUMConditionalOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L191) | :closed_lock_with_key: | POST | `papi/v1/um/conditional/order` | +| [submitNewUMAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L198) | :closed_lock_with_key: | POST | `papi/v1/um/algo/order` | +| [submitNewCMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L205) | :closed_lock_with_key: | POST | `papi/v1/cm/order` | +| [submitNewCMConditionalOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L212) | :closed_lock_with_key: | POST | `papi/v1/cm/conditional/order` | +| [submitNewMarginOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L219) | :closed_lock_with_key: | POST | `papi/v1/margin/order` | +| [submitMarginLoan()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L226) | :closed_lock_with_key: | POST | `papi/v1/marginLoan` | +| [submitMarginRepay()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L232) | :closed_lock_with_key: | POST | `papi/v1/repayLoan` | +| [submitNewMarginOCO()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L238) | :closed_lock_with_key: | POST | `papi/v1/margin/order/oco` | +| [cancelUMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L247) | :closed_lock_with_key: | DELETE | `papi/v1/um/order` | +| [cancelAllUMOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L253) | :closed_lock_with_key: | DELETE | `papi/v1/um/allOpenOrders` | +| [cancelUMConditionalOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L263) | :closed_lock_with_key: | DELETE | `papi/v1/um/conditional/order` | +| [cancelUMAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L269) | :closed_lock_with_key: | DELETE | `papi/v1/um/algo/order` | +| [cancelAllUMConditionalOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L278) | :closed_lock_with_key: | DELETE | `papi/v1/um/conditional/allOpenOrders` | +| [cancelAllUMAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L285) | :closed_lock_with_key: | DELETE | `papi/v1/um/algo/allOpenOrders` | +| [cancelCMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L291) | :closed_lock_with_key: | DELETE | `papi/v1/cm/order` | +| [cancelAllCMOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L297) | :closed_lock_with_key: | DELETE | `papi/v1/cm/allOpenOrders` | +| [cancelCMConditionalOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L304) | :closed_lock_with_key: | DELETE | `papi/v1/cm/conditional/order` | +| [cancelAllCMConditionalOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L310) | :closed_lock_with_key: | DELETE | `papi/v1/cm/conditional/allOpenOrders` | +| [cancelMarginOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L317) | :closed_lock_with_key: | DELETE | `papi/v1/margin/order` | +| [cancelMarginOCO()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L323) | :closed_lock_with_key: | DELETE | `papi/v1/margin/orderList` | +| [cancelAllMarginOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L329) | :closed_lock_with_key: | DELETE | `papi/v1/margin/allOpenOrders` | +| [modifyUMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L335) | :closed_lock_with_key: | PUT | `papi/v1/um/order` | +| [modifyCMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L341) | :closed_lock_with_key: | PUT | `papi/v1/cm/order` | +| [getUMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L347) | :closed_lock_with_key: | GET | `papi/v1/um/order` | +| [getAllUMOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L351) | :closed_lock_with_key: | GET | `papi/v1/um/allOrders` | +| [getUMOpenOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L357) | :closed_lock_with_key: | GET | `papi/v1/um/openOrder` | +| [getAllUMOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L363) | :closed_lock_with_key: | GET | `papi/v1/um/openOrders` | +| [getAllUMConditionalOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L370) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/allOrders` | +| [getAllUMAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L376) | :closed_lock_with_key: | GET | `papi/v1/um/algo/allAlgoOrders` | +| [getUMOpenConditionalOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L385) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/openOrders` | +| [getUMAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L391) | :closed_lock_with_key: | GET | `papi/v1/um/algo/openAlgoOrders` | +| [getUMOpenConditionalOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L400) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/openOrder` | +| [getUMAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L406) | :closed_lock_with_key: | GET | `papi/v1/um/algo/algoOrder` | +| [getUMConditionalOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L415) | :closed_lock_with_key: | GET | `papi/v1/um/conditional/orderHistory` | +| [getCMOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L421) | :closed_lock_with_key: | GET | `papi/v1/cm/order` | +| [getAllCMOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L425) | :closed_lock_with_key: | GET | `papi/v1/cm/allOrders` | +| [getCMOpenOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L431) | :closed_lock_with_key: | GET | `papi/v1/cm/openOrder` | +| [getAllCMOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L437) | :closed_lock_with_key: | GET | `papi/v1/cm/openOrders` | +| [getCMOpenConditionalOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L444) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/openOrders` | +| [getCMOpenConditionalOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L450) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/openOrder` | +| [getAllCMConditionalOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L458) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/allOrders` | +| [getCMConditionalOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L464) | :closed_lock_with_key: | GET | `papi/v1/cm/conditional/orderHistory` | +| [getUMForceOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L470) | :closed_lock_with_key: | GET | `papi/v1/um/forceOrders` | +| [getCMForceOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L476) | :closed_lock_with_key: | GET | `papi/v1/cm/forceOrders` | +| [getUMOrderModificationHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L482) | :closed_lock_with_key: | GET | `papi/v1/um/orderAmendment` | +| [getCMOrderModificationHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L488) | :closed_lock_with_key: | GET | `papi/v1/cm/orderAmendment` | +| [getMarginForceOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L494) | :closed_lock_with_key: | GET | `papi/v1/margin/forceOrders` | +| [getUMTrades()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L501) | :closed_lock_with_key: | GET | `papi/v1/um/userTrades` | +| [getCMTrades()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L505) | :closed_lock_with_key: | GET | `papi/v1/cm/userTrades` | +| [getUMADLQuantile()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L509) | :closed_lock_with_key: | GET | `papi/v1/um/adlQuantile` | +| [getCMADLQuantile()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L518) | :closed_lock_with_key: | GET | `papi/v1/cm/adlQuantile` | +| [toggleUMFeeBurn()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L527) | :closed_lock_with_key: | POST | `papi/v1/um/feeBurn` | +| [getUMFeeBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L533) | :closed_lock_with_key: | GET | `papi/v1/um/feeBurn` | +| [getMarginOrder()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L537) | :closed_lock_with_key: | GET | `papi/v1/margin/order` | +| [getMarginOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L543) | :closed_lock_with_key: | GET | `papi/v1/margin/openOrders` | +| [getAllMarginOrders()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L549) | :closed_lock_with_key: | GET | `papi/v1/margin/allOrders` | +| [getMarginOCO()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L555) | :closed_lock_with_key: | GET | `papi/v1/margin/orderList` | +| [getAllMarginOCO()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L561) | :closed_lock_with_key: | GET | `papi/v1/margin/allOrderList` | +| [getMarginOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L567) | :closed_lock_with_key: | GET | `papi/v1/margin/openOrderList` | +| [getMarginTrades()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L571) | :closed_lock_with_key: | GET | `papi/v1/margin/myTrades` | +| [repayMarginDebt()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L577) | :closed_lock_with_key: | POST | `papi/v1/margin/repay-debt` | +| [getBalance()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L589) | :closed_lock_with_key: | GET | `papi/v1/balance` | +| [getAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L593) | :closed_lock_with_key: | GET | `papi/v1/account` | +| [getMarginMaxBorrow()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L597) | :closed_lock_with_key: | GET | `papi/v1/margin/maxBorrowable` | +| [getMarginMaxWithdraw()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L604) | :closed_lock_with_key: | GET | `papi/v1/margin/maxWithdraw` | +| [getUMPosition()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L610) | :closed_lock_with_key: | GET | `papi/v1/um/positionRisk` | +| [getCMPosition()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L614) | :closed_lock_with_key: | GET | `papi/v1/cm/positionRisk` | +| [updateUMLeverage()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L621) | :closed_lock_with_key: | POST | `papi/v1/um/leverage` | +| [updateCMLeverage()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L629) | :closed_lock_with_key: | POST | `papi/v1/cm/leverage` | +| [updateUMPositionMode()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L637) | :closed_lock_with_key: | POST | `papi/v1/um/positionSide/dual` | +| [updateCMPositionMode()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L646) | :closed_lock_with_key: | POST | `papi/v1/cm/positionSide/dual` | +| [getUMPositionMode()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L655) | :closed_lock_with_key: | GET | `papi/v1/um/positionSide/dual` | +| [getCMPositionMode()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L661) | :closed_lock_with_key: | GET | `papi/v1/cm/positionSide/dual` | +| [getUMLeverageBrackets()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L667) | :closed_lock_with_key: | GET | `papi/v1/um/leverageBracket` | +| [getCMLeverageBrackets()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L677) | :closed_lock_with_key: | GET | `papi/v1/cm/leverageBracket` | +| [getUMTradingStatus()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L686) | :closed_lock_with_key: | GET | `papi/v1/um/apiTradingStatus` | +| [getUMCommissionRate()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L692) | :closed_lock_with_key: | GET | `papi/v1/um/commissionRate` | +| [getCMCommissionRate()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L700) | :closed_lock_with_key: | GET | `papi/v1/cm/commissionRate` | +| [getMarginLoanRecords()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L708) | :closed_lock_with_key: | GET | `papi/v1/margin/marginLoan` | +| [getMarginRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L715) | :closed_lock_with_key: | GET | `papi/v1/margin/repayLoan` | +| [getAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L722) | :closed_lock_with_key: | GET | `papi/v1/repay-futures-switch` | +| [updateAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L728) | :closed_lock_with_key: | POST | `papi/v1/repay-futures-switch` | +| [getMarginInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L736) | :closed_lock_with_key: | GET | `papi/v1/margin/marginInterestHistory` | +| [repayFuturesNegativeBalance()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L743) | :closed_lock_with_key: | POST | `papi/v1/repay-futures-negative-balance` | +| [getPortfolioNegativeBalanceInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L749) | :closed_lock_with_key: | GET | `papi/v1/portfolio/interest-history` | +| [autoCollectFunds()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L755) | :closed_lock_with_key: | POST | `papi/v1/auto-collection` | +| [transferAssetFuturesMargin()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L761) | :closed_lock_with_key: | POST | `papi/v1/asset-collection` | +| [transferBNB()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L767) | :closed_lock_with_key: | POST | `papi/v1/bnb-transfer` | +| [getUMIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L776) | :closed_lock_with_key: | GET | `papi/v1/um/income` | +| [getCMIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L782) | :closed_lock_with_key: | GET | `papi/v1/cm/income` | +| [getUMAccount()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L788) | :closed_lock_with_key: | GET | `papi/v1/um/account` | +| [getCMAccount()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L795) | :closed_lock_with_key: | GET | `papi/v1/cm/account` | +| [getUMAccountConfig()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L802) | :closed_lock_with_key: | GET | `papi/v1/um/accountConfig` | +| [getUMSymbolConfig()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L806) | :closed_lock_with_key: | GET | `papi/v1/um/symbolConfig` | +| [getUMAccountV2()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L812) | :closed_lock_with_key: | GET | `papi/v2/um/account` | +| [getUMTradeHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L819) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn` | +| [getUMTradeDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L829) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn/id` | +| [getUMOrderHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L835) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn` | +| [getUMOrderDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L845) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn/id` | +| [getUMTransactionHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L851) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn` | +| [getUMTransactionDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L861) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn/id` | +| [getPMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L900) | | POST | `papi/v1/listenKey` | +| [keepAlivePMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L904) | | PUT | `papi/v1/listenKey` | +| [closePMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L908) | | DELETE | `papi/v1/listenKey` | # websocket-api-client.ts @@ -890,71 +893,71 @@ This client provides WebSocket API endpoints which allow for faster interactions | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [disconnectAll()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L263) | | WS | `ping` | -| [testSpotConnectivity()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L276) | | WS | `ping` | -| [getSpotServerTime()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L288) | | WS | `time` | -| [getSpotExchangeInfo()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L302) | | WS | `exchangeInfo` | -| [getSpotOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L324) | | WS | `depth` | -| [getSpotRecentTrades()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L340) | | WS | `trades.recent` | -| [getSpotHistoricalTrades()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L356) | | WS | `trades.historical` | -| [getSpotHistoricalBlockTrades()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L371) | | WS | `blockTrades.historical` | -| [getSpotAggregateTrades()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L387) | | WS | `trades.aggregate` | -| [getSpotKlines()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L403) | | WS | `klines` | -| [getSpotUIKlines()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L419) | | WS | `uiKlines` | -| [getSpotAveragePrice()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L434) | | WS | `avgPrice` | -| [getSpotExecutionRules()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L449) | | WS | `executionRules` | -| [getSpotReferencePrice()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L464) | | WS | `referencePrice` | -| [getSpotReferencePriceCalculation()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L479) | | WS | `referencePrice.calculation` | -| [getSpot24hrTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L495) | | WS | `ticker.24hr` | -| [getSpotTradingDayTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L514) | | WS | `ticker.tradingDay` | -| [getSpotTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L534) | | WS | `ticker` | -| [getSpotSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L554) | | WS | `ticker.price` | -| [getSpotSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L570) | | WS | `ticker.book` | -| [getSpotSessionStatus()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L590) | | WS | `session.status` | -| [submitNewSpotOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L608) | | WS | `order.place` | -| [testSpotOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L623) | | WS | `order.test` | -| [getSpotOrderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L640) | | WS | `order.status` | -| [cancelSpotOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L655) | | WS | `order.cancel` | -| [cancelReplaceSpotOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L670) | | WS | `order.cancelReplace` | -| [amendSpotOrderKeepPriority()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L686) | | WS | `order.amend.keepPriority` | -| [getSpotOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L701) | | WS | `openOrders.status` | -| [cancelAllSpotOpenOrders()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L716) | | WS | `openOrders.cancelAll` | -| [placeSpotOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L733) | | WS | `orderList.place` | -| [placeSpotOCOOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L748) | | WS | `orderList.place.oco` | -| [placeSpotOTOOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L763) | | WS | `orderList.place.oto` | -| [placeSpotOTOCOOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L778) | | WS | `orderList.place.otoco` | -| [placeSpotOPOOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L793) | | WS | `orderList.place.opo` | -| [placeSpotOPOCOOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L808) | | WS | `orderList.place.opoco` | -| [getSpotOrderListStatus()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L823) | | WS | `orderList.status` | -| [cancelSpotOrderList()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L838) | | WS | `orderList.cancel` | -| [getSpotOpenOrderLists()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L853) | | WS | `openOrderLists.status` | -| [placeSpotSOROrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L868) | | WS | `sor.order.place` | -| [testSpotSOROrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L883) | | WS | `sor.order.test` | -| [getSpotAccountInformation()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L908) | | WS | `account.status` | -| [getSpotOrderRateLimits()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L923) | | WS | `account.rateLimits.orders` | -| [getSpotAllOrders()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L938) | | WS | `allOrders` | -| [getSpotAllOrderLists()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L953) | | WS | `allOrderLists` | -| [getSpotMyTrades()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L968) | | WS | `myTrades` | -| [getSpotPreventedMatches()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L983) | | WS | `myPreventedMatches` | -| [getSpotAllocations()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L998) | | WS | `myAllocations` | -| [getSpotAccountCommission()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1013) | | WS | `account.commission` | -| [getFuturesOrderBook()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1034) | | WS | `depth` | -| [getFuturesSymbolPriceTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1049) | | WS | `ticker.price` | -| [getFuturesSymbolOrderBookTicker()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1066) | | WS | `ticker.book` | -| [submitNewFuturesOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1088) | | WS | `order.place` | -| [modifyFuturesOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1104) | | WS | `order.modify` | -| [cancelFuturesOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1120) | | WS | `order.cancel` | -| [getFuturesOrderStatus()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1136) | | WS | `order.status` | -| [getFuturesPositionV2()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1151) | | WS | `v2/account.position` | -| [getFuturesPosition()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1167) | | WS | `account.position` | -| [submitNewFuturesAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1183) | | WS | `algoOrder.place` | -| [cancelFuturesAlgoOrder()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1199) | | WS | `algoOrder.cancel` | -| [getFuturesAccountBalanceV2()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1219) | | WS | `v2/account.balance` | -| [getFuturesAccountBalance()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1235) | | WS | `account.balance` | -| [getFuturesAccountStatusV2()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1250) | | WS | `v2/account.status` | -| [getFuturesAccountStatus()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1266) | | WS | `account.status` | -| [startUserDataStreamForKey()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1292) | | WS | `userDataStream.start` | -| [pingUserDataStreamForKey()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1312) | | WS | `userDataStream.ping` | -| [stopUserDataStreamForKey()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1326) | | WS | `userDataStream.stop` | -| [subscribeUserDataStream()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1357) | | WS | `userDataStream.unsubscribe` | -| [unsubscribeUserDataStream()](https://github.com/tiagosiebler/binance/blob/master/src/websocket-api-client.ts#L1486) | | WS | `userDataStream.unsubscribe` | \ No newline at end of file +| [disconnectAll()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L263) | | WS | `ping` | +| [testSpotConnectivity()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L276) | | WS | `ping` | +| [getSpotServerTime()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L288) | | WS | `time` | +| [getSpotExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L302) | | WS | `exchangeInfo` | +| [getSpotOrderBook()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L324) | | WS | `depth` | +| [getSpotRecentTrades()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L340) | | WS | `trades.recent` | +| [getSpotHistoricalTrades()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L356) | | WS | `trades.historical` | +| [getSpotHistoricalBlockTrades()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L371) | | WS | `blockTrades.historical` | +| [getSpotAggregateTrades()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L387) | | WS | `trades.aggregate` | +| [getSpotKlines()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L403) | | WS | `klines` | +| [getSpotUIKlines()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L419) | | WS | `uiKlines` | +| [getSpotAveragePrice()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L434) | | WS | `avgPrice` | +| [getSpotExecutionRules()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L449) | | WS | `executionRules` | +| [getSpotReferencePrice()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L464) | | WS | `referencePrice` | +| [getSpotReferencePriceCalculation()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L479) | | WS | `referencePrice.calculation` | +| [getSpot24hrTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L495) | | WS | `ticker.24hr` | +| [getSpotTradingDayTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L514) | | WS | `ticker.tradingDay` | +| [getSpotTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L534) | | WS | `ticker` | +| [getSpotSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L554) | | WS | `ticker.price` | +| [getSpotSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L570) | | WS | `ticker.book` | +| [getSpotSessionStatus()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L590) | | WS | `session.status` | +| [submitNewSpotOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L608) | | WS | `order.place` | +| [testSpotOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L623) | | WS | `order.test` | +| [getSpotOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L640) | | WS | `order.status` | +| [cancelSpotOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L655) | | WS | `order.cancel` | +| [cancelReplaceSpotOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L670) | | WS | `order.cancelReplace` | +| [amendSpotOrderKeepPriority()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L686) | | WS | `order.amend.keepPriority` | +| [getSpotOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L701) | | WS | `openOrders.status` | +| [cancelAllSpotOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L716) | | WS | `openOrders.cancelAll` | +| [placeSpotOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L733) | | WS | `orderList.place` | +| [placeSpotOCOOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L748) | | WS | `orderList.place.oco` | +| [placeSpotOTOOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L763) | | WS | `orderList.place.oto` | +| [placeSpotOTOCOOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L778) | | WS | `orderList.place.otoco` | +| [placeSpotOPOOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L793) | | WS | `orderList.place.opo` | +| [placeSpotOPOCOOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L808) | | WS | `orderList.place.opoco` | +| [getSpotOrderListStatus()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L823) | | WS | `orderList.status` | +| [cancelSpotOrderList()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L838) | | WS | `orderList.cancel` | +| [getSpotOpenOrderLists()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L853) | | WS | `openOrderLists.status` | +| [placeSpotSOROrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L868) | | WS | `sor.order.place` | +| [testSpotSOROrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L883) | | WS | `sor.order.test` | +| [getSpotAccountInformation()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L908) | | WS | `account.status` | +| [getSpotOrderRateLimits()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L923) | | WS | `account.rateLimits.orders` | +| [getSpotAllOrders()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L938) | | WS | `allOrders` | +| [getSpotAllOrderLists()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L953) | | WS | `allOrderLists` | +| [getSpotMyTrades()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L968) | | WS | `myTrades` | +| [getSpotPreventedMatches()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L983) | | WS | `myPreventedMatches` | +| [getSpotAllocations()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L998) | | WS | `myAllocations` | +| [getSpotAccountCommission()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1013) | | WS | `account.commission` | +| [getFuturesOrderBook()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1034) | | WS | `depth` | +| [getFuturesSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1049) | | WS | `ticker.price` | +| [getFuturesSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1066) | | WS | `ticker.book` | +| [submitNewFuturesOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1088) | | WS | `order.place` | +| [modifyFuturesOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1104) | | WS | `order.modify` | +| [cancelFuturesOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1120) | | WS | `order.cancel` | +| [getFuturesOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1136) | | WS | `order.status` | +| [getFuturesPositionV2()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1151) | | WS | `v2/account.position` | +| [getFuturesPosition()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1167) | | WS | `account.position` | +| [submitNewFuturesAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1183) | | WS | `algoOrder.place` | +| [cancelFuturesAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1199) | | WS | `algoOrder.cancel` | +| [getFuturesAccountBalanceV2()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1219) | | WS | `v2/account.balance` | +| [getFuturesAccountBalance()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1235) | | WS | `account.balance` | +| [getFuturesAccountStatusV2()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1250) | | WS | `v2/account.status` | +| [getFuturesAccountStatus()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1266) | | WS | `account.status` | +| [startUserDataStreamForKey()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1292) | | WS | `userDataStream.start` | +| [pingUserDataStreamForKey()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1312) | | WS | `userDataStream.ping` | +| [stopUserDataStreamForKey()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1326) | | WS | `userDataStream.stop` | +| [subscribeUserDataStream()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1357) | | WS | `userDataStream.unsubscribe` | +| [unsubscribeUserDataStream()](https://github.com/sieblyio/binance/blob/master/src/websocket-api-client.ts#L1482) | | WS | `userDataStream.unsubscribe` | \ No newline at end of file diff --git a/examples/apidoc/MainClient/getPortfolioDeltaMode.js b/examples/apidoc/MainClient/getPortfolioDeltaMode.js new file mode 100644 index 00000000..efb4e9b6 --- /dev/null +++ b/examples/apidoc/MainClient/getPortfolioDeltaMode.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/portfolio/delta-mode +// METHOD: GET +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getPortfolioDeltaMode(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getSpotAssetTags.js b/examples/apidoc/MainClient/getSpotAssetTags.js new file mode 100644 index 00000000..c35b6842 --- /dev/null +++ b/examples/apidoc/MainClient/getSpotAssetTags.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/spot/asset/tags +// METHOD: GET +// PUBLIC: YES + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getSpotAssetTags(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/switchPortfolioDeltaMode.js b/examples/apidoc/MainClient/switchPortfolioDeltaMode.js new file mode 100644 index 00000000..11127e54 --- /dev/null +++ b/examples/apidoc/MainClient/switchPortfolioDeltaMode.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/portfolio/delta-mode +// METHOD: POST +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.switchPortfolioDeltaMode(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index 3fc68806..3591ba7f 100644 --- a/llms.txt +++ b/llms.txt @@ -151,6 +151,82 @@ tsconfig.linting.json Files ================================================================ +================ +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/auth/rest-private-ed25519.ts ================ @@ -873,6 +949,20 @@ import { WebsocketClient } from '../../../src'; // Subscribe to a couple of topics // Note: '!ticker@arr' has been deprecated (2025-11-14). Using '!miniTicker@arr' instead. +================ +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'; +⋮---- +// or +// import { WebsocketClient } from 'binance'; +⋮---- +import { SocksProxyAgent } from 'socks-proxy-agent'; +// const { SocksProxyAgent } = require('socks-proxy-agent'); + ================ File: examples/WebSockets/Misc/ws-unsubscribe.ts ================ @@ -927,6 +1017,114 @@ import { ⋮---- // 5 seconds later, unsubscribe from almost all topics except avg price +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-connection-safety.ts +================ +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotUserDataEvent, + isWsFormattedSpotUserDataExecutionReport, + isWsFormattedUserDataEvent, + WebsocketClient, + WsUserDataEvents, +} from '../../../src/index'; +⋮---- +// or +// import { DefaultLogger, WebsocketClient } from 'binance'; +⋮---- +/** + * 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 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) +⋮---- +// 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. +⋮---- +// 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'; +⋮---- +// 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) +⋮---- +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { +⋮---- +// or use a type guard, if one exists (PRs welcome) +⋮---- +// Beautified/formatted events from binance: +⋮---- +// 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 +⋮---- +// wsClient.subscribeMarginUserDataStream(); +// wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); +// wsClient.subscribeUsdFuturesUserDataStream(); +⋮---- +// setTimeout(() => { +// console.log('killing all connections'); +// wsClient.closeAll(); +// }, 1000 * 15); + ================ File: examples/WebSockets/Private(userdata)/ws-userdata-README.MD ================ @@ -1360,149 +1558,193 @@ const optionsExpiration = '260128'; // YYMMDD // wsClient.subscribeContractInfoStream('coinm'); ================ -File: src/types/coin.ts +File: examples/WebSockets/WS-API/ws-api-client.ts ================ -import { FuturesContractType, PositionSide } from './futures'; -import { numberInString, OrderSide } from './shared'; +/* 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 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 { DefaultLogger, WebsocketAPIClient } 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 }; +/** + * 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 CoinMSymbolOrderBookTicker { - symbol: string; - pair: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; -} +// 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 CoinMPaginatedRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: 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 CoinMAccountTradeParamsWithPair extends CoinMPaginatedRequest { - pair: string; - symbol?: never; - fromId?: never; -} +async function main() ⋮---- -export interface CoinMAccountTradeParamsWithSymbol - extends CoinMPaginatedRequest { - symbol: string; - pair?: never; -} +// 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 CoinMAccountTradeParamsWithFromId - extends CoinMPaginatedRequest { - fromId: number; - startTime?: never; - endTime?: never; -} +// Enforce testnet ws connections, regardless of supplied wsKey +// testnet: true, ⋮---- -export type CoinMAccountTradeParams = - | CoinMAccountTradeParamsWithSymbol - | CoinMAccountTradeParamsWithPair - | CoinMAccountTradeParamsWithFromId; +// 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, ⋮---- -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; -} +// 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 FundingRate { - symbol: string; - adjustedFundingRateCap: string; - adjustedFundingRateFloor: string; - fundingIntervalHours: number; - disclaimer: boolean; -} +// Optional, attach basic event handlers, so nothing is left unhandled +// attachEventHandlers(wsClient.getWSClient()); ⋮---- -export interface GetClassicPortfolioMarginNotionalLimitParams { - symbol?: string; - pair?: 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); ⋮---- -export interface ClassicPortfolioMarginNotionalLimit { - symbol: string; - pair: string; - notionalLimit: string; -} +// 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 ClassicPortfolioMarginAccount { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; -} +// SPOT - Market data requests ⋮---- -export interface FuturesTransactionHistoryDownloadLink { - downloadId: string; - status: string; - url: string; - notified: boolean; - expirationTimestamp: number; - isExpired: boolean | null; -} +// SPOT - Trading requests +⋮---- +// SPOT - Account requests +⋮---- +// FUTURES - Market data requests +⋮---- +// FUTURES - Trading requests +⋮---- +// FUTURES - Account requests +⋮---- +// Start executing the example workflow ================ -File: webpack/webpack.config.js +File: examples/WebSockets/WS-API/ws-api-raw-promises.ts ================ -function generateConfig(name) +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + DefaultLogger, + WebsocketClient, + WS_KEY_MAP, + WSAPIWsKey, +} from '../../../src/index'; ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient, WSAPIWsKey } from 'binance'; ⋮---- -// 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 +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: ⋮---- -// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. +// testnet: true, ⋮---- -// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. +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, ⋮---- -// new webpack.DefinePlugin({ -// 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) -// }), +// Start executing the example workflow + +================ +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: .jshintrc @@ -1918,205 +2160,7 @@ File: tsconfig.linting.json } ================ -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'; -⋮---- -// or -// import { WebsocketClient } from 'binance'; -⋮---- -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'; -⋮---- -// or -// import { DefaultLogger, WebsocketClient } from 'binance'; -⋮---- -/** - * 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 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) -⋮---- -// 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. -⋮---- -// 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'; -⋮---- -// 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) -⋮---- -// the market denotes which API category it came from -// if (data.wsMarket.includes('spot')) { -⋮---- -// or use a type guard, if one exists (PRs welcome) -⋮---- -// Beautified/formatted events from binance: -⋮---- -// 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 -⋮---- -// 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 +File: examples/WebSockets/Private(userdata)/ws-userdata-wsapi-margin.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ // or @@ -2227,24830 +2271,25340 @@ logger, // Optional: inject a custom logger, especially to see trace events // Start executing the example workflow ================ -File: examples/WebSockets/WS-API/ws-api-client.ts +File: src/types/coin.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 { FuturesContractType, PositionSide } from './futures'; +import { numberInString, OrderSide } from './shared'; ⋮---- -import { DefaultLogger, WebsocketAPIClient } from '../../../src'; +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; +} ⋮---- -/** - * 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 CoinMOpenInterest { + symbol: string; + pair: string; + openInterest: numberInString; + contractType: FuturesContractType; + time: number; +} +export type SymbolOrPair = + | { pair: string; symbol?: never } + | { pair?: never; symbol: string }; ⋮---- -// 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 CoinMSymbolOrderBookTicker { + symbol: string; + pair: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: 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 CoinMPaginatedRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -async function main() -⋮---- -// 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 CoinMAccountTradeParamsWithPair extends CoinMPaginatedRequest { + pair: string; + symbol?: never; + fromId?: never; +} ⋮---- -// Enforce testnet ws connections, regardless of supplied wsKey -// testnet: true, +export interface CoinMAccountTradeParamsWithSymbol + extends CoinMPaginatedRequest { + symbol: string; + pair?: never; +} ⋮---- -// 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, +export interface CoinMAccountTradeParamsWithFromId + extends CoinMPaginatedRequest { + fromId: number; + startTime?: never; + endTime?: never; +} ⋮---- -// 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 type CoinMAccountTradeParams = + | CoinMAccountTradeParamsWithSymbol + | CoinMAccountTradeParamsWithPair + | CoinMAccountTradeParamsWithFromId; ⋮---- -// Optional, attach basic event handlers, so nothing is left unhandled -// attachEventHandlers(wsClient.getWSClient()); +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; + quoteQty?: numberInString; +} ⋮---- -// 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 FundingRate { + symbol: string; + adjustedFundingRateCap: string; + adjustedFundingRateFloor: string; + fundingIntervalHours: number; + disclaimer: boolean; +} ⋮---- -// 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 GetClassicPortfolioMarginNotionalLimitParams { + symbol?: string; + pair?: string; +} ⋮---- -// SPOT - Market data requests +export interface ClassicPortfolioMarginNotionalLimit { + symbol: string; + pair: string; + notionalLimit: string; +} ⋮---- -// SPOT - Trading requests +export interface ClassicPortfolioMarginAccount { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; +} ⋮---- -// SPOT - Account requests +export interface FuturesTransactionHistoryDownloadLink { + downloadId: string; + status: string; + url: string; + notified: boolean; + expirationTimestamp: number; + isExpired: boolean | null; +} + +================ +File: webpack/webpack.config.js +================ +function generateConfig(name) ⋮---- -// FUTURES - Market data requests +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -// FUTURES - Trading requests +// 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 ⋮---- -// FUTURES - Account requests +// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. ⋮---- -// Start executing the example workflow +// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. ================ -File: examples/WebSockets/WS-API/ws-api-raw-promises.ts +File: eslint.config.cjs ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ + + +================ +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, - WS_KEY_MAP, - WSAPIWsKey, + WsConnectionStateEnum, + WsUserDataEvents, } 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: +// Optional, hook and customise logging behavior ⋮---- // testnet: true, ⋮---- -logger, // Optional: inject a custom logger +// wsClient.on('message', (data) => { +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// }); ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +function onUserDataEvent(data: WsUserDataEvents) ⋮---- -// WS API responses can be processed here too, but that is optional -// console.log('ws response: ', JSON.stringify(data)); +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { ⋮---- -async function main() +// 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 ⋮---- /** + * This example demonstrates subscribing to the user data stream via the + * listen key workflow. * - * 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. + * 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. * - * 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. + * 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. */ ⋮---- /** - * 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: 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'); ⋮---- -// Note: if you set "testnet: true" in the config, this will automatically resolve to WS_KEY_MAP.mainWSAPITestnet (you can keep using mainWSAPI). +/** + * Futures + */ ⋮---- -// 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); +// Example 5: usdm futures ⋮---- -// 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); +// Example 6: coinm futures ⋮---- -// rateLimits: wsAPIResponse.result.rateLimits, -// symbols: wsAPIResponse.result.symbols, +// Example 7: portfolio margin ⋮---- -// 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'; +// Example 8: portfolio margin pro ⋮---- -export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +// after 15 seconds, kill user data connections one by one (or all at once) ⋮---- -export type PMPriceMatch = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; +// console.log('killing all connections at once'); +// wsClient.closeAll(); ⋮---- -export type PMSelfTradePreventionMode = - | 'NONE' - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH'; +// or: ⋮---- -export type PMMarginOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +// console.log('killing all connections'); +// wsClient.closeAll(); +// Example 5: usdm futures ⋮---- -export type PMMarginSideEffectType = - | 'NO_SIDE_EFFECT' - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'AUTO_BORROW_REPAY'; +// Example 6: coinm futures ⋮---- -export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +// // Example 7: portfolio margin +// wsClient.unsubscribePortfolioMarginUserDataStream(); +// // Example 8: portfolio margin pro +// wsClient.unsubscribePortfolioMarginUserDataStream( +// 'portfolioMarginProUserData', +// ); ⋮---- -export interface NewPortfolioUMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode - type: 'LIMIT' | 'MARKET'; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; // Cannot be sent in Hedge Mode - price?: string; - newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ - newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK - priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD -} +// after 20 seconds, list the remaining open connections + +================ +File: examples/WebSockets/Public/ws-usdm-market.ts +================ +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- -positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode +// or, with the npm package +/* +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from 'binance'; +*/ ⋮---- -reduceOnly?: boolean; // Cannot be sent in Hedge Mode +// Without typescript: +// const logger = { ⋮---- -newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ -newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK -priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; +// } ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is 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 interface NewPortfolioUMOrderResponse { - clientOrderId: string; - cumQty: string; - cumQuote: string; - executedQty: string; - orderId: number; - avgPrice: string; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate?: number; - updateTime: number; - priceMatch: PMPriceMatch; -} +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -export interface NewPortfolioUMConditionalOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - strategyType: PMStrategyType; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; - price?: string; - workingType?: PMWorkingType; - priceProtect?: boolean; - newClientStrategyId?: string; - stopPrice?: string; - activationPrice?: string; - callbackRate?: string; - priceMatch?: PMPriceMatch; - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; -} +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -export interface NewPortfolioConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate?: number; - priceMatch: PMPriceMatch; -} +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export type PortfolioUMAlgoType = 'CONDITIONAL'; +// console.log('log rawMessage: ', data); ⋮---- -export interface NewPortfolioUMAlgoOrderReq { - algoType: PortfolioUMAlgoType; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - type: PMStrategyType; - timeInForce?: string; - quantity?: string; - price?: string; - triggerPrice?: string; - workingType?: PMWorkingType; - priceMatch?: PMPriceMatch; - closePosition?: string; - priceProtect?: string; - reduceOnly?: string; - activatePrice?: string; - callbackRate?: string; - clientAlgoId?: string; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; -} +// Formatted data that has gone through the beautifier ⋮---- -export interface PortfolioUMAlgoOrder { - algoId: number; - clientAlgoId: string; - algoType: string; - orderType: string; - symbol: string; - side: string; - positionSide: string; - timeInForce: string; - quantity: string; - algoStatus: string; - triggerPrice: string; - price: string; - icebergQuantity: string | null; - selfTradePreventionMode: string; - workingType: string; - priceMatch: string; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - activatePrice: string; - callbackRate: string; - createTime: number; - updateTime: number; - triggerTime: number; - goodTillDate: number; - actualOrderId?: string; - actualPrice?: string; - tpTriggerPrice?: string; - tpPrice?: string; - slTriggerPrice?: string; - slPrice?: string; - tpOrderType?: string; -} +// console.log('log formattedMessage: ', data); ⋮---- -export interface CancelPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; -} +/** + * 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 interface PortfolioUMCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { - code: number; - msg: string; -} +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -export interface QueryPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; -} +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -export interface QueryPortfolioAllUMAlgoOrdersReq { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -export interface NewPortfolioCMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - type: 'LIMIT' | 'MARKET'; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; - price?: string; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT'; -} +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -export interface NewPortfolioCMOrderResponse { - clientOrderId: string; - cumQty: string; - cumBase: string; - executedQty: string; - orderId: number; - avgPrice: string; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - pair: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -export interface NewPortfolioCMConditionalOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - strategyType: PMStrategyType; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; - price?: string; - workingType?: PMWorkingType; - priceProtect?: boolean; - newClientStrategyId?: string; - stopPrice?: string; - activationPrice?: string; - callbackRate?: string; -} +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -export interface NewPortfolioCMConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - pair: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; -} +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -export interface MarginOrderFill { - price: string; - qty: string; - commission: string; - commissionAsset: string; -} +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -export interface NewPortfolioMarginOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - type: PMMarginOrderType; - quantity?: string; - quoteOrderQty?: string; - price?: string; - stopPrice?: string; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - icebergQty?: string; - sideEffectType?: PMMarginSideEffectType; - timeInForce?: string; - selfTradePreventionMode?: PMSelfTradePreventionMode; - autoRepayAtCancel?: boolean; -} +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- -export interface NewPortfolioMarginOrderResponse { - symbol: string; - orderId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; - marginBuyBorrowAmount?: string; - marginBuyBorrowAsset?: string; - fills: MarginOrderFill[]; -} +/** + * 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 PortfolioMarginOCOOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +// Uses the regular market feeds WS URL dedicated to USDM Futures: wss://fstream.binance.com/market/stream ⋮---- -export interface PortfolioMarginOCOOrderReport { - 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: 'BUY' | 'SELL'; - stopPrice?: string; -} +/** + * Subscribe to each available type of USDM Derivatives market topic, the new way + */ ⋮---- -export interface NewPortfolioMarginOCOReq { - symbol: string; - listClientOrderId?: string; - side: 'BUY' | 'SELL'; - quantity: string; - limitClientOrderId?: string; - price: string; - limitIcebergQty?: string; - stopClientOrderId?: string; - stopPrice: string; - stopLimitPrice?: string; - stopIcebergQty?: string; - stopLimitTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - sideEffectType?: PMMarginSideEffectType; -} +// Aggregate Trade Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams ⋮---- -export interface NewPortfolioMarginOCOResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - marginBuyBorrowAmount?: string; - marginBuyBorrowAsset?: string; - orders: PortfolioMarginOCOOrder[]; - orderReports: PortfolioMarginOCOOrderReport[]; -} +// Mark Price Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream ⋮---- -// Add new interfaces for canceling UM orders -export interface CancelPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// 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 PortfolioUMCancelOrderResponse { - avgPrice: string; - clientOrderId: string; - cumQty: string; - cumQuote: string; - executedQty: string; - orderId: number; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +// Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams ⋮---- -export interface CancelPortfolioUMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +// 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 PortfolioUMCancelConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +// 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 CancelPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// 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 PortfolioCMCancelOrderResponse { - avgPrice: string; - clientOrderId: string; - cumQty: string; - cumBase: string; - executedQty: string; - orderId: number; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - pair: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} +// Individual Symbol Ticker Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams ⋮---- -export interface CancelPortfolioCMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: 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 PortfolioCMCancelConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; -} +// Liquidation Order Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams ⋮---- -export interface CancelPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; -} +// 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 PortfolioMarginCancelOrderResponse { - symbol: string; - orderId: number; - origClientOrderId: string; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; -} +// Composite Index Symbol Information Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams ⋮---- -export interface CancelPortfolioMarginOCOReq { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} +'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 PortfolioMarginOCOCancelOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +// 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 PortfolioMarginOCOCancelOrderReport { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: 'STOP_LOSS_LIMIT' | 'LIMIT_MAKER'; - side: 'BUY' | 'SELL'; - stopPrice?: string; -} +// /** +// * +// * 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 PortfolioMarginOCOCancelResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginOCOCancelOrderReport[]; -} +// 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 PortfolioMarginCancelAllOrdersOrderReport { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; - stopPrice?: string; - icebergQty?: string; -} +// or, with the npm package +/* +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from 'binance'; +*/ ⋮---- -export interface PortfolioMarginCancelAllOrdersOCOReport { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; -} +// Without typescript: +// const logger = { ⋮---- -export type PortfolioMarginCancelAllOrdersResponse = - | PortfolioMarginCancelAllOrdersOrderReport - | PortfolioMarginCancelAllOrdersOCOReport; +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; +// } ⋮---- -export interface ModifyPortfolioUMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - priceMatch?: PMPriceMatch; -} +// 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 PortfolioUMModifyOrderResponse { - orderId: number; - symbol: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumQty: string; - cumQuote: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - origType: 'LIMIT'; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - updateTime: number; - priceMatch: PMPriceMatch; -} +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -export interface ModifyPortfolioCMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; -} +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -export interface PortfolioCMModifyOrderResponse { - orderId: number; - symbol: string; - pair: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumQty: string; - cumBase: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - origType: 'LIMIT'; - updateTime: number; -} +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface QueryPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// console.log('log rawMessage: ', data); ⋮---- -export interface PortfolioUMOrder { - avgPrice: string; - clientOrderId: string; - cumQuote: string; - executedQty: string; - orderId: number; - origQty: string; - origType: 'LIMIT' | 'MARKET'; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - status: string; - symbol: string; - time: number; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +// Formatted data that has gone through the beautifier ⋮---- -export interface QueryPortfolioAllUMOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// console.log('log formattedMessage: ', data); ⋮---- -export interface QueryPortfolioUMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * 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 interface QueryPortfolioAllUMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -export interface PortfolioUMConditionalOrder { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - stopPrice?: string; - symbol: string; - orderId?: number; - status?: string; - bookTime: number; - updateTime: number; - triggerTime?: number; - timeInForce: string; - type?: 'MARKET' | 'LIMIT'; - activatePrice?: string; - priceRate?: string; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -export interface QueryPortfolioUMOpenConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -export interface QueryPortfolioUMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -export interface QueryPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -export interface PortfolioCMOrder { - avgPrice: string; - clientOrderId: string; - cumBase: string; - executedQty: string; - orderId: number; - origQty: string; - origType: 'LIMIT' | 'MARKET'; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - status: string; - symbol: string; - pair: string; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - time: number; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -export interface QueryPortfolioAllCMOrdersReq { - symbol: string; - pair?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -export interface QueryPortfolioCMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -export interface QueryPortfolioAllCMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -export interface PortfolioCMConditionalOrder { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - orderId?: number; - status?: string; - bookTime: number; - updateTime: number; - triggerTime?: number; - timeInForce: string; - type?: 'MARKET' | 'LIMIT'; - activatePrice?: string; - priceRate?: string; - workingType: PMWorkingType; - priceProtect: boolean; -} +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- -export interface QueryPortfolioCMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +/** + * 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 PortfolioCMConditionalHistoryOrder - extends PortfolioCMConditionalOrder { - priceMatch: PMPriceMatch; -} +// Uses the high-frequency order book & core public feeds WS URL dedicated to USDM Futures: +// wss://fstream.binance.com/public/stream ⋮---- -export interface QueryPortfolioUMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Subscribe to each available type of USDM Derivatives market topic, the new way + */ ⋮---- -export interface PortfolioUMForceOrder { - orderId: number; - symbol: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumQuote: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - origType: 'LIMIT'; - time: number; - updateTime: number; -} -⋮---- -export interface QueryPortfolioCMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface PortfolioCMForceOrder { - orderId: number; - symbol: string; - pair: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumBase: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - origType: 'LIMIT'; - time: number; - updateTime: number; -} -⋮---- -export interface QueryPortfolioUMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface PortfolioUMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} -⋮---- -export interface PortfolioUMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioUMOrderAmendment; - priceMatch: PMPriceMatch; -} -⋮---- -export interface QueryPortfolioCMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface PortfolioCMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} -⋮---- -export interface PortfolioCMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioCMOrderAmendment; -} -⋮---- -export interface QueryPortfolioMarginForceOrdersReq { - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 -} -⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 -⋮---- -export interface PortfolioMarginForceOrder { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - updatedTime: number; -} -⋮---- -export interface QueryPortfolioUMTradesReq { - symbol: string; - startTime?: number; - endTime?: number; - fromId?: number; // Trade id to fetch from. Default gets most recent trades - limit?: number; // Default 500; max 1000 -} -⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 -⋮---- -export interface PortfolioUMTrade { - symbol: string; - id: number; - orderId: number; - side: 'BUY' | 'SELL'; - price: string; - qty: string; - realizedPnl: string; - quoteQty: string; - commission: string; - commissionAsset: string; - time: number; - buyer: boolean; - maker: boolean; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; -} -⋮---- -export interface QueryPortfolioCMTradesReq { - symbol?: string; - pair?: string; - startTime?: number; - endTime?: number; - fromId?: number; // Trade id to fetch from. Default gets most recent trades - limit?: number; // Default 50; max 1000 -} -⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 50; max 1000 -⋮---- -export interface PortfolioCMTrade { - symbol: string; - id: number; - orderId: number; - pair: string; - side: 'BUY' | 'SELL'; - price: string; - qty: string; - realizedPnl: string; - marginAsset: string; - baseQty: string; - commission: string; - commissionAsset: string; - time: number; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - buyer: boolean; - maker: boolean; -} -⋮---- -export interface PortfolioADLQuantile { - LONG: number; - SHORT: number; - BOTH?: number; // For one-way mode or isolated margin in hedge mode - HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) -} -⋮---- -BOTH?: number; // For one-way mode or isolated margin in hedge mode -HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) -⋮---- -export interface QueryPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} -⋮---- -export interface PortfolioMarginOrder { - clientOrderId: string; - cummulativeQuoteQty: string; - executedQty: string; - icebergQty: string; - isWorking: boolean; - orderId: number; - origQty: string; - price: string; - side: 'BUY' | 'SELL'; - status: string; - stopPrice: string; - symbol: string; - time: number; - timeInForce: string; - type: PMMarginOrderType; - updateTime: number; - accountId: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - preventedMatchId: number | null; - preventedQuantity: string | null; -} -⋮---- -export interface QueryPortfolioMarginAllOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; // Default 500; max 500 -} +// Individual Symbol Book Ticker Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams ⋮---- -limit?: number; // Default 500; max 500 +// 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 QueryPortfolioMarginOCOReq { - orderListId?: number; // Either orderListId or origClientOrderId must be provided - origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided -} +// Diff. Book Depth Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams ⋮---- -orderListId?: number; // Either orderListId or origClientOrderId must be provided -origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +// /** +// * +// * 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 PortfolioMarginOCOQueryOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} -⋮---- -export interface PortfolioMarginOCO { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOQueryOrder[]; -} -⋮---- -export interface QueryPortfolioMarginAllOCOReq { - fromId?: number; // If supplied, neither startTime or endTime can be provided - startTime?: number; - endTime?: number; - limit?: number; // Default 500; max 500 -} -⋮---- -fromId?: number; // If supplied, neither startTime or endTime can be provided -⋮---- -limit?: number; // Default 500; max 500 -⋮---- -export interface QueryPortfolioMarginTradesReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; // TradeId to fetch from. Default gets most recent trades - limit?: number; // Default 500; max 1000 -} -⋮---- -fromId?: number; // TradeId to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 -⋮---- -export interface PortfolioMarginTrade { - commission: string; - commissionAsset: string; - id: number; - isBestMatch: boolean; - isBuyer: boolean; - isMaker: boolean; - orderId: number; - price: string; - qty: string; - symbol: string; - time: number; -} -⋮---- -export interface PortfolioMarginRepayDebtReq { - asset: string; - amount?: string; - specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas -} -⋮---- -specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas -⋮---- -export interface PortfolioMarginRepayDebtResponse { - amount: string; - asset: string; - specifyRepayAssets: string[]; - updateTime: number; - success: boolean; -} -⋮---- -/** - * - * DERIVATIVES - ACCOUNT endpoints - * - **/ -⋮---- -export type PMAccountStatus = - | 'NORMAL' - | 'MARGIN_CALL' - | 'SUPPLY_MARGIN' - | 'REDUCE_ONLY' - | 'ACTIVE_LIQUIDATION' - | 'FORCE_LIQUIDATION' - | 'BANKRUPTED'; -⋮---- -export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; -export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; -⋮---- -export interface PortfolioTotalBalance { - asset: string; - totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance - crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked - crossMarginBorrowed: string; // principal of cross margin - crossMarginFree: string; // free asset of cross margin - crossMarginInterest: string; // interest of cross margin - crossMarginLocked: string; // lock asset of cross margin - umWalletBalance: string; // wallet balance of um - umUnrealizedPNL: string; // unrealized profit of um - cmWalletBalance: string; // wallet balance of cm - cmUnrealizedPNL: string; // unrealized profit of cm - updateTime: number; - negativeBalance: string; -} -⋮---- -totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance -crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked -crossMarginBorrowed: string; // principal of cross margin -crossMarginFree: string; // free asset of cross margin -crossMarginInterest: string; // interest of cross margin -crossMarginLocked: string; // lock asset of cross margin -umWalletBalance: string; // wallet balance of um -umUnrealizedPNL: string; // unrealized profit of um -cmWalletBalance: string; // wallet balance of cm -cmUnrealizedPNL: string; // unrealized profit of cm -⋮---- -export interface PortfolioSingleBalance { - asset: string; - totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance - crossMarginBorrowed: string; // principal of cross margin - crossMarginFree: string; // free asset of cross margin - crossMarginInterest: string; // interest of cross margin - crossMarginLocked: string; // lock asset of cross margin - umWalletBalance: string; // wallet balance of um - umUnrealizedPNL: string; // unrealized profit of um - cmWalletBalance: string; // wallet balance of cm - cmUnrealizedPNL: string; // unrealized profit of cm - updateTime: number; - negativeBalance: string; -} -⋮---- -totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance -crossMarginBorrowed: string; // principal of cross margin -crossMarginFree: string; // free asset of cross margin -crossMarginInterest: string; // interest of cross margin -crossMarginLocked: string; // lock asset of cross margin -umWalletBalance: string; // wallet balance of um -umUnrealizedPNL: string; // unrealized profit of um -cmWalletBalance: string; // wallet balance of cm -cmUnrealizedPNL: string; // unrealized profit of cm -⋮---- -export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; -⋮---- -export interface PortfolioAccountInformation { - uniMMR: string; // Portfolio margin account maintenance margin rate - accountEquity: string; // Account equity, in USD value - actualEquity: string; // Account equity without collateral rate, in USD value - accountInitialMargin: string; - accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD - accountStatus: PMAccountStatus; - virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD - totalAvailableBalance: string; - totalMarginOpenLoss: string; // in USD margin open order - updateTime: number; // last update time -} -⋮---- -uniMMR: string; // Portfolio margin account maintenance margin rate -accountEquity: string; // Account equity, in USD value -actualEquity: string; // Account equity without collateral rate, in USD value -⋮---- -accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD -⋮---- -virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD -⋮---- -totalMarginOpenLoss: string; // in USD margin open order -updateTime: number; // last update time -⋮---- -export interface PortfolioUMPosition { - symbol: string; - positionAmt: string; - entryPrice: string; - markPrice: string; - unRealizedProfit: string; - liquidationPrice: string; - leverage: string; - maxNotionalValue: string; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - notional: string; - updateTime: number; -} -⋮---- -export interface PortfolioCMPosition { - symbol: string; - positionAmt: string; - entryPrice: string; - markPrice: string; - unRealizedProfit: string; - liquidationPrice: string; - leverage: string; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - updateTime: number; - maxQty: string; - notionalValue: string; -} -⋮---- -export interface PortfolioUMLeverageBracket { - bracket: number; // Notional bracket - initialLeverage: number; // Max initial leverage for this bracket - notionalCap: number; // Cap notional of this bracket - notionalFloor: number; // Notional threshold of this bracket - maintMarginRatio: number; // Maintenance ratio for this bracket - cum: number; // Auxiliary number for quick calculation -} -⋮---- -bracket: number; // Notional bracket -initialLeverage: number; // Max initial leverage for this bracket -notionalCap: number; // Cap notional of this bracket -notionalFloor: number; // Notional threshold of this bracket -maintMarginRatio: number; // Maintenance ratio for this bracket -cum: number; // Auxiliary number for quick calculation -⋮---- -export interface PortfolioCMLeverageBracket { - bracket: number; // bracket level - initialLeverage: number; // the maximum leverage - qtyCap: number; // upper edge of base asset quantity - qtyFloor: number; // lower edge of base asset quantity - maintMarginRatio: number; // maintenance margin rate - cum: number; // Auxiliary number for quick calculation -} -⋮---- -bracket: number; // bracket level -initialLeverage: number; // the maximum leverage -qtyCap: number; // upper edge of base asset quantity -qtyFloor: number; // lower edge of base asset quantity -maintMarginRatio: number; // maintenance margin rate -cum: number; // Auxiliary number for quick calculation -⋮---- -export interface PortfolioTradingIndicator { - isLocked: boolean; - plannedRecoverTime: number; - indicator: PMIndicatorType; - value: number; - triggerValue: number; -} -⋮---- -export interface PortfolioTradingStatus { - indicators: { - [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" - }; - updateTime: number; -} -⋮---- -[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" -⋮---- -export interface PortfolioMarginLoanRecord { - txId: number; - asset: string; - principal: string; - timestamp: number; - status: PMMarginLoanStatus; -} -⋮---- -export interface GetMarginLoanRecordsReq { - asset: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 - archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -} -⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 -archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -⋮---- -export interface GetMarginRepayRecordsReq { - asset: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 - archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -} -⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 -archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -⋮---- -export interface PortfolioMarginRepayRecord { - amount: string; // Total amount repaid - asset: string; - interest: string; // Interest repaid - principal: string; // Principal repaid - status: PMMarginLoanStatus; - txId: number; -} -⋮---- -amount: string; // Total amount repaid -⋮---- -interest: string; // Interest repaid -principal: string; // Principal repaid -⋮---- -export interface GetMarginInterestHistoryReq { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 - archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -} -⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 -archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -⋮---- -export type PMInterestType = - | 'PERIODIC' // interest charged per hour - | 'ON_BORROW' // first interest charged on borrow - | 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB - | 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB - | 'PORTFOLIO'; // Portfolio Margin negative balance daily interest -⋮---- -| 'PERIODIC' // interest charged per hour -| 'ON_BORROW' // first interest charged on borrow -| 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB -| 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB -| 'PORTFOLIO'; // Portfolio Margin negative balance daily interest -⋮---- -export interface PortfolioMarginInterestRecord { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset: string; - principal: string; - interest: string; - interestRate: string; - type: PMInterestType; -} -⋮---- -export interface GetPortfolioInterestHistoryReq { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; // Default: 10, Max: 100 -} -⋮---- -size?: number; // Default: 10, Max: 100 -⋮---- -export interface PortfolioNegativeBalanceInterestRecord { - asset: string; - interest: string; // interest amount - interestAccuredTime: number; - interestRate: string; // daily interest rate - principal: string; -} -⋮---- -interest: string; // interest amount -⋮---- -interestRate: string; // daily interest rate -⋮---- -export type UMIncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'COMMISSION' - | 'INSURANCE_CLEAR' - | 'REFERRAL_KICKBACK' - | 'COMMISSION_REBATE' - | 'API_REBATE' - | 'CONTEST_REWARD' - | 'CROSS_COLLATERAL_TRANSFER' - | 'OPTIONS_PREMIUM_FEE' - | 'OPTIONS_SETTLE_PROFIT' - | 'INTERNAL_TRANSFER' - | 'AUTO_EXCHANGE' - | 'DELIVERED_SETTELMENT' - | 'COIN_SWAP_DEPOSIT' - | 'COIN_SWAP_WITHDRAW' - | 'POSITION_LIMIT_INCREASE_FEE'; -⋮---- -export interface QueryPortfolioUMIncomeReq { - symbol?: string; - incomeType?: UMIncomeType; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 100; max 1000 -} -⋮---- -limit?: number; // Default 100; max 1000 -⋮---- -export interface PortfolioUMIncome { - symbol: string; // trade symbol, if existing - incomeType: UMIncomeType; - income: string; // income amount - asset: string; // income asset - info: string; // extra information - time: number; - tranId: string; // transaction id - tradeId: string; // trade id, if existing -} -⋮---- -symbol: string; // trade symbol, if existing -⋮---- -income: string; // income amount -asset: string; // income asset -info: string; // extra information -⋮---- -tranId: string; // transaction id -tradeId: string; // trade id, if existing -⋮---- -export type CMIncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'FUNDING_FEE' - | 'REALIZED_PNL' - | 'COMMISSION' - | 'INSURANCE_CLEAR' - | 'DELIVERED_SETTELMENT'; -⋮---- -export interface QueryPortfolioCMIncomeReq { - symbol?: string; - incomeType?: CMIncomeType; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 100; max 1000 -} -⋮---- -limit?: number; // Default 100; max 1000 -⋮---- -export interface PortfolioCMIncome { - symbol: string; // trade symbol, if existing - incomeType: CMIncomeType; - income: string; // income amount - asset: string; // income asset - info: string; // extra information - time: number; - tranId: string; // transaction id - tradeId: string; // trade id, if existing -} -⋮---- -symbol: string; // trade symbol, if existing -⋮---- -income: string; // income amount -asset: string; // income asset -info: string; // extra information -⋮---- -tranId: string; // transaction id -tradeId: string; // trade id, if existing -⋮---- -export interface PortfolioUMAccountAsset { - asset: string; // asset name - crossWalletBalance: string; // wallet balance - crossUnPnl: string; // unrealized profit - maintMargin: string; // maintenance margin required - initialMargin: string; // total initial margin required with current mark price - positionInitialMargin: string; // initial margin required for positions with current mark price - openOrderInitialMargin: string; // initial margin required for open orders with current mark price - updateTime: number; // last update time -} -⋮---- -asset: string; // asset name -crossWalletBalance: string; // wallet balance -crossUnPnl: string; // unrealized profit -maintMargin: string; // maintenance margin required -initialMargin: string; // total initial margin required with current mark price -positionInitialMargin: string; // initial margin required for positions with current mark price -openOrderInitialMargin: string; // initial margin required for open orders with current mark price -updateTime: number; // last update time -⋮---- -export interface PortfolioUMAccountPosition { - symbol: string; // symbol name - initialMargin: string; // initial margin required with current mark price - maintMargin: string; // maintenance margin required - unrealizedProfit: string; // unrealized profit - positionInitialMargin: string; // initial margin required for positions with current mark price - openOrderInitialMargin: string; // initial margin required for open orders with current mark price - leverage: string; // current initial leverage - entryPrice: string; // average entry price - maxNotional: string; // maximum available notional with current leverage - bidNotional: string; // bids notional - askNotional: string; // ask notional - positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side - positionAmt: string; // position amount - updateTime: number; // last update time -} -⋮---- -symbol: string; // symbol name -initialMargin: string; // initial margin required with current mark price -maintMargin: string; // maintenance margin required -unrealizedProfit: string; // unrealized profit -positionInitialMargin: string; // initial margin required for positions with current mark price -openOrderInitialMargin: string; // initial margin required for open orders with current mark price -leverage: string; // current initial leverage -entryPrice: string; // average entry price -maxNotional: string; // maximum available notional with current leverage -bidNotional: string; // bids notional -askNotional: string; // ask notional -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side -positionAmt: string; // position amount -updateTime: number; // last update time -⋮---- -export interface PortfolioCMAccountAsset { - asset: string; // asset name - crossWalletBalance: string; // total wallet balance - crossUnPnl: string; // unrealized profit or loss - maintMargin: string; // maintenance margin - initialMargin: string; // total initial margin required with the latest mark price - positionInitialMargin: string; // positions' margin required with the latest mark price - openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price - updateTime: number; // last update time -} -⋮---- -asset: string; // asset name -crossWalletBalance: string; // total wallet balance -crossUnPnl: string; // unrealized profit or loss -maintMargin: string; // maintenance margin -initialMargin: string; // total initial margin required with the latest mark price -positionInitialMargin: string; // positions' margin required with the latest mark price -openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price -updateTime: number; // last update time -⋮---- -export interface PortfolioCMAccountPosition { - symbol: string; // symbol name - positionAmt: string; // position amount - initialMargin: string; - maintMargin: string; - unrealizedProfit: string; - positionInitialMargin: string; - openOrderInitialMargin: string; - leverage: string; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode - entryPrice: string; - maxQty: string; // maximum quantity of base asset - updateTime: number; -} -⋮---- -symbol: string; // symbol name -positionAmt: string; // position amount -⋮---- -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode -⋮---- -maxQty: string; // maximum quantity of base asset -⋮---- -export interface PortfolioUMAccountConfig { - feeTier: number; // account commission tier - canTrade: boolean; // if can trade - canDeposit: boolean; // if can transfer in asset - canWithdraw: boolean; // if can transfer out asset - dualSidePosition: boolean; - updateTime: number; // reserved property - multiAssetsMargin: boolean; - tradeGroupId: number; -} -⋮---- -feeTier: number; // account commission tier -canTrade: boolean; // if can trade -canDeposit: boolean; // if can transfer in asset -canWithdraw: boolean; // if can transfer out asset -⋮---- -updateTime: number; // reserved property -⋮---- -export interface PortfolioUMSymbolConfig { - symbol: string; - marginType: 'CROSSED' | 'ISOLATED'; - isAutoAddMargin: string; // "true" or "false" as string - leverage: number; - maxNotionalValue: string; -} -⋮---- -isAutoAddMargin: string; // "true" or "false" as string -⋮---- -export interface PortfolioUMAccountAssetV2 { - asset: string; // asset name - crossWalletBalance: string; // wallet balance - crossUnPnl: string; // unrealized profit - maintMargin: string; // maintenance margin required - initialMargin: string; // total initial margin required with current mark price - positionInitialMargin: string; // initial margin required for positions with current mark price - openOrderInitialMargin: string; // initial margin required for open orders with current mark price - updateTime: number; // last update time -} -⋮---- -asset: string; // asset name -crossWalletBalance: string; // wallet balance -crossUnPnl: string; // unrealized profit -maintMargin: string; // maintenance margin required -initialMargin: string; // total initial margin required with current mark price -positionInitialMargin: string; // initial margin required for positions with current mark price -openOrderInitialMargin: string; // initial margin required for open orders with current mark price -updateTime: number; // last update time -⋮---- -export interface PortfolioUMAccountPositionV2 { - symbol: string; // symbol name - initialMargin: string; // initial margin required with current mark price - maintMargin: string; // maintenance margin required - unrealizedProfit: string; // unrealized profit - positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side - positionAmt: string; // position amount - updateTime: number; // last update time - notional: string; // position notional value -} -⋮---- -symbol: string; // symbol name -initialMargin: string; // initial margin required with current mark price -maintMargin: string; // maintenance margin required -unrealizedProfit: string; // unrealized profit -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side -positionAmt: string; // position amount -updateTime: number; // last update time -notional: string; // position notional value -⋮---- -export interface DownloadLinkResponse { - downloadId: string; - status: 'completed' | 'processing'; // Enum: completed, processing - url: string; // The link is mapped to download id - s3Link: string | null; - notified: boolean; // ignore - expirationTimestamp: number; // The link would expire after this timestamp - isExpired: boolean | null; -} -⋮---- -status: 'completed' | 'processing'; // Enum: completed, processing -url: string; // The link is mapped to download id -⋮---- -notified: boolean; // ignore -expirationTimestamp: number; // The link would expire after this timestamp -⋮---- -export interface PortfolioTradFiPerpsContractSignResponse { - code: number; - msg: string; -} - -================ -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/Public/ws-usdm-market.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'; -*/ -⋮---- -// 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('log rawMessage: ', data); -⋮---- -// Formatted data that has gone through the beautifier -⋮---- -// console.log('log formattedMessage: ', data); -⋮---- -/** - * 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); -// } -⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } -⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. -⋮---- -/** - * 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 - */ -⋮---- -// Uses the regular market feeds WS URL dedicated to USDM Futures: wss://fstream.binance.com/market/stream -⋮---- -/** - * 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 -⋮---- -// 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 -⋮---- -// 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 -⋮---- -// 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 -⋮---- -// Liquidation Order Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams -⋮---- -// Liquidation Order Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams -⋮---- -// 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 -⋮---- -// /** -// * -// * 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'); - -================ -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'; -*/ -⋮---- -// 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('log rawMessage: ', data); -⋮---- -// Formatted data that has gone through the beautifier -⋮---- -// console.log('log formattedMessage: ', data); -⋮---- -/** - * 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); -// } -⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } -⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. -⋮---- -/** - * 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 - */ -⋮---- -// Uses the high-frequency order book & core public feeds WS URL dedicated to USDM Futures: -// wss://fstream.binance.com/public/stream -⋮---- -/** - * Subscribe to each available type of USDM Derivatives market topic, the new way - */ -⋮---- -// Individual Symbol Book Ticker Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams -⋮---- -// 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 -⋮---- -// Diff. Book Depth Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams -⋮---- -// /** -// * -// * 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'); - -================ -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-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'; -⋮---- -/** - * 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; -} -⋮---- -/** - * General response types - */ -export interface WSAPIServerTime { - serverTime: number; -} -⋮---- -/** - * Market data response types - */ -export interface WSAPIOrderBook { - lastUpdateId: number; - // [price, quantity] - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} -⋮---- -// [price, quantity] -⋮---- -export interface WSAPITrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; -} -⋮---- -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? -} -⋮---- -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? -⋮---- -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 -]; -⋮---- -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 -⋮---- -export interface WSAPIAvgPrice { - mins: number; // Average price interval (in minutes) - price: numberInString; // Average price - closeTime: number; // Last trade time -} -⋮---- -mins: number; // Average price interval (in minutes) -price: numberInString; // Average price -closeTime: number; // Last trade time -⋮---- -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 -} -⋮---- -firstId: number; // First trade ID -lastId: number; // Last trade ID -count: number; // Number of trades -⋮---- -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 -} -⋮---- -firstId: number; // First trade ID -lastId: number; // Last trade ID -count: number; // Number of trades -⋮---- -export interface WSAPIPriceTicker { - symbol: string; - price: numberInString; -} -⋮---- -export interface WSAPIBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; -} -⋮---- -/** - * 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][]; -} -⋮---- -E: number; // Message output time -T: number; // Transaction time -// [price, quantity] -⋮---- -export interface WSAPIFuturesPriceTicker { - symbol: string; - price: numberInString; - time: number; // Transaction time -} -⋮---- -time: number; // Transaction time -⋮---- -export interface WSAPIFuturesBookTicker { - lastUpdateId: number; - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; // Transaction time -} -⋮---- -time: number; // Transaction time -⋮---- -/** - * 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; -} -⋮---- -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; - }; -} -⋮---- -export interface WSAPIRateLimit { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} -⋮---- -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; -} -⋮---- -/** Present only for expired orders. */ -⋮---- -export interface WSAPIBlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface WSAPIOrderList { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; -} -⋮---- -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; -} -⋮---- -export interface WSAPIPreventedMatch { - symbol: string; - preventedMatchId: number; - takerOrderId: number; - makerSymbol: string; - makerOrderId: number; - tradeGroupId: number; - selfTradePreventionMode: string; - price: numberInString; - makerPreventedQuantity: numberInString; - transactTime: number; -} -⋮---- -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; -} -⋮---- -/** - * Trading response types - */ -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; - }; -} -⋮---- -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; -} -⋮---- -export interface WSAPIOrderCancelReplaceResponse { - cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: WSAPIOrderCancel | ErrorResponse; - newOrderResponse: OrderResponse | ErrorResponse | null; -} -⋮---- -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[]; -} -⋮---- -/** - * 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[]; -} -⋮---- -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; - }[]; -} -⋮---- -/** Present only for expired orders. */ -⋮---- -/** - * 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; -} -⋮---- -/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ -⋮---- -export interface WSAPISOROrderTestResponse { - // Empty response object - [key: string]: never; -} -⋮---- -// Empty response object -⋮---- -export interface WSAPISOROrderTestResponseWithCommission { - standardCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - discount: numberInString; - }; -} -⋮---- -/** - * 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; -} -⋮---- -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; -} -⋮---- -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; -} -⋮---- -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; -} -⋮---- -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[]; -} -⋮---- -/** - * 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; -} -⋮---- -orderListId: number; // always -1 for singular orders -⋮---- -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; -} -⋮---- -/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ -⋮---- -export interface WSAPISpotOrderFill { - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; - tradeId: number; -} -⋮---- -export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { - fills: WSAPISpotOrderFill[]; -} -⋮---- -export type WSAPISpotOrderResponse = - | WSAPISpotOrderACK - | WSAPISpotOrderRESULT - | WSAPISpotOrderFULL; - -================ -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'; - 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; - }; -} -⋮---- -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; - }; -} -⋮---- -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; -} -⋮---- -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; -} -⋮---- -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; -} -⋮---- -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'; - 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; -} -⋮---- -/** - * @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. - */ -⋮---- -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; -} -⋮---- -export interface WsMessageBookTickerEventFormatted extends WsSharedBase { - eventType: 'bookTicker'; - updateId: number; - eventTime: number; - transactionTime: number; - symbol: string; - bidPrice: number; - bidQty: number; - askPrice: number; - askQty: number; -} -⋮---- -export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { - eventType: 'partialBookDepth' | 'string'; - lastUpdateId: number; - bids: OrderBookRowFormatted[]; - asks: OrderBookRowFormatted[]; -} -⋮---- -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 }[]; -} -⋮---- -transactionTime: number; // futures only -⋮---- -finalUpdateId: number; // futures only -⋮---- -/** - * USER DATA WS EVENTS - **/ -⋮---- -interface SpotBalanceFormatted { - asset: string; - availableBalance: number; - onOrderBalance: number; -} -⋮---- -export interface WsMessageSpotOutboundAccountPositionFormatted - extends WsSharedBase { - eventType: 'outboundAccountPosition'; - eventTime: number; - lastAccountUpdateTime: number; - balances: SpotBalanceFormatted[]; -} -⋮---- -export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { - eventType: 'balanceUpdate'; - eventTime: number; - asset: string; - balanceDelta: number; - clearTime: number; -} -⋮---- -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; -} -⋮---- -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; -} -⋮---- -export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { - eventType: 'serverShutdown'; - eventTime: number; -} -⋮---- -export interface OrderObjectFormatted { - symbol: string; - orderId: number; - clientOrderId: string; -} -⋮---- -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 interface WsAccountUpdatedBalance { - asset: string; - balanceChange: number; // this is except for pnl and commission - crossWalletBalance: number; - walletBalance: number; -} -⋮---- -balanceChange: number; // this is except for pnl and commission -⋮---- -export interface WsUpdatedPosition { - symbol: string; - marginAsset: string; - positionAmount: number; - entryPrice: number; - accumulatedRealisedPreFee: number; - unrealisedPnl: number; - marginType: 'cross' | 'isolated'; - isolatedWalletAmount: number; - positionSide: PositionSide; -} -⋮---- -export interface WsMessageFuturesUserDataListenKeyExpiredFormatted - extends WsSharedBase { - eventType: 'listenKeyExpired'; - eventTime: number; -} -⋮---- -export interface WsMessageFuturesMarginCalledPositionFormatted { - symbol: string; - positionSide: PositionSide; - positionAmount: number; - marginType: Uppercase; - isolatedWalletAmount: number; - markPrice: number; - unrealisedPnl: number; - maintenanceMarginRequired: number; -} -⋮---- -export interface WsMessageFuturesUserDataMarginCallFormatted - extends WsSharedBase { - eventType: 'MARGIN_CALL'; - eventTime: number; - crossWalletBalance: number; - positions: WsMessageFuturesMarginCalledPositionFormatted[]; -} -⋮---- -export interface WsMessageFuturesUserDataAccountUpdateFormatted - extends WsSharedBase { - eventType: 'ACCOUNT_UPDATE'; - eventTime: number; - transactionTime: number; - updateData: { - updateEventType: AccountUpdateEventType; - updatedBalances: WsAccountUpdatedBalance[]; - updatedPositions: WsUpdatedPosition[]; - }; -} -⋮---- -export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted - extends WsSharedBase { - eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; - eventTime: number; - transactionTime: number; - order: { - symbol: string; - orderId: number; - reason: string; - }; -} -⋮---- -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; -} -⋮---- -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 - }; -} -⋮---- -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 WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { - eventType: 'indexPriceUpdate'; - eventTime: number; - symbol: string; - indexPrice: number; -} -⋮---- -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; -} -⋮---- -/** Mark price moving average (USDⓈ-M). */ -⋮---- -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 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 WsMessageForceOrderFormatted extends WsSharedBase { - eventType: 'forceOrder'; - eventTime: number; - liquidationOrder: WsLiquidationOrderFormatted; -} -⋮---- -export interface WsMessageFuturesUserDataStrategyUpdateFormatted - extends WsSharedBase { - eventType: 'STRATEGY_UPDATE'; - transactionTime: number; - eventTime: number; - strategy: { - strategyId: number; - strategyType: string; - strategyStatus: string; - symbol: string; - updateTime: number; - opCode: number; - }; -} -⋮---- -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; - }; -} -⋮---- -export interface WsMessageFuturesUserDataContractInfoFormatted - 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; - }[]; -} -⋮---- -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; - }; -} -⋮---- -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; - 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 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[]; -} -⋮---- -export type AccountUpdateEventType = - | 'DEPOSIT' - | 'WITHDRAW' - | 'ORDER' - | 'FUNDING_FEE' - | 'WITHDRAW_REJECT' - | 'ADJUSTMENT' - | 'INSURANCE_CLEAR' - | 'ADMIN_DEPOSIT' - | 'ADMIN_WITHDRAW' - | 'MARGIN_TRANSFER' - | 'MARGIN_TYPE_CHANGE' - | 'ASSET_TRANSFER' - | 'OPTIONS_PREMIUM_FEE' - | 'OPTIONS_SETTLE_PROFIT' - | 'AUTO_EXCHANGE'; -⋮---- -export interface WsMessageFuturesUserDataListenKeyExpiredRaw - extends WsSharedBase { - e: 'listenKeyExpired'; - E: number; -} -⋮---- -export interface WsEventStreamTerminatedRaw extends WsSharedBase { - e: 'eventStreamTerminated'; - E: number; -} -⋮---- -export interface WsMessageFuturesMarginCalledPositionRaw { - s: string; - ps: PositionSide; - pa: numberInString; - mt: Uppercase; - iw: numberInString; - mp: numberInString; - up: numberInString; - mm: numberInString; -} -⋮---- -export interface WsMessageFuturesUserDataMarginCallRaw extends WsSharedBase { - e: 'MARGIN_CALL'; - E: number; - cw: numberInString; - p: WsMessageFuturesMarginCalledPositionRaw[]; -} -⋮---- -export interface WsMessageFuturesAccountUpdatePositionRaw { - s: string; - pa: numberInString; - ep: numberInString; - cr: numberInString; - up: numberInString; - mt: 'cross' | 'isolated'; - iw: numberInString; - ps: PositionSide; -} -⋮---- -export interface WsMessageFuturesAccountUpdateBalanceRaw { - a: string; - wb: numberInString; - cw: numberInString; - bc: numberInString; -} -⋮---- -export interface WsMessageFuturesUserDataAccountUpdateRaw extends WsSharedBase { - e: 'ACCOUNT_UPDATE'; - E: number; - T: number; - a: { - m: AccountUpdateEventType; - B: WsMessageFuturesAccountUpdateBalanceRaw[]; - P: WsMessageFuturesAccountUpdatePositionRaw[]; - }; -} -⋮---- -export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw - extends WsSharedBase { - e: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; - E: number; - T: number; - or: { - s: string; - i: number; - r: string; - }; -} -⋮---- -export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw - extends WsSharedBase { - e: 'ORDER_TRADE_UPDATE'; - E: number; - T: number; - o: { - s: string; - c: string; - S: OrderSide; - o: FuturesOrderType; - f: OrderTimeInForce; - q: numberInString; - p: numberInString; - ap: numberInString; - sp: numberInString; - x: OrderExecutionType; - X: OrderStatus; - i: number; - l: numberInString; - z: numberInString; - L: numberInString; - N: string; - n: numberInString; - T: numberInString; - t: number; - b: numberInString; - a: numberInString; - m: boolean; - R: boolean; - wt: WorkingType; - ot: FuturesOrderType; - ps: PositionSide; - cp: boolean; - AP: numberInString; - cr: numberInString; - rp: numberInString; - pP: boolean; // ignore - si: numberInString; // ignore - ss: numberInString; // ignore - V: string; - pm: string; - gtd: number; - er?: string; // Order expire reason (available effective 2025-10-23) - }; -} -⋮---- -pP: boolean; // ignore -si: numberInString; // ignore -ss: numberInString; // ignore -⋮---- -er?: string; // Order expire reason (available effective 2025-10-23) -⋮---- -export interface WsMessageFuturesUserDataAlgoUpdateRaw extends WsSharedBase { - e: 'ALGO_UPDATE'; - E: number; - T: number; - o: { - caid: string; - aid: number; - at: FuturesAlgoOrderType; - o: FuturesAlgoConditionalOrderTypes; - s: string; - S: OrderSide; - ps: PositionSide; - f: OrderTimeInForce; - q: numberInString; - X: FuturesAlgoOrderStatus; - ai: string; - tp: numberInString; - p: numberInString; - V: SelfTradePreventionMode; - wt: WorkingType; - pm: PriceMatchMode; - cp: boolean; - pP: boolean; - R: boolean; - tt: number; - gtd: number; - }; -} -⋮---- -export interface WsMessageFuturesUserDataTradeLiteEventRaw - extends WsSharedBase { - e: 'TRADE_LITE'; // Event Type - E: number; // Event Time - T: number; // Transaction Time - s: string; // Symbol - q: string; // Original Quantity - p: string; // Original Price - m: boolean; // Is this trade the maker side? - c: string; // Client Order Id - S: 'BUY' | 'SELL'; // Side - L: string; // Last Filled Price - l: string; // Order Last Filled Quantity - t: number; // Trade Id - i: number; // Order Id -} -⋮---- -e: 'TRADE_LITE'; // Event Type -E: number; // Event Time -T: number; // Transaction Time -s: string; // Symbol -q: string; // Original Quantity -p: string; // Original Price -m: boolean; // Is this trade the maker side? -c: string; // Client Order Id -S: 'BUY' | 'SELL'; // Side -L: string; // Last Filled Price -l: string; // Order Last Filled Quantity -t: number; // Trade Id -i: number; // Order Id -⋮---- -export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw - extends WsSharedBase { - e: 'ACCOUNT_CONFIG_UPDATE'; - E: number; - T: number; - ac?: { - s: string; - l: number; - }; - ai?: { - j: boolean; - }; -} -⋮---- -export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { - e: 'indexPriceUpdate'; - E: number; - i?: string; - s?: string; - p: numberInString; -} -⋮---- -export interface WsMessageMarkPriceUpdateEventRaw extends WsSharedBase { - e: 'markPriceUpdate'; - E: number; - s: string; - p: string; - /** Mark price moving average (USDⓈ-M mark price stream). */ - ap?: string; - P: string; - i: string; - r: string; - T: number; -} -⋮---- -/** Mark price moving average (USDⓈ-M mark price stream). */ -⋮---- -export interface WsMessageForceOrderRaw extends WsSharedBase { - e: 'forceOrder'; - E: number; - o: { - s: string; - S: string; - o: string; - f: string; - q: string; - p: string; - ap: string; - X: string; - l: string; - z: string; - T: number; - }; -} -⋮---- -export interface WsMessageFuturesUserDataStrategyUpdateRaw - extends WsSharedBase { - e: 'STRATEGY_UPDATE'; // Event Type - T: number; // Transaction Time - E: number; // Event Time - su: { - si: number; // Strategy ID - st: string; // Strategy Type - ss: string; // Strategy Status - s: string; // Symbol - ut: number; // Update Time - c: number; // opCode - }; -} -⋮---- -e: 'STRATEGY_UPDATE'; // Event Type -T: number; // Transaction Time -E: number; // Event Time -⋮---- -si: number; // Strategy ID -st: string; // Strategy Type -ss: string; // Strategy Status -s: string; // Symbol -ut: number; // Update Time -c: number; // opCode -⋮---- -export interface WsMessageFuturesUserDataGridUpdateRaw extends WsSharedBase { - e: 'GRID_UPDATE'; // Event Type - T: number; // Transaction Time - E: number; // Event Time - gu: { - si: number; // Strategy ID - st: string; // Strategy Type - ss: string; // Strategy Status - s: string; // Symbol - r: numberInString; // Realized PNL - up: numberInString; // Unmatched Average Price - uq: numberInString; // Unmatched Qty - uf: numberInString; // Unmatched Fee - mp: numberInString; // Matched PNL - ut: number; // Update Time - }; -} -⋮---- -e: 'GRID_UPDATE'; // Event Type -T: number; // Transaction Time -E: number; // Event Time -⋮---- -si: number; // Strategy ID -st: string; // Strategy Type -ss: string; // Strategy Status -s: string; // Symbol -r: numberInString; // Realized PNL -up: numberInString; // Unmatched Average Price -uq: numberInString; // Unmatched Qty -uf: numberInString; // Unmatched Fee -mp: numberInString; // Matched PNL -ut: number; // Update Time -⋮---- -export interface WsMessageFuturesUserDataContractInfoRaw extends WsSharedBase { - e: 'contractInfo'; // Event Type - E: number; // Event Time - s: string; // Symbol - ps: string; // Pair - ct: string; // Contract type - dt: number; // Delivery date time - ot: number; // onboard date time - cs: string; // Contract status - bks: { - bs: number; // Notional bracket - bnf: number; // Floor notional of this bracket - bnc: number; // Cap notional of this bracket - mmr: number; // Maintenance ratio for this bracket - cf: number; // Auxiliary number for quick calculation - mi: number; // Min leverage for this bracket - ma: number; // Max leverage for this bracket - }[]; -} -⋮---- -e: 'contractInfo'; // Event Type -E: number; // Event Time -s: string; // Symbol -ps: string; // Pair -ct: string; // Contract type -dt: number; // Delivery date time -ot: number; // onboard date time -cs: string; // Contract status -⋮---- -bs: number; // Notional bracket -bnf: number; // Floor notional of this bracket -bnc: number; // Cap notional of this bracket -mmr: number; // Maintenance ratio for this bracket -cf: number; // Auxiliary number for quick calculation -mi: number; // Min leverage for this bracket -ma: number; // Max leverage for this bracket -⋮---- -export type WsRawSpotUserDataEventRaw = - | WsMessageSpotUserDataExecutionReportEventRaw - | WsMessageSpotOutboundAccountPositionRaw - | WsMessageSpotBalanceUpdateRaw - | WsMessageSpotUserDataListStatusEventRaw; -⋮---- -export type WsMessageFuturesUserDataEventRaw = - | WsMessageFuturesUserDataAccountUpdateRaw - | WsMessageFuturesUserDataListenKeyExpiredRaw - | WsMessageFuturesUserDataMarginCallRaw - | WsMessageFuturesUserDataOrderTradeUpdateEventRaw - | WsMessageFuturesUserDataAlgoUpdateRaw - | WsMessageFuturesUserDataAccountConfigUpdateEventRaw - | WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw - | WsMessageFuturesUserDataTradeLiteEventRaw - | WsMessageFuturesUserDataStrategyUpdateRaw - | WsMessageFuturesUserDataGridUpdateRaw - | WsMessageFuturesUserDataContractInfoRaw; -⋮---- -export type WsUserDataEventsRaw = - | WsRawSpotUserDataEventRaw - | WsMessageFuturesUserDataEventRaw - | WsMessagePortfolioMarginProAccountUpdateRaw; -⋮---- -export type WsRawMessage = - | WsEventStreamTerminatedRaw - | WsMessageWsapiServerShutdownRaw - | WsUserDataEventsRaw - | WsMessageKlineRaw - | WsMessageAggTradeRaw - | WsMessageTradeRaw - | WsMessage24hrMiniTickerRaw - | WsMessage24hrMiniTickerRaw[] - | WsMessage24hrTickerRaw - | WsMessage24hrTickerRaw[] - | WsMessageRollingWindowTickerRaw[] - | WsMessageBookTickerEventRaw - | WsMessagePartialBookDepthEventRaw - | WsMessageDiffBookDepthEventRaw - | WsMessageForceOrderRaw - | WsMessageIndexPriceUpdateEventRaw; - -================ -File: src/types/shared.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; -⋮---- -export type ExchangeSymbol = string; -⋮---- -export type BooleanString = 'true' | 'false'; -⋮---- -export type BinanceBaseUrlKey = - | 'spot' - | 'spot1' - | 'spot2' - | 'spot3' - | 'spot4' - | 'spottest' - | 'usdmtest' - | 'usdm' - | 'coinm' - | 'coinmtest' - | 'voptions' - | 'voptionstest' - | 'papi' - | 'www'; -⋮---- -/** - * 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'; -⋮---- -export type StringBoolean = 'TRUE' | 'FALSE'; -⋮---- -export type SideEffects = - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'NO_SIDE_EFFECT' - | 'AUTO_BORROW_REPAY' - | 'NO_SIDE_EFFECT'; -⋮---- -/** - * 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'; -⋮---- -export type OrderIdProperty = - | 'newClientOrderId' - | 'newClientStrategyId' - | 'listClientOrderId' - | 'limitClientOrderId' - | 'stopClientOrderId' - | 'clientAlgoId' - | 'aboveClientOrderId' - | 'belowClientOrderId' - | 'workingClientOrderId' - | 'pendingAboveClientOrderId' - | 'pendingBelowClientOrderId' - | 'pendingClientOrderId'; -⋮---- -export type OrderSide = 'BUY' | 'SELL'; -⋮---- -export type OrderStatus = - | 'NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED'; -⋮---- -export type OrderExecutionType = - | 'NEW' - | 'CANCELED' - | 'REJECTED' - | 'TRADE' - | 'EXPIRED'; -⋮---- -// listStatusType -export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; -⋮---- -// listOrderStatus -export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; -⋮---- -export type OrderType = - | 'LIMIT' - | 'LIMIT_MAKER' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; -⋮---- -export type OrderListOrderType = - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; -⋮---- -export type SelfTradePreventionMode = - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; -⋮---- -export interface BasicAssetParam { - asset: string; -} -⋮---- -export interface BasicSymbolParam { - symbol: string; - isIsolated?: StringBoolean; -} -⋮---- -export interface SymbolArrayParam { - symbols: string[]; -} -⋮---- -export interface BasicAssetPaginatedParams { - asset?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -export interface BasicSymbolPaginatedParams { - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface SymbolPrice { - symbol: string; - price: numberInString; - time?: number; -} -⋮---- -// used by spot and usdm -export interface OrderBookParams { - symbol: string; - limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; - symbolStatus?: string; -} -⋮---- -export type KlineInterval = - | '1s' - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '3d' - | '1w' - | '1M'; -⋮---- -export interface GetOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} -⋮---- -export interface GetOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface HistoricalTradesParams { - symbol: string; - limit?: number; - fromId?: number; -} -⋮---- -export interface KlinesParams { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} -⋮---- -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? -]; -⋮---- -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? -⋮---- -/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ -export type FuturesKline = Kline; -export interface RecentTradesParams { - symbol: string; - limit?: number; -} -⋮---- -export interface CancelOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} -⋮---- -export interface AmendKeepPriorityParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - newQty: numberInString; -} -⋮---- -export interface CancelOCOParams { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} -⋮---- -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; -} -⋮---- -/** For isolated margin trading only */ -⋮---- -/** Define a side effect, only for margin trading */ -⋮---- -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; -} -⋮---- -export interface SymbolFromPaginatedRequestFromId { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetAllOrdersParams { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface RateLimiter { - rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; - interval: 'SECOND' | 'MINUTE' | 'DAY'; - intervalNum: number; - limit: number; -} -⋮---- -export interface SymbolPriceFilter { - filterType: 'PRICE_FILTER'; - minPrice: numberInString; - maxPrice: numberInString; - tickSize: numberInString; -} -⋮---- -export interface SymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - avgPriceMins: number; -} -⋮---- -export interface SymbolPercentPriceBySideFilter { - filterType: 'PERCENT_PRICE_BY_SIDE'; - bidMultiplierUp: numberInString; - bidMultiplierDown: numberInString; - askMultiplierUp: numberInString; - askMultiplierDown: numberInString; - avgPriceMins: number; -} -⋮---- -export interface SymbolLegacyMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - minNotional: numberInString; - applyToMarket: boolean; - avgPriceMins: number; -} -⋮---- -export interface SymbolLotSizeFilter { - filterType: 'LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} -⋮---- -export interface SymbolMinNotionalFilter { - filterType: 'NOTIONAL'; - minNotional: numberInString; - applyMinToMarket: boolean; - maxNotional: numberInString; - applyMaxToMarket: boolean; - avgPriceMins: number; -} -⋮---- -export interface SymbolIcebergPartsFilter { - filterType: 'ICEBERG_PARTS'; - limit: number; -} -⋮---- -export interface SymbolMarketLotSizeFilter { - filterType: 'MARKET_LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} -⋮---- -export interface SymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - maxNumOrders: number; -} -⋮---- -export interface SymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} -⋮---- -export interface SymbolMaxIcebergOrdersFilter { - filterType: 'MAX_NUM_ICEBERG_ORDERS'; - maxNumIcebergOrders: number; -} -⋮---- -export interface SymbolMaxPositionFilter { - filterType: 'MAX_POSITION'; - maxPosition: numberInString; -} -⋮---- -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; -⋮---- -export type OrderBookPrice = numberInString; -export type OrderBookAmount = numberInString; -⋮---- -export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; -⋮---- -export type OrderBookPriceFormatted = number; -export type OrderBookAmountFormatted = number; -export type OrderBookRowFormatted = [ - OrderBookPriceFormatted, - OrderBookAmountFormatted, -]; -⋮---- -export interface GenericCodeMsgError { - code: number; - msg: string; -} -⋮---- -export interface RowsWithTotal { - rows: T[]; - total: number; -} -⋮---- -export interface CoinStartEndLimit { - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} - -================ -File: src/coinm-client.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; -⋮---- -import { - 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, - logInvalidOrderId, - RestClientOptions, -} from './util/requestUtils'; -⋮---- -export class CoinMClient 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 - * - **/ -⋮---- -testConnectivity(): Promise -⋮---- -getExchangeInfo(): Promise -⋮---- -getOrderBook(params: OrderBookParams): Promise -⋮---- -getRecentTrades(params: RecentTradesParams): Promise -⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, -): Promise -⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise -⋮---- -/** - * Index Price and Mark Price - */ -getMarkPrice(params?: -⋮---- -getFundingRateHistory( - params?: Partial, -): Promise -⋮---- -getFundingRate(params?: -⋮---- -getKlines(params: KlinesParams): Promise -⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, -): Promise -⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise -⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise -⋮---- -getPremiumIndexKlines(params: KlinesParams): Promise -⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; - pair?: string; -}): Promise -⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; - pair?: string; -}): Promise -⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; - pair?: string; -}): Promise -⋮---- -getOpenInterest(params: -⋮---- -getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise -⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise -⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams & { pair?: string }, -): Promise -⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise -⋮---- -getTakerBuySellVolume( - params: FuturesCoinMTakerBuySellVolumeParams, -): Promise -⋮---- -getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise -⋮---- -/** - * 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 - * - **/ -⋮---- -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. - * - * Known issue: `quantity` and `price` should be sent as strings - */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> -⋮---- -/** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue - */ -modifyOrder( - params: ModifyFuturesOrderParams, -): 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. - */ -modifyMultipleOrders( - orders: ModifyFuturesOrderParams[], -): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> -⋮---- -getOrderModifyHistory( - params: GetOrderModifyHistoryParams, -): 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 -⋮---- -/** - * - * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) - * Conditional orders migrate to Algo Service on COIN-M - * - **/ -⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, -): Promise -⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, -): Promise -⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, -): Promise -⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise -⋮---- -getAccountTrades( - params: CoinMAccountTradeParams & { orderId?: number }, -): Promise -⋮---- -getPositions(params?: { - marginAsset?: string; - pair?: string; -}): Promise -⋮---- -setPositionMode(params: PositionModeParams): Promise -⋮---- -setMarginType(params: SetMarginTypeParams): Promise -⋮---- -setLeverage(params: SetLeverageParams): Promise -⋮---- -getADLQuantileEstimation(params?: -⋮---- -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< -⋮---- -getFuturesTradeHistoryDownloadLink(params: { - downloadId: string; -}): Promise -⋮---- -/** - * - * Portfolio Margin Endpoints - * - **/ -⋮---- -getClassicPortfolioMarginAccount(params: { - asset: string; -}): Promise -⋮---- -/** - * @deprecated at 6th August, 2024 - **/ -getClassicPortfolioMarginNotionalLimits( - params?: GetClassicPortfolioMarginNotionalLimitParams, -): 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< -⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, -): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise -⋮---- -/** - * - * User Data Stream Endpoints - * - **/ -⋮---- -getFuturesUserDataListenKey(): Promise< -⋮---- -keepAliveFuturesUserDataListenKey(): Promise -⋮---- -closeFuturesUserDataListenKey(): Promise -⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, -): void - -================ -File: src/portfolio-client.ts -================ -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'; -import { - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - NewOCOParams, - OrderIdProperty, -} from './types/shared'; -import BaseRestClient from './util/BaseRestClient'; -import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - 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 -⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) -⋮---- -getClientId(): BinanceBaseUrlKey -⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise -⋮---- -/** - * - * Misc Endpoints - * - **/ -⋮---- -testConnectivity(): Promise -⋮---- -signTradFiPerpsContract(): Promise -⋮---- -/** - * - * DERIVATIVES -TRADE endpoints - * - **/ -⋮---- -submitNewUMOrder( - params: NewPortfolioUMOrderReq, -): Promise -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). - */ -submitNewUMConditionalOrder( - params: NewPortfolioUMConditionalOrderReq, -): Promise -⋮---- -submitNewUMAlgoOrder( - params: NewPortfolioUMAlgoOrderReq, -): Promise -⋮---- -submitNewCMOrder( - params: NewPortfolioCMOrderReq, -): Promise -⋮---- -submitNewCMConditionalOrder( - params: NewPortfolioCMConditionalOrderReq, -): Promise -⋮---- -submitNewMarginOrder( - params: NewPortfolioMarginOrderReq, -): Promise -⋮---- -submitMarginLoan(params: -⋮---- -submitMarginRepay(params: -⋮---- -submitNewMarginOCO( - params: NewPortfolioMarginOCOReq, -): Promise -⋮---- -cancelUMOrder( - params: CancelPortfolioUMOrderReq, -): Promise -⋮---- -cancelAllUMOrders(params: -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). - */ -cancelUMConditionalOrder( - params: CancelPortfolioUMConditionalOrderReq, -): Promise -⋮---- -cancelUMAlgoOrder( - params: CancelPortfolioUMAlgoOrderReq, -): Promise -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). - */ -cancelAllUMConditionalOrders(params: -⋮---- -cancelAllUMAlgoOpenOrders(params: { - symbol: string; -}): Promise -⋮---- -cancelCMOrder( - params: CancelPortfolioCMOrderReq, -): Promise -⋮---- -cancelAllCMOrders(params: -⋮---- -cancelCMConditionalOrder( - params: CancelPortfolioCMConditionalOrderReq, -): Promise -⋮---- -cancelAllCMConditionalOrders(params: -⋮---- -cancelMarginOrder( - params: CancelPortfolioMarginOrderReq, -): Promise -⋮---- -cancelMarginOCO( - params: CancelPortfolioMarginOCOReq, -): Promise -⋮---- -cancelAllMarginOrders(params: { - symbol: string; -}): Promise -⋮---- -modifyUMOrder( - params: ModifyPortfolioUMOrderReq, -): Promise -⋮---- -modifyCMOrder( - params: ModifyPortfolioCMOrderReq, -): Promise -⋮---- -getUMOrder(params: QueryPortfolioUMOrderReq): Promise -⋮---- -getAllUMOrders( - params: QueryPortfolioAllUMOrdersReq, -): Promise -⋮---- -getUMOpenOrder( - params: QueryPortfolioUMOpenOrderReq, -): Promise -⋮---- -getAllUMOpenOrders(params: -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). - */ -getAllUMConditionalOrders( - params: QueryPortfolioAllUMConditionalOrdersReq, -): Promise -⋮---- -getAllUMAlgoOrders( - params: QueryPortfolioAllUMAlgoOrdersReq, -): Promise -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). - */ -getUMOpenConditionalOrders(params: { - symbol?: string; -}): Promise -⋮---- -getUMAlgoOpenOrders(params?: { - symbol?: string; -}): Promise -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). - */ -getUMOpenConditionalOrder( - params: QueryPortfolioUMOpenConditionalOrderReq, -): Promise -⋮---- -getUMAlgoOrder( - params: QueryPortfolioUMAlgoOrderReq, -): Promise -⋮---- -/** - * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. - */ -getUMConditionalOrderHistory( - params: QueryPortfolioUMConditionalOrderHistoryReq, -): Promise -⋮---- -getCMOrder(params: QueryPortfolioCMOrderReq): Promise -⋮---- -getAllCMOrders( - params: QueryPortfolioAllCMOrdersReq, -): Promise -⋮---- -getCMOpenOrder( - params: QueryPortfolioCMOpenOrderReq, -): Promise -⋮---- -getAllCMOpenOrders(params: { - symbol?: string; - pair?: string; -}): Promise -⋮---- -getCMOpenConditionalOrders(params: { - symbol?: string; -}): Promise -⋮---- -getCMOpenConditionalOrder(params: { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -}): Promise -⋮---- -getAllCMConditionalOrders( - params: QueryPortfolioAllCMConditionalOrdersReq, -): Promise -⋮---- -getCMConditionalOrderHistory( - params: QueryPortfolioCMConditionalOrderHistoryReq, -): Promise -⋮---- -getUMForceOrders( - params: QueryPortfolioUMForceOrdersReq, -): Promise -⋮---- -getCMForceOrders( - params: QueryPortfolioCMForceOrdersReq, -): Promise -⋮---- -getUMOrderModificationHistory( - params: QueryPortfolioUMOrderAmendmentReq, -): Promise -⋮---- -getCMOrderModificationHistory( - params: QueryPortfolioCMOrderAmendmentReq, -): Promise -⋮---- -getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< -⋮---- -getUMTrades(params: QueryPortfolioUMTradesReq): Promise -⋮---- -getCMTrades(params: QueryPortfolioCMTradesReq): Promise -⋮---- -getUMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > { - return this.getPrivate('papi/v1/um/adlQuantile', params); -⋮---- -getCMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > { - return this.getPrivate('papi/v1/cm/adlQuantile', params); -⋮---- -toggleUMFeeBurn(params: { - feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off -}): Promise< -⋮---- -feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off -⋮---- -getUMFeeBurnStatus(): Promise< -⋮---- -getMarginOrder( - params: QueryPortfolioMarginOrderReq, -): Promise -⋮---- -getMarginOpenOrders(params: { - symbol: string; -}): Promise -⋮---- -getAllMarginOrders( - params: QueryPortfolioMarginAllOrdersReq, -): Promise -⋮---- -getMarginOCO( - params: QueryPortfolioMarginOCOReq, -): Promise -⋮---- -getAllMarginOCO( - params: QueryPortfolioMarginAllOCOReq, -): Promise -⋮---- -getMarginOpenOCO(): Promise -⋮---- -getMarginTrades( - params: QueryPortfolioMarginTradesReq, -): Promise -⋮---- -repayMarginDebt( - params: PortfolioMarginRepayDebtReq, -): 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?: { - 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< -⋮---- -getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< -⋮---- -getAutoRepayFuturesStatus(): Promise< -⋮---- -autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off -⋮---- -updateAutoRepayFuturesStatus(params: { - autoRepay: 'true' | 'false'; -}): Promise< -⋮---- -getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< -⋮---- -repayFuturesNegativeBalance(): Promise< -⋮---- -getPortfolioNegativeBalanceInterestHistory( - params?: GetPortfolioInterestHistoryReq, -): Promise -⋮---- -autoCollectFunds(): Promise< -⋮---- -transferAssetFuturesMargin(params: -⋮---- -transferBNB(params: { - amount: string; - transferSide: 'TO_UM' | 'FROM_UM'; -}): Promise< -⋮---- -tranId: number; // transaction id -⋮---- -getUMIncomeHistory( - params?: QueryPortfolioUMIncomeReq, -): Promise -⋮---- -getCMIncomeHistory( - params?: QueryPortfolioCMIncomeReq, -): Promise -⋮---- -getUMAccount(): Promise< -⋮---- -positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market -⋮---- -getCMAccount(): Promise< -⋮---- -getUMAccountConfig(): Promise -⋮---- -getUMSymbolConfig(params?: { - symbol?: string; -}): Promise -⋮---- -getUMAccountV2(): Promise< -⋮---- -positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market -⋮---- -getUMTradeHistoryDownloadId(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 -⋮---- -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: - | NewPortfolioUMOrderReq - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, -): void -⋮---- -/** - * - * User Data Stream Endpoints - * - **/ -getPMUserDataListenKey(): Promise< -⋮---- -keepAlivePMUserDataListenKey(): Promise -⋮---- -closePMUserDataListenKey(): Promise - -================ -File: src/usdm-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'; -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 { - 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 -⋮---- -/** - * - * ACCOUNT endpoints - Rest API - * - **/ -⋮---- -getBalanceV3(): Promise -⋮---- -/** - * @deprecated - * Use getBalanceV3() instead - **/ -getBalance(): Promise -⋮---- -getAccountInformationV3(): Promise -⋮---- -/** - * @deprecated - * Use getAccountInformationV3() instead - **/ -getAccountInformation(): Promise -⋮---- -getAccountCommissionRate(params: { - symbol: string; -}): Promise -⋮---- -getFuturesAccountConfig(): Promise -⋮---- -getFuturesSymbolConfig(params: -⋮---- -getUserForceOrders(): Promise -⋮---- -/** - * 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 -⋮---- -getMultiAssetsMode(): Promise -⋮---- -getCurrentPositionMode(): Promise -⋮---- -getIncomeHistory(params?: GetIncomeHistoryParams): Promise -⋮---- -getApiQuantitativeRulesIndicators(params?: { - symbol?: string; -}): Promise -⋮---- -getFuturesTransactionHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise -⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; -}): Promise -⋮---- -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 -⋮---- -/** - * - * Algo Order Endpoints (Effective 2025-12-02) - * Conditional orders migrate to Algo Service - * - **/ -⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, -): Promise -⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, -): Promise -⋮---- -cancelAllAlgoOpenOrders(params: { - symbol: string; -}): Promise -⋮---- -getAlgoOrder( - params: FuturesQueryAlgoOrderParams, -): Promise -⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, -): Promise -⋮---- -getAllAlgoOrders( - params: FuturesQueryAllAlgoOrdersParams, -): Promise -⋮---- -/** - * - * 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< -⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, -): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise -⋮---- -/** - * - * User Data Stream Endpoints - * - **/ -⋮---- -// USD-M Futures -⋮---- -getFuturesUserDataListenKey(): Promise< -⋮---- -keepAliveFuturesUserDataListenKey(): Promise -⋮---- -closeFuturesUserDataListenKey(): Promise -⋮---- -/** - * 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'; -⋮---- -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 -⋮---- -/** - * 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. - */ -⋮---- -/** - * 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'); -⋮---- -/** - * 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'; -⋮---- -/** - * 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 -⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ -⋮---- -// 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() -⋮---- -// 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) -⋮---- -// 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); -⋮---- -// Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will -// automatically call this method again if reconnected, -⋮---- -WS_KEY_MAP.mainWSAPI, // The `mainWSAPI` wsKey will connect to the "spot" Websocket API on Binance. -⋮---- -// Start executing the example workflow - -================ -File: src/types/websockets/ws-general.ts -================ -import { AxiosRequestConfig } from 'axios'; -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; -⋮---- -import { RestClientOptions } from '../../util/requestUtils'; -import { WsKey } from '../../util/websockets/websocket-util'; -⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; -} -⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike -⋮---- -export type WsMarket = - | 'spot' - | 'spotTestnet' - | 'crossMargin' - | 'isolatedMargin' - | 'riskDataMargin' - | 'usdm' - | 'usdmTestnet' - | 'coinm' - | 'coinmTestnet' - | 'options' - | 'optionsTestnet' - | 'portfoliom' - | 'alpha'; -⋮---- -export interface WsSharedBase { - wsMarket: WsMarket; - wsKey: WsKey; - streamName: string; -} -⋮---- -export interface WsResponse { - type: 'message'; - data: { - result: boolean | string[] | null; - id: number; - isWSAPIResponse: boolean; - wsKey: WsKey; - }; -} -⋮---- -// Same as inverse futures -export type WsPublicInverseTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'klineV2'; -⋮---- -export type WsPublicUSDTPerpTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'kline'; -⋮---- -export type WsPublicSpotV1Topic = - | 'trade' - | 'realtimes' - | 'kline' - | 'mergedDepth' - | 'diffDepth'; -⋮---- -export type WsPublicSpotV2Topic = 'depth' | 'kline' | 'trade' | 'realtimes'; -⋮---- -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data -export type WsPublicUSDMTopic = 'bookTicker' | 'depth'; -⋮---- -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#market-regular-market-data -export type WsMarketUSDMTopic = - | 'aggTrade' - | 'markPrice' - | 'kline' - | 'continuousKline' - | 'miniTicker' - | 'ticker' - | 'forceOrder' - | 'compositeIndex' - | 'contractInfo' - | 'assetIndex'; -⋮---- -export type WsPublicTopics = - | WsPublicInverseTopic - | WsPublicUSDTPerpTopic - | WsPublicSpotV1Topic - | WsPublicSpotV2Topic - | WsMarketUSDMTopic - | WsPublicUSDMTopic - | string; -⋮---- -// Same as inverse futures -export type WsPrivateInverseTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order'; -⋮---- -export type WsPrivateUSDTPerpTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order' - | 'wallet'; -⋮---- -export type WsPrivateSpotTopic = - | 'outboundAccountInfo' - | 'executionReport' - | 'ticketInfo'; -⋮---- -export type WsPrivateTopic = - | WsPrivateInverseTopic - | WsPrivateUSDTPerpTopic - | WsPrivateSpotTopic - | string; -⋮---- -export type WsTopic = WsPublicTopics | WsPrivateTopic; -⋮---- -export interface WSClientConfigurableOptions { - /** Your API key */ - api_key?: string; - - /** Your API secret */ - api_secret?: string; - - beautify?: boolean; - - /** - * If true, log a warning if the beautifier is missing anything for an event - */ - beautifyWarnIfMissing?: boolean; - - /** - * Set to `true` to connect to Binance's testnet environment. - * - * Notes: - * - Not all WebSocket categories support testnet. - * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets - */ - testnet?: boolean; - - /** - * Set to `true` to use Binance's demo trading WebSocket endpoints. - * Demo trading uses real market data but simulated trading. - * More info: https://demo.binance.com/ - * - * Notes: - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. - */ - demoTrading?: boolean; - - /** - * Default: false. If true, use market maker endpoints when available. - * Eligible for high-frequency trading users who have enrolled and qualified - * in at least one of the Futures Liquidity Provider Programs. - * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 - */ - useMMSubdomain?: boolean; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; - - // Disable ping/pong ws heartbeat mechanism (not recommended) - disableHeartbeat?: boolean; - - /** How often to check if the connection is alive */ - pingInterval?: number; - - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; - - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; - - restOptions?: RestClientOptions; - - requestOptions?: AxiosRequestConfig; - - wsOptions?: { - protocols?: string[]; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - agent?: any; - } & Partial; - - wsUrl?: string; - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ - customSignMessageFn?: (message: string, secret: string) => Promise; - - /** - * Optional custom JSON parser used for incoming WS messages. - * Defaults to JSON.parse. - */ - customParseJSONFn?: (raw: string) => object; -} -⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- -/** - * If true, log a warning if the beautifier is missing anything for an event - */ -⋮---- -/** - * Set to `true` to connect to Binance's testnet environment. - * - * Notes: - * - Not all WebSocket categories support testnet. - * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets - */ -⋮---- -/** - * Set to `true` to use Binance's demo trading WebSocket endpoints. - * Demo trading uses real market data but simulated trading. - * More info: https://demo.binance.com/ - * - * Notes: - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. - */ -⋮---- -/** - * Default: false. If true, use market maker endpoints when available. - * Eligible for high-frequency trading users who have enrolled and qualified - * in at least one of the Futures Liquidity Provider Programs. - * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 - */ -⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ -⋮---- -// Disable ping/pong ws heartbeat mechanism (not recommended) -⋮---- -/** How often to check if the connection is alive */ -⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ -⋮---- -/** Delay in milliseconds before respawning the connection */ -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -/** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ -⋮---- -/** - * Optional custom JSON parser used for incoming WS messages. - * Defaults to JSON.parse. - */ -⋮---- -/** - * WS configuration that's always defined, regardless of user configuration - * (usually comes from defaults if there's no user-provided values) - */ -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - pongTimeout: number; - pingInterval: number; - reconnectTimeout: number; - recvWindow: number; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequestsIndividually: boolean; -} - -================ -File: src/types/futures.ts -================ -import { - BooleanString, - ExchangeFilter, - KlineInterval, - numberInString, - OrderBookRow, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - RateLimiter, - SelfTradePreventionMode, - SymbolIcebergPartsFilter, - SymbolLotSizeFilter, - SymbolMarketLotSizeFilter, - SymbolMaxIcebergOrdersFilter, - SymbolMaxPositionFilter, - SymbolPriceFilter, -} from './shared'; -⋮---- -export type FuturesContractType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; -⋮---- -export interface ContinuousContractKlinesParams { - pair: string; - contractType: FuturesContractType; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface IndexPriceKlinesParams { - pair: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface SymbolKlinePaginatedParams { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface FuturesDataPaginatedParams { - symbol: string; - contractType?: string; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMTakerBuySellVolumeParams { - pair: string; - contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMBasisParams { - pair: string; - contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export enum EnumDualSideMode { - HedgeMode = 'true', - OneWayMode = 'false', -} -⋮---- -export type DualSideMode = `${EnumDualSideMode}`; -⋮---- -export enum EnumMultiAssetMode { - MultiAssetsMode = 'true', - SingleAssetsMode = 'false', -} -⋮---- -export type MultiAssetsMode = `${EnumMultiAssetMode}`; -⋮---- -export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; -⋮---- -export type MarginType = 'ISOLATED' | 'CROSSED'; -⋮---- -export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; -⋮---- -export type FuturesOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; -⋮---- -export type PriceMatchMode = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; -⋮---- -// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. -export interface NewFuturesOrderParams { - 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 -} -⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface ModifyFuturesOrderParams { - orderId?: number; - origClientOrderId?: string; - symbol: string; - side: OrderSide; - quantity?: numberType; - price?: numberType; - priceMatch?: PriceMatchMode; -} -⋮---- -export enum EnumPositionMarginChangeType { - AddPositionMargin = 1, - ReducePositionMargin = 0, -} -⋮---- -export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; -⋮---- -export type IncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'COMMISSION' - | 'INSURANCE_CLEAR'; -⋮---- -export interface CancelMultipleOrdersParams { - symbol: string; - orderIdList?: number[]; - origClientOrderIdList?: string[]; -} -⋮---- -export interface CancelOrdersTimeoutParams { - symbol: string; - countdownTime?: 0 | number; -} -⋮---- -export interface SetLeverageParams { - symbol: string; - leverage: number; -} -⋮---- -export interface SetLeverageResult { - leverage: number; - maxNotionalValue: numberInString; - symbol: string; -} -⋮---- -export interface SetMarginTypeParams { - symbol: string; - marginType: MarginType; -} -⋮---- -export interface SetIsolatedMarginParams { - symbol: string; - positionSide?: PositionSide; - amount: number; - type: PositionMarginChangeType; -} -⋮---- -export interface SetIsolatedMarginResult { - amount: numberInString; - code: 200 | number; - msg: string; - type: 1 | 2; -} -⋮---- -export interface GetPositionMarginChangeHistoryParams { - symbol: string; - type?: PositionMarginChangeType; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetIncomeHistoryParams { - symbol?: string; - incomeType?: IncomeType; - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} -⋮---- -export interface IncomeHistory { - symbol?: string; - incomeType: IncomeType; - income: string; - asset: string; - time: number; - info: string; - tranId: number; - tradeId: string; -} -⋮---- -export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; -⋮---- -export interface GetForceOrdersParams { - symbol?: string; - autoCloseType?: ForceOrderCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export type ContactType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; -⋮---- -export type ContractStatus = - | 'PENDING_TRADING' - | 'TRADING' - | 'PRE_DELIVERING' - | 'DELIVERING' - | 'DELIVERED' - | 'CANCELLED' - | 'PRE_SETTLE' - | 'SETTLING' - | 'CLOSE'; -⋮---- -export interface FuturesSymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - multiplierDecimal: numberInString; -} -⋮---- -export interface FuturesSymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - limit: number; -} -⋮---- -export interface FuturesSymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - limit: number; -} -⋮---- -export interface FuturesSymbolMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - notional: numberInString; -} -⋮---- -export type FuturesSymbolFilter = - | SymbolPriceFilter - | FuturesSymbolPercentPriceFilter - | SymbolLotSizeFilter - | FuturesSymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | FuturesSymbolMaxOrdersFilter - | FuturesSymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter; -⋮---- -export interface FuturesSymbolExchangeInfo { - symbol: string; - pair: string; - contractType: ContactType; - deliveryDate: number; - onboardDate: number; - status: ContractStatus; - maintMarginPercent: numberInString; - requiredMarginPercent: numberInString; - baseAsset: string; - quoteAsset: string; - marginAsset: string; - pricePrecision: number; - quantityPrecision: number; - baseAssetPrecision: number; - quotePrecision: number; - underlyingType: 'COIN' | 'INDEX'; // No other known values - underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc - settlePlan: number; - triggerProtect: numberInString; - filters: FuturesSymbolFilter[]; - OrderType: OrderType[]; - timeInForce: OrderTimeInForce[]; - liquidationFee: numberInString; - marketTakeBound: numberInString; - contractSize?: number; -} -⋮---- -underlyingType: 'COIN' | 'INDEX'; // No other known values -underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc -⋮---- -export interface FuturesExchangeInfo { - exchangeFilters: ExchangeFilter[]; - rateLimits: RateLimiter[]; - serverTime: number; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any[]; - symbols: FuturesSymbolExchangeInfo[]; - timezone: string; -} -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface FuturesOrderBook { - lastUpdateId: number; - E: number; - T: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; -} -⋮---- -export interface RawFuturesTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface AggregateFuturesTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; -} -⋮---- -export interface MarkPrice { - symbol: string; - markPrice: numberInString; - indexPrice: numberInString; - estimatedSettlePrice: numberInString; - lastFundingRate: numberInString; - interestRate: numberInString; - nextFundingTime: number; - time: number; -} -⋮---- -export interface FundingRateHistory { - symbol: string; - fundingRate: numberInString; - fundingTime: number; - markPrice: numberInString; -} -⋮---- -export interface FuturesSymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; -} -⋮---- -export interface OpenInterest { - openInterest: numberInString; - symbol: string; - time: number; -} -⋮---- -export interface HistoricOpenInterest { - symbol: string; - sumOpenInterest: string; - sumOpenInterestValue: string; - CMCCirculatingSupply: string; - timestamp: number; -} -⋮---- -export interface PositionModeParams { - dualSidePosition: DualSideMode; -} -⋮---- -export interface ModeChangeResult { - code: 200 | number; - msg: 'success' | string; -} -⋮---- -export interface PositionModeResponse { - dualSidePosition: boolean; -} -⋮---- -export interface MultiAssetModeResponse { - multiAssetsMargin: boolean; -} -⋮---- -export interface NewOrderResult { - clientOrderId: string; - cumQty: numberInString; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - avgPrice: numberInString; - origQty: numberInString; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - origType: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; -} -⋮---- -export interface NewOrderError { - code: number; - msg: string; -} -⋮---- -export interface OrderResult { - avgPrice: numberInString; - clientOrderId: string; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - time: number; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - goodTillDate: number; -} -⋮---- -export interface ModifyFuturesOrderResult { - orderId: number; - symbol: string; - pair: string; - status: OrderStatus; - clientOrderId: string; - price: numberInString; - avgPrice: numberInString; - origQty: numberInString; - executedQty: numberInString; - cumQty: numberInString; - cumBase: numberInString; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - reduceOnly: boolean; - closePosition: boolean; - side: OrderSide; - positionSide: PositionSide; - stopPrice: numberInString; - workingType: WorkingType; - priceProtect: boolean; - origType: FuturesOrderType; - updateTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; -} -⋮---- -export interface CancelFuturesOrderResult { - clientOrderId: string; - cumQty: numberInString; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; -} -⋮---- -export interface CancelAllOpenOrdersResult { - code: 200 | numberInString; - msg: string; -} -⋮---- -export interface FuturesAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - marginAvailable: boolean; - updateTime: numberInString; -} -⋮---- -export interface FuturesCoinMAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - withdrawAvailable: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - updateTime: number; -} -⋮---- -export interface FuturesAccountAsset { - asset: string; - walletBalance: numberInString; - unrealizedProfit: numberInString; - marginBalance: numberInString; - maintMargin: numberInString; - initialMargin: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - maxWithdrawAmount: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - marginAvailable: boolean; - updateTime: number; -} -⋮---- -export interface FuturesAccountPosition { - symbol: string; - initialMargin: numberInString; - maintMargin: numberInString; - unrealizedProfit: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - leverage: numberInString; - isolated: boolean; - entryPrice: numberInString; - maxNotional: numberInString; - positionSide: PositionSide; - positionAmt: numberInString; - notional: numberInString; - isolatedWallet: numberInString; - updateTime: number; - bidNotional: numberInString; - askNotional: numberInString; -} -⋮---- -export interface FuturesCoinMAccountPosition { - symbol: string; - positionAmt: numberInString; - initialMargin: numberInString; - maintMargin: numberInString; - unrealizedProfit: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - leverage: numberInString; - isolated: boolean; - positionSide: PositionSide; - entryPrice: numberInString; - maxQty: numberInString; - updateTime: number; -} -⋮---- -export interface FuturesAccountInformation { - feeTier: numberInString; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - updateTime: numberInString; - multiAssetsMargin: boolean; - totalInitialMargin: numberInString; - totalMaintMargin: numberInString; - totalWalletBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalMarginBalance: numberInString; - totalPositionInitialMargin: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalCrossWalletBalance: numberInString; - totalCrossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - assets: FuturesAccountAsset[]; - positions: FuturesAccountPosition[]; -} -⋮---- -export interface FuturesCoinMAccountInformation { - assets: Omit[]; - positions: FuturesCoinMAccountPosition[]; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; -} -⋮---- -export interface FuturesPosition { - entryPrice: numberInString; - marginType: 'isolated' | 'cross'; - isAutoAddMargin: 'false' | 'true'; - isolatedMargin: numberInString; - leverage: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - maxNotionalValue: numberInString; - positionAmt: numberInString; - notional: numberInString; - isolatedWallet: numberInString; - symbol: string; - unRealizedProfit: numberInString; - positionSide: PositionSide; - updateTime: number; -} -⋮---- -export interface FuturesPositionV3 { - symbol: string; - positionSide: PositionSide; - positionAmt: numberInString; - entryPrice: numberInString; - breakEvenPrice: numberInString; - markPrice: numberInString; - unRealizedProfit: numberInString; - liquidationPrice: numberInString; - isolatedMargin: numberInString; - notional: numberInString; - marginAsset: string; - isolatedWallet: numberInString; - initialMargin: numberInString; - maintMargin: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - adl: number; - bidNotional: numberInString; - askNotional: numberInString; - updateTime: number; -} -⋮---- -export interface FuturesPositionTrade { - buyer: boolean; - commission: numberInString; - commissionAsset: string; - id: number; - maker: boolean; - orderId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - realizedPnl: numberInString; - side: OrderSide; - positionSide: PositionSide; - symbol: string; - time: number; -} -⋮---- -export interface ForceOrderResult { - orderId: number; - symbol: string; - status: OrderStatus; - clientOrderId: string; - price: numberInString; - avgPrice: numberInString; - origQty: numberInString; - executedQty: numberInString; - cumQuote: numberInString; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - reduceOnly: boolean; - closePosition: boolean; - side: OrderSide; - stopPrice: numberInString; - workingType: WorkingType; - origType: FuturesOrderType; - time: number; - updateTime: number; -} -⋮---- -export interface SymbolLeverageBracket { - bracket: number; - initialLeverage: number; - notionalCap: number; - notionalFloor: number; - maintMarginRatio: number; - cum: number; -} -⋮---- -export interface SymbolLeverageBracketsResult { - symbol: string; - brackets: SymbolLeverageBracket[]; -} -⋮---- -export interface UserCommissionRate { - symbol: string; - makerCommissionRate: numberInString; - takerCommissionRate: numberInString; - rpiCommissionRate?: numberInString; -} -⋮---- -export interface FuturesAccountConfig { - feeTier: number; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - dualSidePosition: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId: number; -} -⋮---- -export interface SymbolConfig { - symbol: string; - marginType: string; - isAutoAddMargin: string; - leverage: number; - maxNotionalValue: string; -} -⋮---- -export interface UserForceOrder { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; -} -⋮---- -export interface RebateDataOverview { - brokerId: string; - newTraderRebateCommission: numberInString; - oldTraderRebateCommission: numberInString; - totalTradeUser: number; - unit: string; - totalTradeVol: numberInString; - totalRebateVol: numberInString; - time: number; -} -⋮---- -export interface SetCancelTimeoutResult { - symbol: string; - countdownTime: numberInString; -} -⋮---- -export interface ChangeStats24hr { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First tradeId - lastId: number; // Last tradeId - count: number; -} -⋮---- -firstId: number; // First tradeId -lastId: number; // Last tradeId -⋮---- -export interface OrderAmendmentDetailPrice { - before: numberInString; - after: numberInString; -} -⋮---- -export interface OrderAmendmentDetailQty { - before: numberInString; - after: numberInString; -} -⋮---- -export interface OrderAmendmentDetail { - price: OrderAmendmentDetailPrice; - origQty: OrderAmendmentDetailQty; - count: number; -} -⋮---- -export interface OrderAmendment { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: OrderAmendmentDetail; -} -⋮---- -export interface QuarterlyContractSettlementPrice { - deliveryTime: number; - deliveryPrice: number; -} -⋮---- -export interface BasisParams { - pair: string; - contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface Basis { - indexPrice: string; - contractType: string; - basisRate: string; - futuresPrice: string; - annualizedBasisRate: string; - basis: string; - pair: string; - timestamp: number; -} -⋮---- -export interface IndexPriceConstituent { - exchange: string; - symbol: string; - price: numberInString; - weight: numberInString; -} -⋮---- -export interface IndexPriceConstituents { - symbol: string; - time: number; - constituents: IndexPriceConstituent[]; -} -⋮---- -export interface InsuranceFundBalance { - symbols: string[]; - assets: { - asset: string; - marginBalance: string; - updateTime: number; - }[]; -} -⋮---- -export interface ModifyOrderParams { - orderId?: number; - origClientOrderId?: string; - symbol: string; - side: 'SELL' | 'BUY'; - quantity: string; - price: string; - priceMatch?: - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface GetFuturesOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface FuturesTradeHistoryDownloadId { - avgCostTimestampOfLast30d: number; - downloadId: string; -} -⋮---- -export interface FuturesTransactionDownloadLink { - downloadId: string; - status: 'completed' | 'processing'; - url: string; - expirationTimestamp: number; - isExpired: boolean | null; -} -⋮---- -export interface PortfolioMarginProAccountInfo { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; // This field will be ignored in the response -} -⋮---- -maxWithdrawAmount: string; // This field will be ignored in the response -⋮---- -export interface FuturesConvertPair { - fromAsset: string; - toAsset: string; - fromAssetMinAmount: string; - fromAssetMaxAmount: string; - toAssetMinAmount: string; - toAssetMaxAmount: string; -} -⋮---- -export interface FuturesConvertQuoteRequest { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - validTime?: '10s' | '30s' | '1m' | '2m'; -} -⋮---- -export interface FuturesConvertQuote { - quoteId: string; - ratio: string; - inverseRatio: string; - validTimestamp: number; - toAmount: string; - fromAmount: string; -} -⋮---- -export interface FuturesConvertOrderStatus { - orderId: string; - orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - ratio: string; - inverseRatio: string; - createTime: number; -} -⋮---- -/** - * Algo Order Types (Effective 2025-12-02) - * USDⓈ-M Futures conditional orders migrate to Algo Service - */ -⋮---- -export type FuturesAlgoOrderType = 'CONDITIONAL'; -⋮---- -export type FuturesAlgoConditionalOrderTypes = - | 'STOP_MARKET' - | 'TAKE_PROFIT_MARKET' - | 'STOP' - | 'TAKE_PROFIT' - | 'TRAILING_STOP_MARKET'; -⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update - */ -export type FuturesAlgoOrderStatus = - | 'NEW' - | 'CANCELED' - | 'TRIGGERING' - | 'TRIGGERED' - | 'FINISHED' - | 'REJECTED' - | 'EXPIRED'; -⋮---- -export interface FuturesNewAlgoOrderParams { - algoType: FuturesAlgoOrderType; - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesAlgoConditionalOrderTypes; - timeInForce?: OrderTimeInForce; - quantity?: numberInString; - price?: numberInString; - triggerPrice?: numberInString; - workingType?: WorkingType; - priceMatch?: PriceMatchMode; - closePosition?: BooleanString; - priceProtect?: BooleanString; - reduceOnly?: BooleanString; - activatePrice?: numberInString; - callbackRate?: numberInString; - clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ - selfTradePreventionMode?: SelfTradePreventionMode; - goodTillDate?: number; -} -⋮---- -clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ -⋮---- -export interface FuturesAlgoOrderResponse { - 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; - activatePrice?: numberInString; - callbackRate?: numberInString; - createTime: number; - updateTime: number; - triggerTime: number; - goodTillDate: number; -} -⋮---- -export interface FuturesCancelAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} -⋮---- -export interface FuturesCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} -⋮---- -export interface FuturesCancelAllAlgoOpenOrdersResponse { - code: number; - msg: string; -} -⋮---- -export interface FuturesQueryAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} -⋮---- -export interface FuturesQueryAlgoOrderResponse - extends FuturesAlgoOrderResponse { - actualOrderId: numberInString; - actualPrice: numberInString; - tpTriggerPrice?: numberInString; - tpPrice?: numberInString; - slTriggerPrice?: numberInString; - slPrice?: numberInString; - tpOrderType?: string; -} -⋮---- -export interface FuturesQueryOpenAlgoOrdersParams { - algoType?: FuturesAlgoOrderType; - symbol?: string; - algoId?: number; -} -⋮---- -export interface FuturesQueryAllAlgoOrdersParams { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 500; max 1000 -} -⋮---- -limit?: number; // Default 500; max 1000 -⋮---- -export interface SymbolAdlRisk { - symbol: string; - adlRisk: 'low' | 'medium' | 'high'; - updateTime: number; -} -⋮---- -export interface TradingSession { - startTime: number; - endTime: number; - type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; -} -⋮---- -export interface MarketSchedule { - sessions: TradingSession[]; -} -⋮---- -export interface TradingSchedule { - updateTime: number; - marketSchedules: { - EQUITY?: MarketSchedule; - COMMODITY?: MarketSchedule; - }; -} -⋮---- -export interface RpiOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} -⋮---- -E: number; // Message output time -T: number; // Transaction time - -================ -File: src/websocket-client-legacy.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ -import { EventEmitter } from 'events'; -import WebSocket from 'isomorphic-ws'; -⋮---- -import { KlineInterval } from './types/shared'; -import { - WsFormattedMessage, - WsUserDataEvents, -} from './types/websockets/ws-events-formatted'; -import { WsRawMessage } from './types/websockets/ws-events-raw'; -import { - WebsocketClientOptions, - WSClientConfigurableOptions, - WsMarket, - WsResponse, -} from './types/websockets/ws-general'; -import Beautifier from './util/beautifier'; -import { DefaultLogger } from './util/logger'; -import { appendEventIfMissing, RestClientOptions } from './util/requestUtils'; -import { neverGuard } from './util/typeGuards'; -import { ListenKeyStateCache } from './util/websockets/listen-key-state-cache'; -import { RestClientCache } from './util/websockets/rest-client-cache'; -import { - appendEventMarket, - getContextFromWsKey, - getLegacyWsStoreKeyWithContext, - parseEventTypeFromMessage, - parseRawWsMessageLegacy, - safeTerminateWs, - WS_LOGGER_CATEGORY, - WsKey, -} from './util/websockets/websocket-util'; -import { WsStore } from './util/websockets/WsStore'; -import { WsConnectionStateEnum } from './util/websockets/WsStore.types'; -⋮---- -alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams -⋮---- -type WsEventInternalSrc = 'event' | 'function'; -⋮---- -export declare interface WebsocketClientV1 { - on(event: 'reply', listener: (event: WsResponse) => void): this; - - on(event: 'message', listener: (event: WsRawMessage) => void): this; - - on( - event: 'formattedMessage', - listener: (event: WsFormattedMessage) => void, - ): this; - - on( - event: 'formattedUserDataMessage', - listener: (event: WsUserDataEvents) => void, - ): this; - - on( - event: 'error', - listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, - ): this; - - on( - event: 'open' | 'reconnected' | 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; -} -⋮---- -on(event: 'reply', listener: (event: WsResponse) -⋮---- -on(event: 'message', listener: (event: WsRawMessage) -⋮---- -on( - event: 'formattedMessage', - listener: (event: WsFormattedMessage) => void, - ): this; -⋮---- -on( - event: 'formattedUserDataMessage', - listener: (event: WsUserDataEvents) => void, - ): this; -⋮---- -on( - event: 'error', - listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, - ): this; -⋮---- -on( - event: 'open' | 'reconnected' | 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; -⋮---- -/** - * @deprecated This legacy websocket client creates one websocket connection per topic. - * - * If subscribing to a lot of topics, consider using the new multiplex `WebsocketClient`. - * - * To split your topics into smaller groups (one connection per group), simply make multiple multiplex WebsocketClient instances. - */ -export class WebsocketClientV1 extends EventEmitter -⋮---- -constructor( - options: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, -) -⋮---- -// Some defaults: -⋮---- -// Automatically send an authentication op/request after a connection opens, for private connections. -⋮---- -// Individual requests require a signature -⋮---- -// add default error handling so this doesn't crash node (if the user didn't set a handler) -⋮---- -private getRestClientOptions(): RestClientOptions -⋮---- -public connectToWsUrl( - url: string, - wsKey?: WsKey | string, - forceNewConnection?: boolean, -): WebSocket -⋮---- -// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node -⋮---- -// Add ws connection with key to store -⋮---- -public tryWsSend(wsKey: WsKey | string, wsMessage: string) -⋮---- -public tryWsPing(wsKey: WsKey | string) -⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); -⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) -⋮---- -private onWsOpen(ws: WebSocket, wsKey: WsKey | string, wsUrl: string) -⋮---- -private onWsClose( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - wsUrl: string, -) -⋮---- -// Clear any timers before we initiate revival -⋮---- -// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states -⋮---- -private onWsMessage( - event: MessageEvent, - wsKey: WsKey | string, - source: WsEventInternalSrc, -) -⋮---- -// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e -⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn -⋮---- -// emit a separate event for user data messages -⋮---- -private sendPing(wsKey: WsKey | string, wsUrl: string) -⋮---- -private onWsPing( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - source: WsEventInternalSrc, -) -⋮---- -private onWsPong( - event: any, - wsKey: WsKey | string, - source: WsEventInternalSrc, -) -⋮---- -/** - * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. - * If closed, trigger a reconnect immediately - */ -private executeReconnectableClose( - wsKey: WsKey | string, - reason: string, - wsUrl: string, -) -⋮---- -public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) -⋮---- -public closeAll(shouldReconnectAfterClose?: boolean) -⋮---- -public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) -⋮---- -private parseWsError( - context: string, - error: any, - wsKey: WsKey | string, - wsUrl: string, -) -⋮---- -private reconnectWithDelay( - wsKey: WsKey | string, - connectionDelayMs: number, - wsUrl: string, -) -⋮---- -// We'll set a new one once the new stream respawns, with a diff listenKey in the key -⋮---- -private clearTimers(wsKey: WsKey | string) -⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: WsKey | string) -⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: WsKey | string) -⋮---- -// Timer tracking that a reconnect is about to happen / in progress -private clearReconnectTimer(wsKey: WsKey | string) -⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string -⋮---- -public getWs(wsKey: WsKey | string): WebSocket | undefined -⋮---- -private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) -⋮---- -/** - * Send WS message to subscribe to topics. Use subscribe() to call this. - */ -private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) -⋮---- -/** - * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. - */ -private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) -⋮---- -/** - * Send WS message to unsubscribe from topics. - */ -public requestListSubscriptions(wsKey: WsKey, requestId: number) -⋮---- -/** - * Send WS message to set property state - */ -public requestSetProperty( - wsKey: WsKey, - property: 'combined' | string, - value: any, - requestId: number, -) -⋮---- -/** - * Send WS message to get property state - */ -public requestGetProperty( - wsKey: WsKey, - property: 'combined' | string, - requestId: number, -) -⋮---- -/** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ -⋮---- -private setKeepAliveListenKeyTimer( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, -) -⋮---- -// Set timer to keep WS alive every 50 minutes -⋮---- -// 1000 * 60 -⋮---- -private sendKeepAliveForMarket( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, -) -⋮---- -private async checkKeepAliveListenKey( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, -) -⋮---- -// Simple way to test keep alive failure handling: -// throw new Error(`Fake keep alive failure`); -⋮---- -// code: -1125, -// message: 'This listenKey does not exist.', -⋮---- -// If max failurees reached, tear down and respawn if allowed -⋮---- -// reconnect follows a less automatic workflow since this is tied to a listen key (which may need a new one). -// Kill connection first, with instruction NOT to reconnect automatically -⋮---- -// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) -⋮---- -private teardownUserDataListenKey(listenKey: string, ws: WebSocket) -⋮---- -private async respawnUserDataStream( - market: WsMarket, - symbol?: string, - isTestnet?: boolean, - respawnAttempt?: number, -): Promise -⋮---- -// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key -⋮---- -// This timer should probably be tracked/singleton -⋮---- -/** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ -⋮---- -/** - * Subscribe to a universal market websocket stream - */ -⋮---- -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to trades for a symbol in a market category - * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning - */ -public subscribeTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to coin index for a symbol in COINM Futures markets - */ -public subscribeCoinIndexPrice( - symbol: string, - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to mark price for a symbol in a market category - */ -public subscribeMarkPrice( - symbol: string, - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to continuous contract klines(candles) for a symbol futures - */ -public subscribeContinuousContractKlines( - symbol: string, - contractType: 'perpetual' | 'current_quarter' | 'next_quarter', - interval: KlineInterval, - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -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, - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - 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. - */ -public subscribeSpotUserDataStreamWithListenKey( - listenKey: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, -): WebSocket | undefined -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) -⋮---- -/** - * 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 -⋮---- -/** - * Subscribe to margin user data stream - listen key is automatically generated. - */ -public async subscribeMarginUserDataStream( - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) -⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) -⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ -⋮---- -/** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeUsdFuturesUserDataStream( - 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) -⋮---- -/** - * 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, - }); -} - -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` 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}`); -} - -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. 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 Binance client ID value like a primary key, while keeping the exchange-facing ID short and valid. - -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' }); - -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`](/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 | - -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`](/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. - -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 -================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderType, - FuturesOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; -import { - BooleanString, - KlineInterval, - numberInString, - OrderResponseType, - OrderSide, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; -⋮---- -/** - * Simple request params with timestamp (required) & recv window (optional) - */ -export type WSAPIRecvWindowTimestamp = { - recvWindow?: number; - timestamp: number; -}; -⋮---- -/** - * - * Authentication request types - * - */ -export interface WSAPISessionLogonRequest { - timestamp: number; -} -⋮---- -/** - * - * General request types - * - */ -export interface WSAPIExchangeInfoRequest { - symbol?: string; - symbols?: string[]; - permissions?: string[]; - showPermissionSets?: boolean; - symbolStatus?: string; -} -⋮---- -/** - * - * Market data request types - * - */ -⋮---- -export interface WSAPIOrderBookRequest { - symbol: string; - limit?: number; - symbolStatus?: string; -} -⋮---- -export interface WSAPITradesRecentRequest { - symbol: string; - limit?: number; -} -⋮---- -export interface WSAPITradesHistoricalRequest { - symbol: string; - fromId?: number; - limit?: number; -} -⋮---- -export interface WSAPIBlockTradesHistoricalRequest { - symbol: string; - fromId: number; - limit?: number; -} -⋮---- -export interface WSAPITradesAggregateRequest { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface WSAPIKlinesRequest { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} -⋮---- -export interface WSAPIAvgPriceRequest { - symbol: string; -} -⋮---- -/** - * 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 interface WSAPIReferencePriceRequest { - symbol: string; -} -⋮---- -export interface WSAPIReferencePriceCalculationRequest { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITicker24hrRequest { - symbol?: string; - symbols?: string[]; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerTradingDayRequest { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -/** - * 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; -} -⋮---- -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; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerBookRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} -⋮---- -/** - * - * Account request types - Spot - * - */ -⋮---- -export interface WSAPIAllOrdersRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface WSAPIAllOrderListsRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface WSAPIMyTradesRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} -⋮---- -export interface WSAPIMyPreventedMatchesRequest { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} -⋮---- -export interface WSAPIMyAllocationsRequest { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} -⋮---- -/** - * 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; -} -⋮---- -export interface WSAPIOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - recvWindow?: number; - timestamp: number; -} -⋮---- -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 WSAPIOrderAmendKeepPriorityRequest { - symbol: string; - orderId?: number | string; - origClientOrderId?: string; - newClientOrderId?: string; - newQty?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOpenOrdersStatusRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOpenOrdersCancelAllRequest { - symbol: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -/** - * 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 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 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 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 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 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; -} -⋮---- -export interface WSAPIOrderListStatusRequest { - origClientOrderId?: string; - orderListId?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListCancelRequest { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -/** - * SOR request types - */ -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; -}; -⋮---- -/** - * Futures market data request types - */ -⋮---- -export interface WSAPIFuturesOrderBookRequest { - symbol: string; - limit?: number; -} -⋮---- -export interface WSAPIFuturesTickerPriceRequest { - symbol?: string; -} -⋮---- -export interface WSAPIFuturesTickerBookRequest { - symbol?: string; -} -⋮---- -/** - * Futures trading request types - */ -⋮---- -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; -} -⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -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; -} -⋮---- -export interface WSAPIFuturesOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesPositionRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesPositionV2Request { - symbol?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIAccountInformationRequest { - omitZeroBalances?: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIAccountCommissionWSAPIRequest { - symbol: string; -} -⋮---- -/** - * 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; -} -⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -/** - * 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 WSAPIUserDataListenKeyRequest { - apiKey: string; - listenKey: string; -} -⋮---- -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; -} -⋮---- -// 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; - }[]; - - wsKey: WsKey; - isWSAPIResponse: boolean; - - // 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; - - [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 }; -} -⋮---- -/** - * 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; - - 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; -} -⋮---- -/** - * 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 - */ - -================ -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 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' - | 'CANCEL_ONLY'; -⋮---- -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; -⋮---- -export interface DailyAccountSnapshot { - code: number; - msg: string; - snapshotVos: DailyAccountSnapshotElement[]; -} -⋮---- -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 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 WithdrawParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; -} -⋮---- -export interface TransferBrokerSubAccountParams { - fromId?: string; - toId?: string; - clientTranId?: string; - asset: string; - amount: number; -} -⋮---- -export interface ConvertQuoteRequestParams { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - walletType?: string; - validTime?: string; -} -⋮---- -export interface EnableConvertSubAccountParams { - subAccountId: string; - convert: boolean; -} -⋮---- -export interface AcceptQuoteRequestParams { - quoteId: string; -} -⋮---- -export interface GetOrderStatusParams { - orderId?: string; - quoteId?: string; -} -⋮---- -export interface GetConvertTradeHistoryParams { - startTime: number; - endTime?: number; - limit?: string; -} -⋮---- -export interface TransferBrokerSubAccount { - txnId: numberInString; -} -⋮---- -export enum EnumDepositStatus { - Pending = 0, - CreditedButCannotWithdraw = 6, - WrongDeposit = 7, - WaitingUserConfirm = 8, - Success = 1, - Rejected = 2, -} -⋮---- -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) -} -⋮---- -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 enum EnumWithdrawStatus { - EmailSent = 0, - Cancelled = 1, - AwaitingApproval = 2, - Rejected = 3, - Processing = 4, - Failure = 5, - Completed = 6, -} -⋮---- -export type WithdrawStatusCode = `${EnumWithdrawStatus}`; -⋮---- -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) -} -⋮---- -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 enum EnumWithdrawTransferType { - External = 0, - Interal = 1, -} -⋮---- -export type WithdrawTransferType = `${EnumWithdrawTransferType}`; -⋮---- -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 DepositAddressParams { - coin: string; - network?: string; - amount?: number; -} -⋮---- -export interface DepositAddressResponse { - address: string; - coin: string; - tag: string; - url: string; -} -⋮---- -export interface ConvertDustParams { - asset: string[]; - accountType?: 'SPOT' | 'MARGIN'; -} -⋮---- -export type DustConvertAccountType = 'SPOT' | 'MARGIN'; -⋮---- -export interface DustConvertParams { - asset: string[]; - accountType?: DustConvertAccountType; - clientId?: string; - targetAsset?: string; - thirdPartyClientId?: string; - dustQuotaAssetToTargetAssetPrice?: numberInString; -} -⋮---- -export interface DustConvertibleAssetsParams { - targetAsset: string; - accountType?: DustConvertAccountType; - dustQuotaAssetToTargetAssetPrice?: numberInString; -} -⋮---- -export interface DustConvertibleAssetDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - exchange: numberInString; - toQuotaAssetAmount: numberInString; - toTargetAssetAmount: numberInString; - toTargetAssetOffExchange: numberInString; -} -⋮---- -export interface DustConvertibleAssetsResponse { - dribbletPercentage: numberInString; - totalTransferQuotaAssetAmount: numberInString; - totalTransferTargetAssetAmount: numberInString; - dribbletBase: numberInString; - details: DustConvertibleAssetDetail[]; -} -⋮---- -export interface DustInfoDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - toBTC: numberInString; - toBNB: numberInString; - toBNBOffExchange: numberInString; - exchange: numberInString; -} -⋮---- -export interface DustInfo { - details: DustInfoDetail[]; - totalTransferBtc: numberInString; - totalTransferBNB: numberInString; - dribbletPercentage: numberInString; -} -⋮---- -export interface DustConversionResult { - amount: numberInString; - fromAsset: string; - operateTime: number; - serviceChargeAmount: numberInString; - tranId: number; - transferedAmount: numberInString; -} -⋮---- -export interface DustConversion { - totalServiceCharge: numberInString; - totalTransfered: numberInString; - transferResult: DustConversionResult[]; -} -⋮---- -export interface UserAssetDribbletDetail { - transId: number; - serviceChargeAmount: numberInString; - amount: numberInString; - operateTime: number; - transferedAmount: numberInString; - fromAsset: string; -} -⋮---- -export interface UserAssetDribblet { - operateTime: number; - totalTransferedAmount: numberInString; - totalServiceChargeAmount: numberInString; - transId: number; - userAssetDribbletDetails: UserAssetDribbletDetail[]; -} -⋮---- -export interface DustLog { - total: number; - userAssetDribblets: UserAssetDribblet[]; -} -⋮---- -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 type UniversalTransferType = `${EnumUniversalTransferType}`; -⋮---- -export interface UniversalTransferParams { - type: UniversalTransferType; - asset: string; - amount: number; - fromSymbol: string; - toSymbol: string; -} -⋮---- -export interface UniversalTransferHistoryParams { - type: UniversalTransferType; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface ExchangeInfoParams { - symbol?: string; - symbols?: string[]; - permissions?: string | string[]; - showPermissionSets?: boolean; - symbolStatus?: 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 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 GetOCOParams { - symbol?: string; - orderListId?: number; - origClientOrderId?: string; -} -⋮---- -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 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; -} -⋮---- -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 SymbolTradeFee { - symbol: string; - makerCommission: numberInString; - takerCommission: numberInString; -} -⋮---- -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 ExchangeInfo { - timezone: string; - serverTime: number; - rateLimits: RateLimiter[]; - exchangeFilters: ExchangeFilter[]; - symbols: SymbolExchangeInfo[]; -} -⋮---- -export interface OrderBookResponse { - lastUpdateId: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; -} -⋮---- -export interface RawTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; -} -⋮---- -export interface BlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface HistoricalBlockTradesParams { - symbol: string; - fromId: number; - limit?: number; -} -⋮---- -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 AggregateTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; - M: boolean; -} -⋮---- -export interface CurrentAvgPrice { - mins: number; - 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; -} -⋮---- -export interface SpotSymbolExecutionRules { - symbol: string; - rules: SpotPriceRangeExecutionRule[]; -} -⋮---- -export interface SpotExecutionRulesResponse { - symbolRules: SpotSymbolExecutionRules[]; -} -⋮---- -/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ -export interface SpotExecutionRulesParams { - symbol?: string; - symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -} -⋮---- -/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ -export interface SpotReferencePriceResponse { - symbol: string; - referencePrice: numberInString | null; - 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 type SpotReferencePriceResult = - | SpotReferencePriceResponse - | SpotReferencePriceNeverSetError; -⋮---- -/** Reference price is computed as an arithmetic mean in the matching engine. */ -export interface SpotReferencePriceCalculationArithmeticMean { - symbol: string; - calculationType: 'ARITHMETIC_MEAN'; - bucketCount: number; - bucketWidthMs: number; -} -⋮---- -/** Reference price is computed outside the matching engine. */ -export interface SpotReferencePriceCalculationExternal { - symbol: string; - calculationType: 'EXTERNAL'; - externalCalculationId: number; -} -⋮---- -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 SymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; -} -⋮---- -export interface OrderResponseACK { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: 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; -} -⋮---- -/** 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 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[]; -} -⋮---- -/** 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; -} -⋮---- -/** 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]; -} -⋮---- -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; -} -⋮---- -export type SOROrderResponseFull = OrderResponseFull & { - workingTime: number; - fills: SOROrderFill[]; - workingFloor: string; - selfTradePreventionMode: string; - usedSor: true; -}; -⋮---- -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. - }; -} -⋮---- -//Standard commission rates on trades from the order. -⋮---- -//Tax commission rates for trades from the order. -⋮---- -//Discount on standard commissions when paying in BNB. -⋮---- -discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. -⋮---- -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 CancelOrderListResult extends OrderList { - orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; -} -⋮---- -export interface GenericReplaceSpotOrderResult { - cancelResult: 'SUCCESS' | 'FAILURE'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: C; - newOrderResponse: N; -} -⋮---- -export interface ReplaceSpotOrderCancelStopFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'NOT_ATTEMPTED'; -} -⋮---- -export interface ReplaceSpotOrderNewFailure - extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - GenericCodeMsgError - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'FAILURE'; -} -⋮---- -export interface ReplaceSpotOrderCancelAllowFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'SUCCESS'; -} -⋮---- -export interface ReplaceSpotOrderCancelAllFailure - extends GenericReplaceSpotOrderResult< - GenericCodeMsgError, - GenericCodeMsgError - > { - cancelResult: 'FAILURE'; - newOrderResult: 'FAILURE'; -} -⋮---- -export interface ReplaceSpotOrderResultError { - data: - | ReplaceSpotOrderCancelStopFailure - | ReplaceSpotOrderNewFailure - | ReplaceSpotOrderCancelAllowFailure - | ReplaceSpotOrderCancelAllFailure; -} -⋮---- -export interface ReplaceSpotOrderResultSuccess< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - OrderResponseTypeFor - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'SUCCESS'; -} -⋮---- -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; -} -⋮---- -/** 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 SpotAssetBalance { - asset: string; - free: numberInString; - locked: numberInString; -} -⋮---- -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 CrossMarginAccountTransferParams { - asset: string; - amount: number; - type: 1 | 2; -} -⋮---- -export interface MarginTransactionResponse { - tranId: number; -} -⋮---- -export interface MarginAccountLoanParams { - asset: string; - isIsolated: StringBoolean; - symbol: string; - amount: number; - type: 'BORROW' | 'REPAY'; -} -⋮---- -export interface QueryMarginAssetParams { - asset: string; -} -⋮---- -export interface QueryMarginAssetResponse { - assetFullName: string; - assetName: string; - isBorrowable: boolean; - isMortgageable: boolean; - userMinBorrow: numberInString; - userMinRepay: numberInString; -} -⋮---- -export interface QueryCrossMarginPairParams { - symbol: string; -} -⋮---- -export interface QueryCrossMarginPairResponse { - id: number; - symbol: string; - base: string; - quote: string; - isMarginTrade: boolean; - isBuyAllowed: boolean; - isSellAllowed: boolean; -} -⋮---- -export interface QueryMarginPriceIndexResponse { - calcTime: number; - price: numberInString; - symbol: string; -} -⋮---- -export interface QueryMarginRecordParams { - asset: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - archived?: boolean; -} -⋮---- -export interface GetMarginAccountBorrowRepayRecordsParams { - asset?: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - type: 'BORROW' | 'REPAY'; -} -⋮---- -export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; -⋮---- -export interface MarginAccountRecord { - isolatedSymbol?: string; - asset: string; - principal: numberInString; - status: LoanStatus; - timestamp: number; - txId: number; -} -⋮---- -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 BasicMarginAssetParams { - asset: string; - isolatedSymbol?: string; -} -⋮---- -export interface QueryMaxBorrowResponse { - amount: numberInString; - borrowLimit: numberInString; -} -⋮---- -export interface QueryMaxTransferOutAmountResponse { - amount: numberInString; -} -⋮---- -export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; -⋮---- -export interface IsolatedMarginAccountTransferParams { - asset: string; - symbol: string; - transFrom: IsolatedMarginTransfer; - transTo: IsolatedMarginTransfer; - amount: number; -} -⋮---- -export interface IsolatedMarginAccountAsset { - asset: string; - borrowEnabled: boolean; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; - netAssetOfBtc: numberInString; - repayEnabled: boolean; - totalAsset: numberInString; -} -⋮---- -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 IsolatedMarginAccountInfo { - assets: IsolatedMarginAccountAssets[]; - totalAssetOfBtc?: numberInString; - totalLiabilityOfBtc?: numberInString; - totalNetAssetOfBtc?: numberInString; -} -⋮---- -export interface SpotSubUserAssetBtcList { - email: string; - totalAsset: numberInString; -} -⋮---- -export interface SubAccountList { - email: string; - isFreeze: boolean; - createTime: number; - isManagedSubAccount: boolean; - isAssetManagementSubAccount: boolean; -} -⋮---- -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 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 interface SubAccountStatus { - email: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - insertTime: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - mobile: number; -} -⋮---- -export interface BasicBtcTotals { - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; -} -⋮---- -export interface FuturesSubAccountAssets { - asset: string; - initialMargin: numberInString; - maintenanceMargin: numberInString; - marginBalance: numberInString; - maxWithdrawAmount: numberInString; - openOrderInitialMargin: numberInString; - positionInitialMargin: numberInString; - unrealizedProfit: numberInString; - walletBalance: numberInString; -} -⋮---- -export interface FuturesSubAccountList { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - email: string; -} -⋮---- -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 interface SubAccountUniversalTransferHistory { - tranId: number; - fromEmail: string; - toEmail: string; - asset: 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; -} -⋮---- -export interface CreateBrokerSubAccountParams { - tag?: string; -} -⋮---- -export interface GetBrokerSubAccountParams { - subAccountId?: string; - page?: number; - size?: number; -} -⋮---- -export interface GetApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey?: string; - page?: number; - size?: number; -} -⋮---- -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 interface UpdateIpRestrictionForSubApiKey { - subAccountId: string; - ipAddress?: string; - subAccountApiKey: string; - status: string; -} -⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canUniversalTransfer: boolean; -} -⋮---- -export interface EnableMarginBrokerSubAccountParams { - subAccountId: string; - margin: boolean; -} -⋮---- -export interface EnableMarginBrokerSubAccountResponse { - subAccountId: string; - enableMargin: boolean; - updateTime: number; -} -⋮---- -export interface EnableFuturesBrokerSubAccountParams { - subAccountId: string; - futures: boolean; -} -⋮---- -export interface EnableFuturesBrokerSubAccountResponse { - subAccountId: string; - enableFutures: boolean; - updateTime: number; -} -⋮---- -export interface EnableMarginApiKeyBrokerSubAccountParams { - subAccountId: string; - margin: boolean; -} -export interface UniversalTransferBrokerParams { - fromId?: string; - toId?: string; - fromAccountType: string; - toAccountType: string; - asset: string; - amount: number; -} -⋮---- -export interface GetUniversalTransferBrokerParams { - fromId?: string; - toId?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; -} -⋮---- -export interface GetBrokerSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface DeleteApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; -} -⋮---- -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; -} -⋮---- -export interface BrokerSubAccountHistory { - subAccountsHistory: SubAccountTransferHistoryList[]; -} -⋮---- -export interface BrokerSubAccount { - subaccountId: string; - email: string; - makerCommission?: string; - takerCommission?: string; - marginMakerCommission?: string; - marginTakerCommission?: string; - createTime?: number; - tag: string; -} -⋮---- -export interface CreateApiKeyBrokerSubAccountResponse { - subaccountId: string; - apiKey: string; - secretKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} -⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canUniversalTransfer: boolean; -} -⋮---- -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 SubAccountListResponse { - subAccounts: SubAccountList[]; -} -⋮---- -export interface SubAccountSpotAssetTransferHistoryParams { - fromEmail?: string; - toEmail?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountSpotAssetTransferHistory - extends SubAccountBasicTransfer { - status: string; -} -⋮---- -export interface SubAccountFuturesAssetTransferHistoryParams { - email: string; - futuresType: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountFuturesAssetTransferHistory { - success: boolean; - futuresType: number; - transfers: SubAccountBasicTransfer[]; -} -⋮---- -export interface SubAccountFuturesAssetTransferParams { - fromEmail: string; - toEmail: string; - futuresType: number; - asset: string; - amount: number; -} -⋮---- -export interface SubAccountFuturesAssetTransfer { - success: boolean; - txnId: numberInString; -} -⋮---- -export interface SubAccountAssetsParams { - email: string; -} -⋮---- -export interface SubAccountAssets { - balances: SpotBalance[]; -} -⋮---- -export interface SubAccountSpotAssetsSummaryParams { - email?: string; - page?: number; - size?: number; -} -⋮---- -export interface SubAccountSpotAssetsSummary { - totalCount: number; - masterAccountTotalAsset: numberInString; - spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; -} -⋮---- -export interface SubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; -} -⋮---- -export interface SubAccountDepositAddress { - address: string; - coin: string; - tag: string; - url: string; -} -⋮---- -export interface SubAccountDepositHistoryParams extends DepositHistoryParams { - email: string; -} -⋮---- -export interface SubAccountEnableMargin { - email: string; - isMarginEnabled: boolean; -} -⋮---- -export interface SubAccountMarginAccountDetail extends BasicBtcTotals { - email: string; - marginLevel: numberInString; - marginTradeCoeffVo: MarginTradeCoeffVo; - marginUserAssetVoList: MarginBalance[]; -} -⋮---- -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 SubAccountFuturesAccountSummary extends FuturesSubAccountList { - subAccountList: FuturesSubAccountList[]; -} -⋮---- -export interface FuturesPositionRisk { - entryPrice: numberInString; - leverage: numberInString; - maxNotional: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - positionAmount: numberInString; - symbol: string; - unrealizedProfit: numberInString; -} -⋮---- -export interface SubAccountTransferParams { - email: string; - asset: string; - amount: number; - type: number; -} -⋮---- -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; - limit?: number; -} -⋮---- -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; - priceType: string; - price: string; - quantity: string; - positionSide: string; - side: string; - success: boolean; -} -⋮---- -export interface SubAccountMovePositionHistoryParams { - symbol: string; - startTime?: number; - endTime?: number; - page: number; - row: number; -} -⋮---- -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; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountUniversalTransferHistoryResponse { - result: SubAccountUniversalTransferHistory[]; - totalCount: number; -} -⋮---- -export interface SubAccountEnableLeverageToken { - email: string; - enableBlvt: boolean; -} -⋮---- -export interface AddIpRestriction extends BasicSubAccount { - status: string; - ipAddress: string; -} -⋮---- -export interface SubAccountEnableOrDisableIPRestriction { - ipRestrict: boolean; - ipList: string[]; - updateTime: number; - apiKey: string; -} -⋮---- -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; - 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 COINMSubAccount { - email: string; - totalMarginBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; -} -⋮---- -export interface SubAccountCOINMDetail { - deliveryAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: 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 SubAccountCOINMSummary { - deliveryAccountSummaryResp: { - totalMarginBalanceOfBTC: numberInString; - totalUnrealizedProfitOfBTC: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; - subAccountList: COINMSubAccount[]; - }; -} -⋮---- -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 SubAccountCOINMPositionRisk { - deliveryPositionRiskVos: COINMPositionRisk[]; -} -⋮---- -export interface StakingProductDetail { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - apy: numberInString; -} -⋮---- -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; - 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 FlexibleSavingBasicParams { - status?: string; - featured?: number; - current?: number; - size?: number; - asset?: string; -} -⋮---- -export interface FlexibleProductPositionParams { - status?: string; - featured?: number; - current?: number; - size?: number; -} -⋮---- -export interface PurchaseFlexibleProductParams { - productId: string; - amount: number; - autoSubscribe: boolean; -} -⋮---- -export interface PurchaseFlexibleProductResponse { - purchaseId: number; -} -⋮---- -export interface RedeemFlexibleProductParams { - productId: string; - amount: number; - type: 'FAST' | 'NORMAL'; -} -⋮---- -export interface LeftDailyPurchaseQuotaFlexibleProductResponse { - 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; - current?: number; - size?: number; -} -export interface FixedAndActivityProjectPositionParams { - asset?: string; - projectId?: string; - status?: StakingStatus; -} -⋮---- -export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; -⋮---- -export interface PurchaseRecordParams { - lendingType: LendingType; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -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 interface FutureAccountTransfer { - asset: string; - tranId: number; - amount: string; - type: string; - 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; -} -⋮---- -export interface StakingPersonalLeftQuota { - leftPersonalQuota: numberInString; -} -⋮---- -export interface StakingHistoryParams extends StakingBasicParams { - txnType: StakingTxnType; - asset?: string; - startTime?: number; - endTime?: number; -} -export interface BSwapOperationsParams { - operationId?: number; - poolId?: number; - operation: BSwapOperationType; - startTime?: number; - endTime?: number; - limit: 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; - quantity: number; -} -⋮---- -export interface BSwapShare { - shareAmount: number; - sharePercentage: number; - asset: { [k: string]: number }; -} -⋮---- -export interface BSwapLiquidity { - poolId: number; - poolNmae: string; - updateTime: number; - liquidity: { [k: string]: number }; - share: BSwapShare; -} -⋮---- -export interface FundingAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - btcValuation: string; -} -⋮---- -export interface GetAssetParams { - asset?: string; - needBtcValuation?: boolean; -} -⋮---- -export interface UserAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - ipoable: string; - btcValuation: string; -} -⋮---- -export interface ConvertTransfer { - clientTranId: string; - asset: string; - amount: number; - targetAsset: string; - accountType?: string; -} -⋮---- -export interface ConvertTransferResponse { - tranId: number; - status: string; -} -⋮---- -export interface GetConvertBUSDHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - accountType?: string; - current?: number; - size?: number; -} -⋮---- -export interface BUSDConversionRecord { - tranId: number; - type: number; - time: number; - deductedAsset: string; - deductedAmount: string; - targetAsset: string; - targetAmount: string; - status: string; - accountType: string; -} -⋮---- -export interface CloudMiningHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - current?: number; - size?: number; -} -⋮---- -export interface CloudMining { - createTime: number; - tranId: number; - type: number; - asset: string; - amount: string; - status: string; -} -⋮---- -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 WalletBalance { - activate: boolean; - balance: string; - walletName: string; -} -⋮---- -export interface DelegationHistoryParams { - email: string; - startTime: number; - endTime: number; - type?: 'Delegate' | 'Undelegate'; - asset?: string; - current?: number; - size?: number; -} -⋮---- -export interface DelegationHistory { - clientTranId: string; - transferType: 'Delegate' | 'Undelegate'; - asset: string; - amount: string; - time: number; -} -⋮---- -export interface DelistScheduleResponse { - delistTime: number; - symbols: string[]; -} -⋮---- -export interface WithdrawAddress { - address: string; - addressTag: string; - coin: string; - name: string; - network: string; - origin: string; - originType: string; - whiteStatus: boolean; -} -⋮---- -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; - limit?: number; -} -⋮---- -export interface SubaccountBalances { - asset: string; - free: string; - locked: string; -} -⋮---- -export interface SubaccountUserAssets { - asset: string; - borrowed: string; - free: string; - interest: string; - locked: string; - netAsset: string; -} -⋮---- -export interface SubaccountAssets { - asset: string; - marginBalance: string; - walletBalance: string; -} -⋮---- -export interface SubaccountPosition { - entryPrice: string; - markPrice: string; - positionAmt: string; - symbol: string; - unRealizedProfit: 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 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 ManagerSubTransferHistoryVos { - fromEmail: string; - fromAccountType: string; - toEmail: string; - toAccountType: string; - asset: string; - amount: string; - scheduledData: number; - createTime: number; - status: string; - tranId: number; -} -⋮---- -export interface ManagedSubAccountFuturesAssetsResponse { - code: string; - message: string; - snapshotVos: { - type: string; - updateTime: number; - data: { - assets: SubaccountAssets[]; - position: SubaccountPosition[]; - }; - }[]; -} -⋮---- -export interface ManagedSubAccountMarginAssetsResponse { - marginLevel: string; - totalAssetOfBtc: string; - totalLiabilityOfBtc: string; - totalNetAssetOfBtc: string; - userAssets: SubaccountUserAssets[]; -} -⋮---- -export interface ManagedSubAccountListParams { - email?: string; - page?: number; - limit?: number; -} -⋮---- -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 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 ManagedSubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; -} -⋮---- -export interface ManagedSubAccountDepositAddress { - coin: string; - address: string; - tag: string; - url: string; -} -⋮---- -export interface EnableOptionsForSubAccountResponse { - email: string; - isEOptionsEnabled: boolean; -} -⋮---- -export interface ManagedSubAccountTransferTTLogParams { - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: string; - transferFunctionAccountType?: string; -} -⋮---- -export interface UIKlinesParams { - symbol: string; - interval: string; - startTime?: number; - endTime?: number; - timeZone?: string; - 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 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 type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; -⋮---- -export interface TradingDayTickerParams { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -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 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 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 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 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 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 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 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 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 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 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 OrderRateLimitUsage { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} -⋮---- -export interface PreventedMatchesParams { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} -⋮---- -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 AllocationsParams { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} -⋮---- -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 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 GetCrossMarginTransferHistoryParams { - asset?: string; - type?: 'ROLL_IN' | 'ROLL_OUT'; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - isolatedSymbol?: string; -} -⋮---- -export interface CrossMarginTransferHistory { - amount: string; - asset: string; - status: string; - timestamp: number; - txId: number; - type: 'ROLL_IN' | 'ROLL_OUT'; - transFrom?: string; - transTo?: string; - fromSymbol?: string; - toSymbol?: string; -} -⋮---- -export interface GetMarginInterestHistoryParams { - asset?: string; - isolatedSymbol?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface MarginInterestHistory { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset?: string; - principal: string; - interest: string; - interestRate: string; - type: - | 'PERIODIC' - | 'ON_BORROW' - | 'PERIODIC_CONVERTED' - | 'ON_BORROW_CONVERTED' - | 'PORTFOLIO'; - isolatedSymbol?: string; -} -⋮---- -export interface GetForceLiquidationRecordParams { - startTime?: number; - endTime?: number; - isolatedSymbol?: string; - current?: number; - size?: number; -} -⋮---- -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 QueryMarginAccountAllOCOParams { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface QueryMarginAccountTradeListParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} -⋮---- -export interface IsolatedMarginSymbol { - base: string; - isBuyAllowed: boolean; - isMarginTrade: boolean; - isSellAllowed: boolean; - quote: string; - symbol: string; - delistTime?: number; -} -⋮---- -export interface ToggleBNBBurnParams { - spotBNBBurn?: 'true' | 'false'; - interestBNBBurn?: 'true' | 'false'; -} -⋮---- -export interface BNBBurnResponse { - spotBNBBurn: boolean; - interestBNBBurn: boolean; -} -⋮---- -export interface QueryMarginInterestRateHistoryParams { - asset: string; - vipLevel?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface MarginInterestRateHistory { - asset: string; - dailyInterestRate: string; - timestamp: number; - vipLevel: number; -} -⋮---- -export interface QueryCrossMarginFeeDataParams { - vipLevel?: number; - coin?: string; -} -⋮---- -export interface CrossMarginFeeData { - vipLevel: number; - coin: string; - transferIn: boolean; - borrowable: boolean; - dailyInterest: string; - yearlyInterest: string; - borrowLimit: string; - marginablePairs: string[]; -} -⋮---- -export interface IsolatedMarginFeeData { - vipLevel: number; - symbol: string; - leverage: string; - data: { - coin: string; - dailyInterest: string; - borrowLimit: string; - }[]; -} -⋮---- -export interface QueryIsolatedMarginTierDataParams { - symbol: string; - tier?: number; -} -⋮---- -export interface IsolatedMarginTierData { - symbol: string; - tier: number; - effectiveMultiple: string; - initialRiskRatio: string; - liquidationRiskRatio: string; - baseAssetMaxBorrowable: string; - quoteAssetMaxBorrowable: string; -} -⋮---- -export interface GetMarginOrderCountUsageParams { - isIsolated?: string; - symbol?: string; -} -⋮---- -export interface MarginOrderCountUsageResponse { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} -⋮---- -export interface Collateral { - minUsdValue: string; - maxUsdValue?: string; - discountRate: 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 SmallLiabilityExchangeHistory { - asset: string; - amount: string; - targetAsset: string; - targetAmount: string; - bizType: string; - timestamp: number; -} -⋮---- -export interface GetNextHourlyInterestRateParams { - assets: string; - isIsolated: boolean; -} -⋮---- -export interface NextHourlyInterestRate { - asset: string; - nextHourlyInterestRate: string; -} -⋮---- -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 MarginAvailableInventoryResponse { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any; - updateTime: number; -} -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface ManualLiquidationParams { - type: string; - symbol?: string; -} -⋮---- -export interface ManualLiquidationResponse { - asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; -} -⋮---- -export interface LeverageBracket { - leverage: number; - maxDebt: number; - maintenanceMarginRate: number; - initialMarginRate: number; - fastNum: number; -} -⋮---- -export interface LiabilityCoinLeverageBracket { - assetNames: string[]; - rank: number; - brackets: LeverageBracket[]; -} -export interface GetFlexibleSubscriptionRecordParams { - productId?: string; - purchaseId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface GetFlexibleSubscriptionRecordResponse { - amount: string; - asset: string; - time: number; - purchaseId: number; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; - status: string; -} -⋮---- -export interface GetLockedSubscriptionRecordParams { - purchaseId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface LockedSubscriptionRecord { - positionId: string; - purchaseId: number; - time: 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 FlexibleRedemptionRecord { - amount: string; - asset: string; - time: number; - productId: string; - redeemId: number; - destAccount: string; - status: string; -} -⋮---- -export interface GetLockedRedemptionRecordParams { - positionId?: string; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface LockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; - asset: string; - lockPeriod: string; - amount: string; - type: string; - deliverDate: string; - status: string; -} -⋮---- -export interface GetFlexibleRewardsHistoryParams { - productId?: string; - asset?: string; - startTime?: number; - endTime?: number; - type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; - current?: number; - size?: number; -} -⋮---- -export interface FlexibleRewardsHistory { - asset: string; - rewards: string; - projectId: string; - type: string; - time: number; -} -⋮---- -export interface GetLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface GetLockedRewardsHistory { - positionId: string; - time: number; - asset: string; - lockPeriod: string; - amount: string; - type: string; -} -⋮---- -export interface SetAutoSubscribeParams { - productId: string; - autoSubscribe: boolean; -} -⋮---- -export interface GetFlexibleSubscriptionPreviewParams { - productId: string; - amount: number; -} -⋮---- -export interface FlexibleSubscriptionPreview { - totalAmount: string; - rewardAsset: string; - airDropAsset: string; - estDailyBonusRewards: string; - estDailyRealTimeRewards: string; - estDailyAirdropRewards: string; -} -⋮---- -export interface GetLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; -} -⋮---- -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 GetRateHistoryParams { - productId: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface GetRateHistory { - productId: string; - asset: string; - annualPercentageRate: string; - time: number; -} -⋮---- -export interface GetCollateralRecordParams { - productId?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface CollateralRecord { - amount: string; - productId: string; - asset: string; - createTime: number; - type: string; - productName: string; - orderId: number; -} -⋮---- -export interface GetDualInvestmentProductListParams { - optionType: string; - exercisedCoin: string; - investCoin: string; - pageSize?: number; - pageIndex?: 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 SubscribeDualInvestmentProductParams { - id: string; - orderId: string; - depositAmount: number; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} -⋮---- -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 GetDualInvestmentPositionsParams { - status?: - | 'PENDING' - | 'PURCHASE_SUCCESS' - | 'SETTLED' - | 'PURCHASE_FAIL' - | 'REFUNDING' - | 'REFUND_SUCCESS' - | 'SETTLING'; - pageSize?: number; - pageIndex?: 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 CheckDualInvestmentAccountsResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; -} -⋮---- -export interface ChangeAutoCompoundStatusParams { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} -⋮---- -export interface ChangeAutoCompoundStatusResponse { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} -⋮---- -export interface GetTargetAssetListParams { - targetAsset?: string; - size?: number; - current?: number; -} -⋮---- -export interface RoiAndDimensionType { - simulateRoi: string; - dimensionValue: string; - dimensionUnit: string; -} -⋮---- -export interface AutoInvestAsset { - targetAsset: string; - roiAndDimensionTypeList: RoiAndDimensionType[]; -} -⋮---- -export interface GetTargetAssetListResponse { - targetAssets: string[]; - autoInvestAssetList: AutoInvestAsset[]; -} -⋮---- -export interface GetTargetAssetROIParams { - targetAsset: string; - hisRoiType: - | 'FIVE_YEAR' - | 'THREE_YEAR' - | 'ONE_YEAR' - | 'SIX_MONTH' - | 'THREE_MONTH' - | 'SEVEN_DAY'; -} -⋮---- -export interface TargetAssetROI { - date: string; - simulateRoi: string; -} -⋮---- -export interface GetSourceAssetListParams { - targetAsset?: string[]; - indexId?: number; - usageType: 'RECURRING' | 'ONE_TIME'; - flexibleAllowedToUse?: boolean; - sourceType?: 'MAIN_SITE' | 'TR'; -} -⋮---- -export interface SourceAsset { - sourceAsset: string; - assetMinAmount: string; - assetMaxAmount: string; - scale: string; - flexibleAmount: string; -} -⋮---- -export interface GetSourceAssetListResponse { - feeRate: string; - taxRate: string; - sourceAssets: SourceAsset[]; -} -⋮---- -export interface AutoInvestPortfolioDetail { - targetAsset: string; - percentage: number; -} -⋮---- -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 CreateInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; -} -⋮---- -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 EditInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; -} -⋮---- -export interface ChangePlanStatusParams { - planId: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; -} -⋮---- -export interface ChangePlanStatusResponse { - planId: number; - nextExecutionDateTime: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; -} -⋮---- -export interface GetPlanDetailsParams { - planId?: number; - requestId?: string; -} -⋮---- -export interface GetSubscriptionTransactionHistoryParams { - planId?: number; - 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; -} -⋮---- -export interface GetOneTimeTransactionStatusResponse { - transactionId: number; - status: 'SUCCESS' | 'CONVERTING'; -} -⋮---- -export interface SubmitIndexLinkedPlanRedemptionParams { - indexId: number; - requestId?: string; - redemptionPercentage: number; -} -⋮---- -export interface GetIndexLinkedPlanRedemptionHistoryParams { - requestId: number; - startTime?: number; - endTime?: number; - current?: number; - asset?: string; - size?: number; -} -⋮---- -export interface IndexLinkedPlanRedemptionRecord { - indexId: number; - indexName: string; - redemptionId: number; - status: 'SUCCESS' | 'FAILED'; - asset: string; - amount: string; - redemptionDateTime: number; - transactionFee: string; - transactionFeeUnit: string; -} -⋮---- -export interface GetIndexLinkedPlanRebalanceHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RebalanceTransactionDetail { - 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; -} -⋮---- -export interface GetEthStakingHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface EthStakingHistory { - time: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAmount: string; - conversionRatio: string; -} -⋮---- -export interface GetEthRedemptionHistoryParams { - 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; -} -⋮---- -export interface GetBethRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BethRewardsHistory { - time: number; - asset: string; - holding: string; - amount: string; - annualPercentageRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; -} -⋮---- -export interface GetEthStakingQuotaResponse { - leftStakingPersonalQuota: string; - leftRedemptionPersonalQuota: 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 GetEthStakingAccountV2Response { - holdingInETH: string; - holdings: { - wbethAmount: string; - bethAmount: string; - }; - thirtyDaysProfitInETH: string; - profit: { - amountFromWBETH: string; - amountFromBETH: string; - }; -} -⋮---- -export interface WrapBethResponse { - success: boolean; - wbethAmount: string; - exchangeRate: string; -} -⋮---- -export interface GetWrapHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface WrapHistory { - time: number; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - exchangeRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; -} -⋮---- -export interface WbethRewardsHistory { - time: number; - amountInETH: string; - holding: string; - holdingInETH: string; - annualPercentageRate: string; -} -⋮---- -export interface GetWbethRewardsHistoryResponse { - estRewardsInETH: string; - rows: WbethRewardsHistory[]; - total: number; -} -⋮---- -/** - * BFUSD (sapi/v1/bfusd/*) - */ -⋮---- -export interface BfusdAccountResponse { - bfusdAmount: string; - usdtProfit: string; - bfusdProfit: string; -} -⋮---- -export interface BfusdSubscriptionQuota { - leftQuota: string; -} -⋮---- -export interface BfusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; -} -⋮---- -export interface BfusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; -} -⋮---- -export interface BfusdQuotaResponse { - subscriptionQuota: BfusdSubscriptionQuota; - fastRedemptionQuota: BfusdFastRedemptionQuota; - standardRedemptionQuota: BfusdStandardRedemptionQuota; -} -⋮---- -export interface BfusdSubscribeParams { - asset: string; - amount: number; -} -⋮---- -export interface BfusdSubscribeResponse { - success: boolean; - bfusdAmount: string; -} -⋮---- -export interface BfusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; -} -⋮---- -export interface BfusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; -} -⋮---- -export interface GetBfusdSubscriptionHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BfusdSubscriptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetBfusdRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BfusdRedemptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetBfusdRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: 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; - current?: number; - size?: number; -} -⋮---- -export interface BfusdRateHistoryRow { - annualPercentageRate: string; - 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; -} -⋮---- -export interface GetRwusdSubscriptionHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdSubscriptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetRwusdRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdRedemptionHistoryRow { - time: number; - asset: 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; -} -⋮---- -export interface RwusdRewardsHistoryRow { - time: number; - rewardsAmount: string; - rwusdPosition: string; - annualPercentageRate: string; -} -⋮---- -export interface GetRwusdRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdRateHistoryRow { - annualPercentageRate: string; - time: number; -} -⋮---- -export interface GetMiningAlgoListResponse { - algoName: string; // Algorithm name - algoId: number; // Algorithm ID - poolIndex: number; // Sequence - unit: string; // Unit -} -⋮---- -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 -} -⋮---- -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 HashrateData { - time: number; - hashrate: string; - reject: number; -} -⋮---- -export interface MinerDetail { - workerName: string; - type: string; - hashrateDatas: HashrateData[]; -} -⋮---- -export interface GetMinerDetailsResponse { - code: number; - msg: string; - data: MinerDetail[]; -} -⋮---- -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 GetMinerListResponse { - code: number; - msg: string; - data: { - workerDatas: WorkerData[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetEarningsListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface AccountEarningsProfit { - time: number; - type: number; - hashTransfer: number | null; - transferAmount: number | null; - dayHashRate: number; - profitAmount: number; - coinName: string; - status: number; -} -⋮---- -export interface GetEarningsListResponse { - code: number; - msg: string; - data: { - accountProfits: AccountEarningsProfit[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetExtraBonusListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface OtherProfit { - time: number; - coinName: string; - type: number; - profitAmount: number; - status: number; -} -⋮---- -export interface GetExtraBonusListResponse { - code: number; - msg: string; - data: { - otherProfits: OtherProfit[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetHashrateResaleListParams { - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface ConfigDetail { - configId: number; - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - startDay: number; - endDay: number; - status: number; -} -⋮---- -export interface GetHashrateResaleListResponse { - code: number; - msg: string; - data: { - configDetails: ConfigDetail[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetHashrateResaleDetailParams { - configId: number; - userName: string; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface ProfitTransferDetail { - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - day: number; - amount: number; - coinName: string; -} -⋮---- -export interface GetHashrateResaleDetailResponse { - code: number; - msg: string; - data: { - profitTransferDetails: ProfitTransferDetail[]; - totalNum: number; - pageSize: number; - }; -} -export interface SubmitHashrateResaleParams { - userName: string; - algo: string; - endDate: number; - startDate: number; - toPoolUser: string; - hashRate: number; -} -⋮---- -export interface CancelHashrateResaleConfigParams { - configId: number; - userName: string; -} -⋮---- -export interface GetStatisticListParams { - algo: string; - userName: string; -} -⋮---- -export interface Profit { - BTC: string; - BSV: string; - BCH: string; -} -⋮---- -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 getMiningAccountsListParams { - algo: string; - userName: string; -} -⋮---- -export interface MiningHashrateData { - time: number; - hashrate: string; - reject: string; -} -⋮---- -export interface MiningAccountData { - type: string; - userName: string; - list: MiningHashrateData[]; -} -⋮---- -export interface getMiningAccountsListResponse { - code: number; - msg: string; - data: MiningAccountData[]; -} -⋮---- -export interface GetMiningAccountEarningParams { - algo: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface AccountMiningProfit { - time: number; - coinName: string; - type: number; - puid: number; - subName: string; - amount: number; -} -⋮---- -export interface GetMiningAccountEarningResponse { - code: number; - msg: string; - data: { - accountProfits: AccountMiningProfit[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetFutureTickLevelOrderbookDataLinkParams { - symbol: string; - dataType: 'T_DEPTH' | 'S_DEPTH'; - startTime: number; - endTime: number; -} -⋮---- -export interface HistoricalDataLink { - day: string; - url: string; -} -⋮---- -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 SubmitVpNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: 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 SubmitTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface CancelAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: 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 GetAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; - startTime?: number; - endTime?: number; - page?: number; - pageSize?: 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 GetAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: 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 GetAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SubOrder[]; -} -⋮---- -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 SubmitSpotTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface CancelSpotAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: 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 GetSpotAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; - startTime?: number; - endTime?: number; - page?: number; - pageSize?: 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 GetSpotAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: 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 GetSpotAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SpotSubOrder[]; -} -⋮---- -export interface GetPortfolioMarginProAccountInfoResponse { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - accountStatus: string; - accountType: string; -} -⋮---- -export interface GetPortfolioMarginProCollateralRateResponse { - asset: string; - collateralRate: string; -} -⋮---- -export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { - asset: string; - amount: string; -} -⋮---- -export interface GetPortfolioMarginProInterestHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; -} -⋮---- -export interface GetPortfolioMarginProInterestHistoryResponse { - asset: string; - interest: string; - interestAccruedTime: number; - interestRate: string; - principal: string; -} -⋮---- -export interface GetPortfolioMarginAssetIndexPriceResponse { - asset: string; - assetIndexPrice: string; - time: number; -} -⋮---- -export interface BnbTransferParams { - amount: number; - transferSide: 'TO_UM' | 'FROM_UM'; -} -⋮---- -export interface GetPortfolioMarginAssetLeverageResponse { - asset: string; - leverage: number; -} -⋮---- -export interface SetPortfolioMarginMarginCallLevelParams { - marginCallLevel: number; -} -⋮---- -export interface PortfolioMarginMarginCallLevelResponse { - marginCallLevel: string; -} -⋮---- -export type PortfolioMarginMarginCallLevelGetResponse = - | PortfolioMarginMarginCallLevelResponse - | Record; -⋮---- -export interface PortfolioMarginMarginCallLevelDeleteResponse { - msg: string; -} -⋮---- -export interface SubscribeBlvtParams { - tokenName: string; - cost: number; -} -⋮---- -export interface SubscribeBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - amount: string; - cost: string; - timestamp: number; -} -⋮---- -export interface GetBlvtSubscriptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface BlvtSubscriptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; - fee: string; - totalCharge: string; - timestamp: number; -} -⋮---- -export interface RedeemBlvtParams { - tokenName: string; - amount: number; -} -⋮---- -export interface RedeemBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - redeemAmount: string; - amount: string; - timestamp: number; -} -⋮---- -export interface GetBlvtRedemptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface BlvtRedemptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; - fee: string; - netProceed: string; - timestamp: number; -} -⋮---- -export interface BlvtUserLimitInfo { - tokenName: string; - userDailyTotalPurchaseLimit: string; - userDailyTotalRedeemLimit: string; -} -⋮---- -export interface GetFiatOrderHistoryParams { - transactionType: string; - beginTime?: number; - endTime?: number; - page?: number; - rows?: 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 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; -} -⋮---- -export interface WithdrawFiatAccountInfo { - accountNumber: string; - agency: string; - bankCodeForPix: string; - accountType: string; -} -⋮---- -export interface WithdrawFiatParams { - currency: string; - apiPaymentMethod: string; - amount: number; - accountInfo?: WithdrawFiatAccountInfo; -} -⋮---- -export interface FiatDepositParams { - currency: string; - apiPaymentMethod: string; - amount: number; - ext?: object; - recvWindow?: number; - timestamp?: number; -} -⋮---- -export interface FiatDepositResponse { - code: string; - message: string; - data: { - orderId: string; - }; -} -⋮---- -export interface GetFiatOrderDetailParams { - orderNo: string; - recvWindow?: number; - timestamp?: 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; - }; -} -⋮---- -export interface GetC2CTradeHistoryParams { - tradeType: string; - startTimestamp?: number; - endTimestamp?: number; - page?: number; - rows?: number; -} -⋮---- -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 GetC2CTradeHistoryResponse { - code: string; - message: string; - data: c2cTradeData[]; - total: number; - success: boolean; -} -⋮---- -export interface GetVipLoanOngoingOrdersParams { - orderId?: number; - collateralAccountId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: 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 VipLoanRepayParams { - orderId: number; - amount: number; -} -⋮---- -export interface VipLoanRepayResponse { - loanCoin: string; - repayAmount: string; - remainingPrincipal: string; - remainingInterest: string; - collateralCoin: string; - currentLTV: string; - repayStatus: string; -} -⋮---- -export interface GetVipLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface VipLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - repayStatus: string; - loanDate: string; - repayTime: string; - orderId: string; -} -⋮---- -export interface VipLoanRenewParams { - orderId: number; - loanTerm?: number; -} -⋮---- -export interface VipLoanRenewResponse { - loanAccountId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; -} -⋮---- -export interface CheckVipCollateralAccountParams { - orderId?: number; - collateralAccountId?: number; -} -⋮---- -export interface VipCollateralAccount { - collateralAccountId: string; - collateralCoin: string; -} -⋮---- -export interface VipLoanBorrowParams { - loanAccountId: number; - loanCoin: string; - loanAmount: number; - collateralAccountId: string; - collateralCoin: string; - isFlexibleRate: boolean; - loanTerm?: number; -} -⋮---- -export interface VipLoanBorrowResponse { - loanAccountId: string; - requestId: string; - loanCoin: string; - isFlexibleRate: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm?: string; -} -⋮---- -export interface GetLoanableAssetsDataParams { - loanCoin?: string; - vipLevel?: number; -} -⋮---- -export interface GetApplicationStatusParams { - current?: number; - limit?: 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 BorrowInterestRate { - asset: string; - flexibleDailyInterestRate: string; - flexibleYearlyInterestRate: string; - time: number; -} -⋮---- -export interface GetCryptoLoansIncomeHistoryParams { - asset?: string; - type?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetCryptoLoansIncomeHistoryResponse { - asset: string; - type: string; - amount: string; - timestamp: number; - tranId: string; -} -⋮---- -export interface BorrowCryptoLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; - loanTerm: number; -} -⋮---- -export interface BorrowCryptoLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - hourlyInterestRate: string; - orderId: string; -} -⋮---- -export interface GetLoanBorrowHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface LoanBorrowHistory { - orderId: number; - loanCoin: string; - initialLoanAmount: string; - hourlyInterestRate: string; - loanTerm: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: string; -} -⋮---- -export interface GetLoanOngoingOrdersParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} -⋮---- -export interface LoanOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - residualInterest: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; - expirationTime: number; -} -⋮---- -export interface RepayCryptoLoanParams { - orderId: number; - amount: number; - type?: number; - collateralReturn?: boolean; -} -⋮---- -export interface RepayCryptoLoanResponse { - loanCoin: string; - remainingPrincipal?: string; - remainingInterest?: string; - collateralCoin: string; - remainingCollateral?: string; - currentLTV?: string; - repayStatus: string; -} -⋮---- -export interface GetLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface LoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralUsed: string; - collateralReturn: string; - repayType: string; - repayStatus: string; - repayTime: number; - orderId: number; -} -⋮---- -export interface AdjustCryptoLoanLTVParams { - orderId: number; - amount: number; - direction: 'ADDITIONAL' | 'REDUCED'; -} -⋮---- -export interface AdjustCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - currentLTV: string; -} -⋮---- -export interface GetLoanLTVAdjustmentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface LoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; - orderId: number; -} -⋮---- -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 GetCollateralAssetDataParams { - collateralCoin?: string; - vipLevel?: number; -} -⋮---- -export interface CollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; - vipLevel: number; -} -⋮---- -export interface CheckCollateralRepayRateParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; -} -⋮---- -export interface CheckCollateralRepayRateResponse { - loanCoin: string; - collateralCoin: string; - repayAmount: string; - rate: string; -} -⋮---- -export interface CustomizeMarginCallParams { - orderId?: number; - collateralCoin?: string; - marginCall: number; -} -⋮---- -export interface CustomizeMarginCall { - orderId: string; - collateralCoin: string; - preMarginCall: string; - afterMarginCall: string; - customizeTime: number; -} -⋮---- -export interface BorrowFlexibleLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; -} -⋮---- -export interface BorrowFlexibleLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - status: 'Succeeds' | 'Failed' | 'Processing'; -} -⋮---- -export interface GetFlexibleLoanOngoingOrdersParams { - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleLoanOngoingOrder { - loanCoin: string; - totalDebt: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; -} -⋮---- -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; -} -⋮---- -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 GetFlexibleCryptoLoanBorrowHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleCryptoLoanBorrowHistory { - loanCoin: string; - initialLoanAmount: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: 'Succeeds' | 'Failed' | 'Processing'; -} -⋮---- -export interface RepayCryptoFlexibleLoanParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; - collateralReturn?: boolean; - fullRepayment?: boolean; -} -⋮---- -export interface RepayCryptoFlexibleLoanResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; -} -⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; // Amount of loan to repay - fullRepayment?: boolean; // Default: FALSE -} -⋮---- -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 FlexibleCryptoLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralReturn: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; - repayTime: number; -} -⋮---- -export interface AdjustFlexibleCryptoLoanLTVParams { - loanCoin: string; - collateralCoin: string; - adjustmentAmount: number; - direction: 'ADDITIONAL' | 'REDUCED'; -} -⋮---- -export interface AdjustFlexibleCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - adjustmentAmount: string; - currentLTV: string; -} -⋮---- -export interface GetFlexibleLoanLTVAdjustmentHistoryParams { - loanCoin?: string; - collateralCoin?: string; - 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; -} -⋮---- -export interface FlexibleLoanCollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; -} -⋮---- -export interface GetFuturesLeadTraderStatusResponse { - code: string; - message: string; - data: { - isLeadTrader: boolean; - time: number; - }; - success: boolean; -} -⋮---- -export interface GetFuturesLeadTradingSymbolWhitelistResponse { - code: string; - message: string; - data: { - symbol: string; - baseAsset: string; - quoteAsset: string; - }[]; -} -⋮---- -export interface GetPayTradeHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetAllConvertPairsParams { - fromAsset?: string; - toAsset?: 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 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 GetSpotRebateHistoryRecordsParams { - startTime?: number; - endTime?: number; - page?: number; -} -⋮---- -export interface SpotRebateHistoryRecord { - asset: string; - type: number; - amount: string; - updateTime: number; -} -⋮---- -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; - limit?: number; - page?: number; -} -⋮---- -export interface NftToken { - network: string; - tokenId: string; - contractAddress: string; -} -⋮---- -export interface NftTransaction { - orderNo: string; - tokens: NftToken[]; - tradeTime: number; - tradeAmount: string; - tradeCurrency: string; -} -⋮---- -export interface GetNftDepositHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} -⋮---- -export interface NftDeposit { - network: string; - txID: string | null; - contractAdrress: string; - tokenId: string; - timestamp: number; -} -⋮---- -export interface GetNftWithdrawHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} -⋮---- -export interface NftWithdraw { - network: string; - txID: string; - contractAdrress: string; - tokenId: 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; - 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 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; - }; -} -⋮---- -export interface SimpleEarnSubscribeProductParams { - productId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; -} -⋮---- -export interface SimpleEarnSubscribeFlexibleProductResponse { - purchaseId: string; - success: boolean; -} -⋮---- -export interface SimpleEarnSubscribeLockedProductResponse { - purchaseId: string; - positionId: string; - success: boolean; -} -⋮---- -export interface SimpleEarnRedeemFlexibleProductParams { - productId: string; - redeemAll?: boolean; - amount?: number; - destAccount?: 'SPOT' | 'FUND'; -} -⋮---- -export interface SimpleEarnRedeemResponse { - success: boolean; - redeemId: string; -} -⋮---- -export interface SimpleEarnFlexibleProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; -} -⋮---- -export interface SimpleEarnLockedProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; - positionId?: string; -} -⋮---- -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 SimpleEarnAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedinBTC: string; - totalLockedinUSDT: string; -} -⋮---- -export interface GetSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: 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; -} -⋮---- -// Request interface for querying sub account spot asset info -export interface QuerySubAccountSpotMarginAssetInfoParams { - subAccountId?: string; - page?: number; - size?: number; -} -⋮---- -export interface SubaccountBrokerSpotAsset { - subAccountId: string; - totalBalanceOfBtc: string; -} -⋮---- -export interface SubAccountBrokerMarginAsset { - marginEnable: boolean; - subAccountId: string; - totalAssetOfBtc?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - marginLevel?: string; -} -⋮---- -// 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; -} -⋮---- -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; - totalWalletBalance: string; - totalUnrealizedProfit: string; - totalMarginBalance: string; - totalPositionInitialMargin: string; - totalOpenOrderInitialMargin: string; - futuresEnable: boolean; - asset: string; -} -⋮---- -// 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 BrokerUniversalTransfer { - toId: string; - asset: string; - qty: string; - time: number; - status: string; - txnId: string; - clientTranId: string; - fromAccountType: string; - toAccountType: string; -} -⋮---- -// 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; -} -⋮---- -// Request interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface QuerySubAccountFuturesCommissionParams { - subAccountId: string; - symbol?: string; -} -⋮---- -// Response interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface BrokerSubAccountFuturesCommission { - subAccountId: string; - symbol: string; - makerCommission: number; - takerCommission: number; -} -⋮---- -export interface ChangeSubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair: string; - makerAdjustment: number; - takerAdjustment: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface QuerySubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -// Response interface for querying sub account COIN-Ⓜ futures commission adjustment -export interface BrokerSubAccountCoinFuturesCommission { - subAccountId: string; - pair: string; - makerCommission: number; - takerCommission: number; -} -⋮---- -export interface QueryBrokerSpotCommissionRebateParams { - subAccountId?: string; - startTime?: number; - endTime?: number; - page?: number; - size?: number; - recvWindow?: number; - timestamp: 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 QueryBrokerFuturesCommissionRebateParams { - futuresType: number; // 1: USDT Futures, 2: Coin Futures - startTime: number; - endTime: number; - page?: number; - size?: number; - filterResult?: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -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'; -} -⋮---- -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 CreateSpecialLowLatencyKeyParams { - apiName: string; - symbol?: string; - ip?: string; - publicKey?: string; -} -⋮---- -export interface SpecialLowLatencyKeyResponse { - apiKey: string; - secretKey: string | null; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; -} -⋮---- -export interface SpecialLowLatencyKeyInfo { - apiName: string; - apiKey: string; - ip: string; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; -} -⋮---- -export interface MarginLiquidationLoan { - asset: string; - amount: string; - repaidAmount: string; - remainingAmount: string; -} -⋮---- -export interface RepayMarginLiquidationLoanParams { - asset: string; - amount: string; -} -⋮---- -export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; -⋮---- -export interface MarginLiquidationLoanRepayResponse { - repayId: number; - asset: string; - amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; -} -⋮---- -export interface GetMarginLiquidationLoanRepayHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface MarginLiquidationLoanRepayHistoryRecord { - repayId: number; - asset: string; - amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; -} -⋮---- -export interface MarginLiquidationLoanRepayHistoryResponse { - total: number; - rows: MarginLiquidationLoanRepayHistoryRecord[]; -} -⋮---- -export interface SolStakingAccount { - bnsolAmount: string; // Amount in bNSOL - holdingInSOL: string; // Holding in SOL - thirtyDaysProfitInSOL: string; // 30 days profit in SOL -} -⋮---- -bnsolAmount: string; // Amount in bNSOL -holdingInSOL: string; // Holding in SOL -thirtyDaysProfitInSOL: string; // 30 days profit in SOL -⋮---- -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 -} -⋮---- -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 SubscribeSolStakingResponse { - success: boolean; // Indicates if the subscription was successful - bnsolAmount: string; // Amount in bNSOL received - exchangeRate: string; // SOL amount per 1 BNSOL -} -⋮---- -success: boolean; // Indicates if the subscription was successful -bnsolAmount: string; // Amount in bNSOL received -exchangeRate: string; // SOL amount per 1 BNSOL -⋮---- -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 -} -⋮---- -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 -} -⋮---- -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 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 -} -⋮---- -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 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 -} -⋮---- -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 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 -} -⋮---- -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 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 -} -⋮---- -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 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%) -} -⋮---- -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 -} -⋮---- -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 SolBoostRewardsHistoryReq { - type: 'CLAIM' | 'DISTRIBUTE'; - startTime?: number; - endTime?: number; - current?: number; - size?: 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" -} -⋮---- -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 -} -⋮---- -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 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) -} -⋮---- -accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) -⋮---- -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 -} -⋮---- -optionWalletBalance: string; // only for PM PRO SPAN -optionEquity: string; // only for PM PRO SPAN -⋮---- -export interface PMProMintBFUSDParams { - fromAsset: string; // USDT only - targetAsset: string; // BFUSD only - amount: number; -} -⋮---- -fromAsset: string; // USDT only -targetAsset: string; // BFUSD only -⋮---- -export interface PMProMintBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; -} -⋮---- -export interface PMProRedeemBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; -} -⋮---- -export interface PMProBankruptcyLoanRepaymentHistory { - asset: string; - amount: string; - repayTime: number; -} -⋮---- -export interface VipLoanInterestRateHistoryParams { - coin: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface VipLoanInterestRateRecord { - coin: string; - annualizedInterestRate: string; - time: number; -} -⋮---- -export interface VipLoanAccruedInterestParams { - orderId?: number; - loanCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: 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 GetTravelRuleWithdrawHistoryParams { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -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 SubmitTravelRuleDepositQuestionnaireParams { - tranId: number; - questionnaire: 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 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 SubmitTravelRuleDepositQuestionnaireResponse { - trId: number; - accepted: boolean; - info: 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 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; -} -⋮---- -/** 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 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; - principal: string; - interest: string; -} -⋮---- -export interface InstitutionalLoanWallet { - accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; -} -⋮---- -export interface InstitutionalLoanCollateralAccount { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - wallets: InstitutionalLoanWallet[]; -} -⋮---- -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 GetInstitutionalLoanRiskUnitDetailsParams { - groupId?: number; -} -⋮---- -export interface CloseInstitutionalLoanRiskUnitResponse { - groupId: number; - status: 'CLOSED'; -} -⋮---- -export interface AddInstitutionalLoanCollateralAccountParams { - groupId: number; - subEmail: string; - enableSpot: boolean; - enableMargin: boolean; -} -⋮---- -export interface InstitutionalLoanRiskUnitMember { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - enableMargin: boolean; - enableSpot: boolean; -} -⋮---- -export interface ActiveInstitutionalLoanRiskUnit { - groupId: number; - members: InstitutionalLoanRiskUnitMember[]; - createTime: number; -} -export interface ClosedInstitutionalLoanRiskUnit { - groupId: number; - parentEmail: string; - creditEmail: string; - enabled: boolean; - createTime: number; - closeTime: number; -} -⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsParams { - current?: number; - size?: number; -} -⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsResponse { - total: number; - rows: ClosedInstitutionalLoanRiskUnit[]; -} -⋮---- -// 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 InstitutionalLoanLiquidationSnapshotData { - snapshots: InstitutionalLoanLiquidationSnapshot[]; - liabilities: InstitutionalLoanLiability[]; -} -⋮---- -export interface InstitutionalLoanForceLiquidationRecord { - groupId: number; - startLtv: number; - endLtv: number; - liquidationStartTime: number; - liquidationEndTime: number; - totalNetEquity: string; - totalMaintenanceMargin: string; - totalLiability: string; - liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; -} -⋮---- -export interface GetInstitutionalLoanForceLiquidationParams { - groupId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface GetInstitutionalLoanForceLiquidationResponse { - total: number; - rows: InstitutionalLoanForceLiquidationRecord[]; -} -⋮---- -// 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 -} -⋮---- -subEmail?: string; // Optional: subEmail can be credit account or collateral account -asset: string; // Asset Name -amount: number; // Transfer amount of the asset -⋮---- -// 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; - amount: number; -} -⋮---- -export interface InstitutionalLoanBorrowResponse { - transactionId: string; - amount: number; - status: string; -} -⋮---- -export interface InstitutionalLoanRepayParams { - groupId: number; - assetName: string; - amount: number; -} -⋮---- -export interface InstitutionalLoanRepayResponse { - transactionId: string; - amount: number; -} -⋮---- -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; -} -⋮---- -export interface InstitutionalLoanInterestHistoryResponse { - total: number; - rows: InstitutionalLoanInterestHistoryRecord[]; -} -⋮---- -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 -} -⋮---- -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 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 -} -⋮---- -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 GetInstitutionalLoanBorrowRepayRecordsResponse { - total: number; - rows: InstitutionalLoanBorrowRepayRecord[]; -} -⋮---- -export interface MarginInterestRebateBalanceResponse { - asset: string; - balance: string; - totalGranted: string; - totalConsumed: string; -} -⋮---- -export interface GetMarginInterestRebateBalanceRecordsParams { - type?: 0 | 1 | 2; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface MarginInterestRebateBalanceRecord { - type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; - rebateAsset: string; - delta: string; - createTime: number; - groupId?: number; - liabilityAsset?: string; - deductedInterest?: string; - exchangeRate?: string; -} -⋮---- -export interface MarginInterestRebateBalanceRecordsResponse { - total: number; - rows: MarginInterestRebateBalanceRecord[]; -} -⋮---- -// On-chain Yields types -⋮---- -export interface OnchainYieldsLockedProductListParams { - asset?: string; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedProductDetail { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: 'PREHEATING' | 'PURCHASING'; - subscriptionStartTime: string; - canRedeemToFlex: boolean; -} -⋮---- -export interface OnchainYieldsLockedProductQuota { - totalPersonalQuota: string; - minimum: string; -} -⋮---- -export interface OnchainYieldsLockedProduct { - projectId: string; - detail: OnchainYieldsLockedProductDetail; - quota: OnchainYieldsLockedProductQuota; -} -⋮---- -export interface OnchainYieldsLockedProductListResponse { - rows: OnchainYieldsLockedProduct[]; - total: number; -} -⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaParams { - projectId: string; -} -⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaResponse { - leftPersonalQuota: string; -} -⋮---- -export interface OnchainYieldsLockedPositionParams { - asset?: string; - positionId?: number; - projectId?: string; - current?: number; - size?: number; -} -⋮---- -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'; -} -⋮---- -export interface OnchainYieldsLockedPositionResponse { - rows: OnchainYieldsLockedPosition[]; - total: number; -} -⋮---- -export interface OnchainYieldsAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedInBTC: string; - totalLockedInUSDT: string; -} -⋮---- -// On-chain Yields Earn types -⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; -} -⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewResponse { - rewardAsset: string; - totalRewardAmt: string; - nextPay?: string; - nextPayDate?: string; - rewardsPayDate?: string; - valueDate: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; -} -⋮---- -export interface OnchainYieldsLockedSubscribeParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; - redeemTo?: 'SPOT' | 'FLEXIBLE'; - channelId?: string; - clientId?: string; -} -⋮---- -export interface OnchainYieldsLockedSubscribeResponse { - purchaseId: number; - positionId: string; - amount: string; - success: boolean; -} -⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeParams { - positionId: string; - autoSubscribe: boolean; -} -⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeResponse { - success: boolean; -} -⋮---- -export interface OnchainYieldsLockedSetRedeemOptionParams { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; -} -⋮---- -export interface OnchainYieldsLockedSetRedeemOptionResponse { - success: boolean; -} -⋮---- -export interface OnchainYieldsLockedRedeemParams { - positionId: number; - channelId?: string; -} -⋮---- -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; -} -⋮---- -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'; -} -⋮---- -export interface OnchainYieldsLockedSubscriptionRecordResponse { - rows: OnchainYieldsLockedSubscriptionRecord[]; - total: number; -} -⋮---- -export interface OnchainYieldsLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedRewardsRecord { - positionId: string; - time: number; - asset: string; - lockPeriod: string; - amount: string; -} -⋮---- -export interface OnchainYieldsLockedRewardsHistoryResponse { - rows: OnchainYieldsLockedRewardsRecord[]; - total: number; -} -⋮---- -export interface OnchainYieldsLockedRedemptionRecordParams { - positionId?: number; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -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'; -} -⋮---- -export interface OnchainYieldsLockedRedemptionRecordResponse { - rows: OnchainYieldsLockedRedemptionRecord[]; - total: number; -} -⋮---- -/** - * ALPHA TRADING INTERFACES - */ -⋮---- -export interface AlphaToken { - alphaId: number; - symbol: string; - name: string; - chainId: string; - contractAddress: string; - decimals?: 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; -} -⋮---- -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 AlphaAsset { - asset: string; -} -⋮---- -export interface AlphaExchangeInfo { - timezone: string; - assets: AlphaAsset[]; - symbols: AlphaSymbol[]; -} -⋮---- -export interface AlphaAggTradesParams { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: 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 -} -⋮---- -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; - startTime?: number; - endTime?: 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") -]; -⋮---- -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 AlphaTickerParams { - symbol: string; -} -⋮---- -export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; -⋮---- -export interface AlphaFullDepthParams { - symbol: string; - limit?: AlphaFullDepthLimit; -} -⋮---- -export interface AlphaFullDepthData { - lastUpdateId: number; - symbol: string; - bids: [string, string][]; - asks: [string, string][]; - E: number; - T: number; -} -⋮---- -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; -} -⋮---- -/** - * Soft Staking interfaces - */ -export interface GetSoftStakingProductListParams { - asset?: string; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SoftStakingProduct { - asset: string; - minAmount: string; - maxCap: string; - apr: string; - stakedAmount: string; - totalProfit: string; -} -⋮---- -export interface GetSoftStakingProductListResponse { - status: boolean; - totalRewardsUsdt: string; - rows: SoftStakingProduct[]; - total: number; -} -⋮---- -export interface SetSoftStakingParams { - softStaking: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SetSoftStakingResponse { - success: boolean; -} -⋮---- -export interface GetSoftStakingRewardsHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -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'; - -/** - * 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); -}); - -/** - * Subscribe to public topics either one at a time or many in an array - */ - -// E.g. one at a time, routed to the coinm futures websockets: -wsClient.subscribe('btcusd@indexPrice', 'coinm'); -wsClient.subscribe('btcusd@miniTicker', 'coinm'); - -// Or send many topics at once to a stream, e.g. the usdm futures stream: -wsClient.subscribe( - ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], - 'usdm', -); - -// 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', -); - -/** - * 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(); -``` - -See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. - -#### Preserving large integers in WebSocket messages - -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`. - -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: - -```ts -import { WebsocketClient } from 'binance'; - -/** - * 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); - // }, - - // 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'); - -/** - * 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 -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; -⋮---- -import { - AmendKeepPriorityParams, - BasicAssetPaginatedParams, - BasicAssetParam, - BasicSymbolParam, - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - CoinStartEndLimit, - ExchangeSymbol, - GetAllOrdersParams, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, - NewOCOParams, - NewOrderListParams, - OrderBookParams, - OrderIdProperty, - OrderResponseType, - OrderType, - RecentTradesParams, - RowsWithTotal, - SymbolFromPaginatedRequestFromId, - SymbolPrice, -} from './types/shared'; -import { - AcceptQuoteRequestParams, - AccountInfo, - AccountInformation, - ActiveInstitutionalLoanRiskUnit, - AddBSwapLiquidityParams, - AddInstitutionalLoanCollateralAccountParams, - AddIpRestriction, - AdjustCryptoLoanLTVParams, - AdjustCryptoLoanLTVResponse, - AdjustFlexibleCryptoLoanLTVParams, - AdjustFlexibleCryptoLoanLTVResponse, - AggregateTrade, - AlgoOrder, - AllCoinsInformationResponse, - Allocation, - AllocationsParams, - AlphaAggTrade, - AlphaAggTradesParams, - AlphaExchangeInfo, - AlphaFullDepthParams, - AlphaFullDepthResponse, - AlphaKline, - AlphaKlinesParams, - AlphaTicker, - AlphaToken, - ApiKeyBrokerSubAccount, - APIPermissions, - APITradingStatus, - ApplicationStatus, - AssetDetail, - BasicFromPaginatedParams, - BasicFuturesSubAccountParams, - BasicMarginAssetParams, - BasicSubAccount, - BasicTimeRangeParam, - BethRewardsHistory, - BfusdAccountResponse, - BfusdQuotaResponse, - BfusdRateHistoryRow, - BfusdRedeemParams, - BfusdRedeemResponse, - BfusdRedemptionHistoryRow, - BfusdRewardsHistoryRow, - BfusdSubscribeParams, - BfusdSubscribeResponse, - BfusdSubscriptionHistoryRow, - BlockTrade, - BlvtRedemptionRecord, - BlvtSubscriptionRecord, - BlvtUserLimitInfo, - BNBBurnResponse, - BnbTransferParams, - BnsolRateHistoryRecord, - BnsolRewardHistoryRecord, - BorrowCryptoLoanParams, - BorrowCryptoLoanResponse, - BorrowFlexibleLoanParams, - BorrowFlexibleLoanResponse, - BorrowInterestRate, - BrokerCommissionRebate, - BrokerSubAccount, - BrokerSubAccountCoinFuturesCommission, - BrokerSubAccountFuturesCommission, - BrokerSubAccountHistory, - BrokerUniversalTransfer, - BSwapLiquidity, - BSwapOperations, - BSwapOperationsParams, - BUSDConversionRecord, - CancelAlgoOrderResponse, - CancelHashrateResaleConfigParams, - CancelOrderListResult, - CancelSpotAlgoOrderResponse, - CancelSpotOrderResult, - ChangeAutoCompoundStatusParams, - ChangeAutoCompoundStatusResponse, - ChangePermissionApiKeyBrokerSubAccountParams, - ChangePermissionApiKeyBrokerSubAccountResponse, - ChangePlanStatusParams, - ChangePlanStatusResponse, - ChangeSubAccountCoinFuturesCommissionParams, - ChangeSubAccountCommissionParams, - ChangeSubAccountCommissionResponse, - ChangeSubAccountFuturesCommissionParams, - ChangeSubAccountFuturesCommissionResponse, - CheckCollateralRepayRateParams, - CheckCollateralRepayRateResponse, - CheckDualInvestmentAccountsResponse, - CheckVipCollateralAccountParams, - CloseInstitutionalLoanRiskUnitResponse, - CloudMining, - CloudMiningHistoryParams, - CoinMarginedFuturesResponse, - Collateral, - CollateralAssetData, - CollateralRecord, - CommissionRates, - ConvertDustParams, - ConvertibleCoinsParams, - ConvertibleCoinsResponse, - ConvertLimitOpenOrder, - ConvertQuoteRequestParams, - ConvertTransfer, - ConvertTransferResponse, - CreateApiKeyBrokerSubAccountParams, - CreateApiKeyBrokerSubAccountResponse, - CreateBrokerSubAccountParams, - CreateDualTokenGiftCardParams, - CreateGiftCardParams, - CreateInvestmentPlanParams, - CreateInvestmentPlanResponse, - CreateSpecialLowLatencyKeyParams, - CreateSubAccountParams, - CrossMarginFeeData, - CrossMarginTransferHistory, - CurrentAvgPrice, - CustomizeMarginCall, - CustomizeMarginCallParams, - DailyAccountSnapshot, - DailyAccountSnapshotParams, - DelegationHistory, - DelegationHistoryParams, - DeleteApiKeyBrokerSubAccountParams, - DelistScheduleResponse, - DepositAddress, - DepositAddressListParams, - DepositAddressParams, - DepositAddressResponse, - DepositHistory, - DepositHistoryParams, - DualInvestmentPosition, - DualInvestmentProduct, - DustConversion, - DustConvertibleAssetsParams, - DustConvertibleAssetsResponse, - DustConvertParams, - DustInfo, - DustLog, - EditInvestmentPlanParams, - EditInvestmentPlanResponse, - EnableConvertSubAccountParams, - EnableFuturesBrokerSubAccountParams, - EnableFuturesBrokerSubAccountResponse, - EnableMarginApiKeyBrokerSubAccountParams, - EnableMarginBrokerSubAccountParams, - EnableMarginBrokerSubAccountResponse, - EnableOptionsForSubAccountResponse, - EnableOrDisableIPRestrictionForSubAccountParams, - EnableUniversalTransferApiKeyBrokerSubAccountParams, - EnableUniversalTransferApiKeyBrokerSubAccountResponse, - ETHRateHistory, - EthRedemptionHistory, - EthStakingHistory, - ExchangeInfo, - ExchangeInfoParams, - FiatDepositParams, - FiatDepositResponse, - FixedAndActivityProjectParams, - FixedAndActivityProjectPositionParams, - FlexibleCryptoLoanBorrowHistory, - FlexibleLoanAssetData, - FlexibleLoanCollateralAssetData, - FlexibleLoanLiquidationHistoryRecord, - FlexibleLoanLTVAdjustmentHistory, - FlexibleLoanOngoingOrder, - FlexibleRedemptionRecord, - FlexibleRewardsHistory, - FlexibleSubscriptionPreview, - ForceLiquidationRecord, - FundingAsset, - FutureAccountTransfer, - FuturesPositionRisk, - GetAlgoHistoricalOrdersParams, - GetAlgoSubOrdersParams, - GetAlgoSubOrdersResponse, - GetAllConvertPairsParams, - GetApiKeyBrokerSubAccountParams, - GetApplicationStatusParams, - GetAssetParams, - GetBethRewardsHistoryParams, - GetBfusdRateHistoryParams, - GetBfusdRedemptionHistoryParams, - GetBfusdRewardsHistoryParams, - GetBfusdSubscriptionHistoryParams, - GetBlvtRedemptionRecordParams, - GetBlvtSubscriptionRecordParams, - GetBnsolRateHistoryReq, - GetBnsolRewardsHistoryReq, - GetBrokerInfoResponse, - GetBrokerSubAccountDepositHistoryParams, - GetBrokerSubAccountHistoryParams, - GetBrokerSubAccountParams, - GetC2CTradeHistoryParams, - GetC2CTradeHistoryResponse, - GetClosedInstitutionalLoanRiskUnitsParams, - GetClosedInstitutionalLoanRiskUnitsResponse, - GetCollateralAssetDataParams, - GetCollateralRecordParams, - GetConvertBUSDHistoryParams, - GetConvertTradeHistoryParams, - GetCrossMarginTransferHistoryParams, - GetCryptoLoansIncomeHistoryParams, - GetCryptoLoansIncomeHistoryResponse, - GetDualInvestmentPositionsParams, - GetDualInvestmentProductListParams, - GetEarningsListParams, - GetEarningsListResponse, - GetETHRateHistoryParams, - GetEthRedemptionHistoryParams, - GetEthStakingAccountResponse, - GetEthStakingAccountV2Response, - GetEthStakingHistoryParams, - GetEthStakingQuotaResponse, - GetExtraBonusListParams, - GetExtraBonusListResponse, - GetFiatOrderDetailParams, - GetFiatOrderDetailResponse, - GetFiatOrderHistoryParams, - GetFiatOrderHistoryResponse, - GetFiatPaymentsHistoryResponse, - GetFlexibleCryptoLoanBorrowHistoryParams, - GetFlexibleLoanLiquidationHistoryParams, - GetFlexibleLoanLTVAdjustmentHistoryParams, - GetFlexibleLoanOngoingOrdersParams, - GetFlexibleRedemptionRecordParams, - GetFlexibleRewardsHistoryParams, - GetFlexibleSubscriptionPreviewParams, - GetFlexibleSubscriptionRecordParams, - GetFlexibleSubscriptionRecordResponse, - GetForceLiquidationRecordParams, - GetFutureAccountTransferHistoryParams, - GetFuturesLeadTraderStatusResponse, - GetFuturesLeadTradingSymbolWhitelistResponse, - GetFutureTickLevelOrderbookDataLinkParams, - GetHashrateResaleDetailParams, - GetHashrateResaleDetailResponse, - GetHashrateResaleListParams, - GetHashrateResaleListResponse, - GetIndexDetailsResponse, - GetIndexLinkedPlanPositionDetailsResponse, - GetIndexLinkedPlanRebalanceHistoryParams, - GetIndexLinkedPlanRedemptionHistoryParams, - GetInstitutionalLoanBorrowRepayRecordsParams, - GetInstitutionalLoanBorrowRepayRecordsResponse, - GetInstitutionalLoanForceLiquidationParams, - GetInstitutionalLoanForceLiquidationResponse, - GetInstitutionalLoanInterestHistoryParams, - GetInstitutionalLoanMaxBorrowableParams, - GetInstitutionalLoanRiskUnitDetailsParams, - GetLoanableAssetsDataParams, - GetLoanBorrowHistoryParams, - GetLoanCoinPaginatedHistoryParams, - GetLoanLTVAdjustmentHistoryParams, - GetLoanOngoingOrdersParams, - GetLoanRepaymentHistoryParams, - GetLockedRedemptionRecordParams, - GetLockedRewardsHistory, - GetLockedRewardsHistoryParams, - GetLockedSubscriptionPreviewParams, - GetLockedSubscriptionRecordParams, - GetMarginAccountBorrowRepayRecordsParams, - GetMarginCapitalFlowParams, - GetMarginInterestHistoryParams, - GetMarginInterestRebateBalanceRecordsParams, - GetMarginLiquidationLoanRepayHistoryParams, - GetMarginOrderCountUsageParams, - GetMinerDetailsParams, - GetMinerDetailsResponse, - GetMinerListParams, - GetMinerListResponse, - GetMiningAccountEarningParams, - GetMiningAccountEarningResponse, - getMiningAccountsListParams, - getMiningAccountsListResponse, - GetMiningAlgoListResponse, - GetMiningCoinListResponse, - GetNextHourlyInterestRateParams, - GetNftAssetParams, - GetNftDepositHistoryParams, - GetNftTransactionHistoryParams, - GetNftWithdrawHistoryParams, - GetOCOParams, - GetOneTimeTransactionStatusParams, - GetOneTimeTransactionStatusResponse, - GetOrderStatusParams, - GetPayTradeHistoryParams, - GetPlanDetailsParams, - GetPortfolioMarginAssetIndexPriceResponse, - GetPortfolioMarginAssetLeverageResponse, - GetPortfolioMarginProAccountInfoResponse, - GetPortfolioMarginProBankruptcyLoanAmountResponse, - GetPortfolioMarginProCollateralRateResponse, - GetPortfolioMarginProInterestHistoryParams, - GetPortfolioMarginProInterestHistoryResponse, - GetRateHistory, - GetRateHistoryParams, - GetRwusdRateHistoryParams, - GetRwusdRedemptionHistoryParams, - GetRwusdRewardsHistoryParams, - GetRwusdSubscriptionHistoryParams, - GetSmallLiabilityExchangeHistoryParams, - GetSoftStakingProductListParams, - GetSoftStakingProductListResponse, - GetSoftStakingRewardsHistoryParams, - GetSoftStakingRewardsHistoryResponse, - GetSolStakingHistoryReq, - GetSourceAssetListParams, - GetSourceAssetListResponse, - GetSpotAlgoHistoricalOrdersParams, - GetSpotAlgoSubOrdersParams, - GetSpotAlgoSubOrdersResponse, - GetSpotRebateHistoryRecordsParams, - GetSpotRebateHistoryRecordsResponse, - GetStatisticListParams, - GetStatisticListResponse, - GetSubAccountDepositHistoryParams, - GetSubscriptionTransactionHistoryParams, - GetTargetAssetListParams, - GetTargetAssetListResponse, - GetTargetAssetROIParams, - GetTravelRuleDepositHistoryParams, - GetTravelRuleRegionListParams, - GetTravelRuleWithdrawHistoryParams, - GetTravelRuleWithdrawHistoryV2Params, - GetUniversalTransferBrokerParams, - GetVipLoanFixedRateMarketParams, - GetVipLoanOngoingOrdersParams, - GetVipLoanRepaymentHistoryParams, - GetWbethRewardsHistoryResponse, - GetWrapHistoryParams, - HistoricalAlgoOrder, - HistoricalBlockTradesParams, - HistoricalDataLink, - HistoricalSpotAlgoOrder, - IndexLinkedPlanRedemptionRecord, - InstitutionalLoanBorrowParams, - InstitutionalLoanBorrowResponse, - InstitutionalLoanInterestHistoryResponse, - InstitutionalLoanMaxBorrowableResponse, - InstitutionalLoanRepayParams, - InstitutionalLoanRepayResponse, - InstitutionalLoanRiskUnitDetails, - InstitutionalLoanRiskUnitTransferParams, - IsolatedMarginAccountInfo, - IsolatedMarginAccountTransferParams, - IsolatedMarginFeeData, - IsolatedMarginSymbol, - IsolatedMarginTierData, - LeftDailyPurchaseQuotaFlexibleProductResponse, - LiabilityCoinLeverageBracket, - LoanableAssetData, - LoanBorrowHistory, - LoanLTVAdjustmentHistory, - LoanOngoingOrder, - LoanRepaymentHistory, - LockedRedemptionRecord, - LockedSubscriptionPreview, - LockedSubscriptionRecord, - ManagedSubAccountDepositAddress, - ManagedSubAccountDepositAddressParams, - ManagedSubAccountFuturesAssetsResponse, - ManagedSubAccountListParams, - ManagedSubAccountMarginAssetsResponse, - ManagedSubAccountSnapshot, - ManagedSubAccountSnapshotParams, - ManagedSubAccountTransferLogParams, - ManagedSubAccountTransferTTLogParams, - ManagerSubTransferHistoryVos, - ManagerSubUserInfoVo, - ManualLiquidationParams, - ManualLiquidationResponse, - MarginAccountLoanParams, - MarginAccountRecord, - MarginAvailableInventoryResponse, - MarginCapitalFlow, - MarginDelistSchedule, - MarginInterestHistory, - MarginInterestRateHistory, - MarginInterestRebateBalanceRecordsResponse, - MarginInterestRebateBalanceResponse, - MarginLiquidationLoan, - MarginLiquidationLoanRepayHistoryResponse, - MarginLiquidationLoanRepayResponse, - MarginOrderCountUsageResponse, - MarginOTOCOOrder, - MarginOTOOrder, - MarginTransactionResponse, - NewFutureAccountTransferParams, - NewOrderListOPOCOParams, - NewOrderListOPOCOResponse, - NewOrderListOPOParams, - NewOrderListOPOResponse, - NewOrderListOTOCOParams, - NewOrderListOTOCOResponse, - NewOrderListOTOParams, - NewOrderListOTOResponse, - NewSpotOrderParams, - NewSpotSOROrderParams, - NextHourlyInterestRate, - NftAsset, - NftDeposit, - NftTransaction, - NftWithdraw, - OnchainYieldsAccountResponse, - OnchainYieldsLockedPersonalLeftQuotaParams, - OnchainYieldsLockedPersonalLeftQuotaResponse, - OnchainYieldsLockedPositionParams, - OnchainYieldsLockedPositionResponse, - OnchainYieldsLockedProductListParams, - OnchainYieldsLockedProductListResponse, - OnchainYieldsLockedRedeemParams, - OnchainYieldsLockedRedeemResponse, - OnchainYieldsLockedRedemptionRecordParams, - OnchainYieldsLockedRedemptionRecordResponse, - OnchainYieldsLockedRewardsHistoryParams, - OnchainYieldsLockedRewardsHistoryResponse, - OnchainYieldsLockedSetAutoSubscribeParams, - OnchainYieldsLockedSetAutoSubscribeResponse, - OnchainYieldsLockedSetRedeemOptionParams, - OnchainYieldsLockedSetRedeemOptionResponse, - OnchainYieldsLockedSubscribeParams, - OnchainYieldsLockedSubscribeResponse, - OnchainYieldsLockedSubscriptionPreviewParams, - OnchainYieldsLockedSubscriptionPreviewResponse, - OnchainYieldsLockedSubscriptionRecordParams, - OnchainYieldsLockedSubscriptionRecordResponse, - OrderBookResponse, - OrderList, - OrderListResponse, - OrderRateLimitUsage, - OrderResponseTypeFor, - PMProBankruptcyLoanRepaymentHistory, - PMProMintBFUSDParams, - PMProMintBFUSDResponse, - PMProRedeemBFUSDResponse, - PortfolioMarginMarginCallLevelDeleteResponse, - PortfolioMarginMarginCallLevelGetResponse, - PortfolioMarginMarginCallLevelResponse, - PortfolioMarginProAccountBalance, - PortfolioMarginProSpanAccountInfo, - PreventedMatch, - PreventedMatchesParams, - PurchaseFlexibleProductResponse, - PurchaseRecordParams, - QueryBrokerFuturesCommissionRebateParams, - QueryBrokerSpotCommissionRebateParams, - QueryCrossMarginAccountDetailsParams, - QueryCrossMarginFeeDataParams, - QueryCrossMarginPairResponse, - QueryIsolatedMarginTierDataParams, - QueryMarginAccountAllOCOParams, - QueryMarginAccountTradeListParams, - QueryMarginAssetResponse, - QueryMarginInterestRateHistoryParams, - QueryMarginPriceIndexResponse, - QueryMarginRecordParams, - QueryMaxBorrowResponse, - QueryMaxTransferOutAmountResponse, - QuerySubAccountCoinFuturesCommissionParams, - QuerySubAccountFuturesAssetInfoParams, - QuerySubAccountFuturesCommissionParams, - QuerySubAccountSpotMarginAssetInfoParams, - RawAccountTrade, - RawTrade, - RedeemBlvtParams, - RedeemBlvtResponse, - RedeemEthParams, - RedeemEthResponse, - RedeemGiftCardParams, - RedeemSolResponse, - RemoveBSwapLiquidityParams, - RepayCryptoFlexibleLoanParams, - RepayCryptoFlexibleLoanResponse, - RepayCryptoLoanFlexibleWithCollateralParams, - RepayCryptoLoanFlexibleWithCollateralResponse, - RepayCryptoLoanParams, - RepayCryptoLoanResponse, - RepayMarginLiquidationLoanParams, - ReplaceSpotOrderParams, - ReplaceSpotOrderResultSuccess, - RollingWindowTickerParams, - RwusdAccountResponse, - RwusdQuotaResponse, - RwusdRateHistoryRow, - RwusdRedeemParams, - RwusdRedeemResponse, - RwusdRedemptionHistoryRow, - RwusdRewardsHistoryRow, - RwusdSubscribeParams, - RwusdSubscribeResponse, - RwusdSubscriptionHistoryRow, - SetAutoSubscribeParams, - SetPortfolioMarginMarginCallLevelParams, - SetSoftStakingParams, - SetSoftStakingResponse, - SimpleEarnAccountResponse, - SimpleEarnFlexibleProduct, - SimpleEarnFlexibleProductPositionParams, - SimpleEarnLockedProduct, - SimpleEarnLockedProductPosition, - SimpleEarnLockedProductPositionParams, - SimpleEarnProductListParams, - SimpleEarnRedeemFlexibleProductParams, - SimpleEarnRedeemResponse, - SimpleEarnSubscribeFlexibleProductResponse, - SimpleEarnSubscribeLockedProductResponse, - SimpleEarnSubscribeProductParams, - SmallLiabilityExchangeCoin, - SmallLiabilityExchangeHistory, - SolBoostRewardsHistoryRecord, - SolBoostRewardsHistoryReq, - SolRedemptionHistoryRecord, - SolStakingAccount, - SolStakingHistoryRecord, - SolStakingQuota, - SOROrderResponseFull, - SORTestOrderResponse, - SpecialLowLatencyKeyInfo, - SpecialLowLatencyKeyResponse, - SpotAlgoOrder, +// 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/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/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 + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; // Cannot be sent in Hedge Mode + price?: string; + newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ + newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK + priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD +} +⋮---- +positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode +⋮---- +reduceOnly?: boolean; // Cannot be sent in Hedge Mode +⋮---- +newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ +newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK +priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +export interface NewPortfolioUMOrderResponse { + clientOrderId: string; + cumQty: string; + cumQuote?: string; + executedQty: string; + orderId: number; + avgPrice?: string; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + status: string; + symbol: string; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate?: number; + updateTime: number; + priceMatch: PMPriceMatch; +} +⋮---- +export interface NewPortfolioUMConditionalOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + strategyType: PMStrategyType; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; + price?: string; + workingType?: PMWorkingType; + priceProtect?: boolean; + newClientStrategyId?: string; + stopPrice?: string; + activationPrice?: string; + callbackRate?: string; + priceMatch?: PMPriceMatch; + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; +} +⋮---- +export interface NewPortfolioConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate?: number; + priceMatch: PMPriceMatch; +} +⋮---- +export type PortfolioUMAlgoType = 'CONDITIONAL'; +⋮---- +export interface NewPortfolioUMAlgoOrderReq { + algoType: PortfolioUMAlgoType; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + type: PMStrategyType; + timeInForce?: string; + quantity?: string; + price?: string; + triggerPrice?: string; + workingType?: PMWorkingType; + priceMatch?: PMPriceMatch; + closePosition?: string; + priceProtect?: string; + reduceOnly?: string; + activatePrice?: string; + callbackRate?: string; + clientAlgoId?: string; + newOrderRespType?: 'ACK' | 'RESULT'; + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; +} +⋮---- +export interface PortfolioUMAlgoOrder { + algoId: number; + clientAlgoId: string; + algoType: string; + orderType: string; + symbol: string; + side: string; + positionSide: string; + timeInForce: string; + quantity: string; + algoStatus: string; + triggerPrice: string; + price: string; + icebergQuantity: string | null; + selfTradePreventionMode: string; + workingType: string; + priceMatch: string; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + activatePrice: string; + callbackRate: string; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; + actualOrderId?: string; + actualPrice?: string; + tpTriggerPrice?: string; + tpPrice?: string; + slTriggerPrice?: string; + slPrice?: string; + tpOrderType?: string; +} +⋮---- +export interface CancelPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} +⋮---- +export interface PortfolioUMCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} +⋮---- +export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { + code: number; + msg: string; +} +⋮---- +export interface QueryPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} +⋮---- +export interface QueryPortfolioAllUMAlgoOrdersReq { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface NewPortfolioCMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; + price?: string; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT'; +} +⋮---- +export interface NewPortfolioCMOrderResponse { + clientOrderId: string; + cumQty: string; + cumBase?: string; + executedQty: string; + orderId: number; + avgPrice?: string; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + status: string; + symbol: string; + pair: string; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + updateTime: number; +} +⋮---- +export interface NewPortfolioCMConditionalOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + strategyType: PMStrategyType; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; + price?: string; + workingType?: PMWorkingType; + priceProtect?: boolean; + newClientStrategyId?: string; + stopPrice?: string; + activationPrice?: string; + callbackRate?: string; +} +⋮---- +export interface NewPortfolioCMConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + pair: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; +} +⋮---- +export interface MarginOrderFill { + price: string; + qty: string; + commission: string; + commissionAsset: string; +} +⋮---- +export interface NewPortfolioMarginOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + type: PMMarginOrderType; + quantity?: string; + quoteOrderQty?: string; + price?: string; + stopPrice?: string; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + icebergQty?: string; + sideEffectType?: PMMarginSideEffectType; + timeInForce?: string; + selfTradePreventionMode?: PMSelfTradePreventionMode; + autoRepayAtCancel?: boolean; +} +⋮---- +export interface NewPortfolioMarginOrderResponse { + symbol: string; + orderId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: PMMarginOrderType; + side: 'BUY' | 'SELL'; + marginBuyBorrowAmount?: string; + marginBuyBorrowAsset?: string; + fills: MarginOrderFill[]; +} +⋮---- +export interface PortfolioMarginOCOOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} +⋮---- +export interface PortfolioMarginOCOOrderReport { + 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: 'BUY' | 'SELL'; + stopPrice?: string; +} +⋮---- +export interface NewPortfolioMarginOCOReq { + symbol: string; + listClientOrderId?: string; + side: 'BUY' | 'SELL'; + quantity: string; + limitClientOrderId?: string; + price: string; + limitIcebergQty?: string; + stopClientOrderId?: string; + stopPrice: string; + stopLimitPrice?: string; + stopIcebergQty?: string; + stopLimitTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + sideEffectType?: PMMarginSideEffectType; +} +⋮---- +export interface NewPortfolioMarginOCOResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + marginBuyBorrowAmount?: string; + marginBuyBorrowAsset?: string; + orders: PortfolioMarginOCOOrder[]; + orderReports: PortfolioMarginOCOOrderReport[]; +} +⋮---- +// Add new interfaces for canceling UM orders +export interface CancelPortfolioUMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface PortfolioUMCancelOrderResponse { + avgPrice?: string; + clientOrderId: string; + cumQty: string; + cumQuote?: string; + executedQty: string; + orderId: number; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + status: string; + symbol: string; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + updateTime: number; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate: number; + priceMatch: PMPriceMatch; +} +⋮---- +export interface CancelPortfolioUMConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} +⋮---- +export interface PortfolioUMCancelConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate: number; + priceMatch: PMPriceMatch; +} +⋮---- +export interface CancelPortfolioCMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface PortfolioCMCancelOrderResponse { + avgPrice?: string; + clientOrderId: string; + cumQty: string; + cumBase?: string; + executedQty: string; + orderId: number; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + status: string; + symbol: string; + pair: string; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + updateTime: number; +} +⋮---- +export interface CancelPortfolioCMConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} +⋮---- +export interface PortfolioCMCancelConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; +} +⋮---- +export interface CancelPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; +} +⋮---- +export interface PortfolioMarginCancelOrderResponse { + symbol: string; + orderId: number; + origClientOrderId: string; + clientOrderId: string; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: PMMarginOrderType; + side: 'BUY' | 'SELL'; +} +⋮---- +export interface CancelPortfolioMarginOCOReq { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} +⋮---- +export interface PortfolioMarginOCOCancelOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} +⋮---- +export interface PortfolioMarginOCOCancelOrderReport { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: 'STOP_LOSS_LIMIT' | 'LIMIT_MAKER'; + side: 'BUY' | 'SELL'; + stopPrice?: string; +} +⋮---- +export interface PortfolioMarginOCOCancelResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOCancelOrder[]; + orderReports: PortfolioMarginOCOCancelOrderReport[]; +} +⋮---- +export interface PortfolioMarginCancelAllOrdersOrderReport { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: PMMarginOrderType; + side: 'BUY' | 'SELL'; + stopPrice?: string; + icebergQty?: string; +} +⋮---- +export interface PortfolioMarginCancelAllOrdersOCOReport { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOCancelOrder[]; + orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; +} +⋮---- +export type PortfolioMarginCancelAllOrdersResponse = + | PortfolioMarginCancelAllOrdersOrderReport + | PortfolioMarginCancelAllOrdersOCOReport; +⋮---- +export interface ModifyPortfolioUMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: string; + price: string; + orderId?: number; + origClientOrderId?: string; + priceMatch?: PMPriceMatch; + modifyId?: number; +} +⋮---- +export interface PortfolioUMModifyOrderResponse { + orderId: number; + symbol: string; + status: string; + clientOrderId: string; + price: string; + avgPrice?: string; + origQty: string; + executedQty: string; + cumQty: string; + cumQuote?: string; + timeInForce: string; + type: 'LIMIT'; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'LONG' | 'SHORT' | 'BOTH'; + origType: 'LIMIT'; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate: number; + updateTime: number; + priceMatch: PMPriceMatch; + modifyId?: number; +} +⋮---- +export interface ModifyPortfolioCMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: string; + price: string; + orderId?: number; + origClientOrderId?: string; + modifyId?: number; +} +⋮---- +export interface PortfolioCMModifyOrderResponse { + orderId: number; + symbol: string; + pair: string; + status: string; + clientOrderId: string; + price: string; + avgPrice?: string; + origQty: string; + executedQty: string; + cumQty: string; + cumBase?: string; + timeInForce: string; + type: 'LIMIT'; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'LONG' | 'SHORT' | 'BOTH'; + origType: 'LIMIT'; + updateTime: number; + modifyId?: number; +} +⋮---- +export interface QueryPortfolioUMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface PortfolioUMOrder { + avgPrice: string; + clientOrderId: string; + cumQuote: string; + executedQty: string; + orderId: number; + origQty: string; + origType: 'LIMIT' | 'MARKET'; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'LONG' | 'SHORT' | 'BOTH'; + status: string; + symbol: string; + time: number; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + updateTime: number; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate: number; + priceMatch: PMPriceMatch; +} +⋮---- +export interface QueryPortfolioAllUMOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface QueryPortfolioUMOpenOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface QueryPortfolioAllUMConditionalOrdersReq { + symbol?: string; + strategyId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface PortfolioUMConditionalOrder { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'LONG' | 'SHORT' | 'BOTH'; + stopPrice?: string; + symbol: string; + orderId?: number; + status?: string; + bookTime: number; + updateTime: number; + triggerTime?: number; + timeInForce: string; + type?: 'MARKET' | 'LIMIT'; + activatePrice?: string; + priceRate?: string; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate: number; + priceMatch: PMPriceMatch; +} +⋮---- +export interface QueryPortfolioUMOpenConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} +⋮---- +export interface QueryPortfolioUMConditionalOrderHistoryReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} +⋮---- +export interface QueryPortfolioCMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface PortfolioCMOrder { + avgPrice: string; + clientOrderId: string; + cumBase: string; + executedQty: string; + orderId: number; + origQty: string; + origType: 'LIMIT' | 'MARKET'; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + status: string; + symbol: string; + pair: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + time: number; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + updateTime: number; +} +⋮---- +export interface QueryPortfolioAllCMOrdersReq { + symbol: string; + pair?: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface QueryPortfolioCMOpenOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface QueryPortfolioAllCMConditionalOrdersReq { + symbol?: string; + strategyId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface PortfolioCMConditionalOrder { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + orderId?: number; + status?: string; + bookTime: number; + updateTime: number; + triggerTime?: number; + timeInForce: string; + type?: 'MARKET' | 'LIMIT'; + activatePrice?: string; + priceRate?: string; + workingType: PMWorkingType; + priceProtect: boolean; +} +⋮---- +export interface QueryPortfolioCMConditionalOrderHistoryReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} +⋮---- +export interface PortfolioCMConditionalHistoryOrder + extends PortfolioCMConditionalOrder { + priceMatch: PMPriceMatch; +} +⋮---- +export interface QueryPortfolioUMForceOrdersReq { + symbol?: string; + autoCloseType?: PMAutoCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface PortfolioUMForceOrder { + orderId: number; + symbol: string; + status: string; + clientOrderId: string; + price: string; + avgPrice: string; + origQty: string; + executedQty: string; + cumQuote: string; + timeInForce: string; + type: 'LIMIT'; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + origType: 'LIMIT'; + time: number; + updateTime: number; +} +⋮---- +export interface QueryPortfolioCMForceOrdersReq { + symbol?: string; + autoCloseType?: PMAutoCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface PortfolioCMForceOrder { + orderId: number; + symbol: string; + pair: string; + status: string; + clientOrderId: string; + price: string; + avgPrice: string; + origQty: string; + executedQty: string; + cumBase: string; + timeInForce: string; + type: 'LIMIT'; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + origType: 'LIMIT'; + time: number; + updateTime: number; +} +⋮---- +export interface QueryPortfolioUMOrderAmendmentReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface PortfolioUMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; +} +⋮---- +export interface PortfolioUMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioUMOrderAmendment; + priceMatch: PMPriceMatch; + modifyId?: number; +} +⋮---- +export interface QueryPortfolioCMOrderAmendmentReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface PortfolioCMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; +} +⋮---- +export interface PortfolioCMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioCMOrderAmendment; + modifyId?: number; +} +⋮---- +export interface QueryPortfolioMarginForceOrdersReq { + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 +} +⋮---- +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +⋮---- +export interface PortfolioMarginForceOrder { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + updatedTime: number; +} +⋮---- +export interface QueryPortfolioUMTradesReq { + symbol: string; + startTime?: number; + endTime?: number; + fromId?: number; // Trade id to fetch from. Default gets most recent trades + limit?: number; // Default 500; max 1000 +} +⋮---- +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 +⋮---- +export interface PortfolioUMTrade { + symbol: string; + id: number; + orderId: number; + side: 'BUY' | 'SELL'; + price: string; + qty: string; + realizedPnl: string; + quoteQty: string; + commission: string; + commissionAsset: string; + time: number; + buyer: boolean; + maker: boolean; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + pair?: string; + baseQty?: string; + marginAsset?: string; +} +⋮---- +export interface QueryPortfolioCMTradesReq { + symbol?: string; + pair?: string; + startTime?: number; + endTime?: number; + fromId?: number; // Trade id to fetch from. Default gets most recent trades + limit?: number; // Default 50; max 1000 +} +⋮---- +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 50; max 1000 +⋮---- +export interface PortfolioCMTrade { + symbol: string; + id: number; + orderId: number; + pair: string; + side: 'BUY' | 'SELL'; + price: string; + qty: string; + realizedPnl: string; + marginAsset: string; + baseQty: string; + commission: string; + commissionAsset: string; + time: number; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + buyer: boolean; + maker: boolean; + quoteQty?: string; +} +⋮---- +export interface PortfolioADLQuantile { + LONG: number; + SHORT: number; + BOTH?: number; // For one-way mode or isolated margin in hedge mode + HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) +} +⋮---- +BOTH?: number; // For one-way mode or isolated margin in hedge mode +HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) +⋮---- +export interface QueryPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface PortfolioMarginOrder { + clientOrderId: string; + cummulativeQuoteQty: string; + executedQty: string; + icebergQty: string; + isWorking: boolean; + orderId: number; + origQty: string; + price: string; + side: 'BUY' | 'SELL'; + status: string; + stopPrice: string; + symbol: string; + time: number; + timeInForce: string; + type: PMMarginOrderType; + updateTime: number; + accountId: number; + selfTradePreventionMode: PMSelfTradePreventionMode; + preventedMatchId: number | null; + preventedQuantity: string | null; +} +⋮---- +export interface QueryPortfolioMarginAllOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} +⋮---- +limit?: number; // Default 500; max 500 +⋮---- +export interface QueryPortfolioMarginOCOReq { + orderListId?: number; // Either orderListId or origClientOrderId must be provided + origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +} +⋮---- +orderListId?: number; // Either orderListId or origClientOrderId must be provided +origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +⋮---- +export interface PortfolioMarginOCOQueryOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} +⋮---- +export interface PortfolioMarginOCO { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOQueryOrder[]; +} +⋮---- +export interface QueryPortfolioMarginAllOCOReq { + fromId?: number; // If supplied, neither startTime or endTime can be provided + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} +⋮---- +fromId?: number; // If supplied, neither startTime or endTime can be provided +⋮---- +limit?: number; // Default 500; max 500 +⋮---- +export interface QueryPortfolioMarginTradesReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; // TradeId to fetch from. Default gets most recent trades + limit?: number; // Default 500; max 1000 +} +⋮---- +fromId?: number; // TradeId to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 +⋮---- +export interface PortfolioMarginTrade { + commission: string; + commissionAsset: string; + id: number; + isBestMatch: boolean; + isBuyer: boolean; + isMaker: boolean; + orderId: number; + price: string; + qty: string; + symbol: string; + time: number; +} +⋮---- +export interface PortfolioMarginRepayDebtReq { + asset: string; + amount?: string; + specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas +} +⋮---- +specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas +⋮---- +export interface PortfolioMarginRepayDebtResponse { + amount: string; + asset: string; + specifyRepayAssets: string[]; + updateTime: number; + success: boolean; +} +⋮---- +/** + * + * DERIVATIVES - ACCOUNT endpoints + * + **/ +⋮---- +export type PMAccountStatus = + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; +⋮---- +export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; +export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; +⋮---- +export interface PortfolioTotalBalance { + asset: string; + totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance + crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked + crossMarginBorrowed: string; // principal of cross margin + crossMarginFree: string; // free asset of cross margin + crossMarginInterest: string; // interest of cross margin + crossMarginLocked: string; // lock asset of cross margin + umWalletBalance: string; // wallet balance of um + umUnrealizedPNL: string; // unrealized profit of um + cmWalletBalance: string; // wallet balance of cm + cmUnrealizedPNL: string; // unrealized profit of cm + updateTime: number; + negativeBalance: string; +} +⋮---- +totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance +crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked +crossMarginBorrowed: string; // principal of cross margin +crossMarginFree: string; // free asset of cross margin +crossMarginInterest: string; // interest of cross margin +crossMarginLocked: string; // lock asset of cross margin +umWalletBalance: string; // wallet balance of um +umUnrealizedPNL: string; // unrealized profit of um +cmWalletBalance: string; // wallet balance of cm +cmUnrealizedPNL: string; // unrealized profit of cm +⋮---- +export interface PortfolioSingleBalance { + asset: string; + totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance + crossMarginBorrowed: string; // principal of cross margin + crossMarginFree: string; // free asset of cross margin + crossMarginInterest: string; // interest of cross margin + crossMarginLocked: string; // lock asset of cross margin + umWalletBalance: string; // wallet balance of um + umUnrealizedPNL: string; // unrealized profit of um + cmWalletBalance: string; // wallet balance of cm + cmUnrealizedPNL: string; // unrealized profit of cm + updateTime: number; + negativeBalance: string; +} +⋮---- +totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance +crossMarginBorrowed: string; // principal of cross margin +crossMarginFree: string; // free asset of cross margin +crossMarginInterest: string; // interest of cross margin +crossMarginLocked: string; // lock asset of cross margin +umWalletBalance: string; // wallet balance of um +umUnrealizedPNL: string; // unrealized profit of um +cmWalletBalance: string; // wallet balance of cm +cmUnrealizedPNL: string; // unrealized profit of cm +⋮---- +export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; +⋮---- +export interface PortfolioAccountInformation { + uniMMR: string; // Portfolio margin account maintenance margin rate + accountEquity: string; // Account equity, in USD value + actualEquity: string; // Account equity without collateral rate, in USD value + accountInitialMargin: string; + accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD + accountStatus: PMAccountStatus; + virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD + totalAvailableBalance: string; + totalMarginOpenLoss: string; // in USD margin open order + updateTime: number; // last update time +} +⋮---- +uniMMR: string; // Portfolio margin account maintenance margin rate +accountEquity: string; // Account equity, in USD value +actualEquity: string; // Account equity without collateral rate, in USD value +⋮---- +accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD +⋮---- +virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD +⋮---- +totalMarginOpenLoss: string; // in USD margin open order +updateTime: number; // last update time +⋮---- +export interface PortfolioUMPosition { + symbol: string; + positionAmt: string; + entryPrice: string; + markPrice: string; + unRealizedProfit: string; + liquidationPrice: string; + leverage: string; + maxNotionalValue: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + notional: string; + updateTime: number; +} +⋮---- +export interface PortfolioCMPosition { + symbol: string; + positionAmt: string; + entryPrice: string; + markPrice: string; + unRealizedProfit: string; + liquidationPrice: string; + leverage: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + updateTime: number; + maxQty: string; + notionalValue: string; +} +⋮---- +export interface PortfolioUMLeverageBracket { + bracket: number; // Notional bracket + initialLeverage: number; // Max initial leverage for this bracket + notionalCap: number; // Cap notional of this bracket + notionalFloor: number; // Notional threshold of this bracket + maintMarginRatio: number; // Maintenance ratio for this bracket + cum: number; // Auxiliary number for quick calculation +} +⋮---- +bracket: number; // Notional bracket +initialLeverage: number; // Max initial leverage for this bracket +notionalCap: number; // Cap notional of this bracket +notionalFloor: number; // Notional threshold of this bracket +maintMarginRatio: number; // Maintenance ratio for this bracket +cum: number; // Auxiliary number for quick calculation +⋮---- +export interface PortfolioCMLeverageBracket { + bracket: number; // bracket level + initialLeverage: number; // the maximum leverage + qtyCap: number; // upper edge of base asset quantity + qtyFloor: number; // lower edge of base asset quantity + maintMarginRatio: number; // maintenance margin rate + cum: number; // Auxiliary number for quick calculation +} +⋮---- +bracket: number; // bracket level +initialLeverage: number; // the maximum leverage +qtyCap: number; // upper edge of base asset quantity +qtyFloor: number; // lower edge of base asset quantity +maintMarginRatio: number; // maintenance margin rate +cum: number; // Auxiliary number for quick calculation +⋮---- +export interface PortfolioTradingIndicator { + isLocked: boolean; + plannedRecoverTime: number; + indicator: PMIndicatorType; + value: number; + triggerValue: number; +} +⋮---- +export interface PortfolioTradingStatus { + indicators: { + [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" + }; + updateTime: number; +} +⋮---- +[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" +⋮---- +export interface PortfolioMarginLoanRecord { + txId: number; + asset: string; + principal: string; + timestamp: number; + status: PMMarginLoanStatus; +} +⋮---- +export interface GetMarginLoanRecordsReq { + asset: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +} +⋮---- +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +⋮---- +export interface GetMarginRepayRecordsReq { + asset: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +} +⋮---- +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +⋮---- +export interface PortfolioMarginRepayRecord { + amount: string; // Total amount repaid + asset: string; + interest: string; // Interest repaid + principal: string; // Principal repaid + status: PMMarginLoanStatus; + txId: number; +} +⋮---- +amount: string; // Total amount repaid +⋮---- +interest: string; // Interest repaid +principal: string; // Principal repaid +⋮---- +export interface GetMarginInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +} +⋮---- +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +⋮---- +export type PMInterestType = + | 'PERIODIC' // interest charged per hour + | 'ON_BORROW' // first interest charged on borrow + | 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB + | 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB + | 'PORTFOLIO'; // Portfolio Margin negative balance daily interest +⋮---- +| 'PERIODIC' // interest charged per hour +| 'ON_BORROW' // first interest charged on borrow +| 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB +| 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB +| 'PORTFOLIO'; // Portfolio Margin negative balance daily interest +⋮---- +export interface PortfolioMarginInterestRecord { + txId: number; + interestAccuredTime: number; + asset: string; + rawAsset: string; + principal: string; + interest: string; + interestRate: string; + type: PMInterestType; +} +⋮---- +export interface GetPortfolioInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; // Default: 10, Max: 100 +} +⋮---- +size?: number; // Default: 10, Max: 100 +⋮---- +export interface PortfolioNegativeBalanceInterestRecord { + asset: string; + interest: string; // interest amount + interestAccuredTime: number; + interestRate: string; // daily interest rate + principal: string; +} +⋮---- +interest: string; // interest amount +⋮---- +interestRate: string; // daily interest rate +⋮---- +export type UMIncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR' + | 'REFERRAL_KICKBACK' + | 'COMMISSION_REBATE' + | 'API_REBATE' + | 'CONTEST_REWARD' + | 'CROSS_COLLATERAL_TRANSFER' + | 'OPTIONS_PREMIUM_FEE' + | 'OPTIONS_SETTLE_PROFIT' + | 'INTERNAL_TRANSFER' + | 'AUTO_EXCHANGE' + | 'DELIVERED_SETTELMENT' + | 'COIN_SWAP_DEPOSIT' + | 'COIN_SWAP_WITHDRAW' + | 'POSITION_LIMIT_INCREASE_FEE'; +⋮---- +export interface QueryPortfolioUMIncomeReq { + symbol?: string; + incomeType?: UMIncomeType; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 100; max 1000 +} +⋮---- +limit?: number; // Default 100; max 1000 +⋮---- +export interface PortfolioUMIncome { + symbol: string; // trade symbol, if existing + incomeType: UMIncomeType; + income: string; // income amount + asset: string; // income asset + info: string; // extra information + time: number; + tranId: string; // transaction id + tradeId: string; // trade id, if existing +} +⋮---- +symbol: string; // trade symbol, if existing +⋮---- +income: string; // income amount +asset: string; // income asset +info: string; // extra information +⋮---- +tranId: string; // transaction id +tradeId: string; // trade id, if existing +⋮---- +export type CMIncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'FUNDING_FEE' + | 'REALIZED_PNL' + | 'COMMISSION' + | 'INSURANCE_CLEAR' + | 'DELIVERED_SETTELMENT'; +⋮---- +export interface QueryPortfolioCMIncomeReq { + symbol?: string; + incomeType?: CMIncomeType; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 100; max 1000 +} +⋮---- +limit?: number; // Default 100; max 1000 +⋮---- +export interface PortfolioCMIncome { + symbol: string; // trade symbol, if existing + incomeType: CMIncomeType; + income: string; // income amount + asset: string; // income asset + info: string; // extra information + time: number; + tranId: string; // transaction id + tradeId: string; // trade id, if existing +} +⋮---- +symbol: string; // trade symbol, if existing +⋮---- +income: string; // income amount +asset: string; // income asset +info: string; // extra information +⋮---- +tranId: string; // transaction id +tradeId: string; // trade id, if existing +⋮---- +export interface PortfolioUMAccountAsset { + asset: string; // asset name + crossWalletBalance: string; // wallet balance + crossUnPnl: string; // unrealized profit + maintMargin: string; // maintenance margin required + initialMargin: string; // total initial margin required with current mark price + positionInitialMargin: string; // initial margin required for positions with current mark price + openOrderInitialMargin: string; // initial margin required for open orders with current mark price + updateTime: number; // last update time +} +⋮---- +asset: string; // asset name +crossWalletBalance: string; // wallet balance +crossUnPnl: string; // unrealized profit +maintMargin: string; // maintenance margin required +initialMargin: string; // total initial margin required with current mark price +positionInitialMargin: string; // initial margin required for positions with current mark price +openOrderInitialMargin: string; // initial margin required for open orders with current mark price +updateTime: number; // last update time +⋮---- +export interface PortfolioUMAccountPosition { + symbol: string; // symbol name + initialMargin: string; // initial margin required with current mark price + maintMargin: string; // maintenance margin required + unrealizedProfit: string; // unrealized profit + positionInitialMargin: string; // initial margin required for positions with current mark price + openOrderInitialMargin: string; // initial margin required for open orders with current mark price + leverage: string; // current initial leverage + entryPrice: string; // average entry price + maxNotional: string; // maximum available notional with current leverage + bidNotional: string; // bids notional + askNotional: string; // ask notional + positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side + positionAmt: string; // position amount + updateTime: number; // last update time +} +⋮---- +symbol: string; // symbol name +initialMargin: string; // initial margin required with current mark price +maintMargin: string; // maintenance margin required +unrealizedProfit: string; // unrealized profit +positionInitialMargin: string; // initial margin required for positions with current mark price +openOrderInitialMargin: string; // initial margin required for open orders with current mark price +leverage: string; // current initial leverage +entryPrice: string; // average entry price +maxNotional: string; // maximum available notional with current leverage +bidNotional: string; // bids notional +askNotional: string; // ask notional +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side +positionAmt: string; // position amount +updateTime: number; // last update time +⋮---- +export interface PortfolioCMAccountAsset { + asset: string; // asset name + crossWalletBalance: string; // total wallet balance + crossUnPnl: string; // unrealized profit or loss + maintMargin: string; // maintenance margin + initialMargin: string; // total initial margin required with the latest mark price + positionInitialMargin: string; // positions' margin required with the latest mark price + openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price + updateTime: number; // last update time +} +⋮---- +asset: string; // asset name +crossWalletBalance: string; // total wallet balance +crossUnPnl: string; // unrealized profit or loss +maintMargin: string; // maintenance margin +initialMargin: string; // total initial margin required with the latest mark price +positionInitialMargin: string; // positions' margin required with the latest mark price +openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price +updateTime: number; // last update time +⋮---- +export interface PortfolioCMAccountPosition { + symbol: string; // symbol name + positionAmt: string; // position amount + initialMargin: string; + maintMargin: string; + unrealizedProfit: string; + positionInitialMargin: string; + openOrderInitialMargin: string; + leverage: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode + entryPrice: string; + maxQty: string; // maximum quantity of base asset + updateTime: number; +} +⋮---- +symbol: string; // symbol name +positionAmt: string; // position amount +⋮---- +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode +⋮---- +maxQty: string; // maximum quantity of base asset +⋮---- +export interface PortfolioUMAccountConfig { + feeTier: number; // account commission tier + canTrade: boolean; // if can trade + canDeposit: boolean; // if can transfer in asset + canWithdraw: boolean; // if can transfer out asset + dualSidePosition: boolean; + updateTime: number; // reserved property + multiAssetsMargin: boolean; + tradeGroupId: number; +} +⋮---- +feeTier: number; // account commission tier +canTrade: boolean; // if can trade +canDeposit: boolean; // if can transfer in asset +canWithdraw: boolean; // if can transfer out asset +⋮---- +updateTime: number; // reserved property +⋮---- +export interface PortfolioUMSymbolConfig { + symbol: string; + marginType: 'CROSSED' | 'ISOLATED'; + isAutoAddMargin: string; // "true" or "false" as string + leverage: number; + maxNotionalValue: string; +} +⋮---- +isAutoAddMargin: string; // "true" or "false" as string +⋮---- +export interface PortfolioUMAccountAssetV2 { + asset: string; // asset name + crossWalletBalance: string; // wallet balance + crossUnPnl: string; // unrealized profit + maintMargin: string; // maintenance margin required + initialMargin: string; // total initial margin required with current mark price + positionInitialMargin: string; // initial margin required for positions with current mark price + openOrderInitialMargin: string; // initial margin required for open orders with current mark price + updateTime: number; // last update time +} +⋮---- +asset: string; // asset name +crossWalletBalance: string; // wallet balance +crossUnPnl: string; // unrealized profit +maintMargin: string; // maintenance margin required +initialMargin: string; // total initial margin required with current mark price +positionInitialMargin: string; // initial margin required for positions with current mark price +openOrderInitialMargin: string; // initial margin required for open orders with current mark price +updateTime: number; // last update time +⋮---- +export interface PortfolioUMAccountPositionV2 { + symbol: string; // symbol name + initialMargin: string; // initial margin required with current mark price + maintMargin: string; // maintenance margin required + unrealizedProfit: string; // unrealized profit + positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side + positionAmt: string; // position amount + updateTime: number; // last update time + notional: string; // position notional value +} +⋮---- +symbol: string; // symbol name +initialMargin: string; // initial margin required with current mark price +maintMargin: string; // maintenance margin required +unrealizedProfit: string; // unrealized profit +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side +positionAmt: string; // position amount +updateTime: number; // last update time +notional: string; // position notional value +⋮---- +export interface DownloadLinkResponse { + downloadId: string; + status: 'completed' | 'processing'; // Enum: completed, processing + url: string; // The link is mapped to download id + s3Link: string | null; + notified: boolean; // ignore + expirationTimestamp: number; // The link would expire after this timestamp + isExpired: boolean | null; +} +⋮---- +status: 'completed' | 'processing'; // Enum: completed, processing +url: string; // The link is mapped to download id +⋮---- +notified: boolean; // ignore +expirationTimestamp: number; // The link would expire after this timestamp +⋮---- +export interface PortfolioTradFiPerpsContractSignResponse { + code: number; + msg: string; +} + +================ +File: src/types/shared.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; +⋮---- +export type ExchangeSymbol = string; +⋮---- +export type BooleanString = 'true' | 'false'; +⋮---- +export type BinanceBaseUrlKey = + | 'spot' + | 'spot1' + | 'spot2' + | 'spot3' + | 'spot4' + | 'spottest' + | 'usdmtest' + | 'usdm' + | 'coinm' + | 'coinmtest' + | 'voptions' + | 'voptionstest' + | 'papi' + | 'www'; +⋮---- +/** + * 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'; +⋮---- +export type StringBoolean = 'TRUE' | 'FALSE'; +⋮---- +export type SideEffects = + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'NO_SIDE_EFFECT' + | 'AUTO_BORROW_REPAY' + | 'NO_SIDE_EFFECT'; +⋮---- +/** + * 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'; +⋮---- +export type OrderIdProperty = + | 'newClientOrderId' + | 'newClientStrategyId' + | 'listClientOrderId' + | 'limitClientOrderId' + | 'stopClientOrderId' + | 'clientAlgoId' + | 'aboveClientOrderId' + | 'belowClientOrderId' + | 'workingClientOrderId' + | 'pendingAboveClientOrderId' + | 'pendingBelowClientOrderId' + | 'pendingClientOrderId'; +⋮---- +export type OrderSide = 'BUY' | 'SELL'; +⋮---- +export type OrderStatus = + | 'NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED'; +⋮---- +export type OrderExecutionType = + | 'NEW' + | 'CANCELED' + | 'REJECTED' + | 'TRADE' + | 'EXPIRED'; +⋮---- +// listStatusType +export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; +⋮---- +// listOrderStatus +export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; +⋮---- +export type OrderType = + | 'LIMIT' + | 'LIMIT_MAKER' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; +⋮---- +export type OrderListOrderType = + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; +⋮---- +export type SelfTradePreventionMode = + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; +⋮---- +export interface BasicAssetParam { + asset: string; +} +⋮---- +export interface BasicSymbolParam { + symbol: string; + isIsolated?: StringBoolean; +} +⋮---- +export interface SymbolArrayParam { + symbols: string[]; +} +⋮---- +export interface BasicAssetPaginatedParams { + asset?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +export interface BasicSymbolPaginatedParams { + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface SymbolPrice { + symbol: string; + price: numberInString; + time?: number; +} +⋮---- +// used by spot and usdm +export interface OrderBookParams { + symbol: string; + limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; + symbolStatus?: string; +} +⋮---- +export type KlineInterval = + | '1s' + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '3d' + | '1w' + | '1M'; +⋮---- +export interface GetOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface GetOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface HistoricalTradesParams { + symbol: string; + limit?: number; + fromId?: number; +} +⋮---- +export interface KlinesParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} +⋮---- +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? +]; +⋮---- +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? +⋮---- +/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ +export type FuturesKline = Kline; +export interface RecentTradesParams { + symbol: string; + limit?: number; +} +⋮---- +export interface CancelOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} +⋮---- +export interface AmendKeepPriorityParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + newQty: numberInString; +} +⋮---- +export interface CancelOCOParams { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} +⋮---- +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; +} +⋮---- +/** For isolated margin trading only */ +⋮---- +/** Define a side effect, only for margin trading */ +⋮---- +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; +} +⋮---- +export interface SymbolFromPaginatedRequestFromId { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetAllOrdersParams { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface RateLimiter { + rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; + interval: 'SECOND' | 'MINUTE' | 'DAY'; + intervalNum: number; + limit: number; +} +⋮---- +export interface SymbolPriceFilter { + filterType: 'PRICE_FILTER'; + minPrice: numberInString; + maxPrice: numberInString; + tickSize: numberInString; +} +⋮---- +export interface SymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + avgPriceMins: number; +} +⋮---- +export interface SymbolPercentPriceBySideFilter { + filterType: 'PERCENT_PRICE_BY_SIDE'; + bidMultiplierUp: numberInString; + bidMultiplierDown: numberInString; + askMultiplierUp: numberInString; + askMultiplierDown: numberInString; + avgPriceMins: number; +} +⋮---- +export interface SymbolLegacyMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + minNotional: numberInString; + applyToMarket: boolean; + avgPriceMins: number; +} +⋮---- +export interface SymbolLotSizeFilter { + filterType: 'LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} +⋮---- +export interface SymbolMinNotionalFilter { + filterType: 'NOTIONAL'; + minNotional: numberInString; + applyMinToMarket: boolean; + maxNotional: numberInString; + applyMaxToMarket: boolean; + avgPriceMins: number; +} +⋮---- +export interface SymbolIcebergPartsFilter { + filterType: 'ICEBERG_PARTS'; + limit: number; +} +⋮---- +export interface SymbolMarketLotSizeFilter { + filterType: 'MARKET_LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} +⋮---- +export interface SymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + maxNumOrders: number; +} +⋮---- +export interface SymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} +⋮---- +export interface SymbolMaxIcebergOrdersFilter { + filterType: 'MAX_NUM_ICEBERG_ORDERS'; + maxNumIcebergOrders: number; +} +⋮---- +export interface SymbolMaxPositionFilter { + filterType: 'MAX_POSITION'; + maxPosition: numberInString; +} +⋮---- +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; +⋮---- +export type OrderBookPrice = numberInString; +export type OrderBookAmount = numberInString; +⋮---- +export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; +⋮---- +export type OrderBookPriceFormatted = number; +export type OrderBookAmountFormatted = number; +export type OrderBookRowFormatted = [ + OrderBookPriceFormatted, + OrderBookAmountFormatted, +]; +⋮---- +export interface GenericCodeMsgError { + code: number; + msg: string; +} +⋮---- +export interface RowsWithTotal { + rows: T[]; + total: number; +} +⋮---- +export interface CoinStartEndLimit { + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} + +================ +File: src/portfolio-client.ts +================ +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'; +import { + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + NewOCOParams, + OrderIdProperty, +} from './types/shared'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + 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 +⋮---- +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) +⋮---- +getClientId(): BinanceBaseUrlKey +⋮---- +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise +⋮---- +/** + * + * Misc Endpoints + * + **/ +⋮---- +testConnectivity(): Promise +⋮---- +signTradFiPerpsContract(): Promise +⋮---- +/** + * + * DERIVATIVES -TRADE endpoints + * + **/ +⋮---- +submitNewUMOrder( + params: NewPortfolioUMOrderReq, +): Promise +⋮---- +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). + */ +submitNewUMConditionalOrder( + params: NewPortfolioUMConditionalOrderReq, +): Promise +⋮---- +submitNewUMAlgoOrder( + params: NewPortfolioUMAlgoOrderReq, +): Promise +⋮---- +submitNewCMOrder( + params: NewPortfolioCMOrderReq, +): Promise +⋮---- +submitNewCMConditionalOrder( + params: NewPortfolioCMConditionalOrderReq, +): Promise +⋮---- +submitNewMarginOrder( + params: NewPortfolioMarginOrderReq, +): Promise +⋮---- +submitMarginLoan(params: +⋮---- +submitMarginRepay(params: +⋮---- +submitNewMarginOCO( + params: NewPortfolioMarginOCOReq, +): Promise +⋮---- +cancelUMOrder( + params: CancelPortfolioUMOrderReq, +): Promise +⋮---- +cancelAllUMOrders(params: +⋮---- +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). + */ +cancelUMConditionalOrder( + params: CancelPortfolioUMConditionalOrderReq, +): Promise +⋮---- +cancelUMAlgoOrder( + params: CancelPortfolioUMAlgoOrderReq, +): Promise +⋮---- +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). + */ +cancelAllUMConditionalOrders(params: +⋮---- +cancelAllUMAlgoOpenOrders(params: { + symbol: string; +}): Promise +⋮---- +cancelCMOrder( + params: CancelPortfolioCMOrderReq, +): Promise +⋮---- +cancelAllCMOrders(params: +⋮---- +cancelCMConditionalOrder( + params: CancelPortfolioCMConditionalOrderReq, +): Promise +⋮---- +cancelAllCMConditionalOrders(params: +⋮---- +cancelMarginOrder( + params: CancelPortfolioMarginOrderReq, +): Promise +⋮---- +cancelMarginOCO( + params: CancelPortfolioMarginOCOReq, +): Promise +⋮---- +cancelAllMarginOrders(params: { + symbol: string; +}): Promise +⋮---- +modifyUMOrder( + params: ModifyPortfolioUMOrderReq, +): Promise +⋮---- +modifyCMOrder( + params: ModifyPortfolioCMOrderReq, +): Promise +⋮---- +getUMOrder(params: QueryPortfolioUMOrderReq): Promise +⋮---- +getAllUMOrders( + params: QueryPortfolioAllUMOrdersReq, +): Promise +⋮---- +getUMOpenOrder( + params: QueryPortfolioUMOpenOrderReq, +): Promise +⋮---- +getAllUMOpenOrders(params: +⋮---- +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). + */ +getAllUMConditionalOrders( + params: QueryPortfolioAllUMConditionalOrdersReq, +): Promise +⋮---- +getAllUMAlgoOrders( + params: QueryPortfolioAllUMAlgoOrdersReq, +): Promise +⋮---- +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). + */ +getUMOpenConditionalOrders(params: { + symbol?: string; +}): Promise +⋮---- +getUMAlgoOpenOrders(params?: { + symbol?: string; +}): Promise +⋮---- +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). + */ +getUMOpenConditionalOrder( + params: QueryPortfolioUMOpenConditionalOrderReq, +): Promise +⋮---- +getUMAlgoOrder( + params: QueryPortfolioUMAlgoOrderReq, +): Promise +⋮---- +/** + * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. + */ +getUMConditionalOrderHistory( + params: QueryPortfolioUMConditionalOrderHistoryReq, +): Promise +⋮---- +getCMOrder(params: QueryPortfolioCMOrderReq): Promise +⋮---- +getAllCMOrders( + params: QueryPortfolioAllCMOrdersReq, +): Promise +⋮---- +getCMOpenOrder( + params: QueryPortfolioCMOpenOrderReq, +): Promise +⋮---- +getAllCMOpenOrders(params: { + symbol?: string; + pair?: string; +}): Promise +⋮---- +getCMOpenConditionalOrders(params: { + symbol?: string; +}): Promise +⋮---- +getCMOpenConditionalOrder(params: { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +}): Promise +⋮---- +getAllCMConditionalOrders( + params: QueryPortfolioAllCMConditionalOrdersReq, +): Promise +⋮---- +getCMConditionalOrderHistory( + params: QueryPortfolioCMConditionalOrderHistoryReq, +): Promise +⋮---- +getUMForceOrders( + params: QueryPortfolioUMForceOrdersReq, +): Promise +⋮---- +getCMForceOrders( + params: QueryPortfolioCMForceOrdersReq, +): Promise +⋮---- +getUMOrderModificationHistory( + params: QueryPortfolioUMOrderAmendmentReq, +): Promise +⋮---- +getCMOrderModificationHistory( + params: QueryPortfolioCMOrderAmendmentReq, +): Promise +⋮---- +getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< +⋮---- +getUMTrades(params: QueryPortfolioUMTradesReq): Promise +⋮---- +getCMTrades(params: QueryPortfolioCMTradesReq): Promise +⋮---- +getUMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > { + return this.getPrivate('papi/v1/um/adlQuantile', params); +⋮---- +getCMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > { + return this.getPrivate('papi/v1/cm/adlQuantile', params); +⋮---- +toggleUMFeeBurn(params: { + feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +}): Promise< +⋮---- +feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +⋮---- +getUMFeeBurnStatus(): Promise< +⋮---- +getMarginOrder( + params: QueryPortfolioMarginOrderReq, +): Promise +⋮---- +getMarginOpenOrders(params: { + symbol: string; +}): Promise +⋮---- +getAllMarginOrders( + params: QueryPortfolioMarginAllOrdersReq, +): Promise +⋮---- +getMarginOCO( + params: QueryPortfolioMarginOCOReq, +): Promise +⋮---- +getAllMarginOCO( + params: QueryPortfolioMarginAllOCOReq, +): Promise +⋮---- +getMarginOpenOCO(): Promise +⋮---- +getMarginTrades( + params: QueryPortfolioMarginTradesReq, +): Promise +⋮---- +repayMarginDebt( + params: PortfolioMarginRepayDebtReq, +): 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?: { + 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< +⋮---- +getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< +⋮---- +getAutoRepayFuturesStatus(): Promise< +⋮---- +autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off +⋮---- +updateAutoRepayFuturesStatus(params: { + autoRepay: 'true' | 'false'; +}): Promise< +⋮---- +getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< +⋮---- +repayFuturesNegativeBalance(): Promise< +⋮---- +getPortfolioNegativeBalanceInterestHistory( + params?: GetPortfolioInterestHistoryReq, +): Promise +⋮---- +autoCollectFunds(): Promise< +⋮---- +transferAssetFuturesMargin(params: +⋮---- +transferBNB(params: { + amount: string; + transferSide: 'TO_UM' | 'FROM_UM'; +}): Promise< +⋮---- +tranId: number; // transaction id +⋮---- +getUMIncomeHistory( + params?: QueryPortfolioUMIncomeReq, +): Promise +⋮---- +getCMIncomeHistory( + params?: QueryPortfolioCMIncomeReq, +): Promise +⋮---- +getUMAccount(): Promise< +⋮---- +positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market +⋮---- +getCMAccount(): Promise< +⋮---- +getUMAccountConfig(): Promise +⋮---- +getUMSymbolConfig(params?: { + symbol?: string; +}): Promise +⋮---- +getUMAccountV2(): Promise< +⋮---- +positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market +⋮---- +getUMTradeHistoryDownloadId(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 +⋮---- +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: + | NewPortfolioUMOrderReq + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, +): void +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +getPMUserDataListenKey(): Promise< +⋮---- +keepAlivePMUserDataListenKey(): Promise +⋮---- +closePMUserDataListenKey(): Promise + +================ +File: src/usdm-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'; +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 { + 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 +⋮---- +/** + * + * ACCOUNT endpoints - Rest API + * + **/ +⋮---- +getBalanceV3(): Promise +⋮---- +/** + * @deprecated + * Use getBalanceV3() instead + **/ +getBalance(): Promise +⋮---- +getAccountInformationV3(): Promise +⋮---- +/** + * @deprecated + * Use getAccountInformationV3() instead + **/ +getAccountInformation(): Promise +⋮---- +getAccountCommissionRate(params: { + symbol: string; +}): Promise +⋮---- +getFuturesAccountConfig(): Promise +⋮---- +getFuturesSymbolConfig(params: +⋮---- +getUserForceOrders(): Promise +⋮---- +/** + * 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 +⋮---- +getMultiAssetsMode(): Promise +⋮---- +getCurrentPositionMode(): Promise +⋮---- +getIncomeHistory(params?: GetIncomeHistoryParams): Promise +⋮---- +getApiQuantitativeRulesIndicators(params?: { + symbol?: string; +}): Promise +⋮---- +getFuturesTransactionHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise +⋮---- +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +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 +⋮---- +/** + * + * Algo Order Endpoints (Effective 2025-12-02) + * Conditional orders migrate to Algo Service + * + **/ +⋮---- +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, +): Promise +⋮---- +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, +): Promise +⋮---- +cancelAllAlgoOpenOrders(params: { + symbol: string; +}): Promise +⋮---- +getAlgoOrder( + params: FuturesQueryAlgoOrderParams, +): Promise +⋮---- +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, +): Promise +⋮---- +getAllAlgoOrders( + params: FuturesQueryAllAlgoOrdersParams, +): Promise +⋮---- +/** + * + * 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< +⋮---- +/** + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, +): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +⋮---- +// USD-M Futures +⋮---- +getFuturesUserDataListenKey(): Promise< +⋮---- +keepAliveFuturesUserDataListenKey(): Promise +⋮---- +closeFuturesUserDataListenKey(): Promise +⋮---- +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, +): void + +================ +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'; +⋮---- +/** + * 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 +⋮---- +/** + * General event handlers for monitoring the WebsocketClient + */ +⋮---- +// 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() +⋮---- +// 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) +⋮---- +// 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); +⋮---- +// Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will +// automatically call this method again if reconnected, +⋮---- +WS_KEY_MAP.mainWSAPI, // The `mainWSAPI` wsKey will connect to the "spot" Websocket API on Binance. +⋮---- +// Start executing the example workflow + +================ +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'; +⋮---- +/** + * 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; +} +⋮---- +/** + * General response types + */ +export interface WSAPIServerTime { + serverTime: number; +} +⋮---- +/** + * Market data response types + */ +export interface WSAPIOrderBook { + lastUpdateId: number; + // [price, quantity] + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} +⋮---- +// [price, quantity] +⋮---- +export interface WSAPITrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; +} +⋮---- +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? +} +⋮---- +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? +⋮---- +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 +]; +⋮---- +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 +⋮---- +export interface WSAPIAvgPrice { + mins: number; // Average price interval (in minutes) + price: numberInString; // Average price + closeTime: number; // Last trade time +} +⋮---- +mins: number; // Average price interval (in minutes) +price: numberInString; // Average price +closeTime: number; // Last trade time +⋮---- +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 +} +⋮---- +firstId: number; // First trade ID +lastId: number; // Last trade ID +count: number; // Number of trades +⋮---- +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 +} +⋮---- +firstId: number; // First trade ID +lastId: number; // Last trade ID +count: number; // Number of trades +⋮---- +export interface WSAPIPriceTicker { + symbol: string; + price: numberInString; +} +⋮---- +export interface WSAPIBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; +} +⋮---- +/** + * 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][]; +} +⋮---- +E: number; // Message output time +T: number; // Transaction time +// [price, quantity] +⋮---- +export interface WSAPIFuturesPriceTicker { + symbol: string; + price: numberInString; + time: number; // Transaction time +} +⋮---- +time: number; // Transaction time +⋮---- +export interface WSAPIFuturesBookTicker { + lastUpdateId: number; + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; // Transaction time +} +⋮---- +time: number; // Transaction time +⋮---- +/** + * 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; +} +⋮---- +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; + }; +} +⋮---- +export interface WSAPIRateLimit { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} +⋮---- +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; +} +⋮---- +/** Present only for expired orders. */ +⋮---- +export interface WSAPIBlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} +⋮---- +export interface WSAPIOrderList { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; +} +⋮---- +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; +} +⋮---- +export interface WSAPIPreventedMatch { + symbol: string; + preventedMatchId: number; + takerOrderId: number; + makerSymbol: string; + makerOrderId: number; + tradeGroupId: number; + selfTradePreventionMode: string; + price: numberInString; + makerPreventedQuantity: numberInString; + transactTime: number; +} +⋮---- +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; +} +⋮---- +/** + * Trading response types + */ +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; + }; +} +⋮---- +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; +} +⋮---- +export interface WSAPIOrderCancelReplaceResponse { + cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: WSAPIOrderCancel | ErrorResponse; + newOrderResponse: OrderResponse | ErrorResponse | null; +} +⋮---- +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[]; +} +⋮---- +/** + * 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[]; +} +⋮---- +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; + }[]; +} +⋮---- +/** Present only for expired orders. */ +⋮---- +/** + * 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; +} +⋮---- +/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ +⋮---- +export interface WSAPISOROrderTestResponse { + // Empty response object + [key: string]: never; +} +⋮---- +// Empty response object +⋮---- +export interface WSAPISOROrderTestResponseWithCommission { + standardCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + discount: numberInString; + }; +} +⋮---- +/** + * 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; + modifyId?: number; +} +⋮---- +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; +} +⋮---- +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; +} +⋮---- +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; +} +⋮---- +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[]; +} +⋮---- +/** + * 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; +} +⋮---- +orderListId: number; // always -1 for singular orders +⋮---- +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; +} +⋮---- +/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ +⋮---- +export interface WSAPISpotOrderFill { + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; + tradeId: number; +} +⋮---- +export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { + fills: WSAPISpotOrderFill[]; +} +⋮---- +export type WSAPISpotOrderResponse = + | WSAPISpotOrderACK + | WSAPISpotOrderRESULT + | WSAPISpotOrderFULL; + +================ +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'; + 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; + }; +} +⋮---- +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; + }; +} +⋮---- +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; +} +⋮---- +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; +} +⋮---- +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; +} +⋮---- +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'; + 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; +} +⋮---- +/** + * @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. + */ +⋮---- +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; +} +⋮---- +export interface WsMessageBookTickerEventFormatted extends WsSharedBase { + eventType: 'bookTicker'; + updateId: number; + eventTime: number; + transactionTime: number; + symbol: string; + bidPrice: number; + bidQty: number; + askPrice: number; + askQty: number; +} +⋮---- +export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { + eventType: 'partialBookDepth' | 'string'; + lastUpdateId: number; + bids: OrderBookRowFormatted[]; + asks: OrderBookRowFormatted[]; +} +⋮---- +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 }[]; +} +⋮---- +transactionTime: number; // futures only +⋮---- +finalUpdateId: number; // futures only +⋮---- +/** + * USER DATA WS EVENTS + **/ +⋮---- +interface SpotBalanceFormatted { + asset: string; + availableBalance: number; + onOrderBalance: number; +} +⋮---- +export interface WsMessageSpotOutboundAccountPositionFormatted + extends WsSharedBase { + eventType: 'outboundAccountPosition'; + eventTime: number; + lastAccountUpdateTime: number; + balances: SpotBalanceFormatted[]; +} +⋮---- +export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { + eventType: 'balanceUpdate'; + eventTime: number; + asset: string; + balanceDelta: number; + clearTime: number; +} +⋮---- +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; +} +⋮---- +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; +} +⋮---- +export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { + eventType: 'serverShutdown'; + eventTime: number; +} +⋮---- +export interface OrderObjectFormatted { + symbol: string; + orderId: number; + clientOrderId: string; +} +⋮---- +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 interface WsAccountUpdatedBalance { + asset: string; + balanceChange: number; // this is except for pnl and commission + crossWalletBalance: number; + walletBalance: number; +} +⋮---- +balanceChange: number; // this is except for pnl and commission +⋮---- +export interface WsUpdatedPosition { + symbol: string; + marginAsset: string; + positionAmount: number; + entryPrice: number; + accumulatedRealisedPreFee: number; + unrealisedPnl: number; + marginType: 'cross' | 'isolated'; + isolatedWalletAmount: number; + positionSide: PositionSide; +} +⋮---- +export interface WsMessageFuturesUserDataListenKeyExpiredFormatted + extends WsSharedBase { + eventType: 'listenKeyExpired'; + eventTime: number; +} +⋮---- +export interface WsMessageFuturesMarginCalledPositionFormatted { + symbol: string; + positionSide: PositionSide; + positionAmount: number; + marginType: Uppercase; + isolatedWalletAmount: number; + markPrice: number; + unrealisedPnl: number; + maintenanceMarginRequired: number; +} +⋮---- +export interface WsMessageFuturesUserDataMarginCallFormatted + extends WsSharedBase { + eventType: 'MARGIN_CALL'; + eventTime: number; + crossWalletBalance: number; + positions: WsMessageFuturesMarginCalledPositionFormatted[]; +} +⋮---- +export interface WsMessageFuturesUserDataAccountUpdateFormatted + extends WsSharedBase { + eventType: 'ACCOUNT_UPDATE'; + eventTime: number; + transactionTime: number; + updateData: { + updateEventType: AccountUpdateEventType; + symbol?: string; // only when updateEventType is FUNDING_FEE + updatedBalances: WsAccountUpdatedBalance[]; + updatedPositions: WsUpdatedPosition[]; + }; +} +⋮---- +symbol?: string; // only when updateEventType is FUNDING_FEE +⋮---- +export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted + extends WsSharedBase { + eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; + eventTime: number; + transactionTime: number; + order: { + symbol: string; + orderId: number; + reason: string; + }; +} +⋮---- +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; +} +⋮---- +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 + modifyId?: string; // from modify request; only when executionType is AMENDMENT + pP?: boolean; // ignore + si?: number; // ignore + ss?: number; // ignore + }; +} +⋮---- +orderExpireReason?: string; // Order expire reason +modifyId?: string; // from modify request; only when executionType is AMENDMENT +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 WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { + eventType: 'indexPriceUpdate'; + eventTime: number; + symbol: string; + indexPrice: number; +} +⋮---- +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; +} +⋮---- +/** Mark price moving average (USDⓈ-M). */ +⋮---- +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 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 WsMessageForceOrderFormatted extends WsSharedBase { + eventType: 'forceOrder'; + eventTime: number; + liquidationOrder: WsLiquidationOrderFormatted; +} +⋮---- +export interface WsMessageFuturesUserDataStrategyUpdateFormatted + extends WsSharedBase { + eventType: 'STRATEGY_UPDATE'; + transactionTime: number; + eventTime: number; + strategy: { + strategyId: number; + strategyType: string; + strategyStatus: string; + symbol: string; + updateTime: number; + opCode: number; + }; +} +⋮---- +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; + }; +} +⋮---- +export interface WsMessageFuturesUserDataContractInfoFormatted + 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; + }[]; +} +⋮---- +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; + isActivated?: boolean; // trailing stop activation; placeholder, always false for now + }; +} +⋮---- +actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType +⋮---- +isActivated?: boolean; // trailing stop activation; placeholder, always false for now +⋮---- +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/coinm-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; +⋮---- +import { + 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, + logInvalidOrderId, + RestClientOptions, +} from './util/requestUtils'; +⋮---- +export class CoinMClient 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 + * + **/ +⋮---- +testConnectivity(): Promise +⋮---- +getExchangeInfo(): Promise +⋮---- +getOrderBook(params: OrderBookParams): Promise +⋮---- +getRecentTrades(params: RecentTradesParams): Promise +⋮---- +getHistoricalTrades( + params: HistoricalTradesParams, +): Promise +⋮---- +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise +⋮---- +/** + * Index Price and Mark Price + */ +getMarkPrice(params?: +⋮---- +getFundingRateHistory( + params?: Partial, +): Promise +⋮---- +getFundingRate(params?: +⋮---- +getKlines(params: KlinesParams): Promise +⋮---- +getContinuousContractKlines( + params: ContinuousContractKlinesParams, +): Promise +⋮---- +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +⋮---- +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +⋮---- +getPremiumIndexKlines(params: KlinesParams): Promise +⋮---- +get24hrChangeStatistics(params?: { + symbol?: string; + pair?: string; +}): Promise +⋮---- +getSymbolPriceTicker(params?: { + symbol?: string; + pair?: string; +}): Promise +⋮---- +getSymbolOrderBookTicker(params?: { + symbol?: string; + pair?: string; +}): Promise +⋮---- +getOpenInterest(params: +⋮---- +getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise +⋮---- +getTopTradersLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise +⋮---- +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams & { pair?: string }, +): Promise +⋮---- +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise +⋮---- +getTakerBuySellVolume( + params: FuturesCoinMTakerBuySellVolumeParams, +): Promise +⋮---- +getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise +⋮---- +/** + * 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 + * + **/ +⋮---- +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. + * + * Known issue: `quantity` and `price` should be sent as strings + */ +submitMultipleOrders( + orders: NewFuturesOrderParams[], +): Promise<(NewOrderResult | NewOrderError)[]> +⋮---- +/** + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + */ +modifyOrder( + params: ModifyFuturesOrderParams, +): 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. + */ +modifyMultipleOrders( + orders: ModifyFuturesOrderParams[], +): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> +⋮---- +getOrderModifyHistory( + params: GetOrderModifyHistoryParams, +): 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 +⋮---- +/** + * + * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) + * Conditional orders migrate to Algo Service on COIN-M + * + **/ +⋮---- +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, +): Promise +⋮---- +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, +): Promise +⋮---- +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, +): Promise +⋮---- +getForceOrders(params?: GetForceOrdersParams): Promise +⋮---- +getAccountTrades( + params: CoinMAccountTradeParams & { orderId?: number }, +): Promise +⋮---- +getPositions(params?: { + marginAsset?: string; + pair?: string; +}): Promise +⋮---- +setPositionMode(params: PositionModeParams): Promise +⋮---- +setMarginType(params: SetMarginTypeParams): Promise +⋮---- +setLeverage(params: SetLeverageParams): Promise +⋮---- +getADLQuantileEstimation(params?: +⋮---- +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< +⋮---- +getFuturesTradeHistoryDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +/** + * + * Portfolio Margin Endpoints + * + **/ +⋮---- +getClassicPortfolioMarginAccount(params: { + asset: string; +}): Promise +⋮---- +/** + * @deprecated at 6th August, 2024 + **/ +getClassicPortfolioMarginNotionalLimits( + params?: GetClassicPortfolioMarginNotionalLimitParams, +): 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< +⋮---- +/** + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, +): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise +⋮---- +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +⋮---- +getFuturesUserDataListenKey(): Promise< +⋮---- +keepAliveFuturesUserDataListenKey(): Promise +⋮---- +closeFuturesUserDataListenKey(): Promise +⋮---- +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, +): void + +================ +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; + 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 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[]; +} +⋮---- +export type AccountUpdateEventType = + | 'DEPOSIT' + | 'WITHDRAW' + | 'ORDER' + | 'FUNDING_FEE' + | 'WITHDRAW_REJECT' + | 'ADJUSTMENT' + | 'INSURANCE_CLEAR' + | 'ADMIN_DEPOSIT' + | 'ADMIN_WITHDRAW' + | 'MARGIN_TRANSFER' + | 'MARGIN_TYPE_CHANGE' + | 'ASSET_TRANSFER' + | 'OPTIONS_PREMIUM_FEE' + | 'OPTIONS_SETTLE_PROFIT' + | 'AUTO_EXCHANGE'; +⋮---- +export interface WsMessageFuturesUserDataListenKeyExpiredRaw + extends WsSharedBase { + e: 'listenKeyExpired'; + E: number; +} +⋮---- +export interface WsEventStreamTerminatedRaw extends WsSharedBase { + e: 'eventStreamTerminated'; + E: number; +} +⋮---- +export interface WsMessageFuturesMarginCalledPositionRaw { + s: string; + ps: PositionSide; + pa: numberInString; + mt: Uppercase; + iw: numberInString; + mp: numberInString; + up: numberInString; + mm: numberInString; +} +⋮---- +export interface WsMessageFuturesUserDataMarginCallRaw extends WsSharedBase { + e: 'MARGIN_CALL'; + E: number; + cw: numberInString; + p: WsMessageFuturesMarginCalledPositionRaw[]; +} +⋮---- +export interface WsMessageFuturesAccountUpdatePositionRaw { + s: string; + pa: numberInString; + ep: numberInString; + cr: numberInString; + up: numberInString; + mt: 'cross' | 'isolated'; + iw: numberInString; + ps: PositionSide; +} +⋮---- +export interface WsMessageFuturesAccountUpdateBalanceRaw { + a: string; + wb: numberInString; + cw: numberInString; + bc: numberInString; +} +⋮---- +export interface WsMessageFuturesUserDataAccountUpdateRaw extends WsSharedBase { + e: 'ACCOUNT_UPDATE'; + E: number; + T: number; + a: { + m: AccountUpdateEventType; + S?: string; // symbol; only when m is FUNDING_FEE + B: WsMessageFuturesAccountUpdateBalanceRaw[]; + P: WsMessageFuturesAccountUpdatePositionRaw[]; + }; +} +⋮---- +S?: string; // symbol; only when m is FUNDING_FEE +⋮---- +export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw + extends WsSharedBase { + e: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; + E: number; + T: number; + or: { + s: string; + i: number; + r: string; + }; +} +⋮---- +export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw + extends WsSharedBase { + e: 'ORDER_TRADE_UPDATE'; + E: number; + T: number; + o: { + s: string; + c: string; + S: OrderSide; + o: FuturesOrderType; + f: OrderTimeInForce; + q: numberInString; + p: numberInString; + ap: numberInString; + sp: numberInString; + x: OrderExecutionType; + X: OrderStatus; + i: number; + l: numberInString; + z: numberInString; + L: numberInString; + N: string; + n: numberInString; + T: numberInString; + t: number; + b: numberInString; + a: numberInString; + m: boolean; + R: boolean; + wt: WorkingType; + ot: FuturesOrderType; + ps: PositionSide; + cp: boolean; + AP: numberInString; + cr: numberInString; + rp: numberInString; + pP: boolean; // ignore + si: numberInString; // ignore + ss: numberInString; // ignore + V: string; + pm: string; + gtd: number; + er?: string; // Order expire reason (available effective 2025-10-23) + M?: string; // modifyId from modify request; only when x is AMENDMENT + }; +} +⋮---- +pP: boolean; // ignore +si: numberInString; // ignore +ss: numberInString; // ignore +⋮---- +er?: string; // Order expire reason (available effective 2025-10-23) +M?: string; // modifyId from modify request; only when x is AMENDMENT +⋮---- +export interface WsMessageFuturesUserDataAlgoUpdateRaw extends WsSharedBase { + e: 'ALGO_UPDATE'; + E: number; + T: number; + o: { + caid: string; + aid: number; + at: FuturesAlgoOrderType; + o: FuturesAlgoConditionalOrderTypes; + s: string; + S: OrderSide; + ps: PositionSide; + f: OrderTimeInForce; + q: numberInString; + X: FuturesAlgoOrderStatus; + ai: string; + tp: numberInString; + p: numberInString; + V: SelfTradePreventionMode; + wt: WorkingType; + pm: PriceMatchMode; + cp: boolean; + pP: boolean; + R: boolean; + tt: number; + gtd: number; + ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now + }; +} +⋮---- +ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now +⋮---- +export interface WsMessageFuturesUserDataTradeLiteEventRaw + extends WsSharedBase { + e: 'TRADE_LITE'; // Event Type + E: number; // Event Time + T: number; // Transaction Time + s: string; // Symbol + q: string; // Original Quantity + p: string; // Original Price + m: boolean; // Is this trade the maker side? + c: string; // Client Order Id + S: 'BUY' | 'SELL'; // Side + L: string; // Last Filled Price + l: string; // Order Last Filled Quantity + t: number; // Trade Id + i: number; // Order Id +} +⋮---- +e: 'TRADE_LITE'; // Event Type +E: number; // Event Time +T: number; // Transaction Time +s: string; // Symbol +q: string; // Original Quantity +p: string; // Original Price +m: boolean; // Is this trade the maker side? +c: string; // Client Order Id +S: 'BUY' | 'SELL'; // Side +L: string; // Last Filled Price +l: string; // Order Last Filled Quantity +t: number; // Trade Id +i: number; // Order Id +⋮---- +export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw + extends WsSharedBase { + e: 'ACCOUNT_CONFIG_UPDATE'; + E: number; + T: number; + ac?: { + s: string; + l: number; + }; + ai?: { + j: boolean; + }; +} +⋮---- +export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { + e: 'indexPriceUpdate'; + E: number; + i?: string; + s?: string; + p: numberInString; +} +⋮---- +export interface WsMessageMarkPriceUpdateEventRaw extends WsSharedBase { + e: 'markPriceUpdate'; + E: number; + s: string; + p: string; + /** Mark price moving average (USDⓈ-M mark price stream). */ + ap?: string; + P: string; + i: string; + r: string; + T: number; +} +⋮---- +/** Mark price moving average (USDⓈ-M mark price stream). */ +⋮---- +export interface WsMessageForceOrderRaw extends WsSharedBase { + e: 'forceOrder'; + E: number; + o: { + s: string; + S: string; + o: string; + f: string; + q: string; + p: string; + ap: string; + X: string; + l: string; + z: string; + T: number; + }; +} +⋮---- +export interface WsMessageFuturesUserDataStrategyUpdateRaw + extends WsSharedBase { + e: 'STRATEGY_UPDATE'; // Event Type + T: number; // Transaction Time + E: number; // Event Time + su: { + si: number; // Strategy ID + st: string; // Strategy Type + ss: string; // Strategy Status + s: string; // Symbol + ut: number; // Update Time + c: number; // opCode + }; +} +⋮---- +e: 'STRATEGY_UPDATE'; // Event Type +T: number; // Transaction Time +E: number; // Event Time +⋮---- +si: number; // Strategy ID +st: string; // Strategy Type +ss: string; // Strategy Status +s: string; // Symbol +ut: number; // Update Time +c: number; // opCode +⋮---- +export interface WsMessageFuturesUserDataGridUpdateRaw extends WsSharedBase { + e: 'GRID_UPDATE'; // Event Type + T: number; // Transaction Time + E: number; // Event Time + gu: { + si: number; // Strategy ID + st: string; // Strategy Type + ss: string; // Strategy Status + s: string; // Symbol + r: numberInString; // Realized PNL + up: numberInString; // Unmatched Average Price + uq: numberInString; // Unmatched Qty + uf: numberInString; // Unmatched Fee + mp: numberInString; // Matched PNL + ut: number; // Update Time + }; +} +⋮---- +e: 'GRID_UPDATE'; // Event Type +T: number; // Transaction Time +E: number; // Event Time +⋮---- +si: number; // Strategy ID +st: string; // Strategy Type +ss: string; // Strategy Status +s: string; // Symbol +r: numberInString; // Realized PNL +up: numberInString; // Unmatched Average Price +uq: numberInString; // Unmatched Qty +uf: numberInString; // Unmatched Fee +mp: numberInString; // Matched PNL +ut: number; // Update Time +⋮---- +export interface WsMessageFuturesUserDataContractInfoRaw extends WsSharedBase { + e: 'contractInfo'; // Event Type + E: number; // Event Time + s: string; // Symbol + ps: string; // Pair + ct: string; // Contract type + dt: number; // Delivery date time + ot: number; // onboard date time + cs: string; // Contract status + bks: { + bs: number; // Notional bracket + bnf: number; // Floor notional of this bracket + bnc: number; // Cap notional of this bracket + mmr: number; // Maintenance ratio for this bracket + cf: number; // Auxiliary number for quick calculation + mi: number; // Min leverage for this bracket + ma: number; // Max leverage for this bracket + }[]; +} +⋮---- +e: 'contractInfo'; // Event Type +E: number; // Event Time +s: string; // Symbol +ps: string; // Pair +ct: string; // Contract type +dt: number; // Delivery date time +ot: number; // onboard date time +cs: string; // Contract status +⋮---- +bs: number; // Notional bracket +bnf: number; // Floor notional of this bracket +bnc: number; // Cap notional of this bracket +mmr: number; // Maintenance ratio for this bracket +cf: number; // Auxiliary number for quick calculation +mi: number; // Min leverage for this bracket +ma: number; // Max leverage for this bracket +⋮---- +export type WsRawSpotUserDataEventRaw = + | WsMessageSpotUserDataExecutionReportEventRaw + | WsMessageSpotOutboundAccountPositionRaw + | WsMessageSpotBalanceUpdateRaw + | WsMessageSpotUserDataListStatusEventRaw; +⋮---- +export type WsMessageFuturesUserDataEventRaw = + | WsMessageFuturesUserDataAccountUpdateRaw + | WsMessageFuturesUserDataListenKeyExpiredRaw + | WsMessageFuturesUserDataMarginCallRaw + | WsMessageFuturesUserDataOrderTradeUpdateEventRaw + | WsMessageFuturesUserDataAlgoUpdateRaw + | WsMessageFuturesUserDataAccountConfigUpdateEventRaw + | WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw + | WsMessageFuturesUserDataTradeLiteEventRaw + | WsMessageFuturesUserDataStrategyUpdateRaw + | WsMessageFuturesUserDataGridUpdateRaw + | WsMessageFuturesUserDataContractInfoRaw; +⋮---- +export type WsUserDataEventsRaw = + | WsRawSpotUserDataEventRaw + | WsMessageFuturesUserDataEventRaw + | WsMessagePortfolioMarginProAccountUpdateRaw; +⋮---- +export type WsRawMessage = + | WsEventStreamTerminatedRaw + | WsMessageWsapiServerShutdownRaw + | WsUserDataEventsRaw + | WsMessageKlineRaw + | WsMessageAggTradeRaw + | WsMessageTradeRaw + | WsMessage24hrMiniTickerRaw + | WsMessage24hrMiniTickerRaw[] + | WsMessage24hrTickerRaw + | WsMessage24hrTickerRaw[] + | WsMessageRollingWindowTickerRaw[] + | WsMessageBookTickerEventRaw + | WsMessagePartialBookDepthEventRaw + | WsMessageDiffBookDepthEventRaw + | WsMessageForceOrderRaw + | WsMessageIndexPriceUpdateEventRaw; + +================ +File: src/types/websockets/ws-general.ts +================ +import { AxiosRequestConfig } from 'axios'; +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; +⋮---- +import { RestClientOptions } from '../../util/requestUtils'; +import { WsKey } from '../../util/websockets/websocket-util'; +⋮---- +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} +⋮---- +export function isMessageEvent(msg: unknown): msg is MessageEventLike +⋮---- +export type WsMarket = + | 'spot' + | 'spotTestnet' + | 'crossMargin' + | 'isolatedMargin' + | 'riskDataMargin' + | 'usdm' + | 'usdmTestnet' + | 'coinm' + | 'coinmTestnet' + | 'options' + | 'optionsTestnet' + | 'portfoliom' + | 'alpha'; +⋮---- +export interface WsSharedBase { + wsMarket: WsMarket; + wsKey: WsKey; + streamName: string; +} +⋮---- +export interface WsResponse { + type: 'message'; + data: { + result: boolean | string[] | null; + id: number; + isWSAPIResponse: boolean; + wsKey: WsKey; + }; +} +⋮---- +// Same as inverse futures +export type WsPublicInverseTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'klineV2'; +⋮---- +export type WsPublicUSDTPerpTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'kline'; +⋮---- +export type WsPublicSpotV1Topic = + | 'trade' + | 'realtimes' + | 'kline' + | 'mergedDepth' + | 'diffDepth'; +⋮---- +export type WsPublicSpotV2Topic = 'depth' | 'kline' | 'trade' | 'realtimes'; +⋮---- +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data +export type WsPublicUSDMTopic = 'bookTicker' | 'depth'; +⋮---- +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#market-regular-market-data +export type WsMarketUSDMTopic = + | 'aggTrade' + | 'markPrice' + | 'kline' + | 'continuousKline' + | 'miniTicker' + | 'ticker' + | 'forceOrder' + | 'compositeIndex' + | 'contractInfo' + | 'assetIndex'; +⋮---- +export type WsPublicTopics = + | WsPublicInverseTopic + | WsPublicUSDTPerpTopic + | WsPublicSpotV1Topic + | WsPublicSpotV2Topic + | WsMarketUSDMTopic + | WsPublicUSDMTopic + | string; +⋮---- +// Same as inverse futures +export type WsPrivateInverseTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order'; +⋮---- +export type WsPrivateUSDTPerpTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order' + | 'wallet'; +⋮---- +export type WsPrivateSpotTopic = + | 'outboundAccountInfo' + | 'executionReport' + | 'ticketInfo'; +⋮---- +export type WsPrivateTopic = + | WsPrivateInverseTopic + | WsPrivateUSDTPerpTopic + | WsPrivateSpotTopic + | string; +⋮---- +export type WsTopic = WsPublicTopics | WsPrivateTopic; +⋮---- +export interface WSClientConfigurableOptions { + /** Your API key */ + api_key?: string; + + /** Your API secret */ + api_secret?: string; + + beautify?: boolean; + + /** + * If true, log a warning if the beautifier is missing anything for an event + */ + beautifyWarnIfMissing?: boolean; + + /** + * Set to `true` to connect to Binance's testnet environment. + * + * Notes: + * - Not all WebSocket categories support testnet. + * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets + */ + testnet?: boolean; + + /** + * Set to `true` to use Binance's demo trading WebSocket endpoints. + * Demo trading uses real market data but simulated trading. + * More info: https://demo.binance.com/ + * + * Notes: + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + */ + demoTrading?: boolean; + + /** + * Default: false. If true, use market maker endpoints when available. + * Eligible for high-frequency trading users who have enrolled and qualified + * in at least one of the Futures Liquidity Provider Programs. + * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + */ + useMMSubdomain?: boolean; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; + + // Disable ping/pong ws heartbeat mechanism (not recommended) + disableHeartbeat?: boolean; + + /** How often to check if the connection is alive */ + pingInterval?: number; + + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; + + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; + + restOptions?: RestClientOptions; + + requestOptions?: AxiosRequestConfig; + + wsOptions?: { + protocols?: string[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); + + wsUrl?: string; + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ + customSignMessageFn?: (message: string, secret: string) => Promise; + + /** + * Optional custom JSON parser used for incoming WS messages. + * Defaults to JSON.parse. + */ + customParseJSONFn?: (raw: string) => object; +} +⋮---- +/** Your API key */ +⋮---- +/** Your API secret */ +⋮---- +/** + * If true, log a warning if the beautifier is missing anything for an event + */ +⋮---- +/** + * Set to `true` to connect to Binance's testnet environment. + * + * Notes: + * - Not all WebSocket categories support testnet. + * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets + */ +⋮---- +/** + * Set to `true` to use Binance's demo trading WebSocket endpoints. + * Demo trading uses real market data but simulated trading. + * More info: https://demo.binance.com/ + * + * Notes: + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + */ +⋮---- +/** + * Default: false. If true, use market maker endpoints when available. + * Eligible for high-frequency trading users who have enrolled and qualified + * in at least one of the Futures Liquidity Provider Programs. + * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + */ +⋮---- +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +⋮---- +// Disable ping/pong ws heartbeat mechanism (not recommended) +⋮---- +/** How often to check if the connection is alive */ +⋮---- +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +⋮---- +/** Delay in milliseconds before respawning the connection */ +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ +⋮---- +/** + * Optional custom JSON parser used for incoming WS messages. + * Defaults to JSON.parse. + */ +⋮---- +/** + * WS configuration that's always defined, regardless of user configuration + * (usually comes from defaults if there's no user-provided values) + */ +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + pongTimeout: number; + pingInterval: number; + reconnectTimeout: number; + recvWindow: number; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequestsIndividually: boolean; +} + +================ +File: src/websocket-client-legacy.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ +import { EventEmitter } from 'events'; +import WebSocket from 'isomorphic-ws'; +⋮---- +import { KlineInterval } from './types/shared'; +import { + WsFormattedMessage, + WsUserDataEvents, +} from './types/websockets/ws-events-formatted'; +import { WsRawMessage } from './types/websockets/ws-events-raw'; +import { + WebsocketClientOptions, + WSClientConfigurableOptions, + WsMarket, + WsResponse, +} from './types/websockets/ws-general'; +import Beautifier from './util/beautifier'; +import { DefaultLogger } from './util/logger'; +import { appendEventIfMissing, RestClientOptions } from './util/requestUtils'; +import { neverGuard } from './util/typeGuards'; +import { ListenKeyStateCache } from './util/websockets/listen-key-state-cache'; +import { RestClientCache } from './util/websockets/rest-client-cache'; +import { + appendEventMarket, + getContextFromWsKey, + getLegacyWsStoreKeyWithContext, + parseEventTypeFromMessage, + parseRawWsMessageLegacy, + safeTerminateWs, + WS_LOGGER_CATEGORY, + WsKey, +} from './util/websockets/websocket-util'; +import { WsStore } from './util/websockets/WsStore'; +import { WsConnectionStateEnum } from './util/websockets/WsStore.types'; +⋮---- +alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams +⋮---- +type WsEventInternalSrc = 'event' | 'function'; +⋮---- +type WebSocketWithMetadata = WebSocket & { + onping?: (event: unknown) => void; + onpong?: (event: unknown) => void; + wsKey?: WsKey | string; +}; +⋮---- +export declare interface WebsocketClientV1 { + on(event: 'reply', listener: (event: WsResponse) => void): this; + + on(event: 'message', listener: (event: WsRawMessage) => void): this; + + on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; + + on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; + + on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; + + on( + event: 'open' | 'reconnected', + listener: (event: { + wsKey: WsKey; + ws: WebSocket.Event; + event?: any; + }) => void, + ): this; + + on( + event: 'reconnecting' | 'close', + listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, + ): this; +} +⋮---- +on(event: 'reply', listener: (event: WsResponse) +⋮---- +on(event: 'message', listener: (event: WsRawMessage) +⋮---- +on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; +⋮---- +on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; +⋮---- +on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; +⋮---- +on( + event: 'open' | 'reconnected', + listener: (event: { + wsKey: WsKey; + ws: WebSocket.Event; + event?: any; + }) => void, + ): this; +⋮---- +on( + event: 'reconnecting' | 'close', + listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, + ): this; +⋮---- +/** + * @deprecated This legacy websocket client creates one websocket connection per topic. + * + * If subscribing to a lot of topics, consider using the new multiplex `WebsocketClient`. + * + * To split your topics into smaller groups (one connection per group), simply make multiple multiplex WebsocketClient instances. + */ +export class WebsocketClientV1 extends EventEmitter +⋮---- +constructor( + options: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, +) +⋮---- +// Some defaults: +⋮---- +// Automatically send an authentication op/request after a connection opens, for private connections. +⋮---- +// Individual requests require a signature +⋮---- +// add default error handling so this doesn't crash node (if the user didn't set a handler) +⋮---- +private getRestClientOptions(): RestClientOptions +⋮---- +public connectToWsUrl( + url: string, + wsKey?: WsKey | string, + forceNewConnection?: boolean, +): WebSocket +⋮---- +// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node +⋮---- +// Add ws connection with key to store +⋮---- +public tryWsSend(wsKey: WsKey | string, wsMessage: string) +⋮---- +public tryWsPing(wsKey: WsKey | string) +⋮---- +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +⋮---- +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +⋮---- +private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) +⋮---- +private onWsClose( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + wsUrl: string, +) +⋮---- +// Clear any timers before we initiate revival +⋮---- +// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states +⋮---- +private onWsMessage( + event: WebSocket.MessageEvent, + wsKey: WsKey | string, + source: WsEventInternalSrc, +) +⋮---- +// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e +⋮---- +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn +⋮---- +// emit a separate event for user data messages +⋮---- +private sendPing(wsKey: WsKey | string, wsUrl: string) +⋮---- +private onWsPing( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + source: WsEventInternalSrc, +) +⋮---- +private onWsPong( + event: any, + wsKey: WsKey | string, + source: WsEventInternalSrc, +) +⋮---- +/** + * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. + * If closed, trigger a reconnect immediately + */ +private executeReconnectableClose( + wsKey: WsKey | string, + reason: string, + wsUrl: string, +) +⋮---- +public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) +⋮---- +public closeAll(shouldReconnectAfterClose?: boolean) +⋮---- +public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) +⋮---- +private parseWsError( + context: string, + error: any, + wsKey: WsKey | string, + wsUrl: string, +) +⋮---- +private reconnectWithDelay( + wsKey: WsKey | string, + connectionDelayMs: number, + wsUrl: string, +) +⋮---- +// We'll set a new one once the new stream respawns, with a diff listenKey in the key +⋮---- +private clearTimers(wsKey: WsKey | string) +⋮---- +// Send a ping at intervals +private clearPingTimer(wsKey: WsKey | string) +⋮---- +// Expect a pong within a time limit +private clearPongTimer(wsKey: WsKey | string) +⋮---- +// Timer tracking that a reconnect is about to happen / in progress +private clearReconnectTimer(wsKey: WsKey | string) +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string +⋮---- +public getWs(wsKey: WsKey | string): WebSocket | undefined +⋮---- +private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) +⋮---- +/** + * Send WS message to subscribe to topics. Use subscribe() to call this. + */ +private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) +⋮---- +/** + * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. + */ +private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) +⋮---- +/** + * Send WS message to unsubscribe from topics. + */ +public requestListSubscriptions(wsKey: WsKey, requestId: number) +⋮---- +/** + * Send WS message to set property state + */ +public requestSetProperty( + wsKey: WsKey, + property: 'combined' | string, + value: any, + requestId: number, +) +⋮---- +/** + * Send WS message to get property state + */ +public requestGetProperty( + wsKey: WsKey, + property: 'combined' | string, + requestId: number, +) +⋮---- +/** + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- + **/ +⋮---- +private setKeepAliveListenKeyTimer( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, +) +⋮---- +// Set timer to keep WS alive every 50 minutes +⋮---- +// 1000 * 60 +⋮---- +private sendKeepAliveForMarket( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, +) +⋮---- +private async checkKeepAliveListenKey( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, +) +⋮---- +// Simple way to test keep alive failure handling: +// throw new Error(`Fake keep alive failure`); +⋮---- +// code: -1125, +// message: 'This listenKey does not exist.', +⋮---- +// If max failurees reached, tear down and respawn if allowed +⋮---- +// reconnect follows a less automatic workflow since this is tied to a listen key (which may need a new one). +// Kill connection first, with instruction NOT to reconnect automatically +⋮---- +// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) +⋮---- +private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) +⋮---- +private async respawnUserDataStream( + market: WsMarket, + symbol?: string, + isTestnet?: boolean, + respawnAttempt?: number, +): Promise +⋮---- +// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key +⋮---- +// This timer should probably be tracked/singleton +⋮---- +/** + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- + **/ +⋮---- +/** + * Subscribe to a universal market websocket stream + */ +⋮---- +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to aggregate trades for a symbol in a market category + */ +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to trades for a symbol in a market category + * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning + */ +public subscribeTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to coin index for a symbol in COINM Futures markets + */ +public subscribeCoinIndexPrice( + symbol: string, + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to mark price for a symbol in a market category + */ +public subscribeMarkPrice( + symbol: string, + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to klines(candles) for a symbol in a market category + */ +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to continuous contract klines(candles) for a symbol futures + */ +public subscribeContinuousContractKlines( + symbol: string, + contractType: 'perpetual' | 'current_quarter' | 'next_quarter', + interval: KlineInterval, + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +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, + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + 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. + */ +public subscribeSpotUserDataStreamWithListenKey( + listenKey: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): WebSocket | undefined +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) +⋮---- +/** + * 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 +⋮---- +/** + * Subscribe to margin user data stream - listen key is automatically generated. + */ +public async subscribeMarginUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) +⋮---- +/** + * Subscribe to isolated margin user data stream - listen key is automatically generated. + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) +⋮---- +/** + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ +⋮---- +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeUsdFuturesUserDataStream( + 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) +⋮---- +/** + * 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: .nvmrc +================ +v24.18.0 + +================ +File: src/types/futures.ts +================ +import { + BooleanString, + ExchangeFilter, + KlineInterval, + numberInString, + OrderBookRow, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SymbolIcebergPartsFilter, + SymbolLotSizeFilter, + SymbolMarketLotSizeFilter, + SymbolMaxIcebergOrdersFilter, + SymbolMaxPositionFilter, + SymbolPriceFilter, +} from './shared'; +⋮---- +export type FuturesContractType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; +⋮---- +export interface ContinuousContractKlinesParams { + pair: string; + contractType: FuturesContractType; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface IndexPriceKlinesParams { + pair: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface SymbolKlinePaginatedParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface FuturesDataPaginatedParams { + symbol: string; + contractType?: string; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface FuturesCoinMTakerBuySellVolumeParams { + pair: string; + contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface FuturesCoinMBasisParams { + pair: string; + contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export enum EnumDualSideMode { + HedgeMode = 'true', + OneWayMode = 'false', +} +⋮---- +export type DualSideMode = `${EnumDualSideMode}`; +⋮---- +export enum EnumMultiAssetMode { + MultiAssetsMode = 'true', + SingleAssetsMode = 'false', +} +⋮---- +export type MultiAssetsMode = `${EnumMultiAssetMode}`; +⋮---- +export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; +⋮---- +export type MarginType = 'ISOLATED' | 'CROSSED'; +⋮---- +export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +⋮---- +export type FuturesOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; +⋮---- +export type PriceMatchMode = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; +⋮---- +// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. +export interface NewFuturesOrderParams { + 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 +} +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +export interface ModifyFuturesOrderParams { + orderId?: number; + origClientOrderId?: string; + symbol: string; + side: OrderSide; + quantity?: numberType; + price?: numberType; + priceMatch?: PriceMatchMode; + modifyId?: number; +} +⋮---- +export enum EnumPositionMarginChangeType { + AddPositionMargin = 1, + ReducePositionMargin = 0, +} +⋮---- +export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; +⋮---- +export type IncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR'; +⋮---- +export interface CancelMultipleOrdersParams { + symbol: string; + orderIdList?: number[]; + origClientOrderIdList?: string[]; +} +⋮---- +export interface CancelOrdersTimeoutParams { + symbol: string; + countdownTime?: 0 | number; +} +⋮---- +export interface SetLeverageParams { + symbol: string; + leverage: number; +} +⋮---- +export interface SetLeverageResult { + leverage: number; + maxNotionalValue: numberInString; + symbol: string; +} +⋮---- +export interface SetMarginTypeParams { + symbol: string; + marginType: MarginType; +} +⋮---- +export interface SetIsolatedMarginParams { + symbol: string; + positionSide?: PositionSide; + amount: number; + type: PositionMarginChangeType; +} +⋮---- +export interface SetIsolatedMarginResult { + amount: numberInString; + code: 200 | number; + msg: string; + type: 1 | 2; +} +⋮---- +export interface GetPositionMarginChangeHistoryParams { + symbol: string; + type?: PositionMarginChangeType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetIncomeHistoryParams { + symbol?: string; + incomeType?: IncomeType; + startTime?: number; + endTime?: number; + limit?: number; + page?: number; +} +⋮---- +export interface IncomeHistory { + symbol?: string; + incomeType: IncomeType; + income: string; + asset: string; + time: number; + info: string; + tranId: number; + tradeId: string; +} +⋮---- +export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; +⋮---- +export interface GetForceOrdersParams { + symbol?: string; + autoCloseType?: ForceOrderCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export type ContactType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; +⋮---- +export type ContractStatus = + | 'PENDING_TRADING' + | 'TRADING' + | 'PRE_DELIVERING' + | 'DELIVERING' + | 'DELIVERED' + | 'CANCELLED' + | 'PRE_SETTLE' + | 'SETTLING' + | 'CLOSE'; +⋮---- +export interface FuturesSymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + multiplierDecimal: numberInString; +} +⋮---- +export interface FuturesSymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + limit: number; +} +⋮---- +export interface FuturesSymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + limit: number; +} +⋮---- +export interface FuturesSymbolMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + notional: numberInString; +} +⋮---- +export type FuturesSymbolFilter = + | SymbolPriceFilter + | FuturesSymbolPercentPriceFilter + | SymbolLotSizeFilter + | FuturesSymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | FuturesSymbolMaxOrdersFilter + | FuturesSymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter; +⋮---- +export interface FuturesSymbolExchangeInfo { + symbol: string; + pair: string; + contractType: ContactType; + deliveryDate: number; + onboardDate: number; + status: ContractStatus; + maintMarginPercent: numberInString; + requiredMarginPercent: numberInString; + baseAsset: string; + quoteAsset: string; + marginAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + underlyingType: 'COIN' | 'INDEX'; // No other known values + underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc + settlePlan: number; + triggerProtect: numberInString; + filters: FuturesSymbolFilter[]; + OrderType: OrderType[]; + timeInForce: OrderTimeInForce[]; + liquidationFee: numberInString; + marketTakeBound: numberInString; + contractSize?: number; +} +⋮---- +underlyingType: 'COIN' | 'INDEX'; // No other known values +underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc +⋮---- +export interface FuturesExchangeInfo { + exchangeFilters: ExchangeFilter[]; + rateLimits: RateLimiter[]; + serverTime: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any[]; + symbols: FuturesSymbolExchangeInfo[]; + timezone: string; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface FuturesOrderBook { + lastUpdateId: number; + E: number; + T: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; +} +⋮---- +export interface RawFuturesTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} +⋮---- +export interface AggregateFuturesTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; +} +⋮---- +export interface MarkPrice { + symbol: string; + markPrice: numberInString; + indexPrice: numberInString; + estimatedSettlePrice: numberInString; + lastFundingRate: numberInString; + interestRate: numberInString; + nextFundingTime: number; + time: number; +} +⋮---- +export interface FundingRateHistory { + symbol: string; + fundingRate: numberInString; + fundingTime: number; + markPrice: numberInString; + rateType?: 'Regular' | 'Special'; +} +⋮---- +export interface FuturesSymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; +} +⋮---- +export interface OpenInterest { + openInterest: numberInString; + symbol: string; + time: number; +} +⋮---- +export interface HistoricOpenInterest { + symbol: string; + sumOpenInterest: string; + sumOpenInterestValue: string; + CMCCirculatingSupply: string; + timestamp: number; +} +⋮---- +export interface PositionModeParams { + dualSidePosition: DualSideMode; +} +⋮---- +export interface ModeChangeResult { + code: 200 | number; + msg: 'success' | string; +} +⋮---- +export interface PositionModeResponse { + dualSidePosition: boolean; +} +⋮---- +export interface MultiAssetModeResponse { + multiAssetsMargin: boolean; +} +⋮---- +export interface NewOrderResult { + clientOrderId: string; + cumQty: numberInString; + cumQuote: numberInString; + executedQty: numberInString; + orderId: number; + avgPrice: numberInString; + origQty: numberInString; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + origType: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; +} +⋮---- +export interface NewOrderError { + code: number; + msg: string; +} +⋮---- +export interface OrderResult { + avgPrice: numberInString; + clientOrderId: string; + cumQuote: numberInString; + executedQty: numberInString; + orderId: number; + origQty: numberInString; + origType: FuturesOrderType; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + time: number; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + goodTillDate: number; + cumBase?: numberInString; + pair?: string; +} +⋮---- +export interface ModifyFuturesOrderResult { + orderId: number; + symbol: string; + pair: string; + status: OrderStatus; + clientOrderId: string; + price: numberInString; + avgPrice: numberInString; + origQty: numberInString; + executedQty: numberInString; + cumQty: numberInString; + cumBase: numberInString; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + reduceOnly: boolean; + closePosition: boolean; + side: OrderSide; + positionSide: PositionSide; + stopPrice: numberInString; + workingType: WorkingType; + priceProtect: boolean; + origType: FuturesOrderType; + updateTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + modifyId?: number; +} +⋮---- +export interface CancelFuturesOrderResult { + clientOrderId: string; + cumQty: numberInString; + cumQuote: numberInString; + executedQty: numberInString; + orderId: number; + origQty: numberInString; + origType: FuturesOrderType; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; +} +⋮---- +export interface CancelAllOpenOrdersResult { + code: 200 | numberInString; + msg: string; +} +⋮---- +export interface FuturesAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + marginAvailable: boolean; + updateTime: numberInString; +} +⋮---- +export interface FuturesCoinMAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + withdrawAvailable: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + updateTime: number; +} +⋮---- +export interface FuturesAccountAsset { + asset: string; + walletBalance: numberInString; + unrealizedProfit: numberInString; + marginBalance: numberInString; + maintMargin: numberInString; + initialMargin: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + maxWithdrawAmount: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + marginAvailable: boolean; + updateTime: number; +} +⋮---- +export interface FuturesAccountPosition { + symbol: string; + initialMargin: numberInString; + maintMargin: numberInString; + unrealizedProfit: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + leverage: numberInString; + isolated: boolean; + entryPrice: numberInString; + maxNotional: numberInString; + positionSide: PositionSide; + positionAmt: numberInString; + notional: numberInString; + isolatedWallet: numberInString; + updateTime: number; + bidNotional: numberInString; + askNotional: numberInString; +} +⋮---- +export interface FuturesCoinMAccountPosition { + symbol: string; + positionAmt: numberInString; + initialMargin: numberInString; + maintMargin: numberInString; + unrealizedProfit: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + leverage: numberInString; + isolated: boolean; + positionSide: PositionSide; + entryPrice: numberInString; + maxQty: numberInString; + updateTime: number; +} +⋮---- +export interface FuturesAccountInformation { + feeTier: numberInString; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + updateTime: numberInString; + multiAssetsMargin: boolean; + totalInitialMargin: numberInString; + totalMaintMargin: numberInString; + totalWalletBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalMarginBalance: numberInString; + totalPositionInitialMargin: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalCrossWalletBalance: numberInString; + totalCrossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + assets: FuturesAccountAsset[]; + positions: FuturesAccountPosition[]; +} +⋮---- +export interface FuturesCoinMAccountInformation { + assets: Omit[]; + positions: FuturesCoinMAccountPosition[]; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; +} +⋮---- +export interface FuturesPosition { + entryPrice: numberInString; + marginType: 'isolated' | 'cross'; + isAutoAddMargin: 'false' | 'true'; + isolatedMargin: numberInString; + leverage: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + maxNotionalValue: numberInString; + positionAmt: numberInString; + notional: numberInString; + isolatedWallet: numberInString; + symbol: string; + unRealizedProfit: numberInString; + positionSide: PositionSide; + updateTime: number; +} +⋮---- +export interface FuturesPositionV3 { + symbol: string; + positionSide: PositionSide; + positionAmt: numberInString; + entryPrice: numberInString; + breakEvenPrice: numberInString; + markPrice: numberInString; + unRealizedProfit: numberInString; + liquidationPrice: numberInString; + isolatedMargin: numberInString; + notional: numberInString; + marginAsset: string; + isolatedWallet: numberInString; + initialMargin: numberInString; + maintMargin: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + adl: number; + bidNotional: numberInString; + askNotional: numberInString; + updateTime: number; +} +⋮---- +export interface FuturesPositionTrade { + buyer: boolean; + commission: numberInString; + commissionAsset: string; + id: number; + maker: boolean; + orderId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + realizedPnl: numberInString; + side: OrderSide; + positionSide: PositionSide; + symbol: string; + time: number; + pair?: string; + baseQty?: numberInString; + marginAsset?: string; +} +⋮---- +export interface ForceOrderResult { + orderId: number; + symbol: string; + status: OrderStatus; + clientOrderId: string; + price: numberInString; + avgPrice: numberInString; + origQty: numberInString; + executedQty: numberInString; + cumQuote: numberInString; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + reduceOnly: boolean; + closePosition: boolean; + side: OrderSide; + stopPrice: numberInString; + workingType: WorkingType; + origType: FuturesOrderType; + time: number; + updateTime: number; + cumBase?: numberInString; + pair?: string; + goodTillDate?: number; +} +⋮---- +export interface SymbolLeverageBracket { + bracket: number; + initialLeverage: number; + notionalCap: number; + notionalFloor: number; + maintMarginRatio: number; + cum: number; +} +⋮---- +export interface SymbolLeverageBracketsResult { + symbol: string; + brackets: SymbolLeverageBracket[]; +} +⋮---- +export interface UserCommissionRate { + symbol: string; + makerCommissionRate: numberInString; + takerCommissionRate: numberInString; + rpiCommissionRate?: numberInString; +} +⋮---- +export interface FuturesAccountConfig { + feeTier: number; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + dualSidePosition: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId: number; +} +⋮---- +export interface SymbolConfig { + symbol: string; + marginType: string; + isAutoAddMargin: string; + leverage: number; + maxNotionalValue: string; +} +⋮---- +export interface UserForceOrder { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; +} +⋮---- +export interface RebateDataOverview { + brokerId: string; + newTraderRebateCommission: numberInString; + oldTraderRebateCommission: numberInString; + totalTradeUser: number; + unit: string; + totalTradeVol: numberInString; + totalRebateVol: numberInString; + time: number; +} +⋮---- +export interface SetCancelTimeoutResult { + symbol: string; + countdownTime: numberInString; +} +⋮---- +export interface ChangeStats24hr { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; // First tradeId + lastId: number; // Last tradeId + count: number; +} +⋮---- +firstId: number; // First tradeId +lastId: number; // Last tradeId +⋮---- +export interface OrderAmendmentDetailPrice { + before: numberInString; + after: numberInString; +} +⋮---- +export interface OrderAmendmentDetailQty { + before: numberInString; + after: numberInString; +} +⋮---- +export interface OrderAmendmentDetail { + price: OrderAmendmentDetailPrice; + origQty: OrderAmendmentDetailQty; + count: number; +} +⋮---- +export interface OrderAmendment { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: OrderAmendmentDetail; + modifyId?: number; +} +⋮---- +export interface QuarterlyContractSettlementPrice { + deliveryTime: number; + deliveryPrice: number; +} +⋮---- +export interface BasisParams { + pair: string; + contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface Basis { + indexPrice: string; + contractType: string; + basisRate: string; + futuresPrice: string; + annualizedBasisRate: string; + basis: string; + pair: string; + timestamp: number; +} +⋮---- +export interface IndexPriceConstituent { + exchange: string; + symbol: string; + price: numberInString; + weight: numberInString; +} +⋮---- +export interface IndexPriceConstituents { + symbol: string; + time: number; + constituents: IndexPriceConstituent[]; +} +⋮---- +export interface InsuranceFundBalance { + symbols: string[]; + assets: { + asset: string; + marginBalance: string; + updateTime: number; + }[]; +} +⋮---- +export interface ModifyOrderParams { + orderId?: number; + origClientOrderId?: string; + symbol: string; + side: 'SELL' | 'BUY'; + quantity: string; + price: string; + priceMatch?: + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; + modifyId?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface GetFuturesOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface FuturesTradeHistoryDownloadId { + avgCostTimestampOfLast30d: number; + downloadId: string; +} +⋮---- +export interface FuturesTransactionDownloadLink { + downloadId: string; + status: 'completed' | 'processing'; + url: string; + expirationTimestamp: number; + isExpired: boolean | null; +} +⋮---- +export interface PortfolioMarginProAccountInfo { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; // This field will be ignored in the response +} +⋮---- +maxWithdrawAmount: string; // This field will be ignored in the response +⋮---- +export interface FuturesConvertPair { + fromAsset: string; + toAsset: string; + fromAssetMinAmount: string; + fromAssetMaxAmount: string; + toAssetMinAmount: string; + toAssetMaxAmount: string; +} +⋮---- +export interface FuturesConvertQuoteRequest { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + validTime?: '10s' | '30s' | '1m' | '2m'; +} +⋮---- +export interface FuturesConvertQuote { + quoteId: string; + ratio: string; + inverseRatio: string; + validTimestamp: number; + toAmount: string; + fromAmount: string; +} +⋮---- +export interface FuturesConvertOrderStatus { + orderId: string; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; +} +⋮---- +/** + * Algo Order Types (Effective 2025-12-02) + * USDⓈ-M Futures conditional orders migrate to Algo Service + */ +⋮---- +export type FuturesAlgoOrderType = 'CONDITIONAL'; +⋮---- +export type FuturesAlgoConditionalOrderTypes = + | 'STOP_MARKET' + | 'TAKE_PROFIT_MARKET' + | 'STOP' + | 'TAKE_PROFIT' + | 'TRAILING_STOP_MARKET'; +⋮---- +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update + */ +export type FuturesAlgoOrderStatus = + | 'NEW' + | 'CANCELED' + | 'TRIGGERING' + | 'TRIGGERED' + | 'FINISHED' + | 'REJECTED' + | 'EXPIRED'; +⋮---- +export interface FuturesNewAlgoOrderParams { + algoType: FuturesAlgoOrderType; + symbol: string; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesAlgoConditionalOrderTypes; + timeInForce?: OrderTimeInForce; + quantity?: numberInString; + price?: numberInString; + triggerPrice?: numberInString; + workingType?: WorkingType; + priceMatch?: PriceMatchMode; + closePosition?: BooleanString; + priceProtect?: BooleanString; + reduceOnly?: BooleanString; + activatePrice?: numberInString; + callbackRate?: numberInString; + clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ + selfTradePreventionMode?: SelfTradePreventionMode; + goodTillDate?: number; +} +⋮---- +clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ +⋮---- +export interface FuturesAlgoOrderResponse { + 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; + activatePrice?: numberInString; + callbackRate?: numberInString; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; +} +⋮---- +export interface FuturesCancelAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; +} +⋮---- +export interface FuturesCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} +⋮---- +export interface FuturesCancelAllAlgoOpenOrdersResponse { + code: number; + msg: string; +} +⋮---- +export interface FuturesQueryAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; +} +⋮---- +export interface FuturesQueryAlgoOrderResponse + extends FuturesAlgoOrderResponse { + actualOrderId: numberInString; + actualPrice: numberInString; + tpTriggerPrice?: numberInString; + tpPrice?: numberInString; + slTriggerPrice?: numberInString; + slPrice?: numberInString; + tpOrderType?: string; +} +⋮---- +export interface FuturesQueryOpenAlgoOrdersParams { + algoType?: FuturesAlgoOrderType; + symbol?: string; + algoId?: number; +} +⋮---- +export interface FuturesQueryAllAlgoOrdersParams { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 500; max 1000 +} +⋮---- +limit?: number; // Default 500; max 1000 +⋮---- +export interface SymbolAdlRisk { + symbol: string; + adlRisk: 'low' | 'medium' | 'high'; + updateTime: number; +} +⋮---- +export interface TradingSession { + startTime: number; + endTime: number; + type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; +} +⋮---- +export interface MarketSchedule { + sessions: TradingSession[]; +} +⋮---- +export interface TradingSchedule { + updateTime: number; + marketSchedules: { + EQUITY?: MarketSchedule; + COMMODITY?: MarketSchedule; + KR_EQUITY?: MarketSchedule; + HK_EQUITY?: MarketSchedule; + }; +} +⋮---- +export interface RpiOrderBook { + lastUpdateId: number; + E: number; // Message output time + T: number; // Transaction time + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} +⋮---- +E: number; // Message output time +T: number; // Transaction time + +================ +File: src/types/websockets/ws-api-requests.ts +================ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderType, + FuturesOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + BooleanString, + KlineInterval, + numberInString, + OrderResponseType, + OrderSide, + OrderTimeInForce, + OrderType, + SelfTradePreventionMode, +} from '../shared'; +⋮---- +/** + * Simple request params with timestamp (required) & recv window (optional) + */ +export type WSAPIRecvWindowTimestamp = { + recvWindow?: number; + timestamp: number; +}; +⋮---- +/** + * + * Authentication request types + * + */ +export interface WSAPISessionLogonRequest { + timestamp: number; +} +⋮---- +/** + * + * General request types + * + */ +export interface WSAPIExchangeInfoRequest { + symbol?: string; + symbols?: string[]; + permissions?: string[]; + showPermissionSets?: boolean; + symbolStatus?: string; +} +⋮---- +/** + * + * Market data request types + * + */ +⋮---- +export interface WSAPIOrderBookRequest { + symbol: string; + limit?: number; + symbolStatus?: string; +} +⋮---- +export interface WSAPITradesRecentRequest { + symbol: string; + limit?: number; +} +⋮---- +export interface WSAPITradesHistoricalRequest { + symbol: string; + fromId?: number; + limit?: number; +} +⋮---- +export interface WSAPIBlockTradesHistoricalRequest { + symbol: string; + fromId: number; + limit?: number; +} +⋮---- +export interface WSAPITradesAggregateRequest { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIKlinesRequest { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} +⋮---- +export interface WSAPIAvgPriceRequest { + symbol: string; +} +⋮---- +/** + * 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 interface WSAPIReferencePriceRequest { + symbol: string; +} +⋮---- +export interface WSAPIReferencePriceCalculationRequest { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITicker24hrRequest { + symbol?: string; + symbols?: string[]; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerTradingDayRequest { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +/** + * 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; +} +⋮---- +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; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerBookRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} +⋮---- +/** + * + * Account request types - Spot + * + */ +⋮---- +export interface WSAPIAllOrdersRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIAllOrderListsRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyTradesRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyPreventedMatchesRequest { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyAllocationsRequest { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; +} +⋮---- +/** + * 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; +} +⋮---- +export interface WSAPIOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + recvWindow?: number; + timestamp: number; +} +⋮---- +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 WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersCancelAllRequest { + symbol: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * 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 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 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 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 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 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; +} +⋮---- +export interface WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListCancelRequest { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * SOR request types + */ +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; +}; +⋮---- +/** + * Futures market data request types + */ +⋮---- +export interface WSAPIFuturesOrderBookRequest { + symbol: string; + limit?: number; +} +⋮---- +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; +} +⋮---- +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; +} +⋮---- +/** + * Futures trading request types + */ +⋮---- +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; +} +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +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'; + modifyId?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesPositionRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesPositionV2Request { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIAccountInformationRequest { + omitZeroBalances?: boolean; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIAccountCommissionWSAPIRequest { + symbol: string; +} +⋮---- +/** + * 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; +} +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +/** + * 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 WSAPIUserDataListenKeyRequest { + apiKey: string; + listenKey: string; +} +⋮---- +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; +} +⋮---- +// 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; + }[]; + + wsKey: WsKey; + isWSAPIResponse: boolean; + + // 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; + + [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 }; +} +⋮---- +/** + * 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; + + 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; +} +⋮---- +/** + * 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 + */ + +================ +File: README.md +================ +# Node.js & JavaScript SDK for Binance REST APIs & WebSockets + +[![Build & Test](https://github.com/sieblyio/binance/actions/workflows/test.yml/badge.svg)](https://github.com/sieblyio/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/sieblyio/binance/badge?label=users)](https://dependents.info/sieblyio/binance) +[![npm downloads](https://img.shields.io/npm/dt/binance)][1] +[![last commit](https://img.shields.io/github/last-commit/sieblyio/binance)][1] +[![CodeFactor](https://www.codefactor.io/repository/github/sieblyio/binance/badge)](https://www.codefactor.io/repository/github/sieblyio/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/sieblyio/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 is now hosted under our [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/sieblyio/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/sieblyio/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'; + +/** + * 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); +}); + +/** + * Subscribe to public topics either one at a time or many in an array + */ + +// E.g. one at a time, routed to the coinm futures websockets: +wsClient.subscribe('btcusd@indexPrice', 'coinm'); +wsClient.subscribe('btcusd@miniTicker', 'coinm'); + +// Or send many topics at once to a stream, e.g. the usdm futures stream: +wsClient.subscribe( + ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], + 'usdm', +); + +// 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/sieblyio/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', +); + +/** + * 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(); +``` + +See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. + +#### Preserving large integers in WebSocket messages + +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`. + +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: + +```ts +import { WebsocketClient } from 'binance'; + +/** + * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: + * https://github.com/sieblyio/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); + // }, + + // 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'); + +/** + * 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/sieblyio/binance/image)](https://github.com/sieblyio/binance/network/dependents) + + + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,sieblyio/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&sieblyio/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: 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. It also covers HTTP, HTTPS, and SOCKS proxy configuration for REST API calls, streams, and user-data helpers. + +The SDK handles request building and connectivity for you, including request signing, WebSocket management, healthchecks, heartbeats, product-specific user data startup, listen-key refreshes where Binance still uses them, 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/Spot/rest-spot-public.ts) +- WebSocket examples: [Binance SDK WebSocket examples](../examples/WebSockets/Public/ws-public.ts) +- 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 uses WebSocket transport for request/response commands such as order tests, order placement, cancellation, status, and account reads. Since much of this surface is a lower-latency alternative to REST, we've introduced the promise-driven `WebsocketAPIClient`. It lets you call a function, send a command over WS, and await the matched response without managing asynchronous WebSocket messaging or connection lifecycle details yourself. + +```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, + }); +} + +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('message', (data) => { + console.log('on message event: ', data.wsKey); +}); + +wsApi.getWSClient().on('open', (data) => { + console.log('ws api open: ', data.wsKey); +}); + +wsApi.getWSClient().on('formattedUserDataMessage', (data) => { + console.log('on formattedUserDataMessage: ', 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` 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}`); +} + +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. 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 Binance client ID value like a primary key, while keeping the exchange-facing ID short and valid. + +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' }); + +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 for the product areas where Binance still uses 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`](/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 | + +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](https://siebly.io/examples/Binance/WebSockets/Public/ws-public) +- [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`](/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. + +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(); + +// raw websocket event, unformatted +wsClient.on('message', (data) => { + console.log('on message event: ', data.wsKey); +}); + +// formatted websocket event +wsClient.on('formattedMessage', (data) => { + console.log('on formattedMessage: ', data); +}); + +// reconnection has started +wsClient.on('reconnecting', ({ wsKey }) => { + console.log('spot user data reconnecting', wsKey); +}); + +// reconnection has completed +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); +``` + +Binance announced deprecation of the old listenKey workflow for Spot and Margin user data streams on April 7, 2025. From February 20, 2026 at 07:00 UTC, the old Spot `POST /api/v3/userDataStream` path returns `410 Gone`; use the WebSocket API user data stream instead. At the time of writing, Spot and Margin are the affected user data stream families. Futures and Portfolio Margin streams still use their existing listenKey-backed workflows. For the migration timeline and JavaScript fix, see [Binance User Data Stream 410 Gone: Fix Spot listenKey in JavaScript](/blog/binance-user-data-stream-410-gone-listenkey-javascript). + +### 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(); + +// raw websocket event, unformatted +wsClient.on('message', (data) => { + console.log('on message event: ', data.wsKey); +}); + +// formatted websocket event +wsClient.on('formattedMessage', (data) => { + console.log('on formattedMessage: ', data); +}); + +// reconnection has started +wsClient.on('reconnecting', ({ wsKey }) => { + console.log('spot user data reconnecting', wsKey); +}); + +// reconnection has completed +wsClient.on('reconnected', ({ wsKey }) => { + console.log('spot user data reconnected', wsKey); + // Fetch account state, open orders, or recent fills here if needed. +}); + +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` + +Futures user data streams are conveniently available through `WebsocketClient` in the [Binance JavaScript SDK](/sdk/binance/javascript). Both USD-M and COIN-M Futures user data streams on Binance follow a listenKey mechanic. The SDK automates the life cycle and maintenance of this listenKey for you. Request the subscription and handle incoming events, as shown in the following example: + +```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 connection safety example]() +- [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>) + +--- + + +## 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. + +--- + + +## Proxies for REST API and WebSocket + +Use a proxy when the process needs a fixed egress IP, must cross an approved corporate network, or has a controlled network failover path. A proxy does not select a Binance product, enable a market-maker endpoint, change account eligibility, or replace the `testnet` and `demoTrading` options. + +The broader [Using proxy with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) article covers the shared constructor pattern. The Binance examples below also cover the extra REST API request used by listen-key and listen-token helpers. + +Proxy agents are a Node.js networking feature. Browser applications cannot select a raw socket agent. + +### HTTP or HTTPS proxy + +Install the agent: + +```bash +npm install binance https-proxy-agent +``` + +Set `BINANCE_PROXY_URL` to the full proxy URL, including URL-encoded credentials when required. + +This public check sends one Spot REST API call and one Spot stream through the same proxy: + + + +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { MainClient, WebsocketClient, WS_KEY_MAP } from 'binance'; + +const proxyUrl = process.env.BINANCE_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BINANCE_PROXY_URL before running this example.'); +} + +const proxyAgent = new HttpsProxyAgent(proxyUrl); + +const rest = new MainClient( + {}, + { + httpsAgent: proxyAgent, + proxy: false, + }, +); + +const ws = new WebsocketClient({ + wsOptions: { + agent: proxyAgent, + }, +}); + +ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through proxy:', wsKey); +}); +ws.on('formattedMessage', (event) => { + console.log('stream update', event); +}); +ws.on('exception', console.error); + +async function main() { + const serverTime = await rest.getServerTime(); + console.log('REST API connected through proxy:', serverTime); + + ws.subscribe(['btcusdt@trade'], WS_KEY_MAP.main); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +REST API networking options belong in the second constructor argument for `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. + +- `httpsAgent` sends the HTTPS request through the agent. +- `proxy: false` prevents Axios from applying another proxy configuration on top of that agent. +- `wsOptions.agent` controls the WebSocket connection. + +Public streams, normal WebSocket API commands, and the current Spot WebSocket API user-data subscription only use the socket path. Those workflows need `wsOptions.agent`, but do not make an auxiliary REST API request. + +### Listen-key and listen-token helpers through a proxy + +Some user-data helpers use two network paths. The SDK opens the WebSocket through `wsOptions.agent`, then uses REST API calls to create or renew a listen key or token through `requestOptions`. + +This example authenticates a USD-M Futures user-data stream without placing an order: + + + +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { WebsocketClient } from 'binance'; + +const proxyUrl = process.env.BINANCE_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BINANCE_PROXY_URL before running this example.'); +} + +const proxyAgent = new HttpsProxyAgent(proxyUrl); + +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + wsOptions: { + agent: proxyAgent, + }, + requestOptions: { + httpsAgent: proxyAgent, + proxy: false, + }, +}); + +ws.on('open', ({ wsKey }) => { + console.log('user-data socket connected:', wsKey); +}); +ws.on('formattedUserDataMessage', (event) => { + console.log('user-data event', event); +}); +ws.on('exception', console.error); + +async function main() { + await ws.subscribeUsdFuturesUserDataStream(); + console.log('USD-M Futures user-data stream is ready'); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +Use both settings for the legacy Spot listen-key helpers, Margin listen-token or listen-key helpers, USD-M and COIN-M user-data helpers, and Portfolio Margin user-data helpers. The same rule applies when `WebsocketAPIClient.subscribeUserDataStream(...)` falls back to one of those helpers. + +Ordinary `WebsocketAPIClient` request and order methods send authentication and commands over the socket. They only need `wsOptions.agent`. The preferred Spot WebSocket API user-data subscription also stays on the socket. + +### SOCKS5 proxy + +Install the SOCKS agent: + +```bash +npm install binance socks-proxy-agent +``` + +Use `SocksProxyAgent` in the same REST API and WebSocket positions: + + + +```typescript +import { MainClient, WebsocketClient, WS_KEY_MAP } from 'binance'; +import { SocksProxyAgent } from 'socks-proxy-agent'; + +const proxyUrl = process.env.BINANCE_SOCKS_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BINANCE_SOCKS_PROXY_URL before running this example.'); +} + +const proxyAgent = new SocksProxyAgent(proxyUrl); + +const rest = new MainClient( + {}, + { + httpsAgent: proxyAgent, + proxy: false, + }, +); + +const ws = new WebsocketClient({ + wsOptions: { + agent: proxyAgent, + }, +}); + +async function main() { + const serverTime = await rest.getServerTime(); + console.log('REST API connected through SOCKS5:', serverTime); + + ws.subscribe(['btcusdt@bookTicker'], WS_KEY_MAP.main); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +See also: + +- [SOCKS WebSocket proxy example](../examples/WebSockets/Misc/ws-proxy-socks.ts) +- [REST API and WebSocket proxy test configuration](../test/proxy.util.ts) + +### Proxy checks + +- Keep proxy URLs and credentials in environment variables or a secret manager. +- URL-encode usernames and passwords when constructing a proxy URL from separate values. +- Make sure the proxy egress IP matches the Binance API key's IP whitelist. +- Test a public REST API call and public WebSocket subscription before private authentication. +- Confirm that every listen-key or listen-token REST API call uses the same intended network path as its socket. +- Measure request, connection, and reconnect latency through the proxy. +- Treat repeated HTTP 407 responses, TLS errors, and WebSocket reconnect loops as network failures. +- Keep the host clock synchronized. Change `recvWindow` only after measuring timestamp failures and proxy latency. +- The SDK does not rotate proxy endpoints. Handle endpoint selection outside the client when rotation is required. + +--- + + +## Production Notes + +Before a 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?** + +Use `WebsocketAPIClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` for Spot user data. Binance retired the older Spot listen-key workflow, so JavaScript apps should not start new Spot user data streams with `POST /api/v3/userDataStream`. + +**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) +- [Binance SDK source on GitHub](https://github.com/tiagosiebler/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/websocket-api-client.ts +================ +import { + ExchangeInfo, SpotAmendKeepPriorityResult, - SpotExecutionRulesParams, SpotExecutionRulesResponse, - SpotOrder, SpotReferencePriceCalculationResponse, SpotReferencePriceResult, - StakingBasicParams, - StakingHistory, - StakingHistoryParams, - StakingPersonalLeftQuota, - StakingProduct, - StakingProductPosition, - StakingProductType, - SubAccountAddOrDeleteIPList, - SubAccountAssetDetails, - SubAccountAssets, - SubAccountAssetsParams, - SubaccountBalances, - SubAccountBrokerMarginAsset, - SubaccountBrokerSpotAsset, - SubAccountCOINMDetail, - SubAccountCOINMPositionRisk, - SubAccountCOINMSummary, - SubAccountDeposit, - SubAccountDepositAddress, - SubAccountDepositAddressParams, - SubAccountDepositHistoryList, - SubAccountDepositHistoryParams, - SubAccountEnableFutures, - SubAccountEnableLeverageToken, - SubAccountEnableMargin, - SubAccountEnableOrDisableIPRestriction, - SubAccountFuturesAccountDetail, - SubAccountFuturesAccountSummary, - SubAccountFuturesAssetTransfer, - SubAccountFuturesAssetTransferHistory, - SubAccountFuturesAssetTransferHistoryParams, - SubAccountFuturesAssetTransferParams, - SubAccountListParams, - SubAccountListResponse, - SubAccountMarginAccountDetail, - SubAccountMovePosition, - SubAccountMovePositionHistory, - SubAccountMovePositionHistoryParams, - SubAccountMovePositionParams, - SubAccountsMarginAccountSummary, - SubAccountSpotAssetsSummary, - SubAccountSpotAssetsSummaryParams, - SubAccountSpotAssetTransferHistory, - SubAccountSpotAssetTransferHistoryParams, - SubAccountStatus, - SubAccountSummaryOnFuturesAccountV2Params, - SubAccountTransactionStatistics, - SubAccountTransfer, - SubAccountTransferHistory, - SubAccountTransferHistoryParams, - SubAccountTransferParams, - SubAccountTransferToMasterParams, - SubAccountTransferToSameMasterParams, - SubAccountUniversalTransfer, - SubAccountUniversalTransferHistoryParams, - SubAccountUniversalTransferHistoryResponse, - SubAccountUniversalTransferParams, - SubAccountUSDMDetail, - SubAccountUSDMPositionRisk, - SubAccountUSDMSummary, - SubmitConvertLimitOrderParams, - SubmitDepositCreditParams, - SubmitDepositCreditResponse, - SubmitHashrateResaleParams, - SubmitIndexLinkedPlanRedemptionParams, - SubmitMarginOTOCOOrderParams, - SubmitMarginOTOOrderParams, - SubmitOneTimeTransactionParams, - SubmitOneTimeTransactionResponse, - SubmitSpotTwapNewOrderParams, - SubmitSpotTwapNewOrderResponse, - SubmitTravelRuleDepositQuestionnaireParams, - SubmitTravelRuleDepositQuestionnaireResponse, - SubmitTwapNewOrderParams, - SubmitTwapNewOrderResponse, - SubmitVpNewOrderParams, - SubmitVpNewOrderResponse, - SubscribeBlvtParams, - SubscribeBlvtResponse, - SubscribeDualInvestmentProductParams, - SubscribeDualInvestmentProductResponse, - SubscribeEthStakingV2Response, - SubscribeSolStakingResponse, - SymbolOrderBookTicker, - SymbolTradeFee, - SystemStatusResponse, - TargetAssetROI, - Ticker24hrResponse, - ToggleBNBBurnParams, - TradingDayTickerArray, - TradingDayTickerFull, - TradingDayTickerMini, - TradingDayTickerParams, - TradingDayTickerSingle, - TransferBrokerSubAccount, - TransferBrokerSubAccountParams, - TravelRuleCountryListResponse, - TravelRuleDepositHistoryRecord, - TravelRuleRegionListResponse, - TravelRuleWithdrawHistoryRecord, - UniversalTransferBrokerParams, - UniversalTransferHistoryParams, - UniversalTransferParams, - UpdateIpRestrictionForSubApiKey, - UsdtMarginedFuturesResponse, - UserAsset, - VASPInfo, - VipCollateralAccount, - VipLoanAccruedInterestParams, - VipLoanAccruedInterestRecord, - VipLoanBorrowParams, - VipLoanBorrowResponse, - VipLoanFixedRateBorrowParams, - VipLoanFixedRateBorrowResponse, - VipLoanFixedRateMarketRecord, - VipLoanInterestRateHistoryParams, - VipLoanInterestRateRecord, - VipLoanRenewParams, - VipLoanRenewResponse, - VipLoanRepaymentHistory, - VipLoanRepayParams, - VipLoanRepayResponse, - VipOngoingOrder, - VirtualSubAccount, - WalletBalance, - WithdrawAddress, - WithdrawAssetsFromManagedSubAccountParams, - WithdrawFiatParams, - WithdrawHistory, - WithdrawHistoryParams, - WithdrawParams, - WithdrawTravelRuleParams, - WrapBethResponse, - WrapHistory, } from './types/spot'; -import BaseRestClient from './util/BaseRestClient'; import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, - serialiseParams, -} from './util/requestUtils'; + 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; +} +⋮---- +/** + * Default: true + * + * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected + */ +⋮---- +/** + * Default: 2 seconds + * + * Delay automatic userdata resubscribe by x seconds. + */ +⋮---- +/** + * 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(....)`. + */ +⋮---- +/** + * 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. + */ +⋮---- +/** + * 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. + */ +⋮---- +/** + * 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; +} +⋮---- +/** + * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. + */ +⋮---- +/** + * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream + */ +⋮---- +/** + * 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 +⋮---- +/** + * Minimal state store around automating sticky "userDataStream.subscribe" sessions + */ +⋮---- +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) +⋮---- +public getWSClient(): WebsocketClient +⋮---- +public setTimeOffsetMs(newOffset: number): void +⋮---- +public async disconnectAll(): Promise +⋮---- +/* + * + * SPOT - General requests + * + */ +⋮---- +/** + * Test connectivity to the WebSocket API + */ +testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> +⋮---- +/** + * Test connectivity to the WebSocket API and get the current server time + */ +getSpotServerTime( + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query current exchange trading rules, rate limits, and symbol information + */ +getSpotExchangeInfo( + params?: WSAPIExchangeInfoRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/* + * + * SPOT - Market data requests + * + */ +⋮---- +/** + * Get current order book + * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + */ +getSpotOrderBook( + params: WSAPIOrderBookRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Get recent trades + * Note: If you need access to real-time trading activity, consider using WebSocket Streams + */ +getSpotRecentTrades( + params: WSAPITradesRecentRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Get historical trades + * Note: If fromId is not specified, the most recent trades are returned + */ +getSpotHistoricalTrades( + params: WSAPITradesHistoricalRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Get historical block trades + */ +getSpotHistoricalBlockTrades( + params: WSAPIBlockTradesHistoricalRequest, + wsKey?: WSAPIWsKeyMain, +): 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> +⋮---- +/** + * Get klines (candlestick bars) + * Note: If you need access to real-time kline updates, consider using WebSocket Streams + */ +getSpotKlines( + params: WSAPIKlinesRequest, + wsKey?: WSAPIWsKeyMain, +): 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> +⋮---- +/** + * Get current average price for a symbol + */ +getSpotAveragePrice( + params: WSAPIAvgPriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. + */ +getSpotExecutionRules( + params?: WSAPIExecutionRulesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query reference price for a symbol. + */ +getSpotReferencePrice( + params: WSAPIReferencePriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query how reference price is calculated for a symbol. + */ +getSpotReferencePriceCalculation( + params: WSAPIReferencePriceCalculationRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * 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 }, + ); +⋮---- +/** + * 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 }, + ); +⋮---- +/** + * 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 }, + ); +⋮---- +/** + * 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> +⋮---- +/** + * 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> +⋮---- +/* + * + * SPOT - Session authentication requests + * + * Note: authentication is automatic + * + */ +⋮---- +getSpotSessionStatus( + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/* + * + * SPOT - Trading requests + * + */ +⋮---- +/** + * Submit a spot order + */ +submitNewSpotOrder( + params: WSAPINewSpotOrderRequest, + wsKey?: WSAPIWsKeyMain, +): 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, + ); +⋮---- +/** + * 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> +⋮---- +/** + * Cancel an active order + * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used + */ +cancelSpotOrder( + params: WSAPIOrderCancelRequest, + wsKey?: WSAPIWsKeyMain, +): 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. + * + * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority + */ +amendSpotOrderKeepPriority( + params: WSAPIOrderAmendKeepPriorityRequest, + wsKey?: WSAPIWsKeyMain, +): 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> +⋮---- +/** + * 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, + ); +⋮---- +/** + * Place a new order list + * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead + */ +placeSpotOrderList( + params: WSAPIOrderListPlaceRequest, + wsKey?: WSAPIWsKeyMain, +): 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> +⋮---- +/** + * 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> +⋮---- +/** + * 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> +⋮---- +/** + * 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> +⋮---- +/** + * 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> +⋮---- +/** + * 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> +⋮---- +/** + * Cancel an active order list + * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used + */ +cancelSpotOrderList( + params: WSAPIOrderListCancelRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * 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> +⋮---- +/** + * 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> +⋮---- +/** + * 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, + ); +⋮---- +/* + * + * SPOT - Account requests + * + */ +⋮---- +/** + * Query information about your account, including balances + * Note: Weight: 20 + */ +getSpotAccountInformation( + params: WSAPIAccountInformationRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query your current unfilled order count for all intervals + * Note: Weight: 40 + */ +getSpotOrderRateLimits( + params: WSAPIRecvWindowTimestamp, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query information about all your orders – active, canceled, filled – filtered by time range + * Note: Weight: 20 + */ +getSpotAllOrders( + params: WSAPIAllOrdersRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query information about all your order lists, filtered by time range + * Note: Weight: 20 + */ +getSpotAllOrderLists( + params: WSAPIAllOrderListsRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Query information about all your trades, filtered by time range + * Note: Weight: 20 + */ +getSpotMyTrades( + params: WSAPIMyTradesRequest, + wsKey?: WSAPIWsKeyMain, +): 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> +⋮---- +/** + * Retrieves allocations resulting from SOR order placement + * Note: Weight: 20 + */ +getSpotAllocations( + params: WSAPIMyAllocationsRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/** + * Get current account commission rates + * Note: Weight: 20 + */ +getSpotAccountCommission( + params: WSAPIAccountCommissionWSAPIRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> +⋮---- +/* + * + * FUTURES - Market data requests + * + */ +⋮---- +/** + * Get current order book for futures + * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + */ +getFuturesOrderBook( + params: WSAPIFuturesOrderBookRequest, +): 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 + * + */ +⋮---- +/** + * Submit a futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +submitNewFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPINewFuturesOrderRequest, +): Promise> +⋮---- +/** + * Modify an existing futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +modifyFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderModifyRequest, +): Promise> +⋮---- +/** + * Cancel a futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +cancelFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderCancelRequest, +): Promise> +⋮---- +/** + * Query futures order status + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesOrderStatus( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderStatusRequest, +): Promise> +⋮---- +/** + * Get current position information (V2) + * Note: Only symbols that have positions or open orders will be returned + */ +getFuturesPositionV2( + params: WSAPIFuturesPositionV2Request, +): 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> +⋮---- +/** + * 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 + * + */ +⋮---- +/** + * Get account balance information (V2) + * Note: Returns balance information for all assets + */ +getFuturesAccountBalanceV2( + params: WSAPIRecvWindowTimestamp, +): 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> +⋮---- +/** + * Get account information (V2) + * Note: Returns detailed account information including positions and assets + */ +getFuturesAccountStatusV2( + params: WSAPIRecvWindowTimestamp, +): Promise> +⋮---- +/** + * 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 + * + */ +⋮---- +/** + * 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> +⋮---- +/** + * Stop the user data stream listen key. + * + * @param params + * @param wsKey + * @returns + */ +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. + * + * @param wsKey + */ +clearUserDataStreamTimers(wsKey: WSAPIWsKey) +⋮---- +// Just in case the refresh timer is still running +// Harmless given one connection, but still unnecessary +⋮---- +/** + * 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. +⋮---- +/** + * 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 { + 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 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 GetOCOParams { + symbol?: string; + orderListId?: number; + origClientOrderId?: string; +} +⋮---- +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 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; +} +⋮---- +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 SymbolTradeFee { + symbol: string; + makerCommission: numberInString; + takerCommission: numberInString; +} +⋮---- +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 ExchangeInfo { + timezone: string; + serverTime: number; + rateLimits: RateLimiter[]; + exchangeFilters: ExchangeFilter[]; + symbols: SymbolExchangeInfo[]; +} +⋮---- +export interface OrderBookResponse { + lastUpdateId: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; +} +⋮---- +export interface RawTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; +} +⋮---- +export interface BlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} +⋮---- +export interface HistoricalBlockTradesParams { + symbol: string; + fromId: number; + limit?: number; +} +⋮---- +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 AggregateTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; + M: boolean; +} +⋮---- +export interface CurrentAvgPrice { + mins: number; + 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; +} +⋮---- +export interface SpotSymbolExecutionRules { + symbol: string; + rules: SpotPriceRangeExecutionRule[]; +} +⋮---- +export interface SpotExecutionRulesResponse { + symbolRules: SpotSymbolExecutionRules[]; +} +⋮---- +/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ +export interface SpotExecutionRulesParams { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +} +⋮---- +/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ +export interface SpotReferencePriceResponse { + symbol: string; + referencePrice: numberInString | null; + 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 type SpotReferencePriceResult = + | SpotReferencePriceResponse + | SpotReferencePriceNeverSetError; +⋮---- +/** Reference price is computed as an arithmetic mean in the matching engine. */ +export interface SpotReferencePriceCalculationArithmeticMean { + symbol: string; + calculationType: 'ARITHMETIC_MEAN'; + bucketCount: number; + bucketWidthMs: number; +} +⋮---- +/** Reference price is computed outside the matching engine. */ +export interface SpotReferencePriceCalculationExternal { + symbol: string; + calculationType: 'EXTERNAL'; + externalCalculationId: number; +} +⋮---- +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 SymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; +} +⋮---- +export interface OrderResponseACK { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: 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; +} +⋮---- +/** 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 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[]; +} +⋮---- +/** 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; +} +⋮---- +/** 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]; +} +⋮---- +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; +} +⋮---- +export type SOROrderResponseFull = OrderResponseFull & { + workingTime: number; + fills: SOROrderFill[]; + workingFloor: string; + selfTradePreventionMode: string; + usedSor: true; +}; +⋮---- +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. + }; +} +⋮---- +//Standard commission rates on trades from the order. +⋮---- +//Tax commission rates for trades from the order. +⋮---- +//Discount on standard commissions when paying in BNB. +⋮---- +discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. +⋮---- +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 CancelOrderListResult extends OrderList { + orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; +} +⋮---- +export interface GenericReplaceSpotOrderResult { + cancelResult: 'SUCCESS' | 'FAILURE'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: C; + newOrderResponse: N; +} +⋮---- +export interface ReplaceSpotOrderCancelStopFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'NOT_ATTEMPTED'; +} +⋮---- +export interface ReplaceSpotOrderNewFailure + extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + GenericCodeMsgError + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'FAILURE'; +} +⋮---- +export interface ReplaceSpotOrderCancelAllowFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'SUCCESS'; +} +⋮---- +export interface ReplaceSpotOrderCancelAllFailure + extends GenericReplaceSpotOrderResult< + GenericCodeMsgError, + GenericCodeMsgError + > { + cancelResult: 'FAILURE'; + newOrderResult: 'FAILURE'; +} +⋮---- +export interface ReplaceSpotOrderResultError { + data: + | ReplaceSpotOrderCancelStopFailure + | ReplaceSpotOrderNewFailure + | ReplaceSpotOrderCancelAllowFailure + | ReplaceSpotOrderCancelAllFailure; +} +⋮---- +export interface ReplaceSpotOrderResultSuccess< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + OrderResponseTypeFor + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'SUCCESS'; +} +⋮---- +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; +} +⋮---- +/** 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 SpotAssetBalance { + asset: string; + free: numberInString; + locked: numberInString; +} +⋮---- +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 CrossMarginAccountTransferParams { + asset: string; + amount: number; + type: 1 | 2; +} +⋮---- +export interface MarginTransactionResponse { + tranId: number; +} +⋮---- +export interface MarginAccountLoanParams { + asset: string; + isIsolated: StringBoolean; + symbol: string; + amount: number; + type: 'BORROW' | 'REPAY'; +} +⋮---- +export interface QueryMarginAssetParams { + asset: string; +} +⋮---- +export interface QueryMarginAssetResponse { + assetFullName: string; + assetName: string; + isBorrowable: boolean; + isMortgageable: boolean; + userMinBorrow: numberInString; + userMinRepay: numberInString; +} +⋮---- +export interface QueryCrossMarginPairParams { + symbol: string; +} +⋮---- +export interface QueryCrossMarginPairResponse { + id: number; + symbol: string; + base: string; + quote: string; + isMarginTrade: boolean; + isBuyAllowed: boolean; + isSellAllowed: boolean; +} +⋮---- +export interface QueryMarginPriceIndexResponse { + calcTime: number; + price: numberInString; + symbol: string; +} +⋮---- +export interface QueryMarginRecordParams { + asset: string; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + archived?: boolean; +} +⋮---- +export interface GetMarginAccountBorrowRepayRecordsParams { + asset?: string; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + type: 'BORROW' | 'REPAY'; +} +⋮---- +export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; +⋮---- +export interface MarginAccountRecord { + isolatedSymbol?: string; + asset: string; + principal: numberInString; + status: LoanStatus; + timestamp: number; + txId: number; +} +⋮---- +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 BasicMarginAssetParams { + asset: string; + isolatedSymbol?: string; +} +⋮---- +export interface QueryMaxBorrowResponse { + amount: numberInString; + borrowLimit: numberInString; +} +⋮---- +export interface QueryMaxTransferOutAmountResponse { + amount: numberInString; +} +⋮---- +export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; +⋮---- +export interface IsolatedMarginAccountTransferParams { + asset: string; + symbol: string; + transFrom: IsolatedMarginTransfer; + transTo: IsolatedMarginTransfer; + amount: number; +} +⋮---- +export interface IsolatedMarginAccountAsset { + asset: string; + borrowEnabled: boolean; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; + netAssetOfBtc: numberInString; + repayEnabled: boolean; + totalAsset: numberInString; +} +⋮---- +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 IsolatedMarginAccountInfo { + assets: IsolatedMarginAccountAssets[]; + totalAssetOfBtc?: numberInString; + totalLiabilityOfBtc?: numberInString; + totalNetAssetOfBtc?: numberInString; +} +⋮---- +export interface SpotSubUserAssetBtcList { + email: string; + totalAsset: numberInString; +} +⋮---- +export interface SubAccountList { + email: string; + isFreeze: boolean; + createTime: number; + isManagedSubAccount: boolean; + isAssetManagementSubAccount: boolean; +} +⋮---- +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 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 interface SubAccountStatus { + email: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + insertTime: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + mobile: number; +} +⋮---- +export interface BasicBtcTotals { + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; +} +⋮---- +export interface FuturesSubAccountAssets { + asset: string; + initialMargin: numberInString; + maintenanceMargin: numberInString; + marginBalance: numberInString; + maxWithdrawAmount: numberInString; + openOrderInitialMargin: numberInString; + positionInitialMargin: numberInString; + unrealizedProfit: numberInString; + walletBalance: numberInString; +} +⋮---- +export interface FuturesSubAccountList { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + email: string; +} +⋮---- +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 interface SubAccountUniversalTransferHistory { + tranId: number; + fromEmail: string; + toEmail: string; + asset: 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; +} +⋮---- +export interface CreateBrokerSubAccountParams { + tag?: string; +} +⋮---- +export interface GetBrokerSubAccountParams { + subAccountId?: string; + page?: number; + size?: number; +} +⋮---- +export interface GetApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey?: string; + page?: number; + size?: number; +} +⋮---- +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 interface UpdateIpRestrictionForSubApiKey { + subAccountId: string; + ipAddress?: string; + subAccountApiKey: string; + status: string; +} +⋮---- +export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canUniversalTransfer: boolean; +} +⋮---- +export interface EnableMarginBrokerSubAccountParams { + subAccountId: string; + margin: boolean; +} +⋮---- +export interface EnableMarginBrokerSubAccountResponse { + subAccountId: string; + enableMargin: boolean; + updateTime: number; +} +⋮---- +export interface EnableFuturesBrokerSubAccountParams { + subAccountId: string; + futures: boolean; +} +⋮---- +export interface EnableFuturesBrokerSubAccountResponse { + subAccountId: string; + enableFutures: boolean; + updateTime: number; +} +⋮---- +export interface EnableMarginApiKeyBrokerSubAccountParams { + subAccountId: string; + margin: boolean; +} +export interface UniversalTransferBrokerParams { + fromId?: string; + toId?: string; + fromAccountType: string; + toAccountType: string; + asset: string; + amount: number; +} +⋮---- +export interface GetUniversalTransferBrokerParams { + fromId?: string; + toId?: string; + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; +} +⋮---- +export interface GetBrokerSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; +} +⋮---- +export interface DeleteApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; +} +⋮---- +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; +} +⋮---- +export interface BrokerSubAccountHistory { + subAccountsHistory: SubAccountTransferHistoryList[]; +} +⋮---- +export interface BrokerSubAccount { + subaccountId: string; + email: string; + makerCommission?: string; + takerCommission?: string; + marginMakerCommission?: string; + marginTakerCommission?: string; + createTime?: number; + tag: string; +} +⋮---- +export interface CreateApiKeyBrokerSubAccountResponse { + subaccountId: string; + apiKey: string; + secretKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canUniversalTransfer: boolean; +} +⋮---- +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 SubAccountListResponse { + subAccounts: SubAccountList[]; +} +⋮---- +export interface SubAccountSpotAssetTransferHistoryParams { + fromEmail?: string; + toEmail?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountSpotAssetTransferHistory + extends SubAccountBasicTransfer { + status: string; +} +⋮---- +export interface SubAccountFuturesAssetTransferHistoryParams { + email: string; + futuresType: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountFuturesAssetTransferHistory { + success: boolean; + futuresType: number; + transfers: SubAccountBasicTransfer[]; +} +⋮---- +export interface SubAccountFuturesAssetTransferParams { + fromEmail: string; + toEmail: string; + futuresType: number; + asset: string; + amount: number; +} +⋮---- +export interface SubAccountFuturesAssetTransfer { + success: boolean; + txnId: numberInString; +} +⋮---- +export interface SubAccountAssetsParams { + email: string; +} +⋮---- +export interface SubAccountAssets { + balances: SpotBalance[]; +} +⋮---- +export interface SubAccountSpotAssetsSummaryParams { + email?: string; + page?: number; + size?: number; +} +⋮---- +export interface SubAccountSpotAssetsSummary { + totalCount: number; + masterAccountTotalAsset: numberInString; + spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; +} +⋮---- +export interface SubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; +} +⋮---- +export interface SubAccountDepositAddress { + address: string; + coin: string; + tag: string; + url: string; +} +⋮---- +export interface SubAccountDepositHistoryParams extends DepositHistoryParams { + email: string; +} +⋮---- +export interface SubAccountEnableMargin { + email: string; + isMarginEnabled: boolean; +} +⋮---- +export interface SubAccountMarginAccountDetail extends BasicBtcTotals { + email: string; + marginLevel: numberInString; + marginTradeCoeffVo: MarginTradeCoeffVo; + marginUserAssetVoList: MarginBalance[]; +} +⋮---- +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 SubAccountFuturesAccountSummary extends FuturesSubAccountList { + subAccountList: FuturesSubAccountList[]; +} +⋮---- +export interface FuturesPositionRisk { + entryPrice: numberInString; + leverage: numberInString; + maxNotional: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + positionAmount: numberInString; + symbol: string; + unrealizedProfit: numberInString; +} +⋮---- +export interface SubAccountTransferParams { + email: string; + asset: string; + amount: number; + type: number; +} +⋮---- +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; + limit?: number; +} +⋮---- +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; + priceType: string; + price: string; + quantity: string; + positionSide: string; + side: string; + success: boolean; +} +⋮---- +export interface SubAccountMovePositionHistoryParams { + symbol: string; + startTime?: number; + endTime?: number; + page: number; + row: number; +} +⋮---- +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; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountUniversalTransferHistoryResponse { + result: SubAccountUniversalTransferHistory[]; + totalCount: number; +} +⋮---- +export interface SubAccountEnableLeverageToken { + email: string; + enableBlvt: boolean; +} +⋮---- +export interface AddIpRestriction extends BasicSubAccount { + status: string; + ipAddress: string; +} +⋮---- +export interface SubAccountEnableOrDisableIPRestriction { + ipRestrict: boolean; + ipList: string[]; + updateTime: number; + apiKey: string; +} +⋮---- +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; + 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 COINMSubAccount { + email: string; + totalMarginBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; +} +⋮---- +export interface SubAccountCOINMDetail { + deliveryAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: 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 SubAccountCOINMSummary { + deliveryAccountSummaryResp: { + totalMarginBalanceOfBTC: numberInString; + totalUnrealizedProfitOfBTC: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; + subAccountList: COINMSubAccount[]; + }; +} +⋮---- +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 SubAccountCOINMPositionRisk { + deliveryPositionRiskVos: COINMPositionRisk[]; +} +⋮---- +export interface StakingProductDetail { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + apy: numberInString; +} +⋮---- +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; + 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 FlexibleSavingBasicParams { + status?: string; + featured?: number; + current?: number; + size?: number; + asset?: string; +} +⋮---- +export interface FlexibleProductPositionParams { + status?: string; + featured?: number; + current?: number; + size?: number; +} +⋮---- +export interface PurchaseFlexibleProductParams { + productId: string; + amount: number; + autoSubscribe: boolean; +} +⋮---- +export interface PurchaseFlexibleProductResponse { + purchaseId: number; +} +⋮---- +export interface RedeemFlexibleProductParams { + productId: string; + amount: number; + type: 'FAST' | 'NORMAL'; +} +⋮---- +export interface LeftDailyPurchaseQuotaFlexibleProductResponse { + 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; + current?: number; + size?: number; +} +export interface FixedAndActivityProjectPositionParams { + asset?: string; + projectId?: string; + status?: StakingStatus; +} +⋮---- +export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +⋮---- +export interface PurchaseRecordParams { + lendingType: LendingType; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +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 interface FutureAccountTransfer { + asset: string; + tranId: number; + amount: string; + type: string; + 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; +} +⋮---- +export interface StakingPersonalLeftQuota { + leftPersonalQuota: numberInString; +} +⋮---- +export interface StakingHistoryParams extends StakingBasicParams { + txnType: StakingTxnType; + asset?: string; + startTime?: number; + endTime?: number; +} +export interface BSwapOperationsParams { + operationId?: number; + poolId?: number; + operation: BSwapOperationType; + startTime?: number; + endTime?: number; + limit: 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; + quantity: number; +} +⋮---- +export interface BSwapShare { + shareAmount: number; + sharePercentage: number; + asset: { [k: string]: number }; +} +⋮---- +export interface BSwapLiquidity { + poolId: number; + poolNmae: string; + updateTime: number; + liquidity: { [k: string]: number }; + share: BSwapShare; +} +⋮---- +export interface FundingAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + btcValuation: string; +} +⋮---- +export interface GetAssetParams { + asset?: string; + needBtcValuation?: boolean; +} +⋮---- +export interface UserAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + ipoable: string; + btcValuation: string; +} +⋮---- +export interface SpotAssetTagsParams { + tag?: string; +} +⋮---- +export interface SpotAssetTag { + assetCode: string; + assetName: string; + trading: boolean; + tags: string[]; +} +⋮---- +export interface ConvertTransfer { + clientTranId: string; + asset: string; + amount: number; + targetAsset: string; + accountType?: string; +} +⋮---- +export interface ConvertTransferResponse { + tranId: number; + status: string; +} +⋮---- +export interface GetConvertBUSDHistoryParams { + tranId?: number; + clientTranId?: string; + asset?: string; + startTime: number; + endTime: number; + accountType?: string; + current?: number; + size?: number; +} +⋮---- +export interface BUSDConversionRecord { + tranId: number; + type: number; + time: number; + deductedAsset: string; + deductedAmount: string; + targetAsset: string; + targetAmount: string; + status: string; + accountType: string; +} +⋮---- +export interface CloudMiningHistoryParams { + tranId?: number; + clientTranId?: string; + asset?: string; + startTime: number; + endTime: number; + current?: number; + size?: number; +} +⋮---- +export interface CloudMining { + createTime: number; + tranId: number; + type: number; + asset: string; + amount: string; + status: string; +} +⋮---- +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 WalletBalance { + activate: boolean; + balance: string; + walletName: string; +} +⋮---- +export interface DelegationHistoryParams { + email: string; + startTime: number; + endTime: number; + type?: 'Delegate' | 'Undelegate'; + asset?: string; + current?: number; + size?: number; +} +⋮---- +export interface DelegationHistory { + clientTranId: string; + transferType: 'Delegate' | 'Undelegate'; + asset: string; + amount: string; + time: number; +} +⋮---- +export interface DelistScheduleResponse { + delistTime: number; + symbols: string[]; +} +⋮---- +export interface WithdrawAddress { + address: string; + addressTag: string; + coin: string; + name: string; + network: string; + origin: string; + originType: string; + whiteStatus: boolean; +} +⋮---- +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; + limit?: number; +} +⋮---- +export interface SubaccountBalances { + asset: string; + free: string; + locked: string; +} +⋮---- +export interface SubaccountUserAssets { + asset: string; + borrowed: string; + free: string; + interest: string; + locked: string; + netAsset: string; +} +⋮---- +export interface SubaccountAssets { + asset: string; + marginBalance: string; + walletBalance: string; +} +⋮---- +export interface SubaccountPosition { + entryPrice: string; + markPrice: string; + positionAmt: string; + symbol: string; + unRealizedProfit: 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 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 ManagerSubTransferHistoryVos { + fromEmail: string; + fromAccountType: string; + toEmail: string; + toAccountType: string; + asset: string; + amount: string; + scheduledData: number; + createTime: number; + status: string; + tranId: number; +} +⋮---- +export interface ManagedSubAccountFuturesAssetsResponse { + code: string; + message: string; + snapshotVos: { + type: string; + updateTime: number; + data: { + assets: SubaccountAssets[]; + position: SubaccountPosition[]; + }; + }[]; +} +⋮---- +export interface ManagedSubAccountMarginAssetsResponse { + marginLevel: string; + totalAssetOfBtc: string; + totalLiabilityOfBtc: string; + totalNetAssetOfBtc: string; + userAssets: SubaccountUserAssets[]; +} +⋮---- +export interface ManagedSubAccountListParams { + email?: string; + page?: number; + limit?: number; +} +⋮---- +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 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 ManagedSubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; +} +⋮---- +export interface ManagedSubAccountDepositAddress { + coin: string; + address: string; + tag: string; + url: string; +} +⋮---- +export interface EnableOptionsForSubAccountResponse { + email: string; + isEOptionsEnabled: boolean; +} +⋮---- +export interface ManagedSubAccountTransferTTLogParams { + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: string; + transferFunctionAccountType?: string; +} +⋮---- +export interface UIKlinesParams { + symbol: string; + interval: string; + startTime?: number; + endTime?: number; + timeZone?: string; + 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 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 type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; +⋮---- +export interface TradingDayTickerParams { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +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 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 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 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 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 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 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 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 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 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 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 OrderRateLimitUsage { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} +⋮---- +export interface PreventedMatchesParams { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} +⋮---- +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 AllocationsParams { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; +} +⋮---- +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 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 GetCrossMarginTransferHistoryParams { + asset?: string; + type?: 'ROLL_IN' | 'ROLL_OUT'; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + isolatedSymbol?: string; +} +⋮---- +export interface CrossMarginTransferHistory { + amount: string; + asset: string; + status: string; + timestamp: number; + txId: number; + type: 'ROLL_IN' | 'ROLL_OUT'; + transFrom?: string; + transTo?: string; + fromSymbol?: string; + toSymbol?: string; +} +⋮---- +export interface GetMarginInterestHistoryParams { + asset?: string; + isolatedSymbol?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface MarginInterestHistory { + txId: number; + interestAccuredTime: number; + asset: string; + rawAsset?: string; + principal: string; + interest: string; + interestRate: string; + type: + | 'PERIODIC' + | 'ON_BORROW' + | 'PERIODIC_CONVERTED' + | 'ON_BORROW_CONVERTED' + | 'PORTFOLIO'; + isolatedSymbol?: string; +} +⋮---- +export interface GetForceLiquidationRecordParams { + startTime?: number; + endTime?: number; + isolatedSymbol?: string; + current?: number; + size?: number; +} +⋮---- +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 QueryMarginAccountAllOCOParams { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface QueryMarginAccountTradeListParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface IsolatedMarginSymbol { + base: string; + isBuyAllowed: boolean; + isMarginTrade: boolean; + isSellAllowed: boolean; + quote: string; + symbol: string; + delistTime?: number; +} +⋮---- +export interface ToggleBNBBurnParams { + spotBNBBurn?: 'true' | 'false'; + interestBNBBurn?: 'true' | 'false'; +} +⋮---- +export interface BNBBurnResponse { + spotBNBBurn: boolean; + interestBNBBurn: boolean; +} +⋮---- +export interface QueryMarginInterestRateHistoryParams { + asset: string; + vipLevel?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface MarginInterestRateHistory { + asset: string; + dailyInterestRate: string; + timestamp: number; + vipLevel: number; +} +⋮---- +export interface QueryCrossMarginFeeDataParams { + vipLevel?: number; + coin?: string; +} +⋮---- +export interface CrossMarginFeeData { + vipLevel: number; + coin: string; + transferIn: boolean; + borrowable: boolean; + dailyInterest: string; + yearlyInterest: string; + borrowLimit: string; + marginablePairs: string[]; +} +⋮---- +export interface IsolatedMarginFeeData { + vipLevel: number; + symbol: string; + leverage: string; + data: { + coin: string; + dailyInterest: string; + borrowLimit: string; + }[]; +} +⋮---- +export interface QueryIsolatedMarginTierDataParams { + symbol: string; + tier?: number; +} +⋮---- +export interface IsolatedMarginTierData { + symbol: string; + tier: number; + effectiveMultiple: string; + initialRiskRatio: string; + liquidationRiskRatio: string; + baseAssetMaxBorrowable: string; + quoteAssetMaxBorrowable: string; +} +⋮---- +export interface GetMarginOrderCountUsageParams { + isIsolated?: string; + symbol?: string; +} +⋮---- +export interface MarginOrderCountUsageResponse { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} +⋮---- +export interface Collateral { + minUsdValue: string; + maxUsdValue?: string; + discountRate: 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 SmallLiabilityExchangeHistory { + asset: string; + amount: string; + targetAsset: string; + targetAmount: string; + bizType: string; + timestamp: number; +} +⋮---- +export interface GetNextHourlyInterestRateParams { + assets: string; + isIsolated: boolean; +} +⋮---- +export interface NextHourlyInterestRate { + asset: string; + nextHourlyInterestRate: string; +} +⋮---- +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 MarginAvailableInventoryResponse { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any; + updateTime: number; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface ManualLiquidationParams { + type: string; + symbol?: string; +} +⋮---- +export interface ManualLiquidationResponse { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; +} +⋮---- +export interface LeverageBracket { + leverage: number; + maxDebt: number; + maintenanceMarginRate: number; + initialMarginRate: number; + fastNum: number; +} +⋮---- +export interface LiabilityCoinLeverageBracket { + assetNames: string[]; + rank: number; + brackets: LeverageBracket[]; +} +export interface GetFlexibleSubscriptionRecordParams { + productId?: string; + purchaseId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface GetFlexibleSubscriptionRecordResponse { + amount: string; + asset: string; + time: number; + purchaseId: number; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; +} +⋮---- +export interface GetLockedSubscriptionRecordParams { + purchaseId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface LockedSubscriptionRecord { + positionId: string; + purchaseId: number; + time: 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 FlexibleRedemptionRecord { + amount: string; + asset: string; + time: number; + productId: string; + redeemId: number; + destAccount: string; + status: string; +} +⋮---- +export interface GetLockedRedemptionRecordParams { + positionId?: string; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface LockedRedemptionRecord { + positionId: string; + redeemId: number; + time: number; + asset: string; + lockPeriod: string; + amount: string; + type: string; + deliverDate: string; + status: string; +} +⋮---- +export interface GetFlexibleRewardsHistoryParams { + productId?: string; + asset?: string; + startTime?: number; + endTime?: number; + type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; + current?: number; + size?: number; +} +⋮---- +export interface FlexibleRewardsHistory { + asset: string; + rewards: string; + projectId: string; + type: string; + time: number; +} +⋮---- +export interface GetLockedRewardsHistoryParams { + positionId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface GetLockedRewardsHistory { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; + type: string; +} +⋮---- +export interface SetAutoSubscribeParams { + productId: string; + autoSubscribe: boolean; +} +⋮---- +export interface GetFlexibleSubscriptionPreviewParams { + productId: string; + amount: number; +} +⋮---- +export interface FlexibleSubscriptionPreview { + totalAmount: string; + rewardAsset: string; + airDropAsset: string; + estDailyBonusRewards: string; + estDailyRealTimeRewards: string; + estDailyAirdropRewards: string; +} +⋮---- +export interface GetLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; +} +⋮---- +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 GetRateHistoryParams { + productId: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface GetRateHistory { + productId: string; + asset: string; + annualPercentageRate: string; + time: number; +} +⋮---- +export interface GetCollateralRecordParams { + productId?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface CollateralRecord { + amount: string; + productId: string; + asset: string; + createTime: number; + type: string; + productName: string; + orderId: number; +} +⋮---- +export interface GetDualInvestmentProductListParams { + optionType: string; + exercisedCoin: string; + investCoin: string; + pageSize?: number; + pageIndex?: 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 SubscribeDualInvestmentProductParams { + id: string; + orderId: string; + depositAmount: number; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} +⋮---- +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 GetDualInvestmentPositionsParams { + status?: + | 'PENDING' + | 'PURCHASE_SUCCESS' + | 'SETTLED' + | 'PURCHASE_FAIL' + | 'REFUNDING' + | 'REFUND_SUCCESS' + | 'SETTLING'; + pageSize?: number; + pageIndex?: 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 CheckDualInvestmentAccountsResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; +} +⋮---- +export interface ChangeAutoCompoundStatusParams { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} +⋮---- +export interface ChangeAutoCompoundStatusResponse { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} +⋮---- +export interface GetTargetAssetListParams { + targetAsset?: string; + size?: number; + current?: number; +} +⋮---- +export interface RoiAndDimensionType { + simulateRoi: string; + dimensionValue: string; + dimensionUnit: string; +} +⋮---- +export interface AutoInvestAsset { + targetAsset: string; + roiAndDimensionTypeList: RoiAndDimensionType[]; +} +⋮---- +export interface GetTargetAssetListResponse { + targetAssets: string[]; + autoInvestAssetList: AutoInvestAsset[]; +} +⋮---- +export interface GetTargetAssetROIParams { + targetAsset: string; + hisRoiType: + | 'FIVE_YEAR' + | 'THREE_YEAR' + | 'ONE_YEAR' + | 'SIX_MONTH' + | 'THREE_MONTH' + | 'SEVEN_DAY'; +} +⋮---- +export interface TargetAssetROI { + date: string; + simulateRoi: string; +} +⋮---- +export interface GetSourceAssetListParams { + targetAsset?: string[]; + indexId?: number; + usageType: 'RECURRING' | 'ONE_TIME'; + flexibleAllowedToUse?: boolean; + sourceType?: 'MAIN_SITE' | 'TR'; +} +⋮---- +export interface SourceAsset { + sourceAsset: string; + assetMinAmount: string; + assetMaxAmount: string; + scale: string; + flexibleAmount: string; +} +⋮---- +export interface GetSourceAssetListResponse { + feeRate: string; + taxRate: string; + sourceAssets: SourceAsset[]; +} +⋮---- +export interface AutoInvestPortfolioDetail { + targetAsset: string; + percentage: number; +} +⋮---- +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 CreateInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; +} +⋮---- +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 EditInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; +} +⋮---- +export interface ChangePlanStatusParams { + planId: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +} +⋮---- +export interface ChangePlanStatusResponse { + planId: number; + nextExecutionDateTime: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +} +⋮---- +export interface GetPlanDetailsParams { + planId?: number; + requestId?: string; +} +⋮---- +export interface GetSubscriptionTransactionHistoryParams { + planId?: number; + 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; +} +⋮---- +export interface GetOneTimeTransactionStatusResponse { + transactionId: number; + status: 'SUCCESS' | 'CONVERTING'; +} +⋮---- +export interface SubmitIndexLinkedPlanRedemptionParams { + indexId: number; + requestId?: string; + redemptionPercentage: number; +} +⋮---- +export interface GetIndexLinkedPlanRedemptionHistoryParams { + requestId: number; + startTime?: number; + endTime?: number; + current?: number; + asset?: string; + size?: number; +} +⋮---- +export interface IndexLinkedPlanRedemptionRecord { + indexId: number; + indexName: string; + redemptionId: number; + status: 'SUCCESS' | 'FAILED'; + asset: string; + amount: string; + redemptionDateTime: number; + transactionFee: string; + transactionFeeUnit: string; +} +⋮---- +export interface GetIndexLinkedPlanRebalanceHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RebalanceTransactionDetail { + 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; +} +⋮---- +export interface GetEthStakingHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface EthStakingHistory { + time: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAmount: string; + conversionRatio: string; +} +⋮---- +export interface GetEthRedemptionHistoryParams { + 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; +} +⋮---- +export interface GetBethRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BethRewardsHistory { + time: number; + asset: string; + holding: string; + amount: string; + annualPercentageRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; +} +⋮---- +export interface GetEthStakingQuotaResponse { + leftStakingPersonalQuota: string; + leftRedemptionPersonalQuota: 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 GetEthStakingAccountV2Response { + holdingInETH: string; + holdings: { + wbethAmount: string; + bethAmount: string; + }; + thirtyDaysProfitInETH: string; + profit: { + amountFromWBETH: string; + amountFromBETH: string; + }; +} +⋮---- +export interface WrapBethResponse { + success: boolean; + wbethAmount: string; + exchangeRate: string; +} +⋮---- +export interface GetWrapHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface WrapHistory { + time: number; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + exchangeRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; +} +⋮---- +export interface WbethRewardsHistory { + time: number; + amountInETH: string; + holding: string; + holdingInETH: string; + annualPercentageRate: string; +} +⋮---- +export interface GetWbethRewardsHistoryResponse { + estRewardsInETH: string; + rows: WbethRewardsHistory[]; + total: number; +} +⋮---- +/** + * BFUSD (sapi/v1/bfusd/*) + */ +⋮---- +export interface BfusdAccountResponse { + bfusdAmount: string; + usdtProfit: string; + bfusdProfit: string; +} +⋮---- +export interface BfusdSubscriptionQuota { + leftQuota: string; +} +⋮---- +export interface BfusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; +} +⋮---- +export interface BfusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; +} +⋮---- +export interface BfusdQuotaResponse { + subscriptionQuota: BfusdSubscriptionQuota; + fastRedemptionQuota: BfusdFastRedemptionQuota; + standardRedemptionQuota: BfusdStandardRedemptionQuota; +} +⋮---- +export interface BfusdSubscribeParams { + asset: string; + amount: number; +} +⋮---- +export interface BfusdSubscribeResponse { + success: boolean; + bfusdAmount: string; +} +⋮---- +export interface BfusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; +} +⋮---- +export interface BfusdRedeemResponse { + success: boolean; + receiveAmount: string; + fee: string; + arrivalTime: number; +} +⋮---- +export interface GetBfusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BfusdSubscriptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetBfusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BfusdRedemptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + fee: string; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetBfusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: 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; + current?: number; + size?: number; +} +⋮---- +export interface BfusdRateHistoryRow { + annualPercentageRate: string; + 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; +} +⋮---- +export interface GetRwusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdSubscriptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetRwusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdRedemptionHistoryRow { + time: number; + asset: 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; +} +⋮---- +export interface RwusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + rwusdPosition: string; + annualPercentageRate: string; +} +⋮---- +export interface GetRwusdRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdRateHistoryRow { + annualPercentageRate: string; + time: number; +} +⋮---- +export interface GetMiningAlgoListResponse { + algoName: string; // Algorithm name + algoId: number; // Algorithm ID + poolIndex: number; // Sequence + unit: string; // Unit +} +⋮---- +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 +} +⋮---- +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 HashrateData { + time: number; + hashrate: string; + reject: number; +} +⋮---- +export interface MinerDetail { + workerName: string; + type: string; + hashrateDatas: HashrateData[]; +} +⋮---- +export interface GetMinerDetailsResponse { + code: number; + msg: string; + data: MinerDetail[]; +} +⋮---- +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 GetMinerListResponse { + code: number; + msg: string; + data: { + workerDatas: WorkerData[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetEarningsListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface AccountEarningsProfit { + time: number; + type: number; + hashTransfer: number | null; + transferAmount: number | null; + dayHashRate: number; + profitAmount: number; + coinName: string; + status: number; +} +⋮---- +export interface GetEarningsListResponse { + code: number; + msg: string; + data: { + accountProfits: AccountEarningsProfit[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetExtraBonusListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface OtherProfit { + time: number; + coinName: string; + type: number; + profitAmount: number; + status: number; +} +⋮---- +export interface GetExtraBonusListResponse { + code: number; + msg: string; + data: { + otherProfits: OtherProfit[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetHashrateResaleListParams { + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface ConfigDetail { + configId: number; + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + startDay: number; + endDay: number; + status: number; +} +⋮---- +export interface GetHashrateResaleListResponse { + code: number; + msg: string; + data: { + configDetails: ConfigDetail[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetHashrateResaleDetailParams { + configId: number; + userName: string; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface ProfitTransferDetail { + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + day: number; + amount: number; + coinName: string; +} +⋮---- +export interface GetHashrateResaleDetailResponse { + code: number; + msg: string; + data: { + profitTransferDetails: ProfitTransferDetail[]; + totalNum: number; + pageSize: number; + }; +} +export interface SubmitHashrateResaleParams { + userName: string; + algo: string; + endDate: number; + startDate: number; + toPoolUser: string; + hashRate: number; +} +⋮---- +export interface CancelHashrateResaleConfigParams { + configId: number; + userName: string; +} +⋮---- +export interface GetStatisticListParams { + algo: string; + userName: string; +} +⋮---- +export interface Profit { + BTC: string; + BSV: string; + BCH: string; +} +⋮---- +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 getMiningAccountsListParams { + algo: string; + userName: string; +} +⋮---- +export interface MiningHashrateData { + time: number; + hashrate: string; + reject: string; +} +⋮---- +export interface MiningAccountData { + type: string; + userName: string; + list: MiningHashrateData[]; +} +⋮---- +export interface getMiningAccountsListResponse { + code: number; + msg: string; + data: MiningAccountData[]; +} +⋮---- +export interface GetMiningAccountEarningParams { + algo: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface AccountMiningProfit { + time: number; + coinName: string; + type: number; + puid: number; + subName: string; + amount: number; +} +⋮---- +export interface GetMiningAccountEarningResponse { + code: number; + msg: string; + data: { + accountProfits: AccountMiningProfit[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetFutureTickLevelOrderbookDataLinkParams { + symbol: string; + dataType: 'T_DEPTH' | 'S_DEPTH'; + startTime: number; + endTime: number; +} +⋮---- +export interface HistoricalDataLink { + day: string; + url: string; +} +⋮---- +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 SubmitVpNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: 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 SubmitTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface CancelAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: 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 GetAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; + startTime?: number; + endTime?: number; + page?: number; + pageSize?: 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 GetAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: 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 GetAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SubOrder[]; +} +⋮---- +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 SubmitSpotTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface CancelSpotAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: 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 GetSpotAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; + startTime?: number; + endTime?: number; + page?: number; + pageSize?: 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 GetSpotAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: 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 GetSpotAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SpotSubOrder[]; +} +⋮---- +export interface GetPortfolioMarginProAccountInfoResponse { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + accountStatus: string; + accountType: string; +} +⋮---- +export interface PortfolioDeltaModeStatus { + deltaEnabled: boolean; +} +⋮---- +export interface SwitchPortfolioDeltaModeParams { + deltaEnabled: 'true' | 'false'; +} +⋮---- +export interface GetPortfolioMarginProCollateralRateResponse { + asset: string; + collateralRate: string; +} +⋮---- +export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { + asset: string; + amount: string; +} +⋮---- +export interface GetPortfolioMarginProInterestHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; +} +⋮---- +export interface GetPortfolioMarginProInterestHistoryResponse { + asset: string; + interest: string; + interestAccruedTime: number; + interestRate: string; + principal: string; +} +⋮---- +export interface GetPortfolioMarginAssetIndexPriceResponse { + asset: string; + assetIndexPrice: string; + time: number; +} +⋮---- +export interface BnbTransferParams { + amount: number; + transferSide: 'TO_UM' | 'FROM_UM'; +} +⋮---- +export interface GetPortfolioMarginAssetLeverageResponse { + asset: string; + leverage: number; +} +⋮---- +export interface SetPortfolioMarginMarginCallLevelParams { + marginCallLevel: number; +} +⋮---- +export interface PortfolioMarginMarginCallLevelResponse { + marginCallLevel: string; +} +⋮---- +export type PortfolioMarginMarginCallLevelGetResponse = + | PortfolioMarginMarginCallLevelResponse + | Record; +⋮---- +export interface PortfolioMarginMarginCallLevelDeleteResponse { + msg: string; +} +⋮---- +export interface SubscribeBlvtParams { + tokenName: string; + cost: number; +} +⋮---- +export interface SubscribeBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + amount: string; + cost: string; + timestamp: number; +} +⋮---- +export interface GetBlvtSubscriptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface BlvtSubscriptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + totalCharge: string; + timestamp: number; +} +⋮---- +export interface RedeemBlvtParams { + tokenName: string; + amount: number; +} +⋮---- +export interface RedeemBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + redeemAmount: string; + amount: string; + timestamp: number; +} +⋮---- +export interface GetBlvtRedemptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface BlvtRedemptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + netProceed: string; + timestamp: number; +} +⋮---- +export interface BlvtUserLimitInfo { + tokenName: string; + userDailyTotalPurchaseLimit: string; + userDailyTotalRedeemLimit: string; +} +⋮---- +export interface GetFiatOrderHistoryParams { + transactionType: string; + beginTime?: number; + endTime?: number; + page?: number; + rows?: 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 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; +} +⋮---- +export interface WithdrawFiatAccountInfo { + accountNumber: string; + agency: string; + bankCodeForPix: string; + accountType: string; +} +⋮---- +export interface WithdrawFiatParams { + currency: string; + apiPaymentMethod: string; + amount: number; + accountInfo?: WithdrawFiatAccountInfo; +} +⋮---- +export interface FiatDepositParams { + currency: string; + apiPaymentMethod: string; + amount: number; + ext?: object; + recvWindow?: number; + timestamp?: number; +} +⋮---- +export interface FiatDepositResponse { + code: string; + message: string; + data: { + orderId: string; + }; +} +⋮---- +export interface GetFiatOrderDetailParams { + orderNo: string; + recvWindow?: number; + timestamp?: 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; + }; +} +⋮---- +export interface GetC2CTradeHistoryParams { + tradeType: string; + startTimestamp?: number; + endTimestamp?: number; + page?: number; + rows?: number; +} +⋮---- +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 GetC2CTradeHistoryResponse { + code: string; + message: string; + data: c2cTradeData[]; + total: number; + success: boolean; +} +⋮---- +export interface GetVipLoanOngoingOrdersParams { + orderId?: number; + collateralAccountId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: 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 VipLoanRepayParams { + orderId: number; + amount: number; +} +⋮---- +export interface VipLoanRepayResponse { + loanCoin: string; + repayAmount: string; + remainingPrincipal: string; + remainingInterest: string; + collateralCoin: string; + currentLTV: string; + repayStatus: string; +} +⋮---- +export interface GetVipLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface VipLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + repayStatus: string; + loanDate: string; + repayTime: string; + orderId: string; +} +⋮---- +export interface VipLoanRenewParams { + orderId: number; + loanTerm?: number; +} +⋮---- +export interface VipLoanRenewResponse { + loanAccountId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; +} +⋮---- +export interface CheckVipCollateralAccountParams { + orderId?: number; + collateralAccountId?: number; +} +⋮---- +export interface VipCollateralAccount { + collateralAccountId: string; + collateralCoin: string; +} +⋮---- +export interface VipLoanBorrowParams { + loanAccountId: number; + loanCoin: string; + loanAmount: number; + collateralAccountId: string; + collateralCoin: string; + isFlexibleRate: boolean; + loanTerm?: number; +} +⋮---- +export interface VipLoanBorrowResponse { + loanAccountId: string; + requestId: string; + loanCoin: string; + isFlexibleRate: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm?: string; +} +⋮---- +export interface GetLoanableAssetsDataParams { + loanCoin?: string; + vipLevel?: number; +} +⋮---- +export interface GetApplicationStatusParams { + current?: number; + limit?: 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 BorrowInterestRate { + asset: string; + flexibleDailyInterestRate: string; + flexibleYearlyInterestRate: string; + time: number; +} +⋮---- +export interface GetCryptoLoansIncomeHistoryParams { + asset?: string; + type?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetCryptoLoansIncomeHistoryResponse { + asset: string; + type: string; + amount: string; + timestamp: number; + tranId: string; +} +⋮---- +export interface BorrowCryptoLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; + loanTerm: number; +} +⋮---- +export interface BorrowCryptoLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + hourlyInterestRate: string; + orderId: string; +} +⋮---- +export interface GetLoanBorrowHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface LoanBorrowHistory { + orderId: number; + loanCoin: string; + initialLoanAmount: string; + hourlyInterestRate: string; + loanTerm: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: string; +} +⋮---- +export interface GetLoanOngoingOrdersParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} +⋮---- +export interface LoanOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + residualInterest: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; + expirationTime: number; +} +⋮---- +export interface RepayCryptoLoanParams { + orderId: number; + amount: number; + type?: number; + collateralReturn?: boolean; +} +⋮---- +export interface RepayCryptoLoanResponse { + loanCoin: string; + remainingPrincipal?: string; + remainingInterest?: string; + collateralCoin: string; + remainingCollateral?: string; + currentLTV?: string; + repayStatus: string; +} +⋮---- +export interface GetLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface LoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralUsed: string; + collateralReturn: string; + repayType: string; + repayStatus: string; + repayTime: number; + orderId: number; +} +⋮---- +export interface AdjustCryptoLoanLTVParams { + orderId: number; + amount: number; + direction: 'ADDITIONAL' | 'REDUCED'; +} +⋮---- +export interface AdjustCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + amount: string; + currentLTV: string; +} +⋮---- +export interface GetLoanLTVAdjustmentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface LoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + amount: string; + preLTV: string; + afterLTV: string; + adjustTime: number; + orderId: number; +} +⋮---- +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 GetCollateralAssetDataParams { + collateralCoin?: string; + vipLevel?: number; +} +⋮---- +export interface CollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; + vipLevel: number; +} +⋮---- +export interface CheckCollateralRepayRateParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; +} +⋮---- +export interface CheckCollateralRepayRateResponse { + loanCoin: string; + collateralCoin: string; + repayAmount: string; + rate: string; +} +⋮---- +export interface CustomizeMarginCallParams { + orderId?: number; + collateralCoin?: string; + marginCall: number; +} +⋮---- +export interface CustomizeMarginCall { + orderId: string; + collateralCoin: string; + preMarginCall: string; + afterMarginCall: string; + customizeTime: number; +} +⋮---- +export interface BorrowFlexibleLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; +} +⋮---- +export interface BorrowFlexibleLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + status: 'Succeeds' | 'Failed' | 'Processing'; +} +⋮---- +export interface GetFlexibleLoanOngoingOrdersParams { + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} +⋮---- +export interface FlexibleLoanOngoingOrder { + loanCoin: string; + totalDebt: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; +} +⋮---- +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; +} +⋮---- +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 GetFlexibleCryptoLoanBorrowHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface FlexibleCryptoLoanBorrowHistory { + loanCoin: string; + initialLoanAmount: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: 'Succeeds' | 'Failed' | 'Processing'; +} +⋮---- +export interface RepayCryptoFlexibleLoanParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; + collateralReturn?: boolean; + fullRepayment?: boolean; +} +⋮---- +export interface RepayCryptoFlexibleLoanResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +} +⋮---- +export interface RepayCryptoLoanFlexibleWithCollateralParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; // Amount of loan to repay + fullRepayment?: boolean; // Default: FALSE +} +⋮---- +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 FlexibleCryptoLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralReturn: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; + repayTime: number; +} +⋮---- +export interface AdjustFlexibleCryptoLoanLTVParams { + loanCoin: string; + collateralCoin: string; + adjustmentAmount: number; + direction: 'ADDITIONAL' | 'REDUCED'; +} +⋮---- +export interface AdjustFlexibleCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + adjustmentAmount: string; + currentLTV: string; +} +⋮---- +export interface GetFlexibleLoanLTVAdjustmentHistoryParams { + loanCoin?: string; + collateralCoin?: string; + 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; +} +⋮---- +export interface FlexibleLoanCollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; +} +⋮---- +export interface GetFuturesLeadTraderStatusResponse { + code: string; + message: string; + data: { + isLeadTrader: boolean; + time: number; + }; + success: boolean; +} +⋮---- +export interface GetFuturesLeadTradingSymbolWhitelistResponse { + code: string; + message: string; + data: { + symbol: string; + baseAsset: string; + quoteAsset: string; + }[]; +} +⋮---- +export interface GetPayTradeHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetAllConvertPairsParams { + fromAsset?: string; + toAsset?: 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 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 GetSpotRebateHistoryRecordsParams { + startTime?: number; + endTime?: number; + page?: number; +} +⋮---- +export interface SpotRebateHistoryRecord { + asset: string; + type: number; + amount: string; + updateTime: number; +} +⋮---- +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; + limit?: number; + page?: number; +} +⋮---- +export interface NftToken { + network: string; + tokenId: string; + contractAddress: string; +} +⋮---- +export interface NftTransaction { + orderNo: string; + tokens: NftToken[]; + tradeTime: number; + tradeAmount: string; + tradeCurrency: string; +} +⋮---- +export interface GetNftDepositHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; + page?: number; +} ⋮---- -export class MainClient extends BaseRestClient +export interface NftDeposit { + network: string; + txID: string | null; + contractAdrress: string; + tokenId: string; + timestamp: number; +} ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +export interface GetNftWithdrawHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; + page?: number; +} +⋮---- +export interface NftWithdraw { + network: string; + txID: string; + contractAdrress: string; + tokenId: 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; + 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 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; + }; +} +⋮---- +export interface SimpleEarnSubscribeProductParams { + productId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; +} +⋮---- +export interface SimpleEarnSubscribeFlexibleProductResponse { + purchaseId: string; + success: boolean; +} +⋮---- +export interface SimpleEarnSubscribeLockedProductResponse { + purchaseId: string; + positionId: string; + success: boolean; +} +⋮---- +export interface SimpleEarnRedeemFlexibleProductParams { + productId: string; + redeemAll?: boolean; + amount?: number; + destAccount?: 'SPOT' | 'FUND'; +} +⋮---- +export interface SimpleEarnRedeemResponse { + success: boolean; + redeemId: string; +} +⋮---- +export interface SimpleEarnFlexibleProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; +} +⋮---- +export interface SimpleEarnLockedProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; + positionId?: string; +} +⋮---- +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 SimpleEarnAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedinBTC: string; + totalLockedinUSDT: string; +} +⋮---- +export interface GetSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: 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; +} +⋮---- +// Request interface for querying sub account spot asset info +export interface QuerySubAccountSpotMarginAssetInfoParams { + subAccountId?: string; + page?: number; + size?: number; +} +⋮---- +export interface SubaccountBrokerSpotAsset { + subAccountId: string; + totalBalanceOfBtc: string; +} +⋮---- +export interface SubAccountBrokerMarginAsset { + marginEnable: boolean; + subAccountId: string; + totalAssetOfBtc?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + marginLevel?: string; +} +⋮---- +// 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; +} +⋮---- +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; + totalWalletBalance: string; + totalUnrealizedProfit: string; + totalMarginBalance: string; + totalPositionInitialMargin: string; + totalOpenOrderInitialMargin: string; + futuresEnable: boolean; + asset: string; +} +⋮---- +// 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; +} ⋮---- -/** - * 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 +// Combined response interface for querying sub account futures asset info +export interface BrokerFuturesSubAccountAssets { + data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; + timestamp: number; +} ⋮---- -// Adjust server time by adding estimated one-way latency +export interface BrokerUniversalTransfer { + toId: string; + asset: string; + qty: string; + time: number; + status: string; + txnId: string; + clientTranId: string; + fromAccountType: string; + toAccountType: string; +} ⋮---- -// Calculate time difference between adjusted server time and local time +// Request interface for changing sub account commission +export interface ChangeSubAccountCommissionParams { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission?: number; + marginTakerCommission?: number; +} ⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise +// Response interface for changing sub account commission +export interface ChangeSubAccountCommissionResponse { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission: number; + marginTakerCommission: number; +} ⋮---- -/** - * - * SPOT TRADING Endpoints - General endpoints - * - **/ +// Request interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionParams { + subAccountId: string; + symbol: string; + makerAdjustment: number; + takerAdjustment: number; +} ⋮---- -testConnectivity(): Promise +// 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; +} ⋮---- -getExchangeInfo(params?: ExchangeInfoParams): Promise +// Request interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface QuerySubAccountFuturesCommissionParams { + subAccountId: string; + symbol?: string; +} ⋮---- -/** - * - * SPOT TRADING Endpoints - Market endpoints - * - **/ +// Response interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface BrokerSubAccountFuturesCommission { + subAccountId: string; + symbol: string; + makerCommission: number; + takerCommission: number; +} ⋮---- -getOrderBook(params: OrderBookParams): Promise +export interface ChangeSubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair: string; + makerAdjustment: number; + takerAdjustment: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -getRecentTrades(params: RecentTradesParams): Promise +export interface QuerySubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -getHistoricalTrades(params: HistoricalTradesParams): Promise +// Response interface for querying sub account COIN-Ⓜ futures commission adjustment +export interface BrokerSubAccountCoinFuturesCommission { + subAccountId: string; + pair: string; + makerCommission: number; + takerCommission: number; +} ⋮---- -getHistoricalBlockTrades( - params: HistoricalBlockTradesParams, -): Promise +export interface QueryBrokerSpotCommissionRebateParams { + subAccountId?: string; + startTime?: number; + endTime?: number; + page?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise +// 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; +} ⋮---- -getKlines(params: KlinesParams): Promise +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; +} ⋮---- -getUIKlines(params: KlinesParams): Promise +futuresType: number; // 1: USDT Futures, 2: Coin Futures ⋮---- -getAvgPrice(params: +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'; +} ⋮---- -getExecutionRules( - params?: SpotExecutionRulesParams, -): Promise +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; + }[]; +} ⋮---- -getReferencePrice(params: { +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; -}): Promise -⋮---- -getReferencePriceCalculation(params: { + orderId: number; + clientOrderId: string; + }[]; + orderReports: { 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; + 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'; + }[]; +} ⋮---- -symbol: string; // use for single symbol -type?: 'FULL' | 'MINI'; // default is FULL +export interface CreateSpecialLowLatencyKeyParams { + apiName: string; + symbol?: string; + ip?: string; + publicKey?: string; +} ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; -}): Promise +export interface SpecialLowLatencyKeyResponse { + apiKey: string; + secretKey: string | null; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +} ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL +export interface SpecialLowLatencyKeyInfo { + apiName: string; + apiKey: string; + ip: string; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +} ⋮---- -getTradingDayTicker( - params: TradingDayTickerParams, -): Promise +export interface MarginLiquidationLoan { + asset: string; + amount: string; + repaidAmount: string; + remainingAmount: string; +} ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise +export interface RepayMarginLiquidationLoanParams { + asset: string; + amount: string; +} ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols +export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; ⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise +export interface MarginLiquidationLoanRepayResponse { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; +} ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols +export interface GetMarginLiquidationLoanRepayHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getRollingWindowTicker( - params: RollingWindowTickerParams, -): Promise +export interface MarginLiquidationLoanRepayHistoryRecord { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; +} ⋮---- -/** - * - * SPOT TRADING Endpoints - Trading endpoints - * - **/ +export interface MarginLiquidationLoanRepayHistoryResponse { + total: number; + rows: MarginLiquidationLoanRepayHistoryRecord[]; +} ⋮---- -submitNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> +export interface SolStakingAccount { + bnsolAmount: string; // Amount in bNSOL + holdingInSOL: string; // Holding in SOL + thirtyDaysProfitInSOL: string; // 30 days profit in SOL +} ⋮---- -testNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise +bnsolAmount: string; // Amount in bNSOL +holdingInSOL: string; // Holding in SOL +thirtyDaysProfitInSOL: string; // 30 days profit in SOL ⋮---- -getOrder(params: GetOrderParams): Promise +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 +} ⋮---- -cancelOrder(params: CancelOrderParams): Promise +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 ⋮---- -cancelAllSymbolOrders(params: { - symbol: string; -}): Promise +export interface SubscribeSolStakingResponse { + success: boolean; // Indicates if the subscription was successful + bnsolAmount: string; // Amount in bNSOL received + exchangeRate: string; // SOL amount per 1 BNSOL +} ⋮---- -replaceOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, - >( - params: ReplaceSpotOrderParams, -): Promise> +success: boolean; // Indicates if the subscription was successful +bnsolAmount: string; // Amount in bNSOL received +exchangeRate: string; // SOL amount per 1 BNSOL ⋮---- -/** - * 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 +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 +} ⋮---- -getOpenOrders(params?: +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 ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +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 +} ⋮---- -/** - * @deprecated - */ -submitNewOCO(params: NewOCOParams): Promise +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 ⋮---- -submitNewOrderList( - params: NewOrderListParams, -): Promise> +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 +} ⋮---- -submitNewOrderListOTO( - params: NewOrderListOTOParams, -): Promise +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 ⋮---- -submitNewOrderListOTOCO( - params: NewOrderListOTOCOParams, -): Promise +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 +} ⋮---- -submitNewOrderListOPO( - params: NewOrderListOPOParams, -): Promise +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 ⋮---- -submitNewOrderListOPOCO( - params: NewOrderListOPOCOParams, -): Promise +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 +} ⋮---- -cancelOCO(params: CancelOCOParams): Promise +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 ⋮---- -getOCO(params?: GetOCOParams): Promise +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 +} ⋮---- -getAllOCO(params?: BasicFromPaginatedParams): Promise +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 ⋮---- -/** - * Query open OCO - */ -getAllOpenOCO(): Promise +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%) +} ⋮---- -/** - * Places an order using smart order routing (SOR). - */ -submitNewSOROrder( - params: NewSpotSOROrderParams, -): Promise +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%) ⋮---- -/** - * 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 +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 +} ⋮---- -/** - * - * SPOT TRADING Endpoints - Account endpoints - * - **/ +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 ⋮---- -/** - * Get current account information - */ -getAccountInformation(params?: { - omitZeroBalances?: boolean; -}): Promise +export interface SolBoostRewardsHistoryReq { + type: 'CLAIM' | 'DISTRIBUTE'; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getAccountTradeList( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise +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" +} ⋮---- -getOrderRateLimit(): Promise +bnsolHolding?: string; // Only present if type is "DISTRIBUTE" +status?: string; // Only present if type is "CLAIM" ⋮---- -getPreventedMatches( - params: PreventedMatchesParams, -): Promise +export interface BnsolRateHistoryRecord { + annualPercentageRate: string; // BNSOL APR + exchangeRate: string; // SOL amount per 1 BNSOL + time: number; // Time of the rate record +} ⋮---- -getAllocations(params: AllocationsParams): Promise +annualPercentageRate: string; // BNSOL APR +exchangeRate: string; // SOL amount per 1 BNSOL +time: number; // Time of the rate record ⋮---- -getCommissionRates(params: +export interface RiskUnitMM { + asset: string; + uniMaintainUsd: string; +} ⋮---- -/** - * - * MARGIN TRADING Endpoints - Market Data endpoints - * - **/ +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) +} ⋮---- -getCrossMarginCollateralRatio(): Promise< - { - collaterals: Collateral[]; - assetNames: string[]; - }[] - > { - return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); +accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) ⋮---- -getAllCrossMarginPairs(): Promise +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 +} ⋮---- -getIsolatedMarginAllSymbols(params?: { - symbol?: string; -}): Promise +optionWalletBalance: string; // only for PM PRO SPAN +optionEquity: string; // only for PM PRO SPAN ⋮---- -getAllMarginAssets(): Promise +export interface PMProMintBFUSDParams { + fromAsset: string; // USDT only + targetAsset: string; // BFUSD only + amount: number; +} ⋮---- -getMarginDelistSchedule(): Promise +fromAsset: string; // USDT only +targetAsset: string; // BFUSD only ⋮---- -getIsolatedMarginTierData( - params: QueryIsolatedMarginTierDataParams, -): Promise +export interface PMProMintBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; +} ⋮---- -queryMarginPriceIndex( - params: BasicSymbolParam, -): Promise +export interface PMProRedeemBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; +} ⋮---- -getMarginAvailableInventory(params: { - type: string; -}): Promise +export interface PMProBankruptcyLoanRepaymentHistory { + asset: string; + amount: string; + repayTime: number; +} ⋮---- -getLeverageBracket(): Promise +export interface VipLoanInterestRateHistoryParams { + coin: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} ⋮---- -/** - * - * MARGIN TRADING Endpoints - Borrow and Repay endpoints - * - **/ +export interface VipLoanInterestRateRecord { + coin: string; + annualizedInterestRate: string; + time: number; +} ⋮---- -getNextHourlyInterestRate( - params: GetNextHourlyInterestRateParams, -): Promise +export interface VipLoanAccruedInterestParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} ⋮---- -getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< +export interface VipLoanAccruedInterestRecord { + loanCoin: string; + principalAmount: string; + interestAmount: string; + annualInterestRate: string; + accrualTime: number; + orderId: number; +} ⋮---- -submitMarginAccountBorrowRepay( - params: MarginAccountLoanParams, -): Promise +export interface WithdrawTravelRuleParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; + amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; + questionnaire: string; +} ⋮---- -getMarginAccountBorrowRepayRecords( - params: GetMarginAccountBorrowRepayRecordsParams, -): Promise< +export interface GetTravelRuleWithdrawHistoryParams { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; +} ⋮---- -getMarginInterestRateHistory( - params: QueryMarginInterestRateHistoryParams, -): Promise +export interface GetTravelRuleWithdrawHistoryV2Params { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; +} ⋮---- -queryMaxBorrow( - params: BasicMarginAssetParams, -): Promise +export interface SubmitTravelRuleDepositQuestionnaireParams { + tranId: number; + questionnaire: string; +} ⋮---- -/** - * - * MARGIN TRADING Endpoints - Trade endpoints - * - **/ +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; +} ⋮---- -getMarginForceLiquidationRecord( - params: GetForceLiquidationRecordParams, -): Promise< +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; +} ⋮---- -getSmallLiabilityExchangeCoins(): Promise +export interface SubmitTravelRuleDepositQuestionnaireResponse { + trId: number; + accepted: boolean; + info: string; +} ⋮---- -getSmallLiabilityExchangeHistory( - params: GetSmallLiabilityExchangeHistoryParams, -): Promise< +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; +} ⋮---- -marginAccountCancelOpenOrders( - params: BasicSymbolParam, -): Promise +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; +} ⋮---- -marginAccountCancelOCO(params: CancelOCOParams): Promise +/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ ⋮---- -marginAccountCancelOrder( - params: CancelOrderParams, -): Promise +export interface TravelRuleCountryInfo { + countryCode: string; + countryName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; + hasRegionRestrictions: boolean; +} ⋮---- -marginAccountNewOCO(params: NewOCOParams): Promise +export interface TravelRuleCountryListResponse { + countries: TravelRuleCountryInfo[]; + lastUpdated: number; +} ⋮---- -marginAccountNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> +export interface GetTravelRuleRegionListParams { + countryCode: string; +} ⋮---- -getMarginOrderCountUsage( - params: GetMarginOrderCountUsageParams, -): Promise +export interface TravelRuleRegionInfo { + regionName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; +} ⋮---- -queryMarginAccountAllOCO( - params: QueryMarginAccountAllOCOParams, -): Promise +export interface TravelRuleRegionListResponse { + countryCode: string; + regions: TravelRuleRegionInfo[]; + lastUpdated: number; +} ⋮---- -queryMarginAccountAllOrders( - params: GetAllOrdersParams, -): Promise +export interface GetVipLoanFixedRateMarketParams { + loanCoin: string; + duration?: number; + current?: number; + size?: number; +} ⋮---- -queryMarginAccountOCO(params: GetOCOParams): Promise +export interface VipLoanFixedRateMarketRecord { + requestId: number; + requestNo: number; + coin: string; + interestRate: numberInString; + duration: number; + minimumAmount: numberInString; + availableAmount: numberInString; + estimatedInterest: numberInString; +} ⋮---- -queryMarginAccountOpenOCO(params: { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; -}): Promise +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'; +} ⋮---- -queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise +// Institutional Loan types +export interface InstitutionalLoanLiability { + assetName: string; + principal: string; + interest: string; +} ⋮---- -queryMarginAccountOrder(params: GetOrderParams): Promise +export interface InstitutionalLoanWallet { + accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; +} ⋮---- -queryMarginAccountTradeList( - params: QueryMarginAccountTradeListParams, -): Promise +export interface InstitutionalLoanCollateralAccount { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + wallets: InstitutionalLoanWallet[]; +} ⋮---- -submitSmallLiabilityExchange(params: +export interface InstitutionalLoanRiskUnitDetails { + groupId: number; + parentEmail: string; + creditEmail: string; + updateTime: number; + ltv: string; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + liabilities: InstitutionalLoanLiability[]; + collateralAccounts: InstitutionalLoanCollateralAccount[]; +} ⋮---- -submitManualLiquidation( - params: ManualLiquidationParams, -): Promise +export interface GetInstitutionalLoanRiskUnitDetailsParams { + groupId?: number; +} ⋮---- -/** - * Post a new OTO order for margin account - */ -submitMarginOTOOrder( - params: SubmitMarginOTOOrderParams, -): Promise +export interface CloseInstitutionalLoanRiskUnitResponse { + groupId: number; + status: 'CLOSED'; +} ⋮---- -/** - * Submit a new OTOCO order for margin account - */ -submitMarginOTOCOOrder( - params: SubmitMarginOTOCOOrderParams, -): Promise +export interface AddInstitutionalLoanCollateralAccountParams { + groupId: number; + subEmail: string; + enableSpot: boolean; + enableMargin: boolean; +} ⋮---- -/** - * Create a special key for low-latency trading (VIP 4+ only) - */ -createMarginSpecialLowLatencyKey( - params: CreateSpecialLowLatencyKeyParams, -): Promise +export interface InstitutionalLoanRiskUnitMember { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + enableMargin: boolean; + enableSpot: boolean; +} ⋮---- -deleteMarginSpecialLowLatencyKey(params?: { - apiKey?: string; - apiName?: string; - symbol?: string; -}): Promise +export interface ActiveInstitutionalLoanRiskUnit { + groupId: number; + members: InstitutionalLoanRiskUnitMember[]; + createTime: number; +} +export interface ClosedInstitutionalLoanRiskUnit { + groupId: number; + parentEmail: string; + creditEmail: string; + enabled: boolean; + createTime: number; + closeTime: number; +} ⋮---- -updateMarginIPForSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; - ip: string; -}): Promise +export interface GetClosedInstitutionalLoanRiskUnitsParams { + current?: number; + size?: number; +} ⋮---- -/** - * Query the list of special keys for low-latency trading - */ -getMarginSpecialLowLatencyKeys(params: { - symbol?: string; -}): Promise +export interface GetClosedInstitutionalLoanRiskUnitsResponse { + total: number; + rows: ClosedInstitutionalLoanRiskUnit[]; +} ⋮---- -/** - * Query information for a specific special key used in low-latency trading - */ -getMarginSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; -}): Promise +// Institutional Loan Force Liquidation interfaces +export interface InstitutionalLoanLiquidationSnapshot { + subEmail: string; + memberType: 'CREDIT' | 'COLLATERAL'; + walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; +} ⋮---- -/** - * Query the current cross-margin liquidation loan status (bankruptcy deficit). - */ -getMarginLiquidationLoan(): Promise +export interface InstitutionalLoanLiquidationSnapshotData { + snapshots: InstitutionalLoanLiquidationSnapshot[]; + liabilities: InstitutionalLoanLiability[]; +} ⋮---- -/** - * Repay an outstanding cross-margin liquidation loan from the spot wallet. - */ -repayMarginLiquidationLoan( - params: RepayMarginLiquidationLoanParams, -): Promise +export interface InstitutionalLoanForceLiquidationRecord { + groupId: number; + startLtv: number; + endLtv: number; + liquidationStartTime: number; + liquidationEndTime: number; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; +} ⋮---- -/** - * Query cross-margin liquidation loan repayment history. - */ -getMarginLiquidationLoanRepayHistory( - params?: GetMarginLiquidationLoanRepayHistoryParams, -): Promise +export interface GetInstitutionalLoanForceLiquidationParams { + groupId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Exit Margin Special Key mode for Cross Margin Classic accounts. - */ -exitMarginSpecialKeyMode(): Promise +export interface GetInstitutionalLoanForceLiquidationResponse { + total: number; + rows: InstitutionalLoanForceLiquidationRecord[]; +} ⋮---- -/** - * - * MARGIN TRADING Endpoints - Transfer endpoints - * - **/ +// 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 +} ⋮---- -getCrossMarginTransferHistory( - params: GetCrossMarginTransferHistoryParams, -): Promise> +subEmail?: string; // Optional: subEmail can be credit account or collateral account +asset: string; // Asset Name +amount: number; // Transfer amount of the asset ⋮---- -queryMaxTransferOutAmount( - params: BasicMarginAssetParams, -): Promise +// Additional institutional loan types for borrow, repay, and interest history +export interface GetInstitutionalLoanMaxBorrowableParams { + groupId?: number; + assetName: string; +} ⋮---- -/** - * - * MARGIN TRADING Endpoints - Account endpoints - * - **/ +export interface InstitutionalLoanMaxBorrowableResponse { + maxBorrowableAmount: numberInString | null; +} ⋮---- -updateCrossMarginMaxLeverage(params: +export interface InstitutionalLoanBorrowParams { + groupId: number; + assetName: string; + amount: number; +} ⋮---- -disableIsolatedMarginAccount(params: +export interface InstitutionalLoanBorrowResponse { + transactionId: string; + amount: number; + status: string; +} ⋮---- -enableIsolatedMarginAccount(params: +export interface InstitutionalLoanRepayParams { + groupId: number; + assetName: string; + amount: number; +} ⋮---- -getBNBBurn(): Promise +export interface InstitutionalLoanRepayResponse { + transactionId: string; + amount: number; +} ⋮---- -getMarginSummary(): Promise +export interface GetInstitutionalLoanInterestHistoryParams { + groupId?: number; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -queryCrossMarginAccountDetails(): Promise +export interface InstitutionalLoanInterestHistoryRecord { + groupId: number; + assetName: string; + principal: string; + interestRate: string; + interest: string; + interestTimestamp: number; +} ⋮---- -getCrossMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise +export interface InstitutionalLoanInterestHistoryResponse { + total: number; + rows: InstitutionalLoanInterestHistoryRecord[]; +} ⋮---- -getIsolatedMarginAccountLimit(): 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 +} ⋮---- -getIsolatedMarginAccountInfo(params?: { - symbols?: string; -}): 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 ⋮---- -getIsolatedMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): 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 +} ⋮---- -toggleBNBBurn(params: ToggleBNBBurnParams): 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 ⋮---- -/** - * Possibly @deprecated - * Only existing in old documentation, not in new documentation - */ -getMarginCapitalFlow( - params: GetMarginCapitalFlowParams, -): Promise +export interface GetInstitutionalLoanBorrowRepayRecordsResponse { + total: number; + rows: InstitutionalLoanBorrowRepayRecord[]; +} ⋮---- -/** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead - */ -queryLoanRecord( - params: QueryMarginRecordParams, -): Promise< +export interface MarginInterestRebateBalanceResponse { + asset: string; + balance: string; + totalGranted: string; + totalConsumed: string; +} ⋮---- -/** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead - */ -queryRepayRecord( - params: QueryMarginRecordParams, -): Promise< +export interface GetMarginInterestRebateBalanceRecordsParams { + type?: 0 | 1 | 2; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * @deprecated on 2024-01-09, use submitUniversalTransfer() instead - */ -isolatedMarginAccountTransfer( - params: IsolatedMarginAccountTransferParams, -): Promise +export interface MarginInterestRebateBalanceRecord { + type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; + rebateAsset: string; + delta: string; + createTime: number; + groupId?: number; + liabilityAsset?: string; + deductedInterest?: string; + exchangeRate?: string; +} ⋮---- -/** - * - * WALLET Endpoints - Capital endpoints - * - **/ +export interface MarginInterestRebateBalanceRecordsResponse { + total: number; + rows: MarginInterestRebateBalanceRecord[]; +} ⋮---- -getBalances(): Promise +// On-chain Yields types ⋮---- -withdraw(params: WithdrawParams): Promise< +export interface OnchainYieldsLockedProductListParams { + asset?: string; + current?: number; + size?: number; +} ⋮---- -getWithdrawHistory( - params?: WithdrawHistoryParams, -): Promise +export interface OnchainYieldsLockedProductDetail { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: 'PREHEATING' | 'PURCHASING'; + subscriptionStartTime: string; + canRedeemToFlex: boolean; +} ⋮---- -getWithdrawAddresses(): Promise +export interface OnchainYieldsLockedProductQuota { + totalPersonalQuota: string; + minimum: string; +} ⋮---- -getWithdrawQuota(): Promise< +export interface OnchainYieldsLockedProduct { + projectId: string; + detail: OnchainYieldsLockedProductDetail; + quota: OnchainYieldsLockedProductQuota; +} ⋮---- -getDepositHistory(params?: DepositHistoryParams): Promise +export interface OnchainYieldsLockedProductListResponse { + rows: OnchainYieldsLockedProduct[]; + total: number; +} ⋮---- -getDepositAddress( - params: DepositAddressParams, -): Promise +export interface OnchainYieldsLockedPersonalLeftQuotaParams { + projectId: string; +} ⋮---- -getDepositAddresses( - params: DepositAddressListParams, -): Promise +export interface OnchainYieldsLockedPersonalLeftQuotaResponse { + leftPersonalQuota: string; +} ⋮---- -submitDepositCredit( - params: SubmitDepositCreditParams, -): Promise +export interface OnchainYieldsLockedPositionParams { + asset?: string; + positionId?: number; + projectId?: string; + current?: number; + size?: number; +} ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - */ -getAutoConvertStablecoins(): 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'; +} ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - */ -setConvertibleCoins(params: ConvertibleCoinsParams): Promise +export interface OnchainYieldsLockedPositionResponse { + rows: OnchainYieldsLockedPosition[]; + total: number; +} ⋮---- -/** - * - * WALLET Endpoints - Asset endpoints - * - **/ +export interface OnchainYieldsAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedInBTC: string; + totalLockedInUSDT: string; +} ⋮---- -getAssetDetail( - params?: Partial, -): Promise> +// On-chain Yields Earn types ⋮---- -getWalletBalances(params?: { - quoteAsset?: string; -}): Promise +export interface OnchainYieldsLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; +} ⋮---- -getUserAsset(params: GetAssetParams): Promise +export interface OnchainYieldsLockedSubscriptionPreviewResponse { + rewardAsset: string; + totalRewardAmt: string; + nextPay?: string; + nextPayDate?: string; + rewardsPayDate?: string; + valueDate: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; +} ⋮---- -submitUniversalTransfer( - params: UniversalTransferParams, -): Promise< +export interface OnchainYieldsLockedSubscribeParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; + redeemTo?: 'SPOT' | 'FLEXIBLE'; + channelId?: string; + clientId?: string; +} +⋮---- +export interface OnchainYieldsLockedSubscribeResponse { + purchaseId: number; + positionId: string; + amount: string; + success: boolean; +} ⋮---- -getUniversalTransferHistory( - params: UniversalTransferHistoryParams, -): Promise +export interface OnchainYieldsLockedSetAutoSubscribeParams { + positionId: string; + autoSubscribe: boolean; +} ⋮---- -getDust(params: +export interface OnchainYieldsLockedSetAutoSubscribeResponse { + success: boolean; +} ⋮---- -convertDustToBnb(params: ConvertDustParams): Promise +export interface OnchainYieldsLockedSetRedeemOptionParams { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; +} ⋮---- -/** - * Convert dust assets to a target asset (e.g. BNB, USDT). - */ -convertDustAssets(params: DustConvertParams): Promise +export interface OnchainYieldsLockedSetRedeemOptionResponse { + success: boolean; +} ⋮---- -/** - * Query assets eligible for dust conversion. - */ -queryDustConvertibleAssets( - params: DustConvertibleAssetsParams, -): Promise +export interface OnchainYieldsLockedRedeemParams { + positionId: number; + channelId?: string; +} ⋮---- -getDustLog(params?: BasicTimeRangeParam): Promise +export interface OnchainYieldsLockedRedeemResponse { + redeemId: number; + success: boolean; +} ⋮---- -getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise +// On-chain Yields History types ⋮---- -getTradeFee(params?: +export interface OnchainYieldsLockedSubscriptionRecordParams { + purchaseId?: string; + clientId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getFundingAsset(params: GetAssetParams): Promise +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'; +} ⋮---- -getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< +export interface OnchainYieldsLockedSubscriptionRecordResponse { + rows: OnchainYieldsLockedSubscriptionRecord[]; + total: number; +} ⋮---- -getDelegationHistory( - params: DelegationHistoryParams, -): Promise> +export interface OnchainYieldsLockedRewardsHistoryParams { + positionId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * - * 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. - * - **/ +export interface OnchainYieldsLockedRewardsRecord { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; +} ⋮---- -/** - * 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. - */ +export interface OnchainYieldsLockedRewardsHistoryResponse { + rows: OnchainYieldsLockedRewardsRecord[]; + total: number; +} ⋮---- -/** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead - */ -submitNewFutureAccountTransfer( - params: NewFutureAccountTransferParams, -): Promise< +export interface OnchainYieldsLockedRedemptionRecordParams { + positionId?: number; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead - */ -getFutureAccountTransferHistory( - params: GetFutureAccountTransferHistoryParams, -): 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'; +} ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise +export interface OnchainYieldsLockedRedemptionRecordResponse { + rows: OnchainYieldsLockedRedemptionRecord[]; + total: number; +} ⋮---- /** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise + * ALPHA TRADING INTERFACES + */ ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralWalletV2(): Promise +export interface AlphaToken { + alphaId: number; + symbol: string; + name: string; + chainId: string; + contractAddress: string; + decimals?: number; +} ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getAdjustCrossCollateralLTVHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): 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; +} ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralLiquidationHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +export interface AlphaSymbol { + symbol: string; + status: string; + baseAsset: string; + quoteAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + filters: AlphaExchangeFilter[]; + orderTypes: string[]; +} ⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralInterestHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +export interface AlphaAsset { + asset: string; +} ⋮---- -/** - * - * WALLET Endpoints - Account endpoints - * - **/ +export interface AlphaExchangeInfo { + timezone: string; + assets: AlphaAsset[]; + symbols: AlphaSymbol[]; +} ⋮---- -getAccountInfo(): Promise +export interface AlphaAggTradesParams { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getDailyAccountSnapshot( - params: DailyAccountSnapshotParams, -): 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 +} ⋮---- -disableFastWithdrawSwitch(): 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 ⋮---- -enableFastWithdrawSwitch(): 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; +} ⋮---- -getAccountStatus(): Promise< +interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M ⋮---- -getApiTradingStatus(): 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") +]; ⋮---- -getApiKeyPermissions(): 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") ⋮---- -/** - * - * WALLET Endpoints - Travel Rule endpoints - * - **/ +export interface AlphaTickerParams { + symbol: string; +} ⋮---- -/** - * 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< +export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; ⋮---- -/** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistory( - params?: GetTravelRuleWithdrawHistoryParams, -): Promise +export interface AlphaFullDepthParams { + symbol: string; + limit?: AlphaFullDepthLimit; +} ⋮---- -/** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistoryV2( - params?: GetTravelRuleWithdrawHistoryV2Params, -): Promise +export interface AlphaFullDepthData { + lastUpdateId: number; + symbol: string; + bids: [string, string][]; + asks: [string, string][]; + E: number; + T: number; +} ⋮---- -/** - * 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 +export interface AlphaFullDepthResponse { + code: string; + message: string | null; + messageDetail: string | null; + success: boolean; + data: AlphaFullDepthData; +} ⋮---- -/** - * Fetch deposit history for local entities that require travel rule - */ -getTravelRuleDepositHistory( - params?: GetTravelRuleDepositHistoryParams, -): Promise +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; +} ⋮---- /** - * 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 + * Soft Staking interfaces + */ +export interface GetSoftStakingProductListParams { + asset?: string; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -getTravelRuleRegionList( - params: GetTravelRuleRegionListParams, -): Promise +export interface SoftStakingProduct { + asset: string; + minAmount: string; + maxCap: string; + apr: string; + stakedAmount: string; + totalProfit: string; +} ⋮---- -/** - * - * WALLET Endpoints - Other endpoints - * - **/ +export interface GetSoftStakingProductListResponse { + status: boolean; + totalRewardsUsdt: string; + rows: SoftStakingProduct[]; + total: number; +} ⋮---- -getSystemStatus(): Promise +export interface SetSoftStakingParams { + softStaking: boolean; + recvWindow?: number; + timestamp: number; +} ⋮---- -getDelistSchedule(): Promise +export interface SetSoftStakingResponse { + success: boolean; +} ⋮---- -/** - * - * SUB ACCOUNT Endpoints - Account management - * - **/ +export interface GetSoftStakingRewardsHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -createVirtualSubAccount( - params: CreateSubAccountParams, -): Promise +export interface SoftStakingRewardsRecord { + asset: string; + rewards: string; + rewardAsset: string; + avgAmount: string; + time: number; +} ⋮---- -getSubAccountList( - params?: SubAccountListParams, -): Promise +export interface GetSoftStakingRewardsHistoryResponse { + rows: SoftStakingRewardsRecord[]; + total: number; +} + +================ +File: src/main-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; ⋮---- -subAccountEnableFutures(email: string): Promise +import { + AmendKeepPriorityParams, + BasicAssetPaginatedParams, + BasicAssetParam, + BasicSymbolParam, + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + CoinStartEndLimit, + ExchangeSymbol, + GetAllOrdersParams, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, + NewOCOParams, + NewOrderListParams, + OrderBookParams, + OrderIdProperty, + OrderResponseType, + OrderType, + RecentTradesParams, + RowsWithTotal, + SymbolFromPaginatedRequestFromId, + SymbolPrice, +} from './types/shared'; +import { + AcceptQuoteRequestParams, + AccountInfo, + AccountInformation, + ActiveInstitutionalLoanRiskUnit, + AddBSwapLiquidityParams, + AddInstitutionalLoanCollateralAccountParams, + AddIpRestriction, + AdjustCryptoLoanLTVParams, + AdjustCryptoLoanLTVResponse, + AdjustFlexibleCryptoLoanLTVParams, + AdjustFlexibleCryptoLoanLTVResponse, + AggregateTrade, + AlgoOrder, + AllCoinsInformationResponse, + Allocation, + AllocationsParams, + AlphaAggTrade, + AlphaAggTradesParams, + AlphaExchangeInfo, + AlphaFullDepthParams, + AlphaFullDepthResponse, + AlphaKline, + AlphaKlinesParams, + AlphaTicker, + AlphaToken, + ApiKeyBrokerSubAccount, + APIPermissions, + APITradingStatus, + ApplicationStatus, + AssetDetail, + BasicFromPaginatedParams, + BasicFuturesSubAccountParams, + BasicMarginAssetParams, + BasicSubAccount, + BasicTimeRangeParam, + BethRewardsHistory, + BfusdAccountResponse, + BfusdQuotaResponse, + BfusdRateHistoryRow, + BfusdRedeemParams, + BfusdRedeemResponse, + BfusdRedemptionHistoryRow, + BfusdRewardsHistoryRow, + BfusdSubscribeParams, + BfusdSubscribeResponse, + BfusdSubscriptionHistoryRow, + BlockTrade, + BlvtRedemptionRecord, + BlvtSubscriptionRecord, + BlvtUserLimitInfo, + BNBBurnResponse, + BnbTransferParams, + BnsolRateHistoryRecord, + BnsolRewardHistoryRecord, + BorrowCryptoLoanParams, + BorrowCryptoLoanResponse, + BorrowFlexibleLoanParams, + BorrowFlexibleLoanResponse, + BorrowInterestRate, + BrokerCommissionRebate, + BrokerSubAccount, + BrokerSubAccountCoinFuturesCommission, + BrokerSubAccountFuturesCommission, + BrokerSubAccountHistory, + BrokerUniversalTransfer, + BSwapLiquidity, + BSwapOperations, + BSwapOperationsParams, + BUSDConversionRecord, + CancelAlgoOrderResponse, + CancelHashrateResaleConfigParams, + CancelOrderListResult, + CancelSpotAlgoOrderResponse, + CancelSpotOrderResult, + ChangeAutoCompoundStatusParams, + ChangeAutoCompoundStatusResponse, + ChangePermissionApiKeyBrokerSubAccountParams, + ChangePermissionApiKeyBrokerSubAccountResponse, + ChangePlanStatusParams, + ChangePlanStatusResponse, + ChangeSubAccountCoinFuturesCommissionParams, + ChangeSubAccountCommissionParams, + ChangeSubAccountCommissionResponse, + ChangeSubAccountFuturesCommissionParams, + ChangeSubAccountFuturesCommissionResponse, + CheckCollateralRepayRateParams, + CheckCollateralRepayRateResponse, + CheckDualInvestmentAccountsResponse, + CheckVipCollateralAccountParams, + CloseInstitutionalLoanRiskUnitResponse, + CloudMining, + CloudMiningHistoryParams, + CoinMarginedFuturesResponse, + Collateral, + CollateralAssetData, + CollateralRecord, + CommissionRates, + ConvertDustParams, + ConvertibleCoinsParams, + ConvertibleCoinsResponse, + ConvertLimitOpenOrder, + ConvertQuoteRequestParams, + ConvertTransfer, + ConvertTransferResponse, + CreateApiKeyBrokerSubAccountParams, + CreateApiKeyBrokerSubAccountResponse, + CreateBrokerSubAccountParams, + CreateDualTokenGiftCardParams, + CreateGiftCardParams, + CreateInvestmentPlanParams, + CreateInvestmentPlanResponse, + CreateSpecialLowLatencyKeyParams, + CreateSubAccountParams, + CrossMarginFeeData, + CrossMarginTransferHistory, + CurrentAvgPrice, + CustomizeMarginCall, + CustomizeMarginCallParams, + DailyAccountSnapshot, + DailyAccountSnapshotParams, + DelegationHistory, + DelegationHistoryParams, + DeleteApiKeyBrokerSubAccountParams, + DelistScheduleResponse, + DepositAddress, + DepositAddressListParams, + DepositAddressParams, + DepositAddressResponse, + DepositHistory, + DepositHistoryParams, + DualInvestmentPosition, + DualInvestmentProduct, + DustConversion, + DustConvertibleAssetsParams, + DustConvertibleAssetsResponse, + DustConvertParams, + DustInfo, + DustLog, + EditInvestmentPlanParams, + EditInvestmentPlanResponse, + EnableConvertSubAccountParams, + EnableFuturesBrokerSubAccountParams, + EnableFuturesBrokerSubAccountResponse, + EnableMarginApiKeyBrokerSubAccountParams, + EnableMarginBrokerSubAccountParams, + EnableMarginBrokerSubAccountResponse, + EnableOptionsForSubAccountResponse, + EnableOrDisableIPRestrictionForSubAccountParams, + EnableUniversalTransferApiKeyBrokerSubAccountParams, + EnableUniversalTransferApiKeyBrokerSubAccountResponse, + ETHRateHistory, + EthRedemptionHistory, + EthStakingHistory, + ExchangeInfo, + ExchangeInfoParams, + FiatDepositParams, + FiatDepositResponse, + FixedAndActivityProjectParams, + FixedAndActivityProjectPositionParams, + FlexibleCryptoLoanBorrowHistory, + FlexibleLoanAssetData, + FlexibleLoanCollateralAssetData, + FlexibleLoanLiquidationHistoryRecord, + FlexibleLoanLTVAdjustmentHistory, + FlexibleLoanOngoingOrder, + FlexibleRedemptionRecord, + FlexibleRewardsHistory, + FlexibleSubscriptionPreview, + ForceLiquidationRecord, + FundingAsset, + FutureAccountTransfer, + FuturesPositionRisk, + GetAlgoHistoricalOrdersParams, + GetAlgoSubOrdersParams, + GetAlgoSubOrdersResponse, + GetAllConvertPairsParams, + GetApiKeyBrokerSubAccountParams, + GetApplicationStatusParams, + GetAssetParams, + GetBethRewardsHistoryParams, + GetBfusdRateHistoryParams, + GetBfusdRedemptionHistoryParams, + GetBfusdRewardsHistoryParams, + GetBfusdSubscriptionHistoryParams, + GetBlvtRedemptionRecordParams, + GetBlvtSubscriptionRecordParams, + GetBnsolRateHistoryReq, + GetBnsolRewardsHistoryReq, + GetBrokerInfoResponse, + GetBrokerSubAccountDepositHistoryParams, + GetBrokerSubAccountHistoryParams, + GetBrokerSubAccountParams, + GetC2CTradeHistoryParams, + GetC2CTradeHistoryResponse, + GetClosedInstitutionalLoanRiskUnitsParams, + GetClosedInstitutionalLoanRiskUnitsResponse, + GetCollateralAssetDataParams, + GetCollateralRecordParams, + GetConvertBUSDHistoryParams, + GetConvertTradeHistoryParams, + GetCrossMarginTransferHistoryParams, + GetCryptoLoansIncomeHistoryParams, + GetCryptoLoansIncomeHistoryResponse, + GetDualInvestmentPositionsParams, + GetDualInvestmentProductListParams, + GetEarningsListParams, + GetEarningsListResponse, + GetETHRateHistoryParams, + GetEthRedemptionHistoryParams, + GetEthStakingAccountResponse, + GetEthStakingAccountV2Response, + GetEthStakingHistoryParams, + GetEthStakingQuotaResponse, + GetExtraBonusListParams, + GetExtraBonusListResponse, + GetFiatOrderDetailParams, + GetFiatOrderDetailResponse, + GetFiatOrderHistoryParams, + GetFiatOrderHistoryResponse, + GetFiatPaymentsHistoryResponse, + GetFlexibleCryptoLoanBorrowHistoryParams, + GetFlexibleLoanLiquidationHistoryParams, + GetFlexibleLoanLTVAdjustmentHistoryParams, + GetFlexibleLoanOngoingOrdersParams, + GetFlexibleRedemptionRecordParams, + GetFlexibleRewardsHistoryParams, + GetFlexibleSubscriptionPreviewParams, + GetFlexibleSubscriptionRecordParams, + GetFlexibleSubscriptionRecordResponse, + GetForceLiquidationRecordParams, + GetFutureAccountTransferHistoryParams, + GetFuturesLeadTraderStatusResponse, + GetFuturesLeadTradingSymbolWhitelistResponse, + GetFutureTickLevelOrderbookDataLinkParams, + GetHashrateResaleDetailParams, + GetHashrateResaleDetailResponse, + GetHashrateResaleListParams, + GetHashrateResaleListResponse, + GetIndexDetailsResponse, + GetIndexLinkedPlanPositionDetailsResponse, + GetIndexLinkedPlanRebalanceHistoryParams, + GetIndexLinkedPlanRedemptionHistoryParams, + GetInstitutionalLoanBorrowRepayRecordsParams, + GetInstitutionalLoanBorrowRepayRecordsResponse, + GetInstitutionalLoanForceLiquidationParams, + GetInstitutionalLoanForceLiquidationResponse, + GetInstitutionalLoanInterestHistoryParams, + GetInstitutionalLoanMaxBorrowableParams, + GetInstitutionalLoanRiskUnitDetailsParams, + GetLoanableAssetsDataParams, + GetLoanBorrowHistoryParams, + GetLoanCoinPaginatedHistoryParams, + GetLoanLTVAdjustmentHistoryParams, + GetLoanOngoingOrdersParams, + GetLoanRepaymentHistoryParams, + GetLockedRedemptionRecordParams, + GetLockedRewardsHistory, + GetLockedRewardsHistoryParams, + GetLockedSubscriptionPreviewParams, + GetLockedSubscriptionRecordParams, + GetMarginAccountBorrowRepayRecordsParams, + GetMarginCapitalFlowParams, + GetMarginInterestHistoryParams, + GetMarginInterestRebateBalanceRecordsParams, + GetMarginLiquidationLoanRepayHistoryParams, + GetMarginOrderCountUsageParams, + GetMinerDetailsParams, + GetMinerDetailsResponse, + GetMinerListParams, + GetMinerListResponse, + GetMiningAccountEarningParams, + GetMiningAccountEarningResponse, + getMiningAccountsListParams, + getMiningAccountsListResponse, + GetMiningAlgoListResponse, + GetMiningCoinListResponse, + GetNextHourlyInterestRateParams, + GetNftAssetParams, + GetNftDepositHistoryParams, + GetNftTransactionHistoryParams, + GetNftWithdrawHistoryParams, + GetOCOParams, + GetOneTimeTransactionStatusParams, + GetOneTimeTransactionStatusResponse, + GetOrderStatusParams, + GetPayTradeHistoryParams, + GetPlanDetailsParams, + GetPortfolioMarginAssetIndexPriceResponse, + GetPortfolioMarginAssetLeverageResponse, + GetPortfolioMarginProAccountInfoResponse, + GetPortfolioMarginProBankruptcyLoanAmountResponse, + GetPortfolioMarginProCollateralRateResponse, + GetPortfolioMarginProInterestHistoryParams, + GetPortfolioMarginProInterestHistoryResponse, + GetRateHistory, + GetRateHistoryParams, + GetRwusdRateHistoryParams, + GetRwusdRedemptionHistoryParams, + GetRwusdRewardsHistoryParams, + GetRwusdSubscriptionHistoryParams, + GetSmallLiabilityExchangeHistoryParams, + GetSoftStakingProductListParams, + GetSoftStakingProductListResponse, + GetSoftStakingRewardsHistoryParams, + GetSoftStakingRewardsHistoryResponse, + GetSolStakingHistoryReq, + GetSourceAssetListParams, + GetSourceAssetListResponse, + GetSpotAlgoHistoricalOrdersParams, + GetSpotAlgoSubOrdersParams, + GetSpotAlgoSubOrdersResponse, + GetSpotRebateHistoryRecordsParams, + GetSpotRebateHistoryRecordsResponse, + GetStatisticListParams, + GetStatisticListResponse, + GetSubAccountDepositHistoryParams, + GetSubscriptionTransactionHistoryParams, + GetTargetAssetListParams, + GetTargetAssetListResponse, + GetTargetAssetROIParams, + GetTravelRuleDepositHistoryParams, + GetTravelRuleRegionListParams, + GetTravelRuleWithdrawHistoryParams, + GetTravelRuleWithdrawHistoryV2Params, + GetUniversalTransferBrokerParams, + GetVipLoanFixedRateMarketParams, + GetVipLoanOngoingOrdersParams, + GetVipLoanRepaymentHistoryParams, + GetWbethRewardsHistoryResponse, + GetWrapHistoryParams, + HistoricalAlgoOrder, + HistoricalBlockTradesParams, + HistoricalDataLink, + HistoricalSpotAlgoOrder, + IndexLinkedPlanRedemptionRecord, + InstitutionalLoanBorrowParams, + InstitutionalLoanBorrowResponse, + InstitutionalLoanInterestHistoryResponse, + InstitutionalLoanMaxBorrowableResponse, + InstitutionalLoanRepayParams, + InstitutionalLoanRepayResponse, + InstitutionalLoanRiskUnitDetails, + InstitutionalLoanRiskUnitTransferParams, + IsolatedMarginAccountInfo, + IsolatedMarginAccountTransferParams, + IsolatedMarginFeeData, + IsolatedMarginSymbol, + IsolatedMarginTierData, + LeftDailyPurchaseQuotaFlexibleProductResponse, + LiabilityCoinLeverageBracket, + LoanableAssetData, + LoanBorrowHistory, + LoanLTVAdjustmentHistory, + LoanOngoingOrder, + LoanRepaymentHistory, + LockedRedemptionRecord, + LockedSubscriptionPreview, + LockedSubscriptionRecord, + ManagedSubAccountDepositAddress, + ManagedSubAccountDepositAddressParams, + ManagedSubAccountFuturesAssetsResponse, + ManagedSubAccountListParams, + ManagedSubAccountMarginAssetsResponse, + ManagedSubAccountSnapshot, + ManagedSubAccountSnapshotParams, + ManagedSubAccountTransferLogParams, + ManagedSubAccountTransferTTLogParams, + ManagerSubTransferHistoryVos, + ManagerSubUserInfoVo, + ManualLiquidationParams, + ManualLiquidationResponse, + MarginAccountLoanParams, + MarginAccountRecord, + MarginAvailableInventoryResponse, + MarginCapitalFlow, + MarginDelistSchedule, + MarginInterestHistory, + MarginInterestRateHistory, + MarginInterestRebateBalanceRecordsResponse, + MarginInterestRebateBalanceResponse, + MarginLiquidationLoan, + MarginLiquidationLoanRepayHistoryResponse, + MarginLiquidationLoanRepayResponse, + MarginOrderCountUsageResponse, + MarginOTOCOOrder, + MarginOTOOrder, + MarginTransactionResponse, + NewFutureAccountTransferParams, + NewOrderListOPOCOParams, + NewOrderListOPOCOResponse, + NewOrderListOPOParams, + NewOrderListOPOResponse, + NewOrderListOTOCOParams, + NewOrderListOTOCOResponse, + NewOrderListOTOParams, + NewOrderListOTOResponse, + NewSpotOrderParams, + NewSpotSOROrderParams, + NextHourlyInterestRate, + NftAsset, + NftDeposit, + NftTransaction, + NftWithdraw, + OnchainYieldsAccountResponse, + OnchainYieldsLockedPersonalLeftQuotaParams, + OnchainYieldsLockedPersonalLeftQuotaResponse, + OnchainYieldsLockedPositionParams, + OnchainYieldsLockedPositionResponse, + OnchainYieldsLockedProductListParams, + OnchainYieldsLockedProductListResponse, + OnchainYieldsLockedRedeemParams, + OnchainYieldsLockedRedeemResponse, + OnchainYieldsLockedRedemptionRecordParams, + OnchainYieldsLockedRedemptionRecordResponse, + OnchainYieldsLockedRewardsHistoryParams, + OnchainYieldsLockedRewardsHistoryResponse, + OnchainYieldsLockedSetAutoSubscribeParams, + OnchainYieldsLockedSetAutoSubscribeResponse, + OnchainYieldsLockedSetRedeemOptionParams, + OnchainYieldsLockedSetRedeemOptionResponse, + OnchainYieldsLockedSubscribeParams, + OnchainYieldsLockedSubscribeResponse, + OnchainYieldsLockedSubscriptionPreviewParams, + OnchainYieldsLockedSubscriptionPreviewResponse, + OnchainYieldsLockedSubscriptionRecordParams, + OnchainYieldsLockedSubscriptionRecordResponse, + OrderBookResponse, + OrderList, + OrderListResponse, + OrderRateLimitUsage, + OrderResponseTypeFor, + PMProBankruptcyLoanRepaymentHistory, + PMProMintBFUSDParams, + PMProMintBFUSDResponse, + PMProRedeemBFUSDResponse, + PortfolioDeltaModeStatus, + PortfolioMarginMarginCallLevelDeleteResponse, + PortfolioMarginMarginCallLevelGetResponse, + PortfolioMarginMarginCallLevelResponse, + PortfolioMarginProAccountBalance, + PortfolioMarginProSpanAccountInfo, + PreventedMatch, + PreventedMatchesParams, + PurchaseFlexibleProductResponse, + PurchaseRecordParams, + QueryBrokerFuturesCommissionRebateParams, + QueryBrokerSpotCommissionRebateParams, + QueryCrossMarginAccountDetailsParams, + QueryCrossMarginFeeDataParams, + QueryCrossMarginPairResponse, + QueryIsolatedMarginTierDataParams, + QueryMarginAccountAllOCOParams, + QueryMarginAccountTradeListParams, + QueryMarginAssetResponse, + QueryMarginInterestRateHistoryParams, + QueryMarginPriceIndexResponse, + QueryMarginRecordParams, + QueryMaxBorrowResponse, + QueryMaxTransferOutAmountResponse, + QuerySubAccountCoinFuturesCommissionParams, + QuerySubAccountFuturesAssetInfoParams, + QuerySubAccountFuturesCommissionParams, + QuerySubAccountSpotMarginAssetInfoParams, + RawAccountTrade, + RawTrade, + RedeemBlvtParams, + RedeemBlvtResponse, + RedeemEthParams, + RedeemEthResponse, + RedeemGiftCardParams, + RedeemSolResponse, + RemoveBSwapLiquidityParams, + RepayCryptoFlexibleLoanParams, + RepayCryptoFlexibleLoanResponse, + RepayCryptoLoanFlexibleWithCollateralParams, + RepayCryptoLoanFlexibleWithCollateralResponse, + RepayCryptoLoanParams, + RepayCryptoLoanResponse, + RepayMarginLiquidationLoanParams, + ReplaceSpotOrderParams, + ReplaceSpotOrderResultSuccess, + RollingWindowTickerParams, + RwusdAccountResponse, + RwusdQuotaResponse, + RwusdRateHistoryRow, + RwusdRedeemParams, + RwusdRedeemResponse, + RwusdRedemptionHistoryRow, + RwusdRewardsHistoryRow, + RwusdSubscribeParams, + RwusdSubscribeResponse, + RwusdSubscriptionHistoryRow, + SetAutoSubscribeParams, + SetPortfolioMarginMarginCallLevelParams, + SetSoftStakingParams, + SetSoftStakingResponse, + SimpleEarnAccountResponse, + SimpleEarnFlexibleProduct, + SimpleEarnFlexibleProductPositionParams, + SimpleEarnLockedProduct, + SimpleEarnLockedProductPosition, + SimpleEarnLockedProductPositionParams, + SimpleEarnProductListParams, + SimpleEarnRedeemFlexibleProductParams, + SimpleEarnRedeemResponse, + SimpleEarnSubscribeFlexibleProductResponse, + SimpleEarnSubscribeLockedProductResponse, + SimpleEarnSubscribeProductParams, + SmallLiabilityExchangeCoin, + SmallLiabilityExchangeHistory, + SolBoostRewardsHistoryRecord, + SolBoostRewardsHistoryReq, + SolRedemptionHistoryRecord, + SolStakingAccount, + SolStakingHistoryRecord, + SolStakingQuota, + SOROrderResponseFull, + SORTestOrderResponse, + SpecialLowLatencyKeyInfo, + SpecialLowLatencyKeyResponse, + SpotAlgoOrder, + SpotAmendKeepPriorityResult, + SpotAssetTag, + SpotAssetTagsParams, + SpotExecutionRulesParams, + SpotExecutionRulesResponse, + SpotOrder, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, + StakingBasicParams, + StakingHistory, + StakingHistoryParams, + StakingPersonalLeftQuota, + StakingProduct, + StakingProductPosition, + StakingProductType, + SubAccountAddOrDeleteIPList, + SubAccountAssetDetails, + SubAccountAssets, + SubAccountAssetsParams, + SubaccountBalances, + SubAccountBrokerMarginAsset, + SubaccountBrokerSpotAsset, + SubAccountCOINMDetail, + SubAccountCOINMPositionRisk, + SubAccountCOINMSummary, + SubAccountDeposit, + SubAccountDepositAddress, + SubAccountDepositAddressParams, + SubAccountDepositHistoryList, + SubAccountDepositHistoryParams, + SubAccountEnableFutures, + SubAccountEnableLeverageToken, + SubAccountEnableMargin, + SubAccountEnableOrDisableIPRestriction, + SubAccountFuturesAccountDetail, + SubAccountFuturesAccountSummary, + SubAccountFuturesAssetTransfer, + SubAccountFuturesAssetTransferHistory, + SubAccountFuturesAssetTransferHistoryParams, + SubAccountFuturesAssetTransferParams, + SubAccountListParams, + SubAccountListResponse, + SubAccountMarginAccountDetail, + SubAccountMovePosition, + SubAccountMovePositionHistory, + SubAccountMovePositionHistoryParams, + SubAccountMovePositionParams, + SubAccountsMarginAccountSummary, + SubAccountSpotAssetsSummary, + SubAccountSpotAssetsSummaryParams, + SubAccountSpotAssetTransferHistory, + SubAccountSpotAssetTransferHistoryParams, + SubAccountStatus, + SubAccountSummaryOnFuturesAccountV2Params, + SubAccountTransactionStatistics, + SubAccountTransfer, + SubAccountTransferHistory, + SubAccountTransferHistoryParams, + SubAccountTransferParams, + SubAccountTransferToMasterParams, + SubAccountTransferToSameMasterParams, + SubAccountUniversalTransfer, + SubAccountUniversalTransferHistoryParams, + SubAccountUniversalTransferHistoryResponse, + SubAccountUniversalTransferParams, + SubAccountUSDMDetail, + SubAccountUSDMPositionRisk, + SubAccountUSDMSummary, + SubmitConvertLimitOrderParams, + SubmitDepositCreditParams, + SubmitDepositCreditResponse, + SubmitHashrateResaleParams, + SubmitIndexLinkedPlanRedemptionParams, + SubmitMarginOTOCOOrderParams, + SubmitMarginOTOOrderParams, + SubmitOneTimeTransactionParams, + SubmitOneTimeTransactionResponse, + SubmitSpotTwapNewOrderParams, + SubmitSpotTwapNewOrderResponse, + SubmitTravelRuleDepositQuestionnaireParams, + SubmitTravelRuleDepositQuestionnaireResponse, + SubmitTwapNewOrderParams, + SubmitTwapNewOrderResponse, + SubmitVpNewOrderParams, + SubmitVpNewOrderResponse, + SubscribeBlvtParams, + SubscribeBlvtResponse, + SubscribeDualInvestmentProductParams, + SubscribeDualInvestmentProductResponse, + SubscribeEthStakingV2Response, + SubscribeSolStakingResponse, + SwitchPortfolioDeltaModeParams, + SymbolOrderBookTicker, + SymbolTradeFee, + SystemStatusResponse, + TargetAssetROI, + Ticker24hrResponse, + ToggleBNBBurnParams, + TradingDayTickerArray, + TradingDayTickerFull, + TradingDayTickerMini, + TradingDayTickerParams, + TradingDayTickerSingle, + TransferBrokerSubAccount, + TransferBrokerSubAccountParams, + TravelRuleCountryListResponse, + TravelRuleDepositHistoryRecord, + TravelRuleRegionListResponse, + TravelRuleWithdrawHistoryRecord, + UniversalTransferBrokerParams, + UniversalTransferHistoryParams, + UniversalTransferParams, + UpdateIpRestrictionForSubApiKey, + UsdtMarginedFuturesResponse, + UserAsset, + VASPInfo, + VipCollateralAccount, + VipLoanAccruedInterestParams, + VipLoanAccruedInterestRecord, + VipLoanBorrowParams, + VipLoanBorrowResponse, + VipLoanFixedRateBorrowParams, + VipLoanFixedRateBorrowResponse, + VipLoanFixedRateMarketRecord, + VipLoanInterestRateHistoryParams, + VipLoanInterestRateRecord, + VipLoanRenewParams, + VipLoanRenewResponse, + VipLoanRepaymentHistory, + VipLoanRepayParams, + VipLoanRepayResponse, + VipOngoingOrder, + VirtualSubAccount, + WalletBalance, + WithdrawAddress, + WithdrawAssetsFromManagedSubAccountParams, + WithdrawFiatParams, + WithdrawHistory, + WithdrawHistoryParams, + WithdrawParams, + WithdrawTravelRuleParams, + WrapBethResponse, + WrapHistory, +} from './types/spot'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, + serialiseParams, +} from './util/requestUtils'; ⋮---- -/** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. - */ -subAccountEnableMargin(email: string): Promise +export class MainClient extends BaseRestClient ⋮---- -enableOptionsForSubAccount(params: { - email: string; -}): Promise +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) ⋮---- /** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. + * 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. */ -subAccountEnableLeverageToken( - params: SubAccountEnableLeverageToken, -): Promise -⋮---- -getSubAccountStatusOnMarginOrFutures(params?: { - email?: string; -}): Promise -⋮---- -getSubAccountFuturesPositionRisk( - email: string, -): Promise -⋮---- -getSubAccountFuturesPositionRiskV2( - params: BasicFuturesSubAccountParams, -): Promise -⋮---- -getSubAccountTransactionStatistics(params: { - email: string; -}): Promise -⋮---- -/** - * - * SUB ACCOUNT Endpoints - API management - * - **/ -⋮---- -getSubAccountIPRestriction( - params: BasicSubAccount, -): Promise -⋮---- -subAccountDeleteIPList( - params: SubAccountAddOrDeleteIPList, -): Promise -⋮---- -subAccountAddIPRestriction( - params: AddIpRestriction, -): Promise -⋮---- -/** - * @deprecated - * Use subAccountAddIPRestriction instead - **/ -subAccountAddIPList( - params: SubAccountEnableOrDisableIPRestriction, -): Promise -⋮---- -/** - * @deprecated - * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList - **/ -subAccountEnableOrDisableIPRestriction( - params: EnableOrDisableIPRestrictionForSubAccountParams, -): Promise -⋮---- -/** - * - * SUB ACCOUNT Endpoints - Asset management - * - **/ -⋮---- -subAccountFuturesTransfer( - params: SubAccountTransferParams, -): Promise -⋮---- -getSubAccountFuturesAccountDetail( - email: string, -): Promise -⋮---- -getSubAccountDetailOnFuturesAccountV2( - params: BasicFuturesSubAccountParams, -): Promise -⋮---- -getSubAccountDetailOnMarginAccount( - email: string, -): Promise -⋮---- -getSubAccountDepositAddress( - params: SubAccountDepositAddressParams, -): Promise -⋮---- -getSubAccountDepositHistory( - params: SubAccountDepositHistoryParams, -): Promise +async fetchLatencySummary(): Promise ⋮---- -getSubAccountFuturesAccountSummary(): Promise +// Adjust server time by adding estimated one-way latency ⋮---- -getSubAccountSummaryOnFuturesAccountV2( - params: SubAccountSummaryOnFuturesAccountV2Params, -): Promise +// Calculate time difference between adjusted server time and local time ⋮---- -getSubAccountsSummaryOfMarginAccount(): Promise +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise ⋮---- -subAccountMarginTransfer( - params: SubAccountTransferParams, -): Promise +/** + * + * SPOT TRADING Endpoints - General endpoints + * + **/ ⋮---- -getSubAccountAssets( - params: SubAccountAssetsParams, -): Promise +testConnectivity(): Promise ⋮---- -getSubAccountAssetsMaster(params: +getExchangeInfo(params?: ExchangeInfoParams): Promise ⋮---- -getSubAccountFuturesAssetTransferHistory( - params: SubAccountFuturesAssetTransferHistoryParams, -): Promise +/** + * + * SPOT TRADING Endpoints - Market endpoints + * + **/ ⋮---- -getSubAccountSpotAssetTransferHistory( - params?: SubAccountSpotAssetTransferHistoryParams, -): Promise +getOrderBook(params: OrderBookParams): Promise ⋮---- -getSubAccountSpotAssetsSummary( - params?: SubAccountSpotAssetsSummaryParams, -): Promise +getRecentTrades(params: RecentTradesParams): Promise ⋮---- -getSubAccountUniversalTransferHistory( - params?: SubAccountUniversalTransferHistoryParams, -): Promise +getHistoricalTrades(params: HistoricalTradesParams): Promise ⋮---- -subAccountFuturesAssetTransfer( - params: SubAccountFuturesAssetTransferParams, -): Promise +getHistoricalBlockTrades( + params: HistoricalBlockTradesParams, +): Promise ⋮---- -subAccountTransferHistory( - params?: SubAccountTransferHistoryParams, -): Promise +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise ⋮---- -subAccountTransferToMaster( - params: SubAccountTransferToMasterParams, -): Promise +getKlines(params: KlinesParams): Promise ⋮---- -subAccountTransferToSameMaster( - params: SubAccountTransferToSameMasterParams, -): Promise +getUIKlines(params: KlinesParams): Promise ⋮---- -subAccountUniversalTransfer( - params: SubAccountUniversalTransferParams, -): Promise +getAvgPrice(params: ⋮---- -subAccountMovePosition( - params: SubAccountMovePositionParams, -): Promise< +getExecutionRules( + params?: SpotExecutionRulesParams, +): Promise ⋮---- -getSubAccountFuturesPositionMoveHistory( - params: SubAccountMovePositionHistoryParams, -): Promise< +getReferencePrice(params: { + symbol: string; +}): Promise ⋮---- -/** - * - * SUB ACCOUNT Endpoints - Managed Sub Account - * - **/ +getReferencePriceCalculation(params: { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +}): Promise ⋮---- -depositAssetsIntoManagedSubAccount( - params: SubAccountTransferToSameMasterParams, -): Promise +get24hrChangeStatistics(params?: { + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; ⋮---- -getManagedSubAccountDepositAddress( - params: ManagedSubAccountDepositAddressParams, -): Promise +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL ⋮---- -withdrawAssetsFromManagedSubAccount( - params: WithdrawAssetsFromManagedSubAccountParams, -): Promise +get24hrChangeStatistics(params: { + symbol: string; // use for single symbol + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; ⋮---- -getManagedSubAccountTransfersParent( - params: ManagedSubAccountTransferLogParams, -): Promise< +symbol: string; // use for single symbol +type?: 'FULL' | 'MINI'; // default is FULL ⋮---- -getManagedSubAccountTransferLog( - params: ManagedSubAccountTransferTTLogParams, -): Promise< +get24hrChangeStatistics(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; +}): Promise ⋮---- -getManagedSubAccountTransfersInvestor( - params: ManagedSubAccountTransferLogParams, -): Promise< +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL ⋮---- -getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< +getTradingDayTicker( + params: TradingDayTickerParams, +): Promise ⋮---- -getManagedSubAccountSnapshot( - params: ManagedSubAccountSnapshotParams, -): Promise +getSymbolPriceTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; +}): Promise ⋮---- -getManagedSubAccountAssetDetails( - email: string, -): Promise +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols ⋮---- -getManagedSubAccountMarginAssets(params: { - email: string; - accountType?: string; -}): Promise +getSymbolOrderBookTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; +}): Promise ⋮---- -getManagedSubAccountFuturesAssets(params: { - email: string; - accountType?: string; -}): Promise +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +⋮---- +getRollingWindowTicker( + params: RollingWindowTickerParams, +): Promise ⋮---- /** * - * AUTO INVEST Endpoints - Market data + * SPOT TRADING Endpoints - Trading endpoints * **/ ⋮---- -getAutoInvestAssets(): Promise< -⋮---- -getAutoInvestSourceAssets( - params: GetSourceAssetListParams, -): Promise +submitNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise> ⋮---- -getAutoInvestTargetAssets( - params: GetTargetAssetListParams, -): Promise +testNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise ⋮---- -getAutoInvestTargetAssetsROI( - params: GetTargetAssetROIParams, -): Promise +getOrder(params: GetOrderParams): Promise ⋮---- -getAutoInvestIndex(params: { - indexId: number; -}): Promise +cancelOrder(params: CancelOrderParams): Promise ⋮---- -getAutoInvestPlans(params: { - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; -}): Promise +cancelAllSymbolOrders(params: { + symbol: string; +}): Promise ⋮---- -/** - * - * AUTO INVEST Endpoints - Trade - * - **/ +replaceOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >( + params: ReplaceSpotOrderParams, +): Promise> ⋮---- /** - * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction - * - * @param params - * @returns + * 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 */ -submitAutoInvestOneTimeTransaction( - params: SubmitOneTimeTransactionParams, -): Promise +amendOrderKeepPriority( + params: AmendKeepPriorityParams, +): Promise ⋮---- -updateAutoInvestPlanStatus( - params: ChangePlanStatusParams, -): Promise +getOpenOrders(params?: ⋮---- -updateAutoInvestmentPlan( - params: EditInvestmentPlanParams, -): Promise +getAllOrders(params: GetAllOrdersParams): Promise ⋮---- -submitAutoInvestRedemption( - params: SubmitIndexLinkedPlanRedemptionParams, -): Promise< +/** + * @deprecated + */ +submitNewOCO(params: NewOCOParams): Promise ⋮---- -getAutoInvestSubscriptionTransactions( - params: GetSubscriptionTransactionHistoryParams, -): Promise +submitNewOrderList( + params: NewOrderListParams, +): Promise> ⋮---- -getOneTimeTransactionStatus( - params: GetOneTimeTransactionStatusParams, -): Promise +submitNewOrderListOTO( + params: NewOrderListOTOParams, +): Promise ⋮---- -submitAutoInvestmentPlan( - params: CreateInvestmentPlanParams, -): Promise +submitNewOrderListOTOCO( + params: NewOrderListOTOCOParams, +): Promise ⋮---- -getAutoInvestRedemptionHistory( - params: GetIndexLinkedPlanRedemptionHistoryParams, -): Promise +submitNewOrderListOPO( + params: NewOrderListOPOParams, +): Promise ⋮---- -getAutoInvestPlan(params: GetPlanDetailsParams): Promise +submitNewOrderListOPOCO( + params: NewOrderListOPOCOParams, +): Promise ⋮---- -getAutoInvestUserIndex(params: { - indexId: number; -}): Promise +cancelOCO(params: CancelOCOParams): Promise ⋮---- -getAutoInvestRebalanceHistory( - params: GetIndexLinkedPlanRebalanceHistoryParams, -): Promise +getOCO(params?: GetOCOParams): Promise +⋮---- +getAllOCO(params?: BasicFromPaginatedParams): Promise ⋮---- /** - * - * CONVERT Endpoints - Market Data - * - **/ + * Query open OCO + */ +getAllOpenOCO(): Promise ⋮---- -getConvertPairs(params: GetAllConvertPairsParams): Promise +/** + * Places an order using smart order routing (SOR). + */ +submitNewSOROrder( + params: NewSpotSOROrderParams, +): Promise ⋮---- -getConvertAssetInfo(): 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 ⋮---- /** * - * CONVERT Endpoints - Trade + * SPOT TRADING Endpoints - Account endpoints * **/ ⋮---- -convertQuoteRequest(params: ConvertQuoteRequestParams): Promise -⋮---- -acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise +/** + * Get current account information + */ +getAccountInformation(params?: { + omitZeroBalances?: boolean; +}): Promise ⋮---- -getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise +getAccountTradeList( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, +): Promise ⋮---- -getOrderStatus(params: GetOrderStatusParams): Promise +getOrderRateLimit(): Promise ⋮---- -submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise +getPreventedMatches( + params: PreventedMatchesParams, +): Promise ⋮---- -cancelConvertLimitOrder(params: +getAllocations(params: AllocationsParams): Promise ⋮---- -getConvertLimitOpenOrders(): Promise< +getCommissionRates(params: ⋮---- /** * - * STAKING Endpoints - ETH Staking - Account + * MARGIN TRADING Endpoints - Market Data endpoints * **/ ⋮---- -/** - * @deprecated use getEthStakingAccountV2 instead - **/ -getEthStakingAccount(): Promise +getCrossMarginCollateralRatio(): Promise< + { + collaterals: Collateral[]; + assetNames: string[]; + }[] + > { + return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); ⋮---- -getEthStakingAccountV2(): Promise +getAllCrossMarginPairs(): Promise ⋮---- -getEthStakingQuota(): 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 ⋮---- /** * - * STAKING Endpoints - ETH Staking- Staking + * MARGIN TRADING Endpoints - Borrow and Repay endpoints * **/ ⋮---- -/** - * @deprecated use subscribeEthStakingV2 instead - **/ -subscribeEthStakingV1(params: +getNextHourlyInterestRate( + params: GetNextHourlyInterestRateParams, +): Promise ⋮---- -subscribeEthStakingV2(params: { - amount: number; -}): Promise +getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< ⋮---- -redeemEth(params: RedeemEthParams): Promise +submitMarginAccountBorrowRepay( + params: MarginAccountLoanParams, +): Promise ⋮---- -wrapBeth(params: +getMarginAccountBorrowRepayRecords( + params: GetMarginAccountBorrowRepayRecordsParams, +): Promise< +⋮---- +getMarginInterestRateHistory( + params: QueryMarginInterestRateHistoryParams, +): Promise +⋮---- +queryMaxBorrow( + params: BasicMarginAssetParams, +): Promise ⋮---- /** * - * STAKING Endpoints - ETH Staking - History + * MARGIN TRADING Endpoints - Trade endpoints * **/ ⋮---- -getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< +getMarginForceLiquidationRecord( + params: GetForceLiquidationRecordParams, +): Promise< ⋮---- -getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< +getSmallLiabilityExchangeCoins(): Promise ⋮---- -getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< +getSmallLiabilityExchangeHistory( + params: GetSmallLiabilityExchangeHistoryParams, +): Promise< ⋮---- -getWbethRewardsHistory( - params: GetWrapHistoryParams, -): Promise +marginAccountCancelOpenOrders( + params: BasicSymbolParam, +): Promise ⋮---- -getEthRateHistory(params: GetETHRateHistoryParams): Promise< +marginAccountCancelOCO(params: CancelOCOParams): Promise ⋮---- -getBethWrapHistory(params: GetWrapHistoryParams): Promise< +marginAccountCancelOrder( + params: CancelOrderParams, +): Promise ⋮---- -getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< +marginAccountNewOCO(params: NewOCOParams): Promise ⋮---- -/** - * - * BFUSD (sapi/v1/bfusd) - * - **/ +marginAccountNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise> ⋮---- -getBfusdAccount(): Promise +getMarginOrderCountUsage( + params: GetMarginOrderCountUsageParams, +): Promise ⋮---- -getBfusdQuota(): Promise +queryMarginAccountAllOCO( + params: QueryMarginAccountAllOCOParams, +): Promise ⋮---- -subscribeBfusd( - params: BfusdSubscribeParams, -): Promise +queryMarginAccountAllOrders( + params: GetAllOrdersParams, +): Promise ⋮---- -redeemBfusd(params: BfusdRedeemParams): Promise +queryMarginAccountOCO(params: GetOCOParams): Promise ⋮---- -getBfusdSubscriptionHistory( - params: GetBfusdSubscriptionHistoryParams, -): Promise< +queryMarginAccountOpenOCO(params: { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; +}): Promise ⋮---- -getBfusdRedemptionHistory( - params: GetBfusdRedemptionHistoryParams, -): Promise< +queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise ⋮---- -getBfusdRewardsHistory( - params: GetBfusdRewardsHistoryParams, -): Promise< +queryMarginAccountOrder(params: GetOrderParams): Promise ⋮---- -getBfusdRateHistory( - params: GetBfusdRateHistoryParams, -): Promise< +queryMarginAccountTradeList( + params: QueryMarginAccountTradeListParams, +): Promise ⋮---- -/** - * - * RWUSD (sapi/v1/rwusd) - * - **/ +submitSmallLiabilityExchange(params: ⋮---- -getRwusdAccount(): Promise +submitManualLiquidation( + params: ManualLiquidationParams, +): Promise ⋮---- -getRwusdQuota(): Promise +/** + * Post a new OTO order for margin account + */ +submitMarginOTOOrder( + params: SubmitMarginOTOOrderParams, +): Promise ⋮---- -subscribeRwusd( - params: RwusdSubscribeParams, -): Promise +/** + * Submit a new OTOCO order for margin account + */ +submitMarginOTOCOOrder( + params: SubmitMarginOTOCOOrderParams, +): Promise ⋮---- -redeemRwusd(params: RwusdRedeemParams): Promise +/** + * Create a special key for low-latency trading (VIP 4+ only) + */ +createMarginSpecialLowLatencyKey( + params: CreateSpecialLowLatencyKeyParams, +): Promise ⋮---- -getRwusdSubscriptionHistory( - params: GetRwusdSubscriptionHistoryParams, -): Promise< +deleteMarginSpecialLowLatencyKey(params?: { + apiKey?: string; + apiName?: string; + symbol?: string; +}): Promise ⋮---- -getRwusdRedemptionHistory( - params: GetRwusdRedemptionHistoryParams, -): Promise< +updateMarginIPForSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; + ip: string; +}): Promise ⋮---- -getRwusdRewardsHistory( - params: GetRwusdRewardsHistoryParams, -): Promise< +/** + * Query the list of special keys for low-latency trading + */ +getMarginSpecialLowLatencyKeys(params: { + symbol?: string; +}): Promise ⋮---- -getRwusdRateHistory( - params: GetRwusdRateHistoryParams, -): Promise< +/** + * Query information for a specific special key used in low-latency trading + */ +getMarginSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; +}): Promise ⋮---- /** - * @deprecated as of 2024-01-19 + * Query the current cross-margin liquidation loan status (bankruptcy deficit). */ -getStakingProducts( - params: StakingBasicParams & { - asset?: string; - }, -): Promise +getMarginLiquidationLoan(): Promise ⋮---- /** - * @deprecated as of 2024-01-19 + * Repay an outstanding cross-margin liquidation loan from the spot wallet. */ -getStakingProductPosition( - params: StakingBasicParams & { - productId?: string; - asset?: string; - }, -): Promise +repayMarginLiquidationLoan( + params: RepayMarginLiquidationLoanParams, +): Promise ⋮---- /** - * @deprecated as of 2024-01-19 + * Query cross-margin liquidation loan repayment history. */ -getStakingHistory(params: StakingHistoryParams): Promise +getMarginLiquidationLoanRepayHistory( + params?: GetMarginLiquidationLoanRepayHistoryParams, +): Promise ⋮---- /** - * @deprecated as of 2024-01-19 + * Exit Margin Special Key mode for Cross Margin Classic accounts. */ -getPersonalLeftQuotaOfStakingProduct(params: { - product: StakingProductType; - productId: string; -}): Promise +exitMarginSpecialKeyMode(): Promise ⋮---- /** * - * STAKING Endpoints - SOL Staking- Account + * MARGIN TRADING Endpoints - Transfer endpoints * **/ ⋮---- -getSolStakingAccount(): Promise +getCrossMarginTransferHistory( + params: GetCrossMarginTransferHistoryParams, +): Promise> ⋮---- -getSolStakingQuota(): Promise +queryMaxTransferOutAmount( + params: BasicMarginAssetParams, +): Promise ⋮---- /** * - * STAKING Endpoints - SOL Staking - Staking + * MARGIN TRADING Endpoints - Account endpoints * **/ ⋮---- -subscribeSolStaking(params: { - amount: number; -}): Promise +updateCrossMarginMaxLeverage(params: ⋮---- -redeemSol(params: +disableIsolatedMarginAccount(params: ⋮---- -claimSolBoostRewards(): Promise< +enableIsolatedMarginAccount(params: ⋮---- -/** - * - * STAKING Endpoints - SOL Staking- History - * - **/ +getBNBBurn(): Promise ⋮---- -getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< +getMarginSummary(): Promise ⋮---- -getSolRedemptionHistory(params?: { - rows: SolRedemptionHistoryRecord[]; - total: number; -}): Promise +queryCrossMarginAccountDetails(): Promise ⋮---- -getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< +getCrossMarginFeeData( + params: QueryCrossMarginFeeDataParams, +): Promise ⋮---- -getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< +getIsolatedMarginAccountLimit(): Promise< ⋮---- -getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< +getIsolatedMarginAccountInfo(params?: { + symbols?: string; +}): Promise ⋮---- -getSolUnclaimedRewards(): Promise< - { - amount: string; - rewardsAsset: string; - }[] - > { - return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); +getIsolatedMarginFeeData( + params: QueryCrossMarginFeeDataParams, +): Promise ⋮---- -/** - * - * STAKING - Onchain Yields - Account - * - **/ +toggleBNBBurn(params: ToggleBNBBurnParams): Promise ⋮---- -getOnchainYieldsLockedProducts( - params?: OnchainYieldsLockedProductListParams, -): Promise +/** + * Possibly @deprecated + * Only existing in old documentation, not in new documentation + */ +getMarginCapitalFlow( + params: GetMarginCapitalFlowParams, +): Promise ⋮---- -getOnchainYieldsLockedPersonalLeftQuota( - params: OnchainYieldsLockedPersonalLeftQuotaParams, -): Promise +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryLoanRecord( + params: QueryMarginRecordParams, +): Promise< ⋮---- -getOnchainYieldsLockedPosition( - params?: OnchainYieldsLockedPositionParams, -): Promise +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryRepayRecord( + params: QueryMarginRecordParams, +): Promise< ⋮---- -getOnchainYieldsAccount(): Promise +/** + * @deprecated on 2024-01-09, use submitUniversalTransfer() instead + */ +isolatedMarginAccountTransfer( + params: IsolatedMarginAccountTransferParams, +): Promise ⋮---- /** * - * STAKING - Onchain Yields - Earn + * WALLET Endpoints - Capital endpoints * **/ ⋮---- -getOnchainYieldsLockedSubscriptionPreview( - params: OnchainYieldsLockedSubscriptionPreviewParams, -): Promise +getBalances(): Promise ⋮---- -subscribeOnchainYieldsLockedProduct( - params: OnchainYieldsLockedSubscribeParams, -): Promise +withdraw(params: WithdrawParams): Promise< ⋮---- -setOnchainYieldsLockedAutoSubscribe( - params: OnchainYieldsLockedSetAutoSubscribeParams, -): Promise +getWithdrawHistory( + params?: WithdrawHistoryParams, +): Promise ⋮---- -setOnchainYieldsLockedRedeemOption( - params: OnchainYieldsLockedSetRedeemOptionParams, -): Promise +getWithdrawAddresses(): Promise ⋮---- -redeemOnchainYieldsLockedProduct( - params: OnchainYieldsLockedRedeemParams, -): Promise +getWithdrawQuota(): Promise< ⋮---- -/** - * - * STAKING - Onchain Yields - History - * - **/ +getDepositHistory(params?: DepositHistoryParams): Promise ⋮---- -getOnchainYieldsLockedSubscriptionRecord( - params?: OnchainYieldsLockedSubscriptionRecordParams, -): Promise +getDepositAddress( + params: DepositAddressParams, +): Promise ⋮---- -getOnchainYieldsLockedRewardsHistory( - params?: OnchainYieldsLockedRewardsHistoryParams, -): Promise +getDepositAddresses( + params: DepositAddressListParams, +): Promise ⋮---- -getOnchainYieldsLockedRedemptionRecord( - params?: OnchainYieldsLockedRedemptionRecordParams, -): Promise +submitDepositCredit( + params: SubmitDepositCreditParams, +): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + */ +getAutoConvertStablecoins(): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + */ +setConvertibleCoins(params: ConvertibleCoinsParams): Promise ⋮---- /** * - * STAKING - Soft staking + * WALLET Endpoints - Asset endpoints * **/ ⋮---- -getSoftStakingProductList( - params?: GetSoftStakingProductListParams, -): Promise +getAssetDetail( + params?: Partial, +): Promise> ⋮---- -setSoftStaking( - params: SetSoftStakingParams, -): Promise +getWalletBalances(params?: { + quoteAsset?: string; +}): Promise ⋮---- -getSoftStakingRewardsHistory( - params?: GetSoftStakingRewardsHistoryParams, -): Promise +getUserAsset(params: GetAssetParams): Promise +⋮---- +getSpotAssetTags(params?: SpotAssetTagsParams): Promise +⋮---- +submitUniversalTransfer( + params: UniversalTransferParams, +): Promise< +⋮---- +getUniversalTransferHistory( + params: UniversalTransferHistoryParams, +): Promise +⋮---- +getDust(params: +⋮---- +convertDustToBnb(params: ConvertDustParams): Promise ⋮---- /** - * - * COPY TRADING Endpoints - Future copy trading - * - **/ + * Convert dust assets to a target asset (e.g. BNB, USDT). + */ +convertDustAssets(params: DustConvertParams): Promise ⋮---- -getFuturesLeadTraderStatus(): Promise +/** + * Query assets eligible for dust conversion. + */ +queryDustConvertibleAssets( + params: DustConvertibleAssetsParams, +): Promise ⋮---- -getFuturesLeadTradingSymbolWhitelist(): Promise< - GetFuturesLeadTradingSymbolWhitelistResponse[] - > { - return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); +getDustLog(params?: BasicTimeRangeParam): Promise +⋮---- +getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise +⋮---- +getTradeFee(params?: +⋮---- +getFundingAsset(params: GetAssetParams): Promise +⋮---- +getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< +⋮---- +getDelegationHistory( + params: DelegationHistoryParams, +): Promise> ⋮---- /** * - * MINING Endpoints - rest api + * 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. * **/ ⋮---- -getMiningAlgos(): Promise -⋮---- -getMiningCoins(): Promise -⋮---- -getHashrateResales( - params: GetHashrateResaleListParams, -): Promise -⋮---- -getMiners(params: GetMinerListParams): Promise -⋮---- -getMinerDetails( - params: GetMinerDetailsParams, -): 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. + */ ⋮---- -getExtraBonuses( - params: GetExtraBonusListParams, -): Promise +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +submitNewFutureAccountTransfer( + params: NewFutureAccountTransferParams, +): Promise< ⋮---- -getMiningEarnings( - params: GetEarningsListParams, -): Promise +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +getFutureAccountTransferHistory( + params: GetFutureAccountTransferHistoryParams, +): Promise> ⋮---- -cancelHashrateResaleConfig( - params: CancelHashrateResaleConfigParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise ⋮---- -getHashrateResale( - params: GetHashrateResaleDetailParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise ⋮---- -getMiningAccountEarnings( - params: GetMiningAccountEarningParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralWalletV2(): Promise ⋮---- -getMiningStatistics( - params: GetStatisticListParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getAdjustCrossCollateralLTVHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -submitHashrateResale(params: SubmitHashrateResaleParams): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralLiquidationHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -getMiningAccounts( - params: getMiningAccountsListParams, -): Promise +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralInterestHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- /** * - * ALGO TRADING Endpoints - Future algo + * WALLET Endpoints - Account endpoints * **/ ⋮---- -submitVpNewOrder( - params: SubmitVpNewOrderParams, -): Promise +getAccountInfo(): Promise ⋮---- -submitTwapNewOrder( - params: SubmitTwapNewOrderParams, -): Promise +getDailyAccountSnapshot( + params: DailyAccountSnapshotParams, +): Promise ⋮---- -cancelAlgoOrder(params: { - algoId: number; -}): Promise +disableFastWithdrawSwitch(): Promise ⋮---- -getAlgoSubOrders( - params: GetAlgoSubOrdersParams, -): Promise +enableFastWithdrawSwitch(): Promise ⋮---- -getAlgoOpenOrders(): Promise< +getAccountStatus(): Promise< ⋮---- -getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< +getApiTradingStatus(): Promise +⋮---- +getApiKeyPermissions(): Promise ⋮---- /** * - * ALGO TRADING Endpoints - Spot algo + * WALLET Endpoints - Travel Rule endpoints * **/ ⋮---- -submitSpotAlgoTwapOrder( - params: SubmitSpotTwapNewOrderParams, -): 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< ⋮---- -cancelSpotAlgoOrder(params: { - algoId: number; -}): Promise +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistory( + params?: GetTravelRuleWithdrawHistoryParams, +): Promise ⋮---- -getSpotAlgoSubOrders( - params: GetSpotAlgoSubOrdersParams, -): Promise +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistoryV2( + params?: GetTravelRuleWithdrawHistoryV2Params, +): Promise ⋮---- -getSpotAlgoOpenOrders(): 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 ⋮---- -getSpotAlgoHistoricalOrders( - params: GetSpotAlgoHistoricalOrdersParams, -): Promise< +/** + * Fetch deposit history for local entities that require travel rule + */ +getTravelRuleDepositHistory( + params?: GetTravelRuleDepositHistoryParams, +): Promise ⋮---- /** - * - * CRYPTO LOAN Endpoints - Flexible rate - Market data - * - **/ + * 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 ⋮---- -getCryptoLoanFlexibleCollateralAssets(params: { - collateralCoin?: string; -}): Promise< +getTravelRuleCountryList(): Promise ⋮---- -getCryptoLoanFlexibleAssets(params: +getTravelRuleRegionList( + params: GetTravelRuleRegionListParams, +): Promise ⋮---- /** * - * CRYPTO LOAN Endpoints - Flexible rate - Trade + * WALLET Endpoints - Other endpoints * **/ ⋮---- -borrowCryptoLoanFlexible( - params: BorrowFlexibleLoanParams, -): Promise -⋮---- -repayCryptoLoanFlexible( - params: RepayCryptoFlexibleLoanParams, -): Promise -⋮---- -repayCryptoLoanFlexibleWithCollateral( - params: RepayCryptoLoanFlexibleWithCollateralParams, -): Promise +getSystemStatus(): Promise ⋮---- -adjustCryptoLoanFlexibleLTV( - params: AdjustFlexibleCryptoLoanLTVParams, -): Promise +getDelistSchedule(): Promise ⋮---- /** * - * CRYPTO LOAN Endpoints - Flexible rate - User info + * SUB ACCOUNT Endpoints - Account management * **/ ⋮---- -getCryptoLoanFlexibleLTVAdjustmentHistory( - params: GetFlexibleLoanLTVAdjustmentHistoryParams, -): Promise< -⋮---- -getFlexibleLoanCollateralRepayRate(params: { - loanCoin: string; - collateralCoin: string; -}): Promise< -⋮---- -getLoanFlexibleBorrowHistory( - params: GetFlexibleCryptoLoanBorrowHistoryParams, -): Promise< -⋮---- -getCryptoLoanFlexibleOngoingOrders( - params: GetFlexibleLoanOngoingOrdersParams, -): Promise< +createVirtualSubAccount( + params: CreateSubAccountParams, +): Promise ⋮---- -getFlexibleLoanLiquidationHistory( - params?: GetFlexibleLoanLiquidationHistoryParams, -): Promise< +getSubAccountList( + params?: SubAccountListParams, +): 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. + */ +subAccountEnableMargin(email: string): 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. */ -getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +subAccountEnableLeverageToken( + params: SubAccountEnableLeverageToken, +): Promise +⋮---- +getSubAccountStatusOnMarginOrFutures(params?: { + email?: string; +}): Promise ⋮---- -getCryptoLoanCollateralRepayRate( - params: CheckCollateralRepayRateParams, -): Promise +getSubAccountFuturesPositionRisk( + email: string, +): Promise ⋮---- -/** - * @deprecated - */ -getCryptoLoanCollateralAssetsData( - params: GetCollateralAssetDataParams, -): Promise< +getSubAccountFuturesPositionRiskV2( + params: BasicFuturesSubAccountParams, +): Promise ⋮---- -getCryptoLoansIncomeHistory( - params: GetCryptoLoansIncomeHistoryParams, -): Promise +getSubAccountTransactionStatistics(params: { + email: string; +}): Promise ⋮---- /** * - * CRYPTO LOAN Endpoints - Stable rate - Trade + * SUB ACCOUNT Endpoints - API management * **/ ⋮---- -/** - * @deprecated - */ -borrowCryptoLoan( - params: BorrowCryptoLoanParams, -): Promise +getSubAccountIPRestriction( + params: BasicSubAccount, +): Promise ⋮---- -/** - * @deprecated - */ -repayCryptoLoan( - params: RepayCryptoLoanParams, -): Promise +subAccountDeleteIPList( + params: SubAccountAddOrDeleteIPList, +): Promise +⋮---- +subAccountAddIPRestriction( + params: AddIpRestriction, +): Promise ⋮---- /** * @deprecated - */ -adjustCryptoLoanLTV( - params: AdjustCryptoLoanLTVParams, -): Promise + * Use subAccountAddIPRestriction instead + **/ +subAccountAddIPList( + params: SubAccountEnableOrDisableIPRestriction, +): Promise ⋮---- /** * @deprecated - */ -customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< + * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList + **/ +subAccountEnableOrDisableIPRestriction( + params: EnableOrDisableIPRestrictionForSubAccountParams, +): Promise ⋮---- /** * - * CRYPTO LOAN Endpoints - Stable rate - User info + * SUB ACCOUNT Endpoints - Asset management * **/ ⋮---- -/** - * @deprecated - */ -getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< +subAccountFuturesTransfer( + params: SubAccountTransferParams, +): Promise ⋮---- -getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< +getSubAccountFuturesAccountDetail( + email: string, +): Promise ⋮---- -getCryptoLoanLTVAdjustmentHistory( - params: GetLoanLTVAdjustmentHistoryParams, -): Promise< +getSubAccountDetailOnFuturesAccountV2( + params: BasicFuturesSubAccountParams, +): Promise ⋮---- -getCryptoLoanRepaymentHistory( - params: GetLoanRepaymentHistoryParams, -): Promise +getSubAccountDetailOnMarginAccount( + email: string, +): Promise ⋮---- -/** - * - * SIMPLE EARN Endpoints - Account - * - **/ +getSubAccountDepositAddress( + params: SubAccountDepositAddressParams, +): Promise ⋮---- -getSimpleEarnAccount(): Promise +getSubAccountDepositHistory( + params: SubAccountDepositHistoryParams, +): Promise ⋮---- -getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< +getSubAccountFuturesAccountSummary(): Promise ⋮---- -getSimpleEarnLockedProductList( - params?: SimpleEarnProductListParams, -): Promise< +getSubAccountSummaryOnFuturesAccountV2( + params: SubAccountSummaryOnFuturesAccountV2Params, +): Promise ⋮---- -getFlexibleProductPosition( - params?: SimpleEarnFlexibleProductPositionParams, -): Promise< +getSubAccountsSummaryOfMarginAccount(): Promise ⋮---- -getLockedProductPosition( - params?: SimpleEarnLockedProductPositionParams, -): Promise< +subAccountMarginTransfer( + params: SubAccountTransferParams, +): Promise ⋮---- -getFlexiblePersonalLeftQuota(params: +getSubAccountAssets( + params: SubAccountAssetsParams, +): Promise ⋮---- -getLockedPersonalLeftQuota(params: +getSubAccountAssetsMaster(params: ⋮---- -/** - * - * SIMPLE EARN Endpoints - Earn - * - **/ +getSubAccountFuturesAssetTransferHistory( + params: SubAccountFuturesAssetTransferHistoryParams, +): Promise ⋮---- -purchaseFlexibleProduct( - params: SimpleEarnSubscribeProductParams, -): Promise +getSubAccountSpotAssetTransferHistory( + params?: SubAccountSpotAssetTransferHistoryParams, +): Promise ⋮---- -subscribeSimpleEarnLockedProduct( - params: SimpleEarnSubscribeProductParams, -): Promise +getSubAccountSpotAssetsSummary( + params?: SubAccountSpotAssetsSummaryParams, +): Promise ⋮---- -redeemFlexibleProduct( - params: SimpleEarnRedeemFlexibleProductParams, -): Promise +getSubAccountUniversalTransferHistory( + params?: SubAccountUniversalTransferHistoryParams, +): Promise ⋮---- -redeemLockedProduct(params: { - positionId: string; -}): Promise +subAccountFuturesAssetTransfer( + params: SubAccountFuturesAssetTransferParams, +): Promise ⋮---- -setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< +subAccountTransferHistory( + params?: SubAccountTransferHistoryParams, +): Promise ⋮---- -setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< +subAccountTransferToMaster( + params: SubAccountTransferToMasterParams, +): Promise ⋮---- -getFlexibleSubscriptionPreview( - params: GetFlexibleSubscriptionPreviewParams, -): Promise +subAccountTransferToSameMaster( + params: SubAccountTransferToSameMasterParams, +): Promise ⋮---- -getLockedSubscriptionPreview( - params: GetLockedSubscriptionPreviewParams, -): Promise +subAccountUniversalTransfer( + params: SubAccountUniversalTransferParams, +): Promise ⋮---- -setLockedProductRedeemOption(params: { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; -}): Promise< +subAccountMovePosition( + params: SubAccountMovePositionParams, +): Promise< +⋮---- +getSubAccountFuturesPositionMoveHistory( + params: SubAccountMovePositionHistoryParams, +): Promise< ⋮---- /** * - * SIMPLE EARN Endpoints - History + * SUB ACCOUNT Endpoints - Managed Sub Account * **/ ⋮---- -getFlexibleSubscriptionRecord( - params: GetFlexibleSubscriptionRecordParams, +depositAssetsIntoManagedSubAccount( + params: SubAccountTransferToSameMasterParams, +): Promise +⋮---- +getManagedSubAccountDepositAddress( + params: ManagedSubAccountDepositAddressParams, +): Promise +⋮---- +withdrawAssetsFromManagedSubAccount( + params: WithdrawAssetsFromManagedSubAccountParams, +): Promise +⋮---- +getManagedSubAccountTransfersParent( + params: ManagedSubAccountTransferLogParams, ): Promise< ⋮---- -getLockedSubscriptionRecord( - params: GetLockedSubscriptionRecordParams, +getManagedSubAccountTransferLog( + params: ManagedSubAccountTransferTTLogParams, ): Promise< ⋮---- -getFlexibleRedemptionRecord( - params: GetFlexibleRedemptionRecordParams, +getManagedSubAccountTransfersInvestor( + params: ManagedSubAccountTransferLogParams, ): Promise< ⋮---- -getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< +getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< ⋮---- -getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< +getManagedSubAccountSnapshot( + params: ManagedSubAccountSnapshotParams, +): Promise ⋮---- -getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< +getManagedSubAccountAssetDetails( + email: string, +): Promise ⋮---- -getCollateralRecord(params: GetCollateralRecordParams): Promise< +getManagedSubAccountMarginAssets(params: { + email: string; + accountType?: string; +}): Promise ⋮---- -getRateHistory(params: GetRateHistoryParams): Promise< +getManagedSubAccountFuturesAssets(params: { + email: string; + accountType?: string; +}): Promise ⋮---- /** * - * VIP LOAN Endpoints - Market Data + * AUTO INVEST Endpoints - Market data * **/ ⋮---- -getVipBorrowInterestRate(params: { - loanCoin: string; -}): Promise +getAutoInvestAssets(): Promise< ⋮---- -getVipLoanInterestRateHistory( - params: VipLoanInterestRateHistoryParams, -): Promise< +getAutoInvestSourceAssets( + params: GetSourceAssetListParams, +): Promise ⋮---- -getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +getAutoInvestTargetAssets( + params: GetTargetAssetListParams, +): Promise +⋮---- +getAutoInvestTargetAssetsROI( + params: GetTargetAssetROIParams, +): Promise +⋮---- +getAutoInvestIndex(params: { + indexId: number; +}): Promise ⋮---- -getVipCollateralAssets(params: +getAutoInvestPlans(params: { + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; +}): Promise ⋮---- /** * - * VIP LOAN Endpoints - User Info + * AUTO INVEST Endpoints - Trade * **/ ⋮---- -getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< -⋮---- -getVipLoanRepaymentHistory( - params: GetVipLoanRepaymentHistoryParams, -): Promise< +/** + * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction + * + * @param params + * @returns + */ +submitAutoInvestOneTimeTransaction( + params: SubmitOneTimeTransactionParams, +): Promise ⋮---- -checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< +updateAutoInvestPlanStatus( + params: ChangePlanStatusParams, +): Promise ⋮---- -getVipApplicationStatus(params: GetApplicationStatusParams): Promise< +updateAutoInvestmentPlan( + params: EditInvestmentPlanParams, +): Promise ⋮---- -/** - * - * VIP LOAN Endpoints - Trade - * - **/ +submitAutoInvestRedemption( + params: SubmitIndexLinkedPlanRedemptionParams, +): Promise< ⋮---- -renewVipLoan(params: VipLoanRenewParams): Promise +getAutoInvestSubscriptionTransactions( + params: GetSubscriptionTransactionHistoryParams, +): Promise ⋮---- -repayVipLoan(params: VipLoanRepayParams): Promise +getOneTimeTransactionStatus( + params: GetOneTimeTransactionStatusParams, +): Promise ⋮---- -borrowVipLoan(params: VipLoanBorrowParams): Promise +submitAutoInvestmentPlan( + params: CreateInvestmentPlanParams, +): Promise ⋮---- -getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise< +getAutoInvestRedemptionHistory( + params: GetIndexLinkedPlanRedemptionHistoryParams, +): Promise ⋮---- -borrowVipLoanFixedRate( - params: VipLoanFixedRateBorrowParams, -): Promise +getAutoInvestPlan(params: GetPlanDetailsParams): Promise ⋮---- -/** - * - * DUAL INVESTMENT Endpoints - Market Data - * - **/ +getAutoInvestUserIndex(params: { + indexId: number; +}): Promise ⋮---- -getDualInvestmentProducts( - params: GetDualInvestmentProductListParams, -): Promise< +getAutoInvestRebalanceHistory( + params: GetIndexLinkedPlanRebalanceHistoryParams, +): Promise ⋮---- /** * - * DUAL INVESTMENT Endpoints - Trade + * CONVERT Endpoints - Market Data * **/ ⋮---- -subscribeDualInvestmentProduct( - params: SubscribeDualInvestmentProductParams, -): Promise -⋮---- -getDualInvestmentPositions( - params: GetDualInvestmentPositionsParams, -): Promise< -⋮---- -getDualInvestmentAccounts(): Promise -⋮---- -getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< +getConvertPairs(params: GetAllConvertPairsParams): Promise ⋮---- -updateAutoCompoundStatus( - params: ChangeAutoCompoundStatusParams, -): Promise +getConvertAssetInfo(): Promise ⋮---- /** * - * GIFT CARD Endpoints - Market Data + * CONVERT Endpoints - Trade * **/ ⋮---- -createGiftCard(params: CreateGiftCardParams): Promise +convertQuoteRequest(params: ConvertQuoteRequestParams): Promise ⋮---- -createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise +acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise ⋮---- -redeemGiftCard(params: RedeemGiftCardParams): Promise +getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise ⋮---- -verifyGiftCard(params: +getOrderStatus(params: GetOrderStatusParams): Promise ⋮---- -getTokenLimit(params: +submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise ⋮---- -getRsaPublicKey(): Promise +cancelConvertLimitOrder(params: +⋮---- +getConvertLimitOpenOrders(): Promise< ⋮---- /** * - * NFT Endpoints - REST api + * STAKING Endpoints - ETH Staking - Account * **/ ⋮---- -getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< -⋮---- -getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< +/** + * @deprecated use getEthStakingAccountV2 instead + **/ +getEthStakingAccount(): Promise ⋮---- -getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< +getEthStakingAccountV2(): Promise ⋮---- -getNftAsset(params: GetNftAssetParams): Promise< +getEthStakingQuota(): Promise ⋮---- /** * - * C2C Endpoints + * STAKING Endpoints - ETH Staking- Staking * **/ ⋮---- -getC2CTradeHistory( - params: GetC2CTradeHistoryParams, -): Promise -⋮---- /** - * - * FIAT Endpoints - REST api - * + * @deprecated use subscribeEthStakingV2 instead **/ +subscribeEthStakingV1(params: ⋮---- -getFiatOrderHistory( - params: GetFiatOrderHistoryParams, -): Promise -⋮---- -getFiatPaymentsHistory( - params: GetFiatOrderHistoryParams, -): Promise -⋮---- -fiatWithdraw(params: WithdrawFiatParams): Promise< +subscribeEthStakingV2(params: { + amount: number; +}): Promise ⋮---- -fiatDeposit(params: FiatDepositParams): Promise +redeemEth(params: RedeemEthParams): Promise ⋮---- -getFiatOrderDetail( - params: GetFiatOrderDetailParams, -): Promise +wrapBeth(params: ⋮---- /** * - * Rebate Endpoints + * STAKING Endpoints - ETH Staking - History * **/ ⋮---- -getSpotRebateHistoryRecords( - params: GetSpotRebateHistoryRecordsParams, -): Promise +getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< ⋮---- -/** - * - * DERIVATIVES - Portfolio Margin Pro - Market Data - * This is in mainclient because it shares the same base url - * - **/ +getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< ⋮---- -getPortfolioMarginIndexPrice(params?: { - asset?: string; -}): Promise +getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< ⋮---- -getPortfolioMarginAssetLeverage(): Promise< - GetPortfolioMarginAssetLeverageResponse[] - > { - return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); +getWbethRewardsHistory( + params: GetWrapHistoryParams, +): Promise ⋮---- -getPortfolioMarginProCollateralRate(): Promise< - GetPortfolioMarginProCollateralRateResponse[] - > { - return this.get('sapi/v1/portfolio/collateralRate'); +getEthRateHistory(params: GetETHRateHistoryParams): Promise< ⋮---- -getPortfolioMarginProTieredCollateralRate(): Promise +getBethWrapHistory(params: GetWrapHistoryParams): Promise< +⋮---- +getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< ⋮---- /** * - * DERIVATIVES - Portfolio Margin Pro - Account - * This is in mainclient because it shares the same base url + * BFUSD (sapi/v1/bfusd) * **/ ⋮---- -getPortfolioMarginProAccountInfo(): Promise +getBfusdAccount(): Promise ⋮---- -setPortfolioMarginMarginCallLevel( - params: SetPortfolioMarginMarginCallLevelParams, -): Promise +getBfusdQuota(): Promise ⋮---- -getPortfolioMarginMarginCallLevel(): Promise +subscribeBfusd( + params: BfusdSubscribeParams, +): Promise ⋮---- -deletePortfolioMarginMarginCallLevel(): Promise +redeemBfusd(params: BfusdRedeemParams): Promise ⋮---- -bnbTransfer(params: BnbTransferParams): Promise< +getBfusdSubscriptionHistory( + params: GetBfusdSubscriptionHistoryParams, +): Promise< ⋮---- -submitPortfolioMarginProFullTransfer(): Promise< +getBfusdRedemptionHistory( + params: GetBfusdRedemptionHistoryParams, +): Promise< ⋮---- -submitPortfolioMarginProSpecificTransfer(params: +getBfusdRewardsHistory( + params: GetBfusdRewardsHistoryParams, +): Promise< ⋮---- -repayPortfolioMarginProBankruptcyLoan(params: { - from?: 'SPOT' | 'MARGIN'; -}): Promise< +getBfusdRateHistory( + params: GetBfusdRateHistoryParams, +): Promise< ⋮---- -getPortfolioMarginProBankruptcyLoanAmount(): Promise +/** + * + * RWUSD (sapi/v1/rwusd) + * + **/ ⋮---- -repayFuturesNegativeBalance(): Promise< +getRwusdAccount(): Promise ⋮---- -updateAutoRepayFuturesStatus(params: +getRwusdQuota(): Promise ⋮---- -getAutoRepayFuturesStatus(): Promise< +subscribeRwusd( + params: RwusdSubscribeParams, +): Promise ⋮---- -getPortfolioMarginProInterestHistory( - params: GetPortfolioMarginProInterestHistoryParams, -): Promise +redeemRwusd(params: RwusdRedeemParams): Promise ⋮---- -getPortfolioMarginProSpanAccountInfo(): Promise +getRwusdSubscriptionHistory( + params: GetRwusdSubscriptionHistoryParams, +): Promise< ⋮---- -getPortfolioMarginProAccountBalance(params?: { - asset?: string; -}): Promise +getRwusdRedemptionHistory( + params: GetRwusdRedemptionHistoryParams, +): Promise< ⋮---- -/** - * @deprecated - * Check Simple Earn endpoints for new way of doing it - */ -mintPortfolioMarginBFUSD( - params: PMProMintBFUSDParams, -): Promise +getRwusdRewardsHistory( + params: GetRwusdRewardsHistoryParams, +): Promise< +⋮---- +getRwusdRateHistory( + params: GetRwusdRateHistoryParams, +): Promise< ⋮---- /** - * @deprecated - * Check Simple Earn endpointsfor new way of doing it + * @deprecated as of 2024-01-19 */ -redeemPortfolioMarginBFUSD(params: { - fromAsset: string; // BFUSD only - targetAsset: string; // USDT only - amount: number; -}): Promise -⋮---- -fromAsset: string; // BFUSD only -targetAsset: string; // USDT only +getStakingProducts( + params: StakingBasicParams & { + asset?: string; + }, +): Promise ⋮---- -getPortfolioMarginBankruptcyLoanRepayHistory(params?: { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -}): Promise< +/** + * @deprecated as of 2024-01-19 + */ +getStakingProductPosition( + params: StakingBasicParams & { + productId?: string; + asset?: string; + }, +): Promise ⋮---- /** - * Transfer LDUSDT as collateral for all types of Portfolio Margin account + * @deprecated as of 2024-01-19 */ -transferLDUSDTPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; - amount: number; -}): Promise< +getStakingHistory(params: StakingHistoryParams): Promise ⋮---- /** - * Get transferable earn asset balance for all types of Portfolio Margin account + * @deprecated as of 2024-01-19 */ -getTransferableEarnAssetBalanceForPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; -}): Promise< +getPersonalLeftQuotaOfStakingProduct(params: { + product: StakingProductType; + productId: string; +}): Promise ⋮---- /** * - * DERIVATIVES - Futures Data - Market - * This is in mainclient because it shares the same base url + * STAKING Endpoints - SOL Staking- Account * **/ ⋮---- -getFuturesTickLevelOrderbookDataLink( - params: GetFutureTickLevelOrderbookDataLinkParams, -): Promise< +getSolStakingAccount(): Promise +⋮---- +getSolStakingQuota(): Promise ⋮---- /** * - * BLVT Endpoints - * BLVT category is possibly @deprecated, found only in old docs + * STAKING Endpoints - SOL Staking - Staking + * **/ ⋮---- -getBlvtInfo(params?: -⋮---- -subscribeBlvt(params: SubscribeBlvtParams): Promise -⋮---- -getBlvtSubscriptionRecord( - params: GetBlvtSubscriptionRecordParams, -): Promise -⋮---- -redeemBlvt(params: RedeemBlvtParams): Promise -⋮---- -getBlvtRedemptionRecord( - params: GetBlvtRedemptionRecordParams, -): Promise +subscribeSolStaking(params: { + amount: number; +}): Promise ⋮---- -getBlvtUserLimitInfo(params: { - tokenName?: string; -}): Promise +redeemSol(params: ⋮---- -/** - * - * Pay endpoints - * Found only in old docs, possibly @deprecated - **/ -getPayTransactions(params: GetPayTradeHistoryParams): Promise +claimSolBoostRewards(): Promise< ⋮---- /** * - * INSTITUTIONAL LOAN - Account Endpoints + * STAKING Endpoints - SOL Staking- History * **/ ⋮---- -getInstLoanRiskUnit( - params?: GetInstitutionalLoanRiskUnitDetailsParams, -): Promise +getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< ⋮---- -closeInstLoanRiskUnit(): Promise +getSolRedemptionHistory(params?: { + rows: SolRedemptionHistoryRecord[]; + total: number; +}): Promise ⋮---- -addInstLoanCollateralAccount( - params: AddInstitutionalLoanCollateralAccountParams, -): Promise +getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< ⋮---- -getActiveInstLoanRiskUnits(): Promise +getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< ⋮---- -getClosedInstLoanRiskUnits( - params?: GetClosedInstitutionalLoanRiskUnitsParams, -): Promise +getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< +⋮---- +getSolUnclaimedRewards(): Promise< + { + amount: string; + rewardsAsset: string; + }[] + > { + return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); ⋮---- /** * - * INSTITUTIONAL LOAN - Trade Endpoints + * STAKING - Onchain Yields - Account * **/ ⋮---- -getInstLoanForceLiquidationRecord( - params: GetInstitutionalLoanForceLiquidationParams, -): Promise +getOnchainYieldsLockedProducts( + params?: OnchainYieldsLockedProductListParams, +): Promise +⋮---- +getOnchainYieldsLockedPersonalLeftQuota( + params: OnchainYieldsLockedPersonalLeftQuotaParams, +): Promise +⋮---- +getOnchainYieldsLockedPosition( + params?: OnchainYieldsLockedPositionParams, +): Promise +⋮---- +getOnchainYieldsAccount(): Promise +⋮---- /** * - * INSTITUTIONAL LOAN - TransferEndpoints + * STAKING - Onchain Yields - Earn * **/ ⋮---- -transferInstLoanRiskUnit( - params: InstitutionalLoanRiskUnitTransferParams, -): Promise +getOnchainYieldsLockedSubscriptionPreview( + params: OnchainYieldsLockedSubscriptionPreviewParams, +): Promise +⋮---- +subscribeOnchainYieldsLockedProduct( + params: OnchainYieldsLockedSubscribeParams, +): Promise +⋮---- +setOnchainYieldsLockedAutoSubscribe( + params: OnchainYieldsLockedSetAutoSubscribeParams, +): Promise +⋮---- +setOnchainYieldsLockedRedeemOption( + params: OnchainYieldsLockedSetRedeemOptionParams, +): Promise +⋮---- +redeemOnchainYieldsLockedProduct( + params: OnchainYieldsLockedRedeemParams, +): Promise ⋮---- /** * - * INSTITUTIONAL LOAN - Borrow/Repay Endpoints + * STAKING - Onchain Yields - History * **/ ⋮---- -getInstitutionalLoanMaxBorrowable( - params: GetInstitutionalLoanMaxBorrowableParams, -): Promise +getOnchainYieldsLockedSubscriptionRecord( + params?: OnchainYieldsLockedSubscriptionRecordParams, +): Promise ⋮---- -borrowInstitutionalLoan( - params: InstitutionalLoanBorrowParams, -): Promise +getOnchainYieldsLockedRewardsHistory( + params?: OnchainYieldsLockedRewardsHistoryParams, +): Promise ⋮---- -getInstLoanInterestHistory( - params?: GetInstitutionalLoanInterestHistoryParams, -): Promise +getOnchainYieldsLockedRedemptionRecord( + params?: OnchainYieldsLockedRedemptionRecordParams, +): Promise ⋮---- -repayInstitutionalLoan( - params: InstitutionalLoanRepayParams, -): Promise +/** + * + * STAKING - Soft staking + * + **/ ⋮---- -getInstLoanBorrowRepayRecords( - params: GetInstitutionalLoanBorrowRepayRecordsParams, -): Promise +getSoftStakingProductList( + params?: GetSoftStakingProductListParams, +): Promise ⋮---- -getMarginInterestRebateBalance(): Promise +setSoftStaking( + params: SetSoftStakingParams, +): Promise ⋮---- -getMarginInterestRebateBalanceRecords( - params?: GetMarginInterestRebateBalanceRecordsParams, -): Promise +getSoftStakingRewardsHistory( + params?: GetSoftStakingRewardsHistoryParams, +): Promise ⋮---- /** * - * ALPHA TRADING - Market Data - * https://developers.binance.com/docs/alpha - */ -⋮---- -getAlphaTokenList(): Promise + * COPY TRADING Endpoints - Future copy trading + * + **/ ⋮---- -getAlphaExchangeInfo(): Promise +getFuturesLeadTraderStatus(): Promise ⋮---- -getAlphaAggTrades(params: AlphaAggTradesParams): Promise +getFuturesLeadTradingSymbolWhitelist(): Promise< + GetFuturesLeadTradingSymbolWhitelistResponse[] + > { + return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); ⋮---- -getAlphaKlines(params: AlphaKlinesParams): Promise +/** + * + * MINING Endpoints - rest api + * + **/ ⋮---- -getAlphaTicker(params: +getMiningAlgos(): Promise ⋮---- -getAlphaFullDepth( - params: AlphaFullDepthParams, -): Promise +getMiningCoins(): Promise ⋮---- -/** - * - * EXCHANGE LINK - Account Endpoints - * https://developers.binance.com/docs/binance_link - */ +getHashrateResales( + params: GetHashrateResaleListParams, +): Promise ⋮---- -createBrokerSubAccount( - params: CreateBrokerSubAccountParams, -): Promise +getMiners(params: GetMinerListParams): Promise ⋮---- -getBrokerSubAccount( - params: GetBrokerSubAccountParams, -): Promise +getMinerDetails( + params: GetMinerDetailsParams, +): Promise ⋮---- -enableMarginBrokerSubAccount( - params: EnableMarginBrokerSubAccountParams, -): Promise +getExtraBonuses( + params: GetExtraBonusListParams, +): Promise ⋮---- -createApiKeyBrokerSubAccount( - params: CreateApiKeyBrokerSubAccountParams, -): Promise +getMiningEarnings( + params: GetEarningsListParams, +): Promise ⋮---- -changePermissionApiKeyBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise +cancelHashrateResaleConfig( + params: CancelHashrateResaleConfigParams, +): Promise ⋮---- -changeComissionBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise +getHashrateResale( + params: GetHashrateResaleDetailParams, +): Promise ⋮---- -enableUniversalTransferApiKeyBrokerSubAccount( - params: EnableUniversalTransferApiKeyBrokerSubAccountParams, -): Promise +getMiningAccountEarnings( + params: GetMiningAccountEarningParams, +): Promise ⋮---- -updateIpRestrictionForSubAccountApiKey( - params: UpdateIpRestrictionForSubApiKey, -): Promise< +getMiningStatistics( + params: GetStatisticListParams, +): Promise ⋮---- -deleteIPRestrictionForSubAccountApiKey(params: { - subAccountId: string; - subAccountApiKey: string; - ipAddress?: string; -}): Promise< +submitHashrateResale(params: SubmitHashrateResaleParams): Promise ⋮---- -deleteApiKeyBrokerSubAccount( - params: DeleteApiKeyBrokerSubAccountParams, -): Promise +getMiningAccounts( + params: getMiningAccountsListParams, +): Promise ⋮---- -getSubAccountBrokerIpRestriction(params: { - subAccountId: string; - subAccountApiKey: string; -}): Promise< +/** + * + * ALGO TRADING Endpoints - Future algo + * + **/ ⋮---- -getApiKeyBrokerSubAccount( - params: GetApiKeyBrokerSubAccountParams, -): Promise +submitVpNewOrder( + params: SubmitVpNewOrderParams, +): Promise ⋮---- -getBrokerInfo(): Promise +submitTwapNewOrder( + params: SubmitTwapNewOrderParams, +): Promise ⋮---- -updateSubAccountBNBBurn(params: { - subAccountId: string; - spotBNBBurn: 'true' | 'false'; -}): Promise< +cancelAlgoOrder(params: { + algoId: number; +}): Promise ⋮---- -updateSubAccountMarginInterestBNBBurn(params: { - subAccountId: string; - interestBNBBurn: 'true' | 'false'; -}): Promise< +getAlgoSubOrders( + params: GetAlgoSubOrdersParams, +): Promise ⋮---- -getSubAccountBNBBurnStatus(params: +getAlgoOpenOrders(): 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: +getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< ⋮---- /** * - * EXCHANGE LINK - Asset Endpoints - * https://developers.binance.com/docs/binance_link - */ + * ALGO TRADING Endpoints - Spot algo + * + **/ ⋮---- -transferBrokerSubAccount( - params: TransferBrokerSubAccountParams, -): Promise +submitSpotAlgoTwapOrder( + params: SubmitSpotTwapNewOrderParams, +): Promise ⋮---- -getBrokerSubAccountHistory( - params: GetBrokerSubAccountHistoryParams, -): Promise +cancelSpotAlgoOrder(params: { + algoId: number; +}): 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< +getSpotAlgoSubOrders( + params: GetSpotAlgoSubOrdersParams, +): Promise ⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures +getSpotAlgoOpenOrders(): Promise< ⋮---- -clientTranId?: string; // The max length is 32 characters +getSpotAlgoHistoricalOrders( + params: GetSpotAlgoHistoricalOrdersParams, +): Promise< ⋮---- -getSubAccountFuturesTransferHistory(params: { - subAccountId: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -}): Promise +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - Market data + * + **/ ⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures +getCryptoLoanFlexibleCollateralAssets(params: { + collateralCoin?: string; +}): Promise< ⋮---- -getBrokerSubDepositHistory( - params: GetSubAccountDepositHistoryParams, -): Promise +getCryptoLoanFlexibleAssets(params: ⋮---- -getBrokerSubAccountSpotAssets( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - Trade + * + **/ ⋮---- -getSubAccountMarginAssetInfo( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< +borrowCryptoLoanFlexible( + params: BorrowFlexibleLoanParams, +): Promise ⋮---- -querySubAccountFuturesAssetInfo( - params: QuerySubAccountFuturesAssetInfoParams, -): Promise< +repayCryptoLoanFlexible( + params: RepayCryptoFlexibleLoanParams, +): Promise ⋮---- -universalTransferBroker(params: UniversalTransferBrokerParams): Promise< +repayCryptoLoanFlexibleWithCollateral( + params: RepayCryptoLoanFlexibleWithCollateralParams, +): Promise ⋮---- -getUniversalTransferBroker( - params: GetUniversalTransferBrokerParams, -): Promise +adjustCryptoLoanFlexibleLTV( + params: AdjustFlexibleCryptoLoanLTVParams, +): Promise ⋮---- /** * - * EXCHANGE LINK - Fee Endpoints - * https://developers.binance.com/docs/binance_link - */ -⋮---- -updateBrokerSubAccountCommission( - params: ChangeSubAccountCommissionParams, -): Promise + * CRYPTO LOAN Endpoints - Flexible rate - User info + * + **/ ⋮---- -updateBrokerSubAccountFuturesCommission( - params: ChangeSubAccountFuturesCommissionParams, -): Promise +getCryptoLoanFlexibleLTVAdjustmentHistory( + params: GetFlexibleLoanLTVAdjustmentHistoryParams, +): Promise< ⋮---- -getBrokerSubAccountFuturesCommission( - params: QuerySubAccountFuturesCommissionParams, -): Promise +getFlexibleLoanCollateralRepayRate(params: { + loanCoin: string; + collateralCoin: string; +}): Promise< ⋮---- -updateBrokerSubAccountCoinFuturesCommission( - params: ChangeSubAccountCoinFuturesCommissionParams, -): Promise +getLoanFlexibleBorrowHistory( + params: GetFlexibleCryptoLoanBorrowHistoryParams, +): Promise< ⋮---- -getBrokerSubAccountCoinFuturesCommission( - params: QuerySubAccountCoinFuturesCommissionParams, -): Promise +getCryptoLoanFlexibleOngoingOrders( + params: GetFlexibleLoanOngoingOrdersParams, +): Promise< ⋮---- -getBrokerSpotCommissionRebate( - params: QueryBrokerSpotCommissionRebateParams, -): Promise +getFlexibleLoanLiquidationHistory( + params?: GetFlexibleLoanLiquidationHistoryParams, +): Promise< ⋮---- -getBrokerFuturesCommissionRebate( - params: QueryBrokerFuturesCommissionRebateParams, -): Promise +getLoanFlexibleRepaymentHistory( + params: GetLoanRepaymentHistoryParams, +): Promise< ⋮---- /** * + * CRYPTO LOAN Endpoints - Stable rate - Market data + * + **/ +⋮---- +/** * @deprecated */ -// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) -getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) +getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +⋮---- +getCryptoLoanCollateralRepayRate( + params: CheckCollateralRepayRateParams, +): Promise ⋮---- /** - * Broker Endpoints - only on old docs - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link + * @deprecated */ +getCryptoLoanCollateralAssetsData( + params: GetCollateralAssetDataParams, +): Promise< ⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerIfNewSpotUser(): Promise< +getCryptoLoansIncomeHistory( + params: GetCryptoLoansIncomeHistoryParams, +): Promise ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead + * + * CRYPTO LOAN Endpoints - Stable rate - Trade + * **/ -getBrokerSubAccountDepositHistory( - params?: GetBrokerSubAccountDepositHistoryParams, -): Promise ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerUserCustomisedId(market: 'spot' | 'futures') + * @deprecated + */ +borrowCryptoLoan( + params: BorrowCryptoLoanParams, +): Promise ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableFuturesBrokerSubAccount( - params: EnableFuturesBrokerSubAccountParams, -): Promise + * @deprecated + */ +repayCryptoLoan( + params: RepayCryptoLoanParams, +): Promise ⋮---- /** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableMarginApiKeyBrokerSubAccount( - params: EnableMarginApiKeyBrokerSubAccountParams, -): Promise + * @deprecated + */ +adjustCryptoLoanLTV( + params: AdjustCryptoLoanLTVParams, +): Promise ⋮---- /** - * Validate syntax meets requirements set by binance. Log warning if not. + * @deprecated */ -private validateOrderId( - params: - | NewSpotOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams - | NewOrderListParams, - orderIdProperty: OrderIdProperty, -): void +customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< ⋮---- /** * - * User Data Stream Endpoints + * CRYPTO LOAN Endpoints - Stable rate - User info * **/ ⋮---- -// spot -getSpotUserDataListenKey(): Promise< -⋮---- -keepAliveSpotUserDataListenKey(listenKey: string): Promise -⋮---- -closeSpotUserDataListenKey(listenKey: string): Promise -⋮---- /** - * Get a cross margin user data listen key + * @deprecated */ -getMarginUserDataListenKey(): Promise< +getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< ⋮---- -keepAliveMarginUserDataListenKey(listenKey: string): Promise +getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< ⋮---- -closeMarginUserDataListenKey(listenKey: string): Promise +getCryptoLoanLTVAdjustmentHistory( + params: GetLoanLTVAdjustmentHistoryParams, +): Promise< ⋮---- -// isolated margin -getIsolatedMarginUserDataListenKey(params: { - symbol: string; -}): Promise< +getCryptoLoanRepaymentHistory( + params: GetLoanRepaymentHistoryParams, +): Promise ⋮---- -keepAliveIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise +/** + * + * SIMPLE EARN Endpoints - Account + * + **/ ⋮---- -closeIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise +getSimpleEarnAccount(): Promise ⋮---- -/** - * Get a cross margin risk data listen key - */ -getMarginRiskUserDataListenKey(): Promise< +getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< ⋮---- -keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise +getSimpleEarnLockedProductList( + params?: SimpleEarnProductListParams, +): Promise< ⋮---- -closeMarginRiskUserDataListenKey(): Promise +getFlexibleProductPosition( + params?: SimpleEarnFlexibleProductPositionParams, +): Promise< ⋮---- -/** - * 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< +getLockedProductPosition( + params?: SimpleEarnLockedProductPositionParams, +): Promise< +⋮---- +getFlexiblePersonalLeftQuota(params: +⋮---- +getLockedPersonalLeftQuota(params: ⋮---- /** * - * DEPRECATED ENDPOINTS - * - **/ -/** + * SIMPLE EARN Endpoints - Earn * - * BSwap Endpoints - * @deprecated as of 2024-01-19 **/ ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -getBSwapLiquidity(params?: +purchaseFlexibleProduct( + params: SimpleEarnSubscribeProductParams, +): Promise ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -addBSwapLiquidity(params: AddBSwapLiquidityParams): Promise< +subscribeSimpleEarnLockedProduct( + params: SimpleEarnSubscribeProductParams, +): Promise ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -removeBSwapLiquidity(params: RemoveBSwapLiquidityParams): Promise< +redeemFlexibleProduct( + params: SimpleEarnRedeemFlexibleProductParams, +): Promise ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -getBSwapOperations( - params?: BSwapOperationsParams, -): Promise +redeemLockedProduct(params: { + positionId: string; +}): Promise +⋮---- +setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< +⋮---- +setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< +⋮---- +getFlexibleSubscriptionPreview( + params: GetFlexibleSubscriptionPreviewParams, +): Promise +⋮---- +getLockedSubscriptionPreview( + params: GetLockedSubscriptionPreviewParams, +): Promise +⋮---- +setLockedProductRedeemOption(params: { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; +}): Promise< ⋮---- /** * - * Savings Endpoints - * @deprecated as of 2023-06-22, now Simple Earn + * SIMPLE EARN Endpoints - History + * **/ ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyPurchaseQuotaFlexibleProduct(params: { - productId: string; -}): Promise +getFlexibleSubscriptionRecord( + params: GetFlexibleSubscriptionRecordParams, +): 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); +getLockedSubscriptionRecord( + params: GetLockedSubscriptionRecordParams, +): Promise< ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -purchaseFixedAndActivityProject(params: { - projectId: string; - lot: number; -}): Promise +getFlexibleRedemptionRecord( + params: GetFlexibleRedemptionRecordParams, +): Promise< ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProjects( - params: FixedAndActivityProjectParams, -): Promise +getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProductPosition( - params: FixedAndActivityProjectPositionParams, -): Promise +getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLendingAccount(): Promise +getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getPurchaseRecord(params: PurchaseRecordParams): Promise +getCollateralRecord(params: GetCollateralRecordParams): Promise< ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getRedemptionRecord(params: PurchaseRecordParams): Promise +getRateHistory(params: GetRateHistoryParams): Promise< ⋮---- /** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getInterestHistory(params: PurchaseRecordParams): Promise + * + * VIP LOAN Endpoints - Market Data + * + **/ ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -changeFixedAndActivityPositionToDailyPosition(params: { - projectId: string; - lot: number; - positionId?: number; -}): Promise +getVipBorrowInterestRate(params: { + loanCoin: string; +}): Promise +⋮---- +getVipLoanInterestRateHistory( + params: VipLoanInterestRateHistoryParams, +): Promise< +⋮---- +getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +⋮---- +getVipCollateralAssets(params: ⋮---- /** * - * Wallet Endpoints - * @deprecated + * VIP LOAN Endpoints - User Info + * **/ ⋮---- -/** - * @deprecated - */ -enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise +getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - * - */ -convertBUSD(params: ConvertTransfer): Promise +getVipLoanRepaymentHistory( + params: GetVipLoanRepaymentHistoryParams, +): 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'; +checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< ⋮---- -function getFuturesMarketWsKey(market: 'usdm' | 'coinm'): WSAPIWsKeyFutures +getVipApplicationStatus(params: GetApplicationStatusParams): Promise< ⋮---- /** - * 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 + * VIP LOAN Endpoints - Trade * - * 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. + **/ +⋮---- +renewVipLoan(params: VipLoanRenewParams): Promise +⋮---- +repayVipLoan(params: VipLoanRepayParams): Promise +⋮---- +borrowVipLoan(params: VipLoanBorrowParams): Promise +⋮---- +getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise< +⋮---- +borrowVipLoanFixedRate( + params: VipLoanFixedRateBorrowParams, +): Promise +⋮---- +/** * - * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. - */ - muteLatencyWarning: boolean; - - /** - * Default: true + * DUAL INVESTMENT Endpoints - Market Data * - * 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; -} + **/ +⋮---- +getDualInvestmentProducts( + params: GetDualInvestmentProductListParams, +): Promise< ⋮---- /** - * Default: true * - * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected - */ + * DUAL INVESTMENT Endpoints - Trade + * + **/ +⋮---- +subscribeDualInvestmentProduct( + params: SubscribeDualInvestmentProductParams, +): Promise +⋮---- +getDualInvestmentPositions( + params: GetDualInvestmentPositionsParams, +): Promise< +⋮---- +getDualInvestmentAccounts(): Promise +⋮---- +getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< +⋮---- +updateAutoCompoundStatus( + params: ChangeAutoCompoundStatusParams, +): Promise ⋮---- /** - * Default: 2 seconds * - * Delay automatic userdata resubscribe by x seconds. - */ + * GIFT CARD Endpoints - Market Data + * + **/ +⋮---- +createGiftCard(params: CreateGiftCardParams): Promise +⋮---- +createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise +⋮---- +redeemGiftCard(params: RedeemGiftCardParams): Promise +⋮---- +verifyGiftCard(params: +⋮---- +getTokenLimit(params: +⋮---- +getRsaPublicKey(): Promise ⋮---- /** - * Default: true * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). + * NFT Endpoints - REST api * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ + **/ +⋮---- +getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< +⋮---- +getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< +⋮---- +getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< +⋮---- +getNftAsset(params: GetNftAssetParams): Promise< ⋮---- /** - * 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. + * C2C Endpoints * - * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. - */ + **/ +⋮---- +getC2CTradeHistory( + params: GetC2CTradeHistoryParams, +): 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. - */ + * FIAT Endpoints - REST api + * + **/ ⋮---- -/** - * 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; -} +getFiatOrderHistory( + params: GetFiatOrderHistoryParams, +): Promise ⋮---- -/** - * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. - */ +getFiatPaymentsHistory( + params: GetFiatOrderHistoryParams, +): Promise ⋮---- -/** - * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream - */ +fiatWithdraw(params: WithdrawFiatParams): Promise< +⋮---- +fiatDeposit(params: FiatDepositParams): Promise +⋮---- +getFiatOrderDetail( + params: GetFiatOrderDetailParams, +): 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 + * + * Rebate Endpoints + * + **/ +⋮---- +getSpotRebateHistoryRecords( + params: GetSpotRebateHistoryRecordsParams, +): Promise ⋮---- /** - * Minimal state store around automating sticky "userDataStream.subscribe" sessions - */ + * + * DERIVATIVES - Portfolio Margin Pro - Market Data + * This is in mainclient because it shares the same base url + * + **/ ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +getPortfolioMarginIndexPrice(params?: { + asset?: string; +}): Promise ⋮---- -public getWSClient(): WebsocketClient +getPortfolioMarginAssetLeverage(): Promise< + GetPortfolioMarginAssetLeverageResponse[] + > { + return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); ⋮---- -public setTimeOffsetMs(newOffset: number): void +getPortfolioMarginProCollateralRate(): Promise< + GetPortfolioMarginProCollateralRateResponse[] + > { + return this.get('sapi/v1/portfolio/collateralRate'); ⋮---- -public async disconnectAll(): Promise +getPortfolioMarginProTieredCollateralRate(): Promise ⋮---- -/* +/** * - * SPOT - General requests + * DERIVATIVES - Portfolio Margin Pro - Account + * This is in mainclient because it shares the same base url * - */ + **/ ⋮---- -/** - * Test connectivity to the WebSocket API - */ -testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> +getPortfolioMarginProAccountInfo(): Promise ⋮---- -/** - * Test connectivity to the WebSocket API and get the current server time - */ -getSpotServerTime( - wsKey?: WSAPIWsKeyMain, -): Promise> +getPortfolioDeltaMode(): Promise ⋮---- -/** - * Query current exchange trading rules, rate limits, and symbol information - */ -getSpotExchangeInfo( - params?: WSAPIExchangeInfoRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +switchPortfolioDeltaMode( + params: SwitchPortfolioDeltaModeParams, +): Promise< ⋮---- -/* - * - * SPOT - Market data requests - * - */ +setPortfolioMarginMarginCallLevel( + params: SetPortfolioMarginMarginCallLevelParams, +): 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> +getPortfolioMarginMarginCallLevel(): Promise ⋮---- -/** - * Get recent trades - * Note: If you need access to real-time trading activity, consider using WebSocket Streams - */ -getSpotRecentTrades( - params: WSAPITradesRecentRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +deletePortfolioMarginMarginCallLevel(): Promise ⋮---- -/** - * Get historical trades - * Note: If fromId is not specified, the most recent trades are returned - */ -getSpotHistoricalTrades( - params: WSAPITradesHistoricalRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +bnbTransfer(params: BnbTransferParams): Promise< ⋮---- -/** - * Get historical block trades - */ -getSpotHistoricalBlockTrades( - params: WSAPIBlockTradesHistoricalRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +submitPortfolioMarginProFullTransfer(): 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> +submitPortfolioMarginProSpecificTransfer(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> +repayPortfolioMarginProBankruptcyLoan(params: { + from?: 'SPOT' | 'MARGIN'; +}): 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> +getPortfolioMarginProBankruptcyLoanAmount(): Promise ⋮---- -/** - * Get current average price for a symbol - */ -getSpotAveragePrice( - params: WSAPIAvgPriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +repayFuturesNegativeBalance(): Promise< ⋮---- -/** - * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. - */ -getSpotExecutionRules( - params?: WSAPIExecutionRulesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +updateAutoRepayFuturesStatus(params: ⋮---- -/** - * Query reference price for a symbol. - */ -getSpotReferencePrice( - params: WSAPIReferencePriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +getAutoRepayFuturesStatus(): Promise< +⋮---- +getPortfolioMarginProInterestHistory( + params: GetPortfolioMarginProInterestHistoryParams, +): Promise +⋮---- +getPortfolioMarginProSpanAccountInfo(): Promise +⋮---- +getPortfolioMarginProAccountBalance(params?: { + asset?: string; +}): Promise ⋮---- /** - * Query how reference price is calculated for a symbol. + * @deprecated + * Check Simple Earn endpoints for new way of doing it */ -getSpotReferencePriceCalculation( - params: WSAPIReferencePriceCalculationRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +mintPortfolioMarginBFUSD( + params: PMProMintBFUSDParams, +): Promise ⋮---- /** - * Get 24-hour rolling window price change statistics - * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams + * @deprecated + * Check Simple Earn endpointsfor new way of doing it */ -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 }, - ); +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< ⋮---- /** - * Get price change statistics for a trading day + * Transfer LDUSDT as collateral for all types of Portfolio Margin account */ -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 }, - ); +transferLDUSDTPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; + amount: number; +}): Promise< ⋮---- /** - * Get rolling window price change statistics with a custom window - * Note: Window size precision is limited to 1 minute + * Get transferable earn asset balance for all types of Portfolio Margin account */ -getSpotTicker( - params: WSAPITickerRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker', - params, - { authIsOptional: true }, - ); +getTransferableEarnAssetBalanceForPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; +}): 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> + * + * DERIVATIVES - Futures Data - Market + * This is in mainclient because it shares the same base url + * + **/ +⋮---- +getFuturesTickLevelOrderbookDataLink( + params: GetFutureTickLevelOrderbookDataLinkParams, +): 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> + * + * 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 +⋮---- +/** * - * SPOT - Session authentication requests + * Pay endpoints + * Found only in old docs, possibly @deprecated + **/ +getPayTransactions(params: GetPayTradeHistoryParams): Promise +⋮---- +/** * - * Note: authentication is automatic + * INSTITUTIONAL LOAN - Account Endpoints * - */ + **/ ⋮---- -getSpotSessionStatus( - wsKey?: WSAPIWsKeyMain, -): Promise> +getInstLoanRiskUnit( + params?: GetInstitutionalLoanRiskUnitDetailsParams, +): Promise ⋮---- -/* +closeInstLoanRiskUnit(): Promise +⋮---- +addInstLoanCollateralAccount( + params: AddInstitutionalLoanCollateralAccountParams, +): Promise +⋮---- +getActiveInstLoanRiskUnits(): Promise +⋮---- +getClosedInstLoanRiskUnits( + params?: GetClosedInstitutionalLoanRiskUnitsParams, +): Promise +⋮---- +/** * - * SPOT - Trading requests + * INSTITUTIONAL LOAN - Trade Endpoints * - */ + **/ ⋮---- +getInstLoanForceLiquidationRecord( + params: GetInstitutionalLoanForceLiquidationParams, +): Promise /** - * Submit a spot order - */ -submitNewSpotOrder( - params: WSAPINewSpotOrderRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> + * + * INSTITUTIONAL LOAN - TransferEndpoints + * + **/ ⋮---- -/** - * 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, - ); +transferInstLoanRiskUnit( + params: InstitutionalLoanRiskUnitTransferParams, +): Promise ⋮---- /** - * 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> + * + * INSTITUTIONAL LOAN - Borrow/Repay Endpoints + * + **/ ⋮---- -/** - * Cancel an active order - * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used - */ -cancelSpotOrder( - params: WSAPIOrderCancelRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +getInstitutionalLoanMaxBorrowable( + params: GetInstitutionalLoanMaxBorrowableParams, +): Promise +⋮---- +borrowInstitutionalLoan( + params: InstitutionalLoanBorrowParams, +): Promise +⋮---- +getInstLoanInterestHistory( + params?: GetInstitutionalLoanInterestHistoryParams, +): Promise +⋮---- +repayInstitutionalLoan( + params: InstitutionalLoanRepayParams, +): Promise +⋮---- +getInstLoanBorrowRepayRecords( + params: GetInstitutionalLoanBorrowRepayRecordsParams, +): Promise +⋮---- +getMarginInterestRebateBalance(): Promise +⋮---- +getMarginInterestRebateBalanceRecords( + params?: GetMarginInterestRebateBalanceRecordsParams, +): Promise ⋮---- /** - * Cancel an existing order and immediately place a new order - * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used + * + * ALPHA TRADING - Market Data + * https://developers.binance.com/docs/alpha */ -cancelReplaceSpotOrder( - params: WSAPIOrderCancelReplaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +⋮---- +getAlphaTokenList(): Promise +⋮---- +getAlphaExchangeInfo(): Promise +⋮---- +getAlphaAggTrades(params: AlphaAggTradesParams): Promise +⋮---- +getAlphaKlines(params: AlphaKlinesParams): Promise +⋮---- +getAlphaTicker(params: +⋮---- +getAlphaFullDepth( + params: AlphaFullDepthParams, +): Promise ⋮---- /** - * 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 + * EXCHANGE LINK - Account Endpoints + * https://developers.binance.com/docs/binance_link */ -amendSpotOrderKeepPriority( - params: WSAPIOrderAmendKeepPriorityRequest, - wsKey?: WSAPIWsKeyMain, -): 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> +createBrokerSubAccount( + params: CreateBrokerSubAccountParams, +): 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, - ); +getBrokerSubAccount( + params: GetBrokerSubAccountParams, +): Promise ⋮---- -/** - * Place a new order list - * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead - */ -placeSpotOrderList( - params: WSAPIOrderListPlaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +enableMarginBrokerSubAccount( + params: EnableMarginBrokerSubAccountParams, +): 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> +createApiKeyBrokerSubAccount( + params: CreateApiKeyBrokerSubAccountParams, +): 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> +changePermissionApiKeyBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, +): 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> +changeComissionBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, +): 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> +enableUniversalTransferApiKeyBrokerSubAccount( + params: EnableUniversalTransferApiKeyBrokerSubAccountParams, +): 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> +updateIpRestrictionForSubAccountApiKey( + params: UpdateIpRestrictionForSubApiKey, +): 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> +deleteIPRestrictionForSubAccountApiKey(params: { + subAccountId: string; + subAccountApiKey: string; + ipAddress?: string; +}): Promise< ⋮---- -/** - * Cancel an active order list - * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used - */ -cancelSpotOrderList( - params: WSAPIOrderListCancelRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +deleteApiKeyBrokerSubAccount( + params: DeleteApiKeyBrokerSubAccountParams, +): Promise ⋮---- -/** - * 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> +getSubAccountBrokerIpRestriction(params: { + subAccountId: string; + subAccountApiKey: string; +}): Promise< ⋮---- -/** - * 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> +getApiKeyBrokerSubAccount( + params: GetApiKeyBrokerSubAccountParams, +): 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, - ); +getBrokerInfo(): Promise ⋮---- -/* - * - * SPOT - Account requests - * - */ +updateSubAccountBNBBurn(params: { + subAccountId: string; + spotBNBBurn: 'true' | 'false'; +}): Promise< ⋮---- -/** - * Query information about your account, including balances - * Note: Weight: 20 - */ -getSpotAccountInformation( - params: WSAPIAccountInformationRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +updateSubAccountMarginInterestBNBBurn(params: { + subAccountId: string; + interestBNBBurn: 'true' | 'false'; +}): Promise< ⋮---- -/** - * Query your current unfilled order count for all intervals - * Note: Weight: 40 - */ -getSpotOrderRateLimits( - params: WSAPIRecvWindowTimestamp, - wsKey?: WSAPIWsKeyMain, -): Promise> +getSubAccountBNBBurnStatus(params: ⋮---- /** - * Query information about all your orders – active, canceled, filled – filtered by time range - * Note: Weight: 20 + * 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. */ -getSpotAllOrders( - params: WSAPIAllOrdersRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +deleteBrokerSubAccount(params: ⋮---- /** - * Query information about all your order lists, filtered by time range - * Note: Weight: 20 + * + * EXCHANGE LINK - Asset Endpoints + * https://developers.binance.com/docs/binance_link */ -getSpotAllOrderLists( - params: WSAPIAllOrderListsRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> ⋮---- -/** - * Query information about all your trades, filtered by time range - * Note: Weight: 20 - */ -getSpotMyTrades( - params: WSAPIMyTradesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +transferBrokerSubAccount( + params: TransferBrokerSubAccountParams, +): Promise +⋮---- +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< +⋮---- +futuresType: number; // 1: USDT Futures, 2: COIN Futures +⋮---- +clientTranId?: string; // The max length is 32 characters ⋮---- -/** - * 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> +getSubAccountFuturesTransferHistory(params: { + subAccountId: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +}): Promise ⋮---- -/** - * Retrieves allocations resulting from SOR order placement - * Note: Weight: 20 - */ -getSpotAllocations( - params: WSAPIMyAllocationsRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +futuresType: number; // 1: USDT Futures, 2: COIN Futures ⋮---- -/** - * Get current account commission rates - * Note: Weight: 20 - */ -getSpotAccountCommission( - params: WSAPIAccountCommissionWSAPIRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +getBrokerSubDepositHistory( + params: GetSubAccountDepositHistoryParams, +): Promise ⋮---- -/* - * - * FUTURES - Market data requests - * - */ +getBrokerSubAccountSpotAssets( + params: QuerySubAccountSpotMarginAssetInfoParams, +): 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> +getSubAccountMarginAssetInfo( + params: QuerySubAccountSpotMarginAssetInfoParams, +): 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 }, - ); +querySubAccountFuturesAssetInfo( + params: QuerySubAccountFuturesAssetInfoParams, +): Promise< ⋮---- -/** - * 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> +universalTransferBroker(params: UniversalTransferBrokerParams): Promise< ⋮---- -/* - * - * FUTURES - Trading requests - * - */ +getUniversalTransferBroker( + params: GetUniversalTransferBrokerParams, +): Promise ⋮---- /** - * Submit a futures order * - * This endpoint is used for both USDM and COINM futures. + * EXCHANGE LINK - Fee Endpoints + * https://developers.binance.com/docs/binance_link */ -submitNewFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPINewFuturesOrderRequest, -): Promise> ⋮---- -/** - * Modify an existing futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -modifyFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderModifyRequest, -): Promise> +updateBrokerSubAccountCommission( + params: ChangeSubAccountCommissionParams, +): Promise ⋮---- -/** - * Cancel a futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -cancelFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderCancelRequest, -): Promise> +updateBrokerSubAccountFuturesCommission( + params: ChangeSubAccountFuturesCommissionParams, +): Promise ⋮---- -/** - * Query futures order status - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesOrderStatus( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderStatusRequest, -): Promise> +getBrokerSubAccountFuturesCommission( + params: QuerySubAccountFuturesCommissionParams, +): Promise ⋮---- -/** - * Get current position information (V2) - * Note: Only symbols that have positions or open orders will be returned - */ -getFuturesPositionV2( - params: WSAPIFuturesPositionV2Request, -): Promise> +updateBrokerSubAccountCoinFuturesCommission( + params: ChangeSubAccountCoinFuturesCommissionParams, +): 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> +getBrokerSubAccountCoinFuturesCommission( + params: QuerySubAccountCoinFuturesCommissionParams, +): 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> +getBrokerSpotCommissionRebate( + params: QueryBrokerSpotCommissionRebateParams, +): 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> +getBrokerFuturesCommissionRebate( + params: QueryBrokerFuturesCommissionRebateParams, +): 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) ⋮---- /** - * Get account balance information (V2) - * Note: Returns balance information for all assets + * Broker Endpoints - only on old docs + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link */ -getFuturesAccountBalanceV2( - params: WSAPIRecvWindowTimestamp, -): 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 + **/ +getBrokerIfNewSpotUser(): 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 + **/ +getBrokerSubAccountDepositHistory( + params?: GetBrokerSubAccountDepositHistoryParams, +): Promise ⋮---- /** - * 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 + **/ +getBrokerUserCustomisedId(market: 'spot' | 'futures') ⋮---- /** - * 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> + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableMarginApiKeyBrokerSubAccount( + params: EnableMarginApiKeyBrokerSubAccountParams, +): Promise ⋮---- /** - * Stop the user data stream listen key. - * - * @param params - * @param wsKey - * @returns + * Validate syntax meets requirements set by binance. Log warning if not. */ -stopUserDataStreamForKey( - params: WSAPIUserDataListenKeyRequest, - wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> +private validateOrderId( + params: + | NewSpotOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams + | NewOrderListParams, + orderIdProperty: OrderIdProperty, +): void ⋮---- /** - * Consolidated method to clear any timers related to user data stream subscriptions for a given wsKey, if found. * - * @param wsKey - */ -clearUserDataStreamTimers(wsKey: WSAPIWsKey) + * User Data Stream Endpoints + * + **/ ⋮---- -// Just in case the refresh timer is still running -// Harmless given one connection, but still unnecessary +// spot +getSpotUserDataListenKey(): Promise< +⋮---- +keepAliveSpotUserDataListenKey(listenKey: string): Promise +⋮---- +closeSpotUserDataListenKey(listenKey: string): Promise ⋮---- /** - * Request user data stream subscription on the currently authenticated connection. - * - * If reconnected, this will automatically resubscribe unless you unsubscribe manually. + * Get a cross margin user data listen key */ -async subscribeUserDataStream( - wsKey: WSAPIWsKey, - isRefreshingToken: boolean = false, -): Promise | WSConnectedResult | undefined> +getMarginUserDataListenKey(): Promise< ⋮---- -// User data stream works differently for margin, since Feb 2026, via a listen token mechanic +keepAliveMarginUserDataListenKey(listenKey: string): Promise ⋮---- -// validity: 30 * 1000, // milliseconds (30 secs) -// validity: 5 * 60 * 1000, // milliseconds (5 mins ) +closeMarginUserDataListenKey(listenKey: string): Promise ⋮---- -// Set respawn timer, to automatically fetch and sub to new token before expiry. Should be seamless on existing connection. +// isolated margin +getIsolatedMarginUserDataListenKey(params: { + symbol: string; +}): Promise< ⋮---- -// try to respawn 30 seconds before expiration +keepAliveIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; +}): Promise ⋮---- -// for Ed25519 keys, no signature is needed, we should already be authenticated in session +closeIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; +}): Promise ⋮---- -// for HMAC & RSA keys, request will be signed and sent to a dedicated topic +/** + * Get a cross margin risk data listen key + */ +getMarginRiskUserDataListenKey(): Promise< ⋮---- -// Used to track whether this connection had the general "userDataStream.subscribe" called. -// Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub. +keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise +⋮---- +closeMarginRiskUserDataListenKey(): Promise ⋮---- /** - * Unsubscribe from the user data stream subscription on the currently authenticated connection. - * - * If reconnected, this will also stop it from automatically resubscribing after reconnect. + * Get/create margin account listenToken for the user data stream + * https://developers.binance.com/docs/margin_trading/trade-data-stream */ -unsubscribeUserDataStream( - wsKey: WSAPIWsKey, -): Promise ⋮---- -// console.log(new Date(), 'ws message received: ', data); +/** + * + * Savings Endpoints + * @deprecated as of 2023-06-22, now Simple Earn + **/ ⋮---- -private setupSignMechanic() +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyPurchaseQuotaFlexibleProduct(params: { + productId: string; +}): Promise ⋮---- -private async tryResubscribeUserDataStream( - wsKey: WSAPIWsKey, - isRefreshingToken: boolean, -) +/** + * @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); ⋮---- -// Just in case the refresh timer is still running +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +purchaseFixedAndActivityProject(params: { + projectId: string; + lot: number; +}): Promise ⋮---- -private getSubscribedUserDataStreamState(wsKey: WSAPIWsKey) +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProjects( + params: FixedAndActivityProjectParams, +): Promise ⋮---- -private handleWSCloseEvent(params: +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProductPosition( + params: FixedAndActivityProjectPositionParams, +): Promise ⋮---- -// Not a WS API connection +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLendingAccount(): 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 +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getPurchaseRecord(params: PurchaseRecordParams): Promise ⋮---- -private handleWSReconnectedEvent(params: +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getRedemptionRecord(params: PurchaseRecordParams): Promise ⋮---- -// Not a WS API connection +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getInterestHistory(params: PurchaseRecordParams): Promise ⋮---- -// No record of ever subscribing to user data stream on this connection, so no need to resubscribe +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +changeFixedAndActivityPositionToDailyPosition(params: { + projectId: string; + lot: number; + positionId?: number; +}): Promise ⋮---- -// Clear token refresh timer, just in case. No need on a dead & potentially respawning connection +/** + * + * Wallet Endpoints + * @deprecated + **/ ⋮---- -// Feature enabled +/** + * @deprecated + */ +enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise ⋮---- -// Delay existing timer, if exists +/** + * @deprecated - deleted as of 2024-11-21 + * + */ +convertBUSD(params: ConvertTransfer): Promise ⋮---- -// Queue resubscribe workflow +/** + * @deprecated + */ +getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise< ================ File: src/websocket-client.ts @@ -27623,7 +28177,7 @@ public async subscribeSpotUserDataStream( wsKey: WsKey = 'main', forceNewConnection?: boolean, miscState?: MiscUserDataConnectionState, -): Promise +): Promise ⋮---- public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise ⋮---- @@ -28184,7 +28738,7 @@ File: package.json ================ { "name": "binance", - "version": "3.5.11", + "version": "3.6.2", "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", @@ -28224,10 +28778,11 @@ File: package.json "0xSmartCrypto <0xsmartcrypto@gmail.com> (https://twitter.com/0xSmartCrypto)" ], "dependencies": { + "@types/ws": "^8.18.1", "axios": "^1.13.2", "isomorphic-ws": "^4.0.1", "nanoid": "^3.3.11", - "ws": "^7.4.0" + "ws": "8.21.1" }, "devDependencies": { "@types/jest": "^30.0.0", @@ -28247,7 +28802,6 @@ File: package.json "source-map-loader": "^2.0.2", "ts-loader": "^8.0.11", "webpack": "^5.102.1", - "webpack-bundle-analyzer": "^5.1.1", "webpack-cli": "^5.1.4" }, "keywords": [ @@ -28278,12 +28832,12 @@ File: package.json "license": "MIT", "repository": { "type": "git", - "url": "git+https://github.com/tiagosiebler/binance.git" + "url": "git+https://github.com/sieblyio/binance.git" }, "bugs": { - "url": "https://github.com/tiagosiebler/binance/issues" + "url": "https://github.com/sieblyio/binance/issues" }, - "homepage": "https://github.com/tiagosiebler/binance#readme" + "homepage": "https://github.com/sieblyio/binance#readme" } diff --git a/package-lock.json b/package-lock.json index 344e53ea..e0258153 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "binance", - "version": "3.6.1", + "version": "3.6.2", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "binance", - "version": "3.6.1", + "version": "3.6.2", "license": "MIT", "dependencies": { "@types/ws": "^8.18.1", diff --git a/package.json b/package.json index 3e67b5e2..c6c30f66 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "binance", - "version": "3.6.1", + "version": "3.6.2", "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/main-client.ts b/src/main-client.ts index 657f2faf..84cce160 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -463,6 +463,7 @@ import { PMProMintBFUSDParams, PMProMintBFUSDResponse, PMProRedeemBFUSDResponse, + PortfolioDeltaModeStatus, PortfolioMarginMarginCallLevelDeleteResponse, PortfolioMarginMarginCallLevelGetResponse, PortfolioMarginMarginCallLevelResponse, @@ -549,6 +550,8 @@ import { SpecialLowLatencyKeyResponse, SpotAlgoOrder, SpotAmendKeepPriorityResult, + SpotAssetTag, + SpotAssetTagsParams, SpotExecutionRulesParams, SpotExecutionRulesResponse, SpotOrder, @@ -637,6 +640,7 @@ import { SubscribeDualInvestmentProductResponse, SubscribeEthStakingV2Response, SubscribeSolStakingResponse, + SwitchPortfolioDeltaModeParams, SymbolOrderBookTicker, SymbolTradeFee, SystemStatusResponse, @@ -1701,6 +1705,10 @@ export class MainClient extends BaseRestClient { return this.postPrivate('sapi/v3/asset/getUserAsset', params); } + getSpotAssetTags(params?: SpotAssetTagsParams): Promise { + return this.get('sapi/v1/spot/asset/tags', params); + } + submitUniversalTransfer( params: UniversalTransferParams, ): Promise<{ tranId: number }> { @@ -4088,6 +4096,16 @@ export class MainClient extends BaseRestClient { return this.getPrivate('sapi/v1/portfolio/account'); } + getPortfolioDeltaMode(): Promise { + return this.getPrivate('sapi/v1/portfolio/delta-mode'); + } + + switchPortfolioDeltaMode( + params: SwitchPortfolioDeltaModeParams, + ): Promise<{ msg: string }> { + return this.postPrivate('sapi/v1/portfolio/delta-mode', params); + } + setPortfolioMarginMarginCallLevel( params: SetPortfolioMarginMarginCallLevelParams, ): Promise { diff --git a/src/types/coin.ts b/src/types/coin.ts index e60528ef..624a3a7d 100644 --- a/src/types/coin.ts +++ b/src/types/coin.ts @@ -86,6 +86,7 @@ export interface CoinMPositionTrade { positionSide: PositionSide; buyer: boolean; maker: boolean; + quoteQty?: numberInString; } export interface FundingRate { diff --git a/src/types/futures.ts b/src/types/futures.ts index 345cfe4d..21e0f528 100644 --- a/src/types/futures.ts +++ b/src/types/futures.ts @@ -148,6 +148,7 @@ export interface ModifyFuturesOrderParams { quantity?: numberType; price?: numberType; priceMatch?: PriceMatchMode; + modifyId?: number; } export enum EnumPositionMarginChangeType { @@ -377,6 +378,7 @@ export interface FundingRateHistory { fundingRate: numberInString; fundingTime: number; markPrice: numberInString; + rateType?: 'Regular' | 'Special'; } export interface FuturesSymbolOrderBookTicker { @@ -479,6 +481,8 @@ export interface OrderResult { selfTradePreventionMode: SelfTradePreventionMode; priceMatch: PriceMatchMode; goodTillDate: number; + cumBase?: numberInString; + pair?: string; } export interface ModifyFuturesOrderResult { @@ -506,6 +510,7 @@ export interface ModifyFuturesOrderResult { updateTime: number; selfTradePreventionMode: SelfTradePreventionMode; priceMatch: PriceMatchMode; + modifyId?: number; } export interface CancelFuturesOrderResult { @@ -704,6 +709,9 @@ export interface FuturesPositionTrade { positionSide: PositionSide; symbol: string; time: number; + pair?: string; + baseQty?: numberInString; + marginAsset?: string; } export interface ForceOrderResult { @@ -726,6 +734,9 @@ export interface ForceOrderResult { origType: FuturesOrderType; time: number; updateTime: number; + cumBase?: numberInString; + pair?: string; + goodTillDate?: number; } export interface SymbolLeverageBracket { @@ -834,6 +845,7 @@ export interface OrderAmendment { clientOrderId: string; time: number; amendment: OrderAmendmentDetail; + modifyId?: number; } export interface QuarterlyContractSettlementPrice { @@ -899,6 +911,7 @@ export interface ModifyOrderParams { | 'QUEUE_5' | 'QUEUE_10' | 'QUEUE_20'; + modifyId?: number; recvWindow?: number; timestamp: number; } @@ -1114,6 +1127,8 @@ export interface TradingSchedule { marketSchedules: { EQUITY?: MarketSchedule; COMMODITY?: MarketSchedule; + KR_EQUITY?: MarketSchedule; + HK_EQUITY?: MarketSchedule; }; } diff --git a/src/types/portfolio-margin.ts b/src/types/portfolio-margin.ts index 28212a02..6b1f4e71 100644 --- a/src/types/portfolio-margin.ts +++ b/src/types/portfolio-margin.ts @@ -60,10 +60,10 @@ export interface NewPortfolioUMOrderReq { export interface NewPortfolioUMOrderResponse { clientOrderId: string; cumQty: string; - cumQuote: string; + cumQuote?: string; executedQty: string; orderId: number; - avgPrice: string; + avgPrice?: string; origQty: string; price: string; reduceOnly: boolean; @@ -229,10 +229,10 @@ export interface NewPortfolioCMOrderReq { export interface NewPortfolioCMOrderResponse { clientOrderId: string; cumQty: string; - cumBase: string; + cumBase?: string; executedQty: string; orderId: number; - avgPrice: string; + avgPrice?: string; origQty: string; price: string; reduceOnly: boolean; @@ -389,10 +389,10 @@ export interface CancelPortfolioUMOrderReq { } export interface PortfolioUMCancelOrderResponse { - avgPrice: string; + avgPrice?: string; clientOrderId: string; cumQty: string; - cumQuote: string; + cumQuote?: string; executedQty: string; orderId: number; origQty: string; @@ -447,10 +447,10 @@ export interface CancelPortfolioCMOrderReq { } export interface PortfolioCMCancelOrderResponse { - avgPrice: string; + avgPrice?: string; clientOrderId: string; cumQty: string; - cumBase: string; + cumBase?: string; executedQty: string; orderId: number; origQty: string; @@ -599,6 +599,7 @@ export interface ModifyPortfolioUMOrderReq { orderId?: number; origClientOrderId?: string; priceMatch?: PMPriceMatch; + modifyId?: number; } export interface PortfolioUMModifyOrderResponse { @@ -607,11 +608,11 @@ export interface PortfolioUMModifyOrderResponse { status: string; clientOrderId: string; price: string; - avgPrice: string; + avgPrice?: string; origQty: string; executedQty: string; cumQty: string; - cumQuote: string; + cumQuote?: string; timeInForce: string; type: 'LIMIT'; reduceOnly: boolean; @@ -622,6 +623,7 @@ export interface PortfolioUMModifyOrderResponse { goodTillDate: number; updateTime: number; priceMatch: PMPriceMatch; + modifyId?: number; } export interface ModifyPortfolioCMOrderReq { @@ -631,6 +633,7 @@ export interface ModifyPortfolioCMOrderReq { price: string; orderId?: number; origClientOrderId?: string; + modifyId?: number; } export interface PortfolioCMModifyOrderResponse { @@ -640,11 +643,11 @@ export interface PortfolioCMModifyOrderResponse { status: string; clientOrderId: string; price: string; - avgPrice: string; + avgPrice?: string; origQty: string; executedQty: string; cumQty: string; - cumBase: string; + cumBase?: string; timeInForce: string; type: 'LIMIT'; reduceOnly: boolean; @@ -652,6 +655,7 @@ export interface PortfolioCMModifyOrderResponse { positionSide: 'LONG' | 'SHORT' | 'BOTH'; origType: 'LIMIT'; updateTime: number; + modifyId?: number; } export interface QueryPortfolioUMOrderReq { @@ -916,6 +920,7 @@ export interface PortfolioUMOrderModificationHistory { time: number; amendment: PortfolioUMOrderAmendment; priceMatch: PMPriceMatch; + modifyId?: number; } export interface QueryPortfolioCMOrderAmendmentReq { @@ -947,6 +952,7 @@ export interface PortfolioCMOrderModificationHistory { clientOrderId: string; time: number; amendment: PortfolioCMOrderAmendment; + modifyId?: number; } export interface QueryPortfolioMarginForceOrdersReq { @@ -991,6 +997,9 @@ export interface PortfolioUMTrade { buyer: boolean; maker: boolean; positionSide: 'BOTH' | 'LONG' | 'SHORT'; + pair?: string; + baseQty?: string; + marginAsset?: string; } export interface QueryPortfolioCMTradesReq { @@ -1019,6 +1028,7 @@ export interface PortfolioCMTrade { positionSide: 'BOTH' | 'LONG' | 'SHORT'; buyer: boolean; maker: boolean; + quoteQty?: string; } export interface PortfolioADLQuantile { diff --git a/src/types/spot.ts b/src/types/spot.ts index ecd3386d..808685cb 100644 --- a/src/types/spot.ts +++ b/src/types/spot.ts @@ -2195,6 +2195,17 @@ export interface UserAsset { btcValuation: string; } +export interface SpotAssetTagsParams { + tag?: string; +} + +export interface SpotAssetTag { + assetCode: string; + assetName: string; + trading: boolean; + tags: string[]; +} + export interface ConvertTransfer { clientTranId: string; asset: string; @@ -4697,6 +4708,14 @@ export interface GetPortfolioMarginProAccountInfoResponse { accountType: string; } +export interface PortfolioDeltaModeStatus { + deltaEnabled: boolean; +} + +export interface SwitchPortfolioDeltaModeParams { + deltaEnabled: 'true' | 'false'; +} + export interface GetPortfolioMarginProCollateralRateResponse { asset: string; collateralRate: string; diff --git a/src/types/websockets/ws-api-requests.ts b/src/types/websockets/ws-api-requests.ts index 41b7d4a4..d5e7a438 100644 --- a/src/types/websockets/ws-api-requests.ts +++ b/src/types/websockets/ws-api-requests.ts @@ -656,6 +656,7 @@ export interface WSAPIFuturesOrderModifyRequest { | 'QUEUE_20'; origType?: string; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + modifyId?: number; recvWindow?: number; timestamp: number; } diff --git a/src/types/websockets/ws-api-responses.ts b/src/types/websockets/ws-api-responses.ts index d6c68086..68f99bd6 100644 --- a/src/types/websockets/ws-api-responses.ts +++ b/src/types/websockets/ws-api-responses.ts @@ -525,6 +525,7 @@ export interface WSAPIFuturesOrder { time?: number; activatePrice?: string; priceRate?: string; + modifyId?: number; } export interface WSAPIFuturesPosition { diff --git a/src/types/websockets/ws-events-formatted.ts b/src/types/websockets/ws-events-formatted.ts index e7fd73f2..815f0f14 100644 --- a/src/types/websockets/ws-events-formatted.ts +++ b/src/types/websockets/ws-events-formatted.ts @@ -369,6 +369,7 @@ export interface WsMessageFuturesUserDataAccountUpdateFormatted transactionTime: number; updateData: { updateEventType: AccountUpdateEventType; + symbol?: string; // only when updateEventType is FUNDING_FEE updatedBalances: WsAccountUpdatedBalance[]; updatedPositions: WsUpdatedPosition[]; }; @@ -440,6 +441,7 @@ export interface WsMessageFuturesUserDataTradeUpdateEventFormatted trailingStopActivationPrice?: number; trailingStopCallbackRate?: number; orderExpireReason?: string; // Order expire reason + modifyId?: string; // from modify request; only when executionType is AMENDMENT pP?: boolean; // ignore si?: number; // ignore ss?: number; // ignore @@ -586,6 +588,7 @@ export interface WsMessageFuturesUserDataAlgoUpdateFormatted reduceOnly: boolean; triggerTime: number; goodTillDate: number; + isActivated?: boolean; // trailing stop activation; placeholder, always false for now }; } diff --git a/src/types/websockets/ws-events-raw.ts b/src/types/websockets/ws-events-raw.ts index 45dab9c0..c7260b3d 100644 --- a/src/types/websockets/ws-events-raw.ts +++ b/src/types/websockets/ws-events-raw.ts @@ -350,6 +350,7 @@ export interface WsMessageFuturesUserDataAccountUpdateRaw extends WsSharedBase { T: number; a: { m: AccountUpdateEventType; + S?: string; // symbol; only when m is FUNDING_FEE B: WsMessageFuturesAccountUpdateBalanceRaw[]; P: WsMessageFuturesAccountUpdatePositionRaw[]; }; @@ -410,6 +411,7 @@ export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw pm: string; gtd: number; er?: string; // Order expire reason (available effective 2025-10-23) + M?: string; // modifyId from modify request; only when x is AMENDMENT }; } @@ -439,6 +441,7 @@ export interface WsMessageFuturesUserDataAlgoUpdateRaw extends WsSharedBase { R: boolean; tt: number; gtd: number; + ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now }; } diff --git a/src/util/beautifier-maps.ts b/src/util/beautifier-maps.ts index 04967763..c78f33b1 100644 --- a/src/util/beautifier-maps.ts +++ b/src/util/beautifier-maps.ts @@ -381,12 +381,15 @@ export const BEAUTIFIER_EVENT_MAP = { gtd: 'goodTillDate', os: 'strategyOrderStatus', ut: 'orderUpdateTime', // Order update Time + er: 'orderExpireReason', + M: 'modifyId', }, ALGO_UPDATEEvent: { e: 'eventType', T: 'transactionTime', // Transaction Time E: 'eventTime', // Event Time o: 'algoOrder', + ao: 'algoOrder', }, algoOrder: { caid: 'clientAlgoId', @@ -410,6 +413,7 @@ export const BEAUTIFIER_EVENT_MAP = { R: 'reduceOnly', tt: 'triggerTime', gtd: 'goodTillDate', + ia: 'isActivated', }, ACCOUNT_CONFIG_UPDATEEvent: { e: 'eventType', @@ -467,6 +471,7 @@ export const BEAUTIFIER_EVENT_MAP = { }, updateData: { m: 'updateEventType', + S: 'symbol', P: 'updatedPositions', B: 'updatedBalances', },