From 992671559cc308a9b0e0be8135e2873a9270f120 Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Mon, 16 Nov 2026 12:18:50 +0100 Subject: [PATCH 1/5] feat(v3.6.13): support Spot order updates and correct legacy helpers - Add Spot expiry reasons, effective STP modes, quote notional limits, shutdown times and subscription filter types. - Document BUY limit order balance-lock releases from 20 November 2026. - Floor tick and step sizes with decimal-safe arithmetic, preserving aligned values (fixes #695) - Route keep-priority order amendments to the Spot endpoint (fixes #696) - Use depth stream names and the default Spot interval in legacy subscriptions (fixes #697) - Correct deprecated broker paths and require referral identifiers (fixes #698) - Update the Node.js version pin to v24.22.3. --- .nvmrc | 2 +- package-lock.json | 4 +- package.json | 2 +- src/main-client.ts | 23 ++++-- src/types/shared.ts | 24 ++++++ src/types/spot.ts | 62 +++++++++++++- src/types/websockets/ws-api-requests.ts | 30 +++++++ src/types/websockets/ws-api-responses.ts | 19 +++-- src/types/websockets/ws-api.ts | 4 +- src/types/websockets/ws-events-formatted.ts | 9 +- src/types/websockets/ws-events-raw.ts | 10 ++- src/util/beautifier-maps.ts | 3 + src/util/beautifier.ts | 1 + src/util/rounding.ts | 91 +++++++++++++-------- src/websocket-client-legacy.ts | 7 +- 15 files changed, 233 insertions(+), 58 deletions(-) diff --git a/.nvmrc b/.nvmrc index 5bcf9c6e..22fbfc06 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v24.18.0 +v24.22.3 diff --git a/package-lock.json b/package-lock.json index fd6840f8..9687c545 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "binance", - "version": "3.6.12", + "version": "3.6.13", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "binance", - "version": "3.6.12", + "version": "3.6.13", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 857926fc..ff7ed690 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "binance", - "version": "3.6.12", + "version": "3.6.13", "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 8361e753..81c0be1b 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -1026,13 +1026,13 @@ export class MainClient extends BaseRestClient { /** * 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 + * https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#order-amend-keep-priority-trade */ amendOrderKeepPriority( params: AmendKeepPriorityParams, ): Promise { this.validateOrderId(params, 'newClientOrderId'); - return this.putPrivate('fapi/v1/order/amend/keepPriority', params); + return this.putPrivate('api/v3/order/amend/keepPriority', params); } getOpenOrders(params?: { symbol?: string }): Promise { @@ -4911,11 +4911,11 @@ export class MainClient extends BaseRestClient { * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ - getBrokerIfNewSpotUser(): Promise<{ + getBrokerIfNewSpotUser(params: { apiAgentCode: string }): Promise<{ rebateWorking: boolean; ifNewUser: boolean; }> { - return this.getPrivate('sapi/v1/apiReferral/ifNewUser'); + return this.getPrivate('sapi/v1/apiReferral/ifNewUser', params); } /** @@ -4925,16 +4925,23 @@ export class MainClient extends BaseRestClient { getBrokerSubAccountDepositHistory( params?: GetBrokerSubAccountDepositHistoryParams, ): Promise { - return this.getPrivate('sapi/v1/bv1/apiReferral/ifNewUser', params); + return this.getPrivate('sapi/v1/broker/subAccount/depositHist', params); } /** * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ - getBrokerUserCustomisedId(market: 'spot' | 'futures') { + getBrokerUserCustomisedId( + ...[market, params]: + | [market: 'spot', params: { apiAgentCode: string }] + | [market: 'futures', params: { brokerId: string }] + ) { const prefix = market === 'spot' ? 'sapi' : 'fapi'; - return this.getPrivate(prefix + '/v1/apiReferral/userCustomization'); + return this.getPrivate( + prefix + '/v1/apiReferral/userCustomization', + params, + ); } /** @@ -4944,7 +4951,7 @@ export class MainClient extends BaseRestClient { enableFuturesBrokerSubAccount( params: EnableFuturesBrokerSubAccountParams, ): Promise { - return this.postPrivate('sapi/v1/broker/subAccount', params); + return this.postPrivate('sapi/v1/broker/subAccount/futures', params); } /** diff --git a/src/types/shared.ts b/src/types/shared.ts index 33144105..2f115dae 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -121,6 +121,26 @@ export type SelfTradePreventionMode = | 'DECREMENT' | 'TRANSFER'; +/** Spot expiry reasons. Unknown strings remain supported for forward compatibility. */ +export type SpotExpiryReason = + | 'NONE' + | 'REJECTED' + | 'EXCHANGE_CANCELED' + | 'OCO_TRIGGER' + | 'OTO_PHASE_ONE_EXPIRED' + | 'UNFILLED_IOC_QUANTITY_EXPIRED' + | 'UNFILLED_FOK_ORDER_EXPIRED' + | 'INSUFFICIENT_LIQUIDITY' + | 'EXECUTION_RULE_PRICE_RANGE_EXCEEDED' + | 'EXHAUSTED' + | 'INSUFFICIENT_QUOTE_NOTIONAL_LIMIT' + | (string & Record); + +export type SpotEffectiveSelfTradePreventionMode = + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'DECREMENT'; + export interface BasicAssetParam { asset: string; } @@ -287,6 +307,8 @@ export interface NewOrderListParams< aboveClientOrderId?: string; aboveIcebergQty?: number; abovePrice?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + aboveQuoteNotionalLimit?: number; aboveStopPrice?: number; aboveTrailingDelta?: number; aboveTimeInForce?: OrderTimeInForce; @@ -296,6 +318,8 @@ export interface NewOrderListParams< belowClientOrderId?: string; belowIcebergQty?: number; belowPrice?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + belowQuoteNotionalLimit?: number; belowStopPrice?: number; belowTrailingDelta?: number; belowTimeInForce?: OrderTimeInForce; diff --git a/src/types/spot.ts b/src/types/spot.ts index 9688678c..0cfbb816 100644 --- a/src/types/spot.ts +++ b/src/types/spot.ts @@ -14,6 +14,8 @@ import { RateLimiter, SelfTradePreventionMode, SideEffects, + SpotEffectiveSelfTradePreventionMode, + SpotExpiryReason, StringBoolean, SymbolFilter, } from './shared'; @@ -467,6 +469,11 @@ export interface ExchangeInfoParams { type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; type SpotPegOffsetType = 'PRICE_LEVEL'; +/** + * From 2026-11-20, BUY limit orders that trade on entry then rest return any lock above + * remaining quantity x limit price to free in the same balance update. Applies to LIMIT GTC, + * triggered STOP_LOSS_LIMIT/TAKE_PROFIT_LIMIT, order-list limits and SOR; icebergs keep the full lock. + */ export interface NewSpotOrderParams< T extends OrderType = OrderType, RT extends OrderResponseType | undefined = OrderResponseType, @@ -477,6 +484,8 @@ export interface NewSpotOrderParams< timeInForce?: OrderTimeInForce; quantity?: number; quoteOrderQty?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: number; price?: number; newClientOrderId?: string; strategyId?: number; @@ -594,6 +603,8 @@ export interface SymbolExchangeInfo { ocoAllowed: boolean; opoAllowed: boolean; quoteOrderQtyMarketAllowed: boolean; + marketQuoteNotionalLimitAllowed?: boolean; + limitQuoteNotionalLimitAllowed?: boolean; allowTrailingStop: boolean; cancelReplaceAllowed: boolean; isSpotTradingAllowed: boolean; @@ -780,6 +791,7 @@ export interface OrderResponseACK { /** Conditional fields on POST /api/v3/order RESULT/FULL. Only present when the matching condition is met. */ export interface SpotNewOrderConditionalFields { + quoteNotionalLimit?: numberInString; icebergQty?: numberInString; preventedMatchId?: number; preventedQuantity?: numberInString; @@ -812,7 +824,7 @@ export interface OrderResponseResult extends SpotNewOrderConditionalFields { workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } export interface OrderFill { @@ -823,6 +835,11 @@ export interface OrderFill { tradeId: number; } +export interface SpotOrderPreventedMatch { + /** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ + effectiveSelfTradePreventionMode?: SpotEffectiveSelfTradePreventionMode; +} + export interface OrderResponseFull extends SpotNewOrderConditionalFields { symbol: string; orderId: number; @@ -844,8 +861,9 @@ export interface OrderResponseFull extends SpotNewOrderConditionalFields { workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; fills: OrderFill[]; + preventedMatches?: SpotOrderPreventedMatch[]; } export type OrderResponse = @@ -871,7 +889,7 @@ export interface OrderListOrder { orderId: number; clientOrderId: string; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } export interface OrderListResponse { @@ -939,6 +957,7 @@ export interface SORTestOrderResponse { } export interface CancelSpotOrderResult { + quoteNotionalLimit?: numberInString; symbol: string; origClientOrderId: string; orderId: number; @@ -1017,6 +1036,7 @@ export interface ReplaceSpotOrderResultSuccess< } export interface SpotOrder { + quoteNotionalLimit?: numberInString; symbol: string; orderId: number; orderListId: number; @@ -1037,13 +1057,15 @@ export interface SpotOrder { origQuoteOrderQty: numberInString; selfTradePreventionMode: SelfTradePreventionMode; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } export interface SpotAmendKeepPriorityResult { transactTime: number; executionId: number; amendedOrder: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; symbol: string; orderId: number; orderListId: number; @@ -2762,6 +2784,8 @@ export interface NewOrderListOTOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; @@ -2771,6 +2795,8 @@ export interface NewOrderListOTOParams { pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: string; pendingStopPrice?: string; pendingTrailingDelta?: string; pendingQuantity: string; @@ -2794,6 +2820,9 @@ export interface NewOrderListOTOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -2821,6 +2850,8 @@ export interface NewOrderListOTOCOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; @@ -2831,6 +2862,8 @@ export interface NewOrderListOTOCOParams { pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: string; pendingAboveStopPrice?: string; pendingAboveTrailingDelta?: string; pendingAboveIcebergQty?: string; @@ -2840,6 +2873,8 @@ export interface NewOrderListOTOCOParams { pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; pendingBelowClientOrderId?: string; pendingBelowPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: string; pendingBelowStopPrice?: string; pendingBelowTrailingDelta?: string; pendingBelowIcebergQty?: string; @@ -2862,6 +2897,9 @@ export interface NewOrderListOTOCOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -2890,6 +2928,8 @@ export interface NewOrderListOPOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; @@ -2902,6 +2942,8 @@ export interface NewOrderListOPOParams { pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: string; pendingStopPrice?: string; pendingTrailingDelta?: string; pendingIcebergQty?: string; @@ -2927,6 +2969,9 @@ export interface NewOrderListOPOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -2955,6 +3000,8 @@ export interface NewOrderListOPOCOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; @@ -2972,6 +3019,8 @@ export interface NewOrderListOPOCOParams { | 'TAKE_PROFIT_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: string; pendingAboveStopPrice?: string; pendingAboveTrailingDelta?: string; pendingAboveIcebergQty?: string; @@ -2988,6 +3037,8 @@ export interface NewOrderListOPOCOParams { | 'TAKE_PROFIT_LIMIT'; pendingBelowClientOrderId?: string; pendingBelowPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: string; pendingBelowStopPrice?: string; pendingBelowTrailingDelta?: string; pendingBelowIcebergQty?: string; @@ -3013,6 +3064,9 @@ export interface NewOrderListOPOCOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; diff --git a/src/types/websockets/ws-api-requests.ts b/src/types/websockets/ws-api-requests.ts index ed2cf346..6db39a44 100644 --- a/src/types/websockets/ws-api-requests.ts +++ b/src/types/websockets/ws-api-requests.ts @@ -226,6 +226,8 @@ export interface WSAPINewSpotOrderRequest { price?: numberInString; quantity?: numberInString; quoteOrderQty?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: numberInString; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; stopPrice?: numberInString; @@ -247,6 +249,8 @@ export interface WSAPIOrderTestRequest { price?: numberInString; quantity?: numberInString; quoteOrderQty?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: numberInString; newClientOrderId?: string; stopPrice?: numberInString; trailingDelta?: number; @@ -292,6 +296,8 @@ export interface WSAPIOrderCancelReplaceRequest { price?: numberInString; quantity?: numberInString; quoteOrderQty?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: numberInString; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; stopPrice?: numberInString; @@ -372,6 +378,8 @@ export interface WSAPIOrderListPlaceOCORequest { aboveClientOrderId?: string; aboveIcebergQty?: numberInString; abovePrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + aboveQuoteNotionalLimit?: numberInString; aboveStopPrice?: numberInString; aboveTrailingDelta?: number; aboveTimeInForce?: string; @@ -386,6 +394,8 @@ export interface WSAPIOrderListPlaceOCORequest { belowClientOrderId?: string; belowIcebergQty?: numberInString; belowPrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + belowQuoteNotionalLimit?: numberInString; belowStopPrice?: numberInString; belowTrailingDelta?: number; belowTimeInForce?: string; @@ -406,6 +416,8 @@ export interface WSAPIOrderListPlaceOTORequest { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: numberInString; workingQuantity: numberInString; workingIcebergQty?: numberInString; workingTimeInForce?: string; @@ -415,6 +427,8 @@ export interface WSAPIOrderListPlaceOTORequest { pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: numberInString; pendingStopPrice?: numberInString; pendingTrailingDelta?: numberInString; pendingQuantity: numberInString; @@ -435,6 +449,8 @@ export interface WSAPIOrderListPlaceOTOCORequest { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: numberInString; workingQuantity: numberInString; workingIcebergQty?: numberInString; workingTimeInForce?: string; @@ -450,6 +466,8 @@ export interface WSAPIOrderListPlaceOTOCORequest { | 'TAKE_PROFIT_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: numberInString; pendingAboveStopPrice?: numberInString; pendingAboveTrailingDelta?: numberInString; pendingAboveIcebergQty?: numberInString; @@ -464,6 +482,8 @@ export interface WSAPIOrderListPlaceOTOCORequest { | 'LIMIT_MAKER'; pendingBelowClientOrderId?: string; pendingBelowPrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: numberInString; pendingBelowStopPrice?: numberInString; pendingBelowTrailingDelta?: numberInString; pendingBelowIcebergQty?: numberInString; @@ -483,6 +503,8 @@ export interface WSAPIOrderListPlaceOPORequest { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: numberInString; workingQuantity: numberInString; workingIcebergQty?: numberInString; workingTimeInForce?: string; @@ -495,6 +517,8 @@ export interface WSAPIOrderListPlaceOPORequest { pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: numberInString; pendingStopPrice?: numberInString; pendingTrailingDelta?: numberInString; pendingIcebergQty?: numberInString; @@ -517,6 +541,8 @@ export interface WSAPIOrderListPlaceOPOCORequest { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: numberInString; workingQuantity: numberInString; workingIcebergQty?: numberInString; workingTimeInForce?: string; @@ -534,6 +560,8 @@ export interface WSAPIOrderListPlaceOPOCORequest { | 'TAKE_PROFIT_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: numberInString; pendingAboveStopPrice?: numberInString; pendingAboveTrailingDelta?: numberInString; pendingAboveIcebergQty?: numberInString; @@ -550,6 +578,8 @@ export interface WSAPIOrderListPlaceOPOCORequest { | 'TAKE_PROFIT_LIMIT'; pendingBelowClientOrderId?: string; pendingBelowPrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: numberInString; pendingBelowStopPrice?: numberInString; pendingBelowTrailingDelta?: numberInString; pendingBelowIcebergQty?: numberInString; diff --git a/src/types/websockets/ws-api-responses.ts b/src/types/websockets/ws-api-responses.ts index ac40765c..4d01e3f2 100644 --- a/src/types/websockets/ws-api-responses.ts +++ b/src/types/websockets/ws-api-responses.ts @@ -11,8 +11,13 @@ import { OrderSide, OrderTimeInForce, SelfTradePreventionMode, + SpotExpiryReason, } from '../shared'; -import { OrderResponse, SpotNewOrderConditionalFields } from '../spot'; +import { + OrderResponse, + SpotNewOrderConditionalFields, + SpotOrderPreventedMatch, +} from '../spot'; /** * Error response type @@ -236,6 +241,7 @@ export interface WSAPIRateLimit { } export interface WSAPIOrder { + quoteNotionalLimit?: numberInString; symbol: string; orderId: number; orderListId: number; @@ -259,7 +265,7 @@ export interface WSAPIOrder { preventedMatchId?: number; preventedQuantity?: numberInString; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } export interface WSAPIBlockTrade { @@ -362,6 +368,7 @@ export interface WSAPIOrderTestWithCommission { } export interface WSAPIOrderCancel { + quoteNotionalLimit?: numberInString; symbol: string; origClientOrderId: string; orderId: number; @@ -441,7 +448,7 @@ export interface WSAPIOrderListStatusResponse { orderId: number; clientOrderId: string; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; }[]; } @@ -449,6 +456,7 @@ export interface WSAPIOrderListStatusResponse { * SOR response types */ export interface WSAPISOROrderPlaceResponse { + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -465,7 +473,7 @@ export interface WSAPISOROrderPlaceResponse { side: string; workingTime: number; /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; fills: { matchType: string; price: string; @@ -713,7 +721,7 @@ export interface WSAPISpotOrderRESULT workingTime: number; selfTradePreventionMode: string; /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } export interface WSAPISpotOrderFill { @@ -726,6 +734,7 @@ export interface WSAPISpotOrderFill { export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { fills: WSAPISpotOrderFill[]; + preventedMatches?: SpotOrderPreventedMatch[]; } export type WSAPISpotOrderResponse = diff --git a/src/types/websockets/ws-api.ts b/src/types/websockets/ws-api.ts index 1557d96a..82dc0fde 100644 --- a/src/types/websockets/ws-api.ts +++ b/src/types/websockets/ws-api.ts @@ -443,7 +443,9 @@ export interface WsAPITopicRequestParamMap { 'userDataStream.start': { apiKey: string }; 'userDataStream.ping': WSAPIUserDataListenKeyRequest; 'userDataStream.stop': WSAPIUserDataListenKeyRequest; - 'userDataStream.subscribe': void; + 'userDataStream.subscribe': void | { + filter?: { e?: string[]; s?: string[]; a?: string[]; x?: string[] }; + }; 'userDataStream.subscribe.signature': { timestamp: number }; 'userDataStream.unsubscribe': void; diff --git a/src/types/websockets/ws-events-formatted.ts b/src/types/websockets/ws-events-formatted.ts index 08e7b06e..8072c8c7 100644 --- a/src/types/websockets/ws-events-formatted.ts +++ b/src/types/websockets/ws-events-formatted.ts @@ -22,6 +22,8 @@ import { OrderTimeInForce, OrderType, SelfTradePreventionMode, + SpotEffectiveSelfTradePreventionMode, + SpotExpiryReason, } from '../shared'; import { AccountUpdateEventType, @@ -284,7 +286,10 @@ export interface WsMessageSpotUserDataExecutionReportEventFormatted orderQuoteQty: number; workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; - expiryReason?: string; + expiryReason?: SpotExpiryReason; + /** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ + effectiveSelfTradePreventionMode?: SpotEffectiveSelfTradePreventionMode; + quoteNotionalLimit?: number; trailingDelta?: number; preventedMatchId?: number; trailingTime?: number; @@ -318,6 +323,8 @@ export interface WsMessagePortfolioMarginProAccountUpdateFormatted export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { eventType: 'serverShutdown'; eventTime: number; + /** Time when the WebSocket session will shut down. */ + shutdownTime?: number; } export interface OrderObjectFormatted { diff --git a/src/types/websockets/ws-events-raw.ts b/src/types/websockets/ws-events-raw.ts index 6f37cb3f..cf23c7dd 100644 --- a/src/types/websockets/ws-events-raw.ts +++ b/src/types/websockets/ws-events-raw.ts @@ -21,6 +21,8 @@ import { OrderTimeInForce, OrderType, SelfTradePreventionMode, + SpotEffectiveSelfTradePreventionMode, + SpotExpiryReason, } from '../shared'; import { WsSharedBase } from './ws-general'; @@ -247,7 +249,11 @@ export interface WsMessageSpotUserDataExecutionReportEventRaw W: number; V: SelfTradePreventionMode; /** Expiry reason when present (user data executionReport). */ - eR?: string; + eR?: SpotExpiryReason; + /** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ + eV?: SpotEffectiveSelfTradePreventionMode; + /** Present only when the order has a quote notional limit. */ + Qq?: numberInString; d?: number; v?: number; D?: number; @@ -281,6 +287,8 @@ export interface WsMessagePortfolioMarginProAccountUpdateRaw export interface WsMessageWsapiServerShutdownRaw extends WsSharedBase { e: 'serverShutdown'; E: number; + /** Time when the WebSocket session will shut down. */ + T?: number; } export interface OrderObjectRaw { diff --git a/src/util/beautifier-maps.ts b/src/util/beautifier-maps.ts index 11019668..0a98d373 100644 --- a/src/util/beautifier-maps.ts +++ b/src/util/beautifier-maps.ts @@ -473,6 +473,7 @@ export const BEAUTIFIER_EVENT_MAP = { serverShutdownEvent: { e: 'eventType', E: 'eventTime', + T: 'shutdownTime', }, updateData: { m: 'updateEventType', @@ -544,6 +545,8 @@ export const BEAUTIFIER_EVENT_MAP = { W: 'workingTime', V: 'selfTradePreventionMode', eR: 'expiryReason', + eV: 'effectiveSelfTradePreventionMode', + Qq: 'quoteNotionalLimit', d: 'trailingDelta', v: 'preventedMatchId', D: 'trailingTime', diff --git a/src/util/beautifier.ts b/src/util/beautifier.ts index 0d26c985..4106a4a2 100644 --- a/src/util/beautifier.ts +++ b/src/util/beautifier.ts @@ -120,6 +120,7 @@ export default class Beautifier { 'qty', 'quoteAssetVolume', 'quoteVolume', + 'quoteNotionalLimit', 'quoteVolumeActive', 'realisedProfit', 'sellerCommission', diff --git a/src/util/rounding.ts b/src/util/rounding.ts index c6d95425..229a88d5 100644 --- a/src/util/rounding.ts +++ b/src/util/rounding.ts @@ -1,43 +1,70 @@ -/** - * Rounds a price to the correct number of decimal places based on the symbol's tick size - */ -export function roundToTickSize(price: number, tickSize: string): number { - if (!tickSize) { - return price; - } +/** Parse a decimal, including exponent notation, without floating-point scaling. */ +function parseDecimal(value: string): { coefficient: bigint; scale: number } { + const [mantissa, exponent = '0'] = value.toLowerCase().split('e'); + const fraction = mantissa.split('.')[1] || ''; + return { + coefficient: BigInt(mantissa.replace('.', '')), + scale: fraction.length - Number(exponent), + }; +} - // Calculate precision from tick size (e.g., 0.00010000 → 4 decimal places) - const precision = tickSize.indexOf('1') - 1; - if (precision < 0) { - return Math.floor(price); +function floorToIncrement(value: number, increment: string): number { + if (!increment) { + return value; } - // Round to the nearest tick - const tickSizeNum = parseFloat(tickSize); - const rounded = Math.floor(price / tickSizeNum) * tickSizeNum; + const decimalIncrement = increment.trim(); + const incrementNumber = Number(decimalIncrement); + if ( + !/^\+?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(decimalIncrement) || + !Number.isFinite(incrementNumber) || + !Number.isFinite(value) + ) { + throw new RangeError( + 'Value must be finite and increment must be a nonnegative decimal', + ); + } - // Format with correct precision - return +rounded.toFixed(precision); -} + const step = parseDecimal(decimalIncrement); + if (!Number.isSafeInteger(step.scale)) { + throw new RangeError('Increment exponent is outside the supported range'); + } -/** - * Rounds a quantity to the correct step size - */ -export function roundToStepSize(quantity: number, stepSize: string): number { - if (!stepSize) { - return quantity; + // A zero tick/step disables the corresponding exchange filter. + if (step.coefficient === BigInt(0) || value === 0) { + return value; } - // Calculate precision from step size - const precision = stepSize.indexOf('1') - 1; - if (precision < 0) { - return Math.floor(quantity); + const amount = parseDecimal(String(value)); + const scale = Math.max(amount.scale, step.scale, 0); + const amountInteger = + amount.coefficient * BigInt('1' + '0'.repeat(scale - amount.scale)); + const stepInteger = + step.coefficient * BigInt('1' + '0'.repeat(scale - step.scale)); + let steps = amountInteger / stepInteger; + + // BigInt division truncates toward zero; preserve mathematical floor for negatives. + if (amountInteger < BigInt(0) && amountInteger % stepInteger !== BigInt(0)) { + steps -= BigInt(1); } - // Round to the nearest step - const stepSizeNum = parseFloat(stepSize); - const rounded = Math.floor(quantity / stepSizeNum) * stepSizeNum; + return Number(`${steps * stepInteger}e-${scale}`); +} + +/** + * Floors a price to a multiple of the tick size using decimal arithmetic. + * Empty or zero tick sizes leave it unchanged; invalid sizes or non-finite prices throw RangeError. + * Inputs and the returned number remain subject to JavaScript number precision limits. + */ +export function roundToTickSize(price: number, tickSize: string): number { + return floorToIncrement(price, tickSize); +} - // Format with correct precision - return +rounded.toFixed(precision); +/** + * Floors a quantity to a multiple of the step size using decimal arithmetic. + * Empty or zero step sizes leave it unchanged; invalid sizes or non-finite quantities throw RangeError. + * Inputs and the returned number remain subject to JavaScript number precision limits. + */ +export function roundToStepSize(quantity: number, stepSize: string): number { + return floorToIncrement(quantity, stepSize); } diff --git a/src/websocket-client-legacy.ts b/src/websocket-client-legacy.ts index 1ee7c377..b8c17f7a 100644 --- a/src/websocket-client-legacy.ts +++ b/src/websocket-client-legacy.ts @@ -1613,7 +1613,7 @@ export class WebsocketClientV1 extends EventEmitter { forceNewConnection?: boolean, ): WebSocket { const lowerCaseSymbol = symbol.toLowerCase(); - const streamName = 'diffBookDepth'; + const streamName = 'depth'; const wsKey = getLegacyWsStoreKeyWithContext( market, 'diffBookDepth', @@ -1621,7 +1621,10 @@ export class WebsocketClientV1 extends EventEmitter { String(updateMs), ); - const updateMsSuffx = typeof updateMs === 'number' ? `@${updateMs}ms` : ''; + const updateMsSuffx = + typeof updateMs === 'number' && !(market === 'spot' && updateMs === 1000) + ? `@${updateMs}ms` + : ''; return this.connectToWsUrl( this.getWsBaseUrl(market, wsKey) + From 892f65b0982d72e613a61ca792f8a681adde5a97 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 16 Nov 2026 13:05:12 +0100 Subject: [PATCH 2/5] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 80 +- .../MainClient/amendOrderKeepPriority.js | 2 +- .../enableFuturesBrokerSubAccount.js | 2 +- .../getBrokerSubAccountDepositHistory.js | 2 +- llms.txt | 13580 ++++++++-------- 5 files changed, 6936 insertions(+), 6730 deletions(-) diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 91d34e34..12d3a729 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -76,7 +76,7 @@ This table includes all endpoints from the official Exchange API docs and corres | [cancelOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1007) | :closed_lock_with_key: | DELETE | `api/v3/order` | | [cancelAllSymbolOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1011) | :closed_lock_with_key: | DELETE | `api/v3/openOrders` | | [replaceOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1017) | :closed_lock_with_key: | POST | `api/v3/order/cancelReplace` | -| [amendOrderKeepPriority()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1031) | :closed_lock_with_key: | PUT | `fapi/v1/order/amend/keepPriority` | +| [amendOrderKeepPriority()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1031) | :closed_lock_with_key: | PUT | `api/v3/order/amend/keepPriority` | | [getOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1038) | :closed_lock_with_key: | GET | `api/v3/openOrders` | | [getAllOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1042) | :closed_lock_with_key: | GET | `api/v3/allOrders` | | [submitNewOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1049) | :closed_lock_with_key: | POST | `api/v3/order/oco` | @@ -549,45 +549,45 @@ This table includes all endpoints from the official Exchange API docs and corres | [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4871) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | | [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4877) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | | [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4914) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | -| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4925) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | -| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4944) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4954) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | -| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4995) | | POST | `api/v3/userDataStream` | -| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4999) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | -| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5003) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | -| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5010) | | POST | `sapi/v1/userDataStream` | -| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5014) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5018) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5023) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5031) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5040) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5052) | | POST | `sapi/v1/margin/listen-key` | -| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5056) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5060) | | DELETE | `sapi/v1/margin/listen-key` | -| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5072) | | POST | `sapi/v2/margin/listen-key` | -| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5080) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5088) | | DELETE | `sapi/v2/margin/listen-key` | -| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5092) | | POST | `sapi/v2/margin/uta/listen-key` | -| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5096) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | -| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5100) | | DELETE | `sapi/v2/margin/uta/listen-key` | -| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5108) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | -| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5130) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | -| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5137) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | -| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5146) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | -| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5155) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | -| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5170) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | -| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5179) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | -| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5193) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | -| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5203) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | -| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5212) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | -| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5221) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | -| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5228) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | -| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5235) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | -| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5242) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | -| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5249) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | -| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5266) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | -| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5274) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | -| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5281) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | +| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4925) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | +| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4951) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | +| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4961) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | +| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5002) | | POST | `api/v3/userDataStream` | +| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5006) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | +| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5010) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | +| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5017) | | POST | `sapi/v1/userDataStream` | +| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5021) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5025) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5030) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5038) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5047) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5059) | | POST | `sapi/v1/margin/listen-key` | +| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5063) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5067) | | DELETE | `sapi/v1/margin/listen-key` | +| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5079) | | POST | `sapi/v2/margin/listen-key` | +| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5087) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5095) | | DELETE | `sapi/v2/margin/listen-key` | +| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5099) | | POST | `sapi/v2/margin/uta/listen-key` | +| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5103) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | +| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5107) | | DELETE | `sapi/v2/margin/uta/listen-key` | +| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5115) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | +| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5137) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | +| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5144) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | +| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5153) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | +| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5162) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | +| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5177) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | +| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5186) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | +| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5200) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | +| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5210) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | +| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5219) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | +| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5228) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | +| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5235) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | +| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5242) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | +| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5249) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | +| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5256) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | +| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5273) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | +| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5281) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | +| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5288) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | # usdm-client.ts diff --git a/examples/apidoc/MainClient/amendOrderKeepPriority.js b/examples/apidoc/MainClient/amendOrderKeepPriority.js index aad3ef11..6f963060 100644 --- a/examples/apidoc/MainClient/amendOrderKeepPriority.js +++ b/examples/apidoc/MainClient/amendOrderKeepPriority.js @@ -4,7 +4,7 @@ import { MainClient } from '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: fapi/v1/order/amend/keepPriority +// ENDPOINT: api/v3/order/amend/keepPriority // METHOD: PUT // PUBLIC: NO diff --git a/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js b/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js index d3f4698b..169a774b 100644 --- a/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js +++ b/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js @@ -4,7 +4,7 @@ import { MainClient } from '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/broker/subAccount +// ENDPOINT: sapi/v1/broker/subAccount/futures // METHOD: POST // PUBLIC: NO diff --git a/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js b/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js index 7fcf832f..8042edc4 100644 --- a/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js +++ b/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js @@ -4,7 +4,7 @@ import { MainClient } from '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/bv1/apiReferral/ifNewUser +// ENDPOINT: sapi/v1/broker/subAccount/depositHist // METHOD: GET // PUBLIC: NO diff --git a/llms.txt b/llms.txt index c324c03c..6d721e2d 100644 --- a/llms.txt +++ b/llms.txt @@ -3517,6 +3517,15 @@ High level summary for some of the available examples, but check the folder for - `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: examples/Rest/Futures/rest-future-bracket-order.ts +================ +import { + FuturesNewAlgoOrderParams, + NewFuturesOrderParams, + USDMClient, +} from '../../../src/index'; + ================ File: src/types/websockets/ws-api.ts ================ @@ -3917,7 +3926,9 @@ export interface WsAPITopicRequestParamMap { 'userDataStream.start': { apiKey: string }; 'userDataStream.ping': WSAPIUserDataListenKeyRequest; 'userDataStream.stop': WSAPIUserDataListenKeyRequest; - 'userDataStream.subscribe': void; + 'userDataStream.subscribe': void | { + filter?: { e?: string[]; s?: string[]; a?: string[]; x?: string[] }; + }; 'userDataStream.subscribe.signature': { timestamp: number }; 'userDataStream.unsubscribe': void; @@ -4186,15 +4197,6 @@ export interface WsAPIOperationResponseMap { * SOR responses */ -================ -File: examples/Rest/Futures/rest-future-bracket-order.ts -================ -import { - FuturesNewAlgoOrderParams, - NewFuturesOrderParams, - USDMClient, -} from '../../../src/index'; - ================ File: src/websocket-api-client.ts ================ @@ -5250,3621 +5252,3091 @@ private handleWSReconnectedEvent(params: { wsKey: WsKey }) // Queue resubscribe workflow ================ -File: src/websocket-client-legacy.ts +File: .nvmrc ================ -/* 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; +v24.22.3 - 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; +================ +File: src/types/portfolio-margin.ts +================ +// Enums +export type PMStrategyType = + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; ⋮---- -on( - event: 'open' | 'reconnected', - listener: (event: { - wsKey: WsKey; - ws: WebSocket.Event; - event?: any; - }) => void, - ): this; +export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- -on( - event: 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; +export type PMPriceMatch = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; ⋮---- -/** - * @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 +export type PMSelfTradePreventionMode = + | 'NONE' + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH'; ⋮---- -constructor( - options: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, - ) +export type PMMarginOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -// Some defaults: +export type PMMarginSideEffectType = + | 'NO_SIDE_EFFECT' + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'AUTO_BORROW_REPAY'; ⋮---- -// Automatically send an authentication op/request after a connection opens, for private connections. +export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; ⋮---- -// Individual requests require a signature +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 +} ⋮---- -// add default error handling so this doesn't crash node (if the user didn't set a handler) +positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode ⋮---- -private getRestClientOptions(): RestClientOptions +reduceOnly?: boolean; // Cannot be sent in Hedge Mode ⋮---- -public connectToWsUrl( - url: string, - wsKey?: WsKey | string, - forceNewConnection?: boolean, - ): WebSocket +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 ⋮---- -// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -// Add ws connection with key to store +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; +} ⋮---- -public tryWsSend(wsKey: WsKey | string, wsMessage: string) +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; +} ⋮---- -public tryWsPing(wsKey: WsKey | string) -⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +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; +} ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +export type PortfolioUMAlgoType = 'CONDITIONAL'; ⋮---- -private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) +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; +} ⋮---- -private onWsClose( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - wsUrl: string, - ) +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; +} ⋮---- -// Clear any timers before we initiate revival +export interface CancelPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states +export interface PortfolioUMCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} ⋮---- -private onWsMessage( - event: WebSocket.MessageEvent, - wsKey: WsKey | string, - source: WsEventInternalSrc, - ) +export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { + code: number; + msg: string; +} ⋮---- -// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e +export interface QueryPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn +export interface QueryPortfolioAllUMAlgoOrdersReq { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// emit a separate event for user data messages +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'; +} ⋮---- -private sendPing(wsKey: WsKey | string, wsUrl: string) +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; +} ⋮---- -private onWsPing( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - source: WsEventInternalSrc, - ) +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; +} ⋮---- -private onWsPong( - event: any, - wsKey: WsKey | string, - source: WsEventInternalSrc, - ) +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; +} ⋮---- -/** - * 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, - ) +export interface MarginOrderFill { + price: string; + qty: string; + commission: string; + commissionAsset: string; +} ⋮---- -public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) +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; +} ⋮---- -public closeAll(shouldReconnectAfterClose?: 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[]; +} ⋮---- -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 +export interface PortfolioMarginOCOOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -private clearTimers(wsKey: WsKey | 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; +} ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: WsKey | 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; +} ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: WsKey | string) +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[]; +} ⋮---- -// Timer tracking that a reconnect is about to happen / in progress -private clearReconnectTimer(wsKey: WsKey | string) +// Add new interfaces for canceling UM orders +export interface CancelPortfolioUMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): 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; +} ⋮---- -public getWs(wsKey: WsKey | string): WebSocket | undefined +export interface CancelPortfolioUMConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) +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; +} ⋮---- -/** - * Send WS message to subscribe to topics. Use subscribe() to call this. - */ -private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) +export interface CancelPortfolioCMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. - */ -private requestUnsubscribeTopics(wsKey: WsKey, topics: 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; +} ⋮---- -/** - * Send WS message to unsubscribe from topics. - */ -public requestListSubscriptions(wsKey: WsKey, requestId: number) +export interface CancelPortfolioCMConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -/** - * Send WS message to set property state - */ -public requestSetProperty( - wsKey: WsKey, - property: 'combined' | string, - value: any, - requestId: number, - ) +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; +} ⋮---- -/** - * Send WS message to get property state - */ -public requestGetProperty( - wsKey: WsKey, - property: 'combined' | string, - requestId: number, - ) +export interface CancelPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -/** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ +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'; +} ⋮---- -private setKeepAliveListenKeyTimer( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +export interface CancelPortfolioMarginOCOReq { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -// Set timer to keep WS alive every 50 minutes +export interface PortfolioMarginOCOCancelOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -// 1000 * 60 +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; +} ⋮---- -private sendKeepAliveForMarket( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +export interface PortfolioMarginOCOCancelResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOCancelOrder[]; + orderReports: PortfolioMarginOCOCancelOrderReport[]; +} ⋮---- -private async checkKeepAliveListenKey( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +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; +} ⋮---- -// Simple way to test keep alive failure handling: -// throw new Error(`Fake keep alive failure`); +export interface PortfolioMarginCancelAllOrdersOCOReport { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOCancelOrder[]; + orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; +} ⋮---- -// code: -1125, -// message: 'This listenKey does not exist.', +export type PortfolioMarginCancelAllOrdersResponse = + | PortfolioMarginCancelAllOrdersOrderReport + | PortfolioMarginCancelAllOrdersOCOReport; ⋮---- -// If max failurees reached, tear down and respawn if allowed +export interface ModifyPortfolioUMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: string; + price: string; + orderId?: number; + origClientOrderId?: string; + priceMatch?: PMPriceMatch; + modifyId?: number; +} ⋮---- -// 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 +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; +} ⋮---- -// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) +export interface ModifyPortfolioCMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: string; + price: string; + orderId?: number; + origClientOrderId?: string; + modifyId?: number; +} ⋮---- -private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) +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; +} ⋮---- -private async respawnUserDataStream( - market: WsMarket, - symbol?: string, - isTestnet?: boolean, - respawnAttempt?: number, - ): Promise +export interface QueryPortfolioUMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -// 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 +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; +} ⋮---- -// This timer should probably be tracked/singleton +export interface QueryPortfolioAllUMOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ +export interface QueryPortfolioUMOpenOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Subscribe to a universal market websocket stream - */ +export interface QueryPortfolioAllUMConditionalOrdersReq { + symbol?: string; + strategyId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioUMOpenConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -/** - * 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 +export interface QueryPortfolioUMConditionalOrderHistoryReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeBlockTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioCMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Subscribe to coin index for a symbol in COINM Futures markets - * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. - */ -public subscribeCoinIndexPrice( - symbol: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface QueryPortfolioAllCMOrdersReq { + symbol: string; + pair?: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * 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 +export interface QueryPortfolioCMOpenOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioAllCMConditionalOrdersReq { + symbol?: string; + strategyId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * 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 +export interface QueryPortfolioCMConditionalOrderHistoryReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioCMConditionalHistoryOrder + extends PortfolioCMConditionalOrder { + priceMatch: PMPriceMatch; +} ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioUMForceOrdersReq { + symbol?: string; + autoCloseType?: PMAutoCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioCMForceOrdersReq { + symbol?: string; + autoCloseType?: PMAutoCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioUMOrderAmendmentReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * 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 +export interface PortfolioUMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioUMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioUMOrderAmendment; + priceMatch: PMPriceMatch; + modifyId?: number; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioCMOrderAmendmentReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioCMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioCMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioCMOrderAmendment; + modifyId?: number; +} ⋮---- -/** - * 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 +export interface QueryPortfolioMarginForceOrdersReq { + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 +} ⋮---- -/** - * 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 +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioMarginForceOrder { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + updatedTime: number; +} ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +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 +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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 +} ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 50; max 1000 ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - forceNewConnection?: boolean, - ): WebSocket +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) +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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) ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket +export interface QueryPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket +export interface QueryPortfolioMarginAllOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} ⋮---- -/** - * 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 +limit?: number; // Default 500; max 500 ⋮---- -/** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioMarginOCOReq { + orderListId?: number; // Either orderListId or origClientOrderId must be provided + origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +} ⋮---- -/** - * 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 +orderListId?: number; // Either orderListId or origClientOrderId must be provided +origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +export interface PortfolioMarginOCOQueryOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -/** - * 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 +export interface PortfolioMarginOCO { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOQueryOrder[]; +} ⋮---- -/** - * Subscribe to margin user data stream - listen key is automatically generated. - */ -public async subscribeMarginUserDataStream( - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +export interface QueryPortfolioMarginAllOCOReq { + fromId?: number; // If supplied, neither startTime or endTime can be provided + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +fromId?: number; // If supplied, neither startTime or endTime can be provided ⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +limit?: number; // Default 500; max 500 ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +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 +} ⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ +fromId?: number; // TradeId to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 ⋮---- -/** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeUsdFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +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; +} ⋮---- -// Necessary so client knows this is a reconnect +export interface PortfolioMarginRepayDebtReq { + asset: string; + amount?: string; + specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas +} ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas ⋮---- -/** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeCoinFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +export interface PortfolioMarginRepayDebtResponse { + amount: string; + asset: string; + specifyRepayAssets: string[]; + updateTime: number; + success: boolean; +} ⋮---- -// Necessary so client knows this is a reconnect +/** + * + * DERIVATIVES - ACCOUNT endpoints + * + **/ ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) - -================ -File: .nvmrc -================ -v24.18.0 - -================ -File: src/types/portfolio-margin.ts -================ -// Enums -export type PMStrategyType = - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; +export type PMAccountStatus = + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; ⋮---- -export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; +export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- -export type PMPriceMatch = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; +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; +} ⋮---- -export type PMSelfTradePreventionMode = - | 'NONE' - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH'; +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 type PMMarginOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +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; +} ⋮---- -export type PMMarginSideEffectType = - | 'NO_SIDE_EFFECT' - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'AUTO_BORROW_REPAY'; +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 PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; ⋮---- -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 +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 } ⋮---- -positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode +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 ⋮---- -reduceOnly?: boolean; // Cannot be sent in Hedge Mode +accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD ⋮---- -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 +virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +totalMarginOpenLoss: string; // in USD margin open order +updateTime: number; // last update time ⋮---- -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; +export interface PortfolioUMPosition { symbol: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate?: number; + positionAmt: string; + entryPrice: string; + markPrice: string; + unRealizedProfit: string; + liquidationPrice: string; + leverage: string; + maxNotionalValue: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + notional: string; updateTime: number; - priceMatch: PMPriceMatch; } ⋮---- -export interface NewPortfolioUMConditionalOrderReq { +export interface PortfolioCMPosition { 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'; + positionAmt: string; + entryPrice: string; + markPrice: string; + unRealizedProfit: string; + liquidationPrice: string; + leverage: string; 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; + maxQty: string; + notionalValue: string; } ⋮---- -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 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 } ⋮---- -export interface CancelPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; -} +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 PortfolioUMCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; +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 } ⋮---- -export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { - code: number; - msg: string; -} +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 QueryPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; +export interface PortfolioTradingIndicator { + isLocked: boolean; + plannedRecoverTime: number; + indicator: PMIndicatorType; + value: number; + triggerValue: number; } ⋮---- -export interface QueryPortfolioAllUMAlgoOrdersReq { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - limit?: number; +export interface PortfolioTradingStatus { + indicators: { + [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" + }; + updateTime: 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'; -} +[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" ⋮---- -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 PortfolioMarginLoanRecord { + txId: number; + asset: string; + principal: string; + timestamp: number; + status: PMMarginLoanStatus; } ⋮---- -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 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 } ⋮---- -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; -} +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 MarginOrderFill { - price: string; - qty: string; - commission: string; - commissionAsset: string; +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 } ⋮---- -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; -} +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 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 PortfolioMarginRepayRecord { + amount: string; // Total amount repaid + asset: string; + interest: string; // Interest repaid + principal: string; // Principal repaid + status: PMMarginLoanStatus; + txId: number; } ⋮---- -export interface PortfolioMarginOCOOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +amount: string; // Total amount repaid ⋮---- -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; -} +interest: string; // Interest repaid +principal: string; // Principal repaid ⋮---- -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 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 } ⋮---- -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[]; -} +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 ⋮---- -// Add new interfaces for canceling UM orders -export interface CancelPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; +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 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 GetPortfolioInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; // Default: 10, Max: 100 } ⋮---- -export interface CancelPortfolioUMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +size?: number; // Default: 10, Max: 100 ⋮---- -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 PortfolioNegativeBalanceInterestRecord { + asset: string; + interest: string; // interest amount + interestAccuredTime: number; + interestRate: string; // daily interest rate + principal: string; } ⋮---- -export interface CancelPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +interest: string; // interest amount ⋮---- -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; -} +interestRate: string; // daily interest rate ⋮---- -export interface CancelPortfolioCMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +export type UMIncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'SPECIAL_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 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; +/** + * UM income history query for `GET /papi/v1/um/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted + * (removed 2026-10-28). + */ +export interface QueryPortfolioUMIncomeReq { + symbol?: string; + incomeType?: UMIncomeType; + startTime?: number; + endTime?: number; + limit?: number; // Default 100; max 1000 } ⋮---- -export interface CancelPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; -} +limit?: number; // Default 100; max 1000 ⋮---- -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 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 } ⋮---- -export interface CancelPortfolioMarginOCOReq { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} +symbol: string; // trade symbol, if existing ⋮---- -export interface PortfolioMarginOCOCancelOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +income: string; // income amount +asset: string; // income asset +info: string; // extra information ⋮---- -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; -} +tranId: string; // transaction id +tradeId: string; // trade id, if existing ⋮---- -export interface PortfolioMarginOCOCancelResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginOCOCancelOrderReport[]; -} +export type CMIncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'FUNDING_FEE' + | 'REALIZED_PNL' + | 'COMMISSION' + | 'INSURANCE_CLEAR' + | 'DELIVERED_SETTELMENT'; ⋮---- -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; +/** + * CM income history query for `GET /papi/v1/cm/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted + * (removed 2026-10-28). + */ +export interface QueryPortfolioCMIncomeReq { + symbol?: string; + incomeType?: CMIncomeType; + startTime?: number; + endTime?: number; + limit?: number; // Default 100; max 1000 } ⋮---- -export interface PortfolioMarginCancelAllOrdersOCOReport { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; +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 } ⋮---- -export type PortfolioMarginCancelAllOrdersResponse = - | PortfolioMarginCancelAllOrdersOrderReport - | PortfolioMarginCancelAllOrdersOCOReport; +symbol: string; // trade symbol, if existing ⋮---- -export interface ModifyPortfolioUMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - priceMatch?: PMPriceMatch; - modifyId?: number; -} +income: string; // income amount +asset: string; // income asset +info: string; // extra information ⋮---- -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; -} +tranId: string; // transaction id +tradeId: string; // trade id, if existing ⋮---- -export interface ModifyPortfolioCMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - modifyId?: number; +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 } ⋮---- -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; +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 } ⋮---- -export interface QueryPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; +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 } ⋮---- -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'; +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; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; } ⋮---- -export interface QueryPortfolioAllUMOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +symbol: string; // symbol name +positionAmt: string; // position amount ⋮---- -export interface QueryPortfolioUMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode ⋮---- -export interface QueryPortfolioAllUMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +maxQty: string; // maximum quantity of base asset ⋮---- -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 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; } ⋮---- -export interface QueryPortfolioUMOpenConditionalOrderReq { +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; - strategyId?: number; - newClientStrategyId?: string; + marginType: 'CROSSED' | 'ISOLATED'; + isAutoAddMargin: string; // "true" or "false" as string + leverage: number; + maxNotionalValue: string; } ⋮---- -export interface QueryPortfolioUMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +isAutoAddMargin: string; // "true" or "false" as string ⋮---- -export interface QueryPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: 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 } ⋮---- -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; -} +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 QueryPortfolioAllCMOrdersReq { - symbol: string; - pair?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; +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 } ⋮---- -export interface QueryPortfolioCMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +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 QueryPortfolioAllCMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; +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; } ⋮---- -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; -} +status: 'completed' | 'processing'; // Enum: completed, processing +url: string; // The link is mapped to download id ⋮---- -export interface QueryPortfolioCMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +notified: boolean; // ignore +expirationTimestamp: number; // The link would expire after this timestamp ⋮---- -export interface PortfolioCMConditionalHistoryOrder - extends PortfolioCMConditionalOrder { - priceMatch: PMPriceMatch; +export interface PortfolioTradFiPerpsContractSignResponse { + code: number; + msg: string; } + +================ +File: src/coinm-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; ⋮---- -export interface QueryPortfolioUMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} +import { + ClassicPortfolioMarginAccount, + ClassicPortfolioMarginNotionalLimit, + CoinMAccountTradeParams, + CoinMOpenInterest, + CoinMPositionTrade, + CoinMSymbolOrderBookTicker, + FundingRate, + FuturesTransactionHistoryDownloadLink, + GetClassicPortfolioMarginNotionalLimitParams, + PositionRisk, +} from './types/coin'; +import { + AggregateFuturesTrade, + CancelAllOpenOrdersResult, + CancelFuturesOrderResult, + CancelMultipleOrdersParams, + CancelOrdersTimeoutParams, + ChangeStats24hr, + ContinuousContractKlinesParams, + ForceOrderResult, + FundingRateHistory, + FuturesAlgoOrderResponse, + FuturesCancelAlgoOrderParams, + FuturesCancelAlgoOrderResponse, + FuturesCoinMAccountBalance, + FuturesCoinMAccountInformation, + FuturesCoinMBasisParams, + FuturesCoinMLongShortAccountRatioParams, + 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 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 class CoinMClient extends BaseRestClient ⋮---- -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; -} +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, + ) ⋮---- -export interface QueryPortfolioUMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- -export interface PortfolioUMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} +/** + * + * Market Data Endpoints + * + **/ ⋮---- -export interface PortfolioUMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioUMOrderAmendment; - priceMatch: PMPriceMatch; - modifyId?: number; -} +testConnectivity(): Promise ⋮---- -export interface QueryPortfolioCMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getExchangeInfo(): Promise ⋮---- -export interface PortfolioCMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} +getOrderBook(params: OrderBookParams): Promise ⋮---- -export interface PortfolioCMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioCMOrderAmendment; - modifyId?: number; -} +getRecentTrades(params: RecentTradesParams): Promise ⋮---- -export interface QueryPortfolioMarginForceOrdersReq { - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 -} +getHistoricalTrades( + params: HistoricalTradesParams, + ): Promise ⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, + ): Promise ⋮---- -export interface PortfolioMarginForceOrder { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - updatedTime: number; -} +/** + * Index Price and Mark Price + */ +getMarkPrice(params?: { symbol?: string }): Promise ⋮---- -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 -} +getFundingRateHistory( + params?: Partial, + ): Promise ⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 +getFundingRate(params?: { symbol?: string }): Promise ⋮---- -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; -} +getKlines(params: KlinesParams): Promise ⋮---- -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 -} +getContinuousContractKlines( + params: ContinuousContractKlinesParams, + ): Promise ⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 50; max 1000 +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- -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; -} +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -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) -} +getPremiumIndexKlines(params: KlinesParams): Promise ⋮---- -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) +get24hrChangeStatistics(params?: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -export interface QueryPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +getSymbolPriceTicker(params?: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -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; -} +getSymbolOrderBookTicker(params?: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -export interface QueryPortfolioMarginAllOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; // Default 500; max 500 -} +getOpenInterest(params: { symbol: string }): Promise ⋮---- -limit?: number; // Default 500; max 500 +getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise ⋮---- -export interface QueryPortfolioMarginOCOReq { - orderListId?: number; // Either orderListId or origClientOrderId must be provided - origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided -} +getTopTradersLongShortAccountRatio( + params: FuturesCoinMLongShortAccountRatioParams, + ): Promise ⋮---- -orderListId?: number; // Either orderListId or origClientOrderId must be provided -origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams & { pair?: string }, + ): Promise ⋮---- -export interface PortfolioMarginOCOQueryOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, + ): Promise ⋮---- -export interface PortfolioMarginOCO { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOQueryOrder[]; -} +getTakerBuySellVolume( + params: FuturesCoinMTakerBuySellVolumeParams, + ): Promise ⋮---- -export interface QueryPortfolioMarginAllOCOReq { - fromId?: number; // If supplied, neither startTime or endTime can be provided - startTime?: number; - endTime?: number; - limit?: number; // Default 500; max 500 -} +getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise ⋮---- -fromId?: number; // If supplied, neither startTime or endTime can be provided +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getIndexPriceConstituents(params: { + symbol: string; + }): Promise ⋮---- -limit?: number; // Default 500; max 500 +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getQuarterlyContractSettlementPrices(params: { + pair: string; + }): Promise ⋮---- -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 -} +/** + * + * Trade Endpoints + * + **/ ⋮---- -fromId?: number; // TradeId to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 +submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- -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; -} +/** + * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. + * + * Known issue: `quantity` and `price` should be sent as strings + */ +submitMultipleOrders( + orders: NewFuturesOrderParams[], + ): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- -export interface PortfolioMarginRepayDebtReq { - asset: string; - amount?: string; - specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas -} +/** + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + */ +modifyOrder( + params: ModifyFuturesOrderParams, + ): Promise ⋮---- -specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas +/** + * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. + */ +modifyMultipleOrders( + orders: ModifyFuturesOrderParams[], + ): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> ⋮---- -export interface PortfolioMarginRepayDebtResponse { - amount: string; - asset: string; - specifyRepayAssets: string[]; - updateTime: number; - success: boolean; -} +getOrderModifyHistory( + params: GetOrderModifyHistoryParams, + ): Promise ⋮---- -/** - * - * DERIVATIVES - ACCOUNT endpoints - * - **/ +cancelOrder(params: CancelOrderParams): Promise ⋮---- -export type PMAccountStatus = - | 'NORMAL' - | 'MARGIN_CALL' - | 'SUPPLY_MARGIN' - | 'REDUCE_ONLY' - | 'ACTIVE_LIQUIDATION' - | 'FORCE_LIQUIDATION' - | 'BANKRUPTED'; +cancelMultipleOrders( + params: CancelMultipleOrdersParams, + ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- -export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; -export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; +cancelAllOpenOrders(params: { + symbol?: string; + }): Promise ⋮---- -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; -} +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, + ): Promise ⋮---- -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 +getOrder(params: GetOrderParams): Promise ⋮---- -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; -} +getAllOrders(params: GetAllOrdersParams): Promise ⋮---- -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 +getAllOpenOrders(params?: { symbol?: string }): Promise ⋮---- -export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; +getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- -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 -} +/** + * + * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) + * Conditional orders migrate to Algo Service on COIN-M + * + **/ ⋮---- -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 +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, + ): Promise ⋮---- -accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, + ): Promise ⋮---- -virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, + ): Promise ⋮---- -totalMarginOpenLoss: string; // in USD margin open order -updateTime: number; // last update time +getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- -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; -} +getAccountTrades( + params: CoinMAccountTradeParams & { orderId?: number }, + ): Promise ⋮---- -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; -} +getPositions(params?: { + marginAsset?: string; + pair?: string; + }): Promise ⋮---- -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 -} +setPositionMode(params: PositionModeParams): Promise ⋮---- -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 +setMarginType(params: SetMarginTypeParams): Promise ⋮---- -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 -} +setLeverage(params: SetLeverageParams): Promise ⋮---- -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 +getADLQuantileEstimation(params?: { symbol?: string }): Promise ⋮---- -export interface PortfolioTradingIndicator { - isLocked: boolean; - plannedRecoverTime: number; - indicator: PMIndicatorType; - value: number; - triggerValue: number; -} +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, + ): Promise ⋮---- -export interface PortfolioTradingStatus { - indicators: { - [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" - }; - updateTime: number; -} +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, + ): Promise +/** + * + * Account Endpoints + * + **/ ⋮---- -[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" +getBalance(): Promise ⋮---- -export interface PortfolioMarginLoanRecord { - txId: number; - asset: string; - principal: string; - timestamp: number; - status: PMMarginLoanStatus; -} +getAccountCommissionRate(params: { + symbol?: string; + }): Promise ⋮---- -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 -} +getAccountInformation(): Promise ⋮---- -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 +/** + * Notional Bracket for Symbol (NOT "pair") + */ +getNotionalAndLeverageBrackets(params?: { + symbol?: string; + }): Promise ⋮---- -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 -} +// TO ADD: dapi/v1/leverageBracket +// can use dapi/v2/leverageBracket ⋮---- -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 +getCurrentPositionMode(): Promise ⋮---- -export interface PortfolioMarginRepayRecord { - amount: string; // Total amount repaid - asset: string; - interest: string; // Interest repaid - principal: string; // Principal repaid - status: PMMarginLoanStatus; - txId: number; -} +/** + * Query income history (`GET /dapi/v1/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- -amount: string; // Total amount repaid +/** + * Get a download id for futures transaction history (`GET /dapi/v1/income/asyn`). + * Limited to 100 requests per month, shared across the web download page, + * REST, USD-M and COIN-M. + */ +getDownloadIdForFuturesTransactionHistory(params: { + startTime: number; + endTime: number; + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- -interest: string; // Interest repaid -principal: string; // Principal repaid +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- -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 -} +getDownloadIdForFuturesOrderHistory(params: { + startTime: number; + endTime: number; + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- -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 +getFuturesOrderHistoryDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- -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 +getDownloadIdForFuturesTradeHistory(params: { + startTime: number; + endTime: number; + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- -| '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 +getFuturesTradeHistoryDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- -export interface PortfolioMarginInterestRecord { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset: string; - principal: string; - interest: string; - interestRate: string; - type: PMInterestType; -} +/** + * + * Portfolio Margin Endpoints + * + **/ ⋮---- -export interface GetPortfolioInterestHistoryReq { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; // Default: 10, Max: 100 -} +getClassicPortfolioMarginAccount(params: { + asset: string; + }): Promise ⋮---- -size?: number; // Default: 10, Max: 100 +/** + * @deprecated at 6th August, 2024 + **/ +getClassicPortfolioMarginNotionalLimits( + params?: GetClassicPortfolioMarginNotionalLimitParams, + ): Promise<{ + notionalLimits: ClassicPortfolioMarginNotionalLimit[]; + }> ⋮---- -export interface PortfolioNegativeBalanceInterestRecord { - asset: string; - interest: string; // interest amount - interestAccuredTime: number; - interestRate: string; // daily interest rate - principal: string; -} +/** + * + * 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 + * + **/ ⋮---- -interest: string; // interest amount +/** + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, + ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> ⋮---- -interestRate: string; // daily interest rate -⋮---- -export type UMIncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'SPECIAL_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'; +/** + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, + ): Promise<{ customerId: string; email: string }> ⋮---- /** - * UM income history query for `GET /papi/v1/um/income`. - * Paginate with `startTime` and `endTime`. `page` is not accepted - * (removed 2026-10-28). - */ -export interface QueryPortfolioUMIncomeReq { - symbol?: string; - incomeType?: UMIncomeType; - startTime?: number; - endTime?: 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'; + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, + ): Promise ⋮---- /** - * CM income history query for `GET /papi/v1/cm/income`. - * Paginate with `startTime` and `endTime`. `page` is not accepted - * (removed 2026-10-28). - */ -export interface QueryPortfolioCMIncomeReq { - symbol?: string; - incomeType?: CMIncomeType; - startTime?: number; - endTime?: 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 + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise ⋮---- -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 -} +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- -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 +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -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 -} +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -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 +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -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; -} +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -symbol: string; // symbol name -positionAmt: string; // position amount +getFuturesUserDataListenKey(): Promise<{ listenKey: string }> ⋮---- -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode +keepAliveFuturesUserDataListenKey(): Promise ⋮---- -maxQty: string; // maximum quantity of base asset +closeFuturesUserDataListenKey(): Promise ⋮---- -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; -} +/** + * 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'; ⋮---- -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'; +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'; ⋮---- /** - * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. + * REST client for Portfolio Margin APIs (papi) + * + * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info */ -export type OrderTimeInForce = - | 'GTC' - | 'IOC' - | 'FOK' - | 'GTX' - | 'GTE_GTC' - | 'GTD' - | 'RPI'; +export class PortfolioClient extends BaseRestClient ⋮---- -export type StringBoolean = 'TRUE' | 'FALSE'; +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, + ) ⋮---- -export type SideEffects = - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'NO_SIDE_EFFECT' - | 'AUTO_BORROW_REPAY' - | 'NO_SIDE_EFFECT'; +getClientId(): BinanceBaseUrlKey ⋮---- /** - * 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' - | 'PENDING_NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED' - | 'EXPIRED_IN_MATCH'; -⋮---- -export type OrderExecutionType = - | 'NEW' - | 'CANCELED' - | 'REJECTED' - | 'TRADE' - | 'EXPIRED'; -⋮---- -export type OrderListContingencyType = - | 'OCO' - | 'OTO' - | 'OTOCO' - | 'OPO' - | 'OPOCO'; -⋮---- -// 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' - | 'DECREMENT' - | 'TRANSFER'; -⋮---- -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; -} + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- -export interface SymbolLegacyMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - minNotional: numberInString; - applyToMarket: boolean; - avgPriceMins: number; -} +/** + * + * Misc Endpoints + * + **/ ⋮---- -export interface SymbolLotSizeFilter { - filterType: 'LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +testConnectivity(): Promise ⋮---- -export interface SymbolMinNotionalFilter { - filterType: 'NOTIONAL'; - minNotional: numberInString; - applyMinToMarket: boolean; - maxNotional: numberInString; - applyMaxToMarket: boolean; - avgPriceMins: number; -} +signTradFiPerpsContract(): Promise ⋮---- -export interface SymbolIcebergPartsFilter { - filterType: 'ICEBERG_PARTS'; - limit: number; -} +/** + * + * DERIVATIVES -TRADE endpoints + * + **/ ⋮---- -export interface SymbolMarketLotSizeFilter { - filterType: 'MARKET_LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +submitNewUMOrder( + params: NewPortfolioUMOrderReq, + ): Promise ⋮---- -export interface SymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - maxNumOrders: number; -} +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). + */ +submitNewUMConditionalOrder( + params: NewPortfolioUMConditionalOrderReq, + ): Promise ⋮---- -export interface SymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +submitNewUMAlgoOrder( + params: NewPortfolioUMAlgoOrderReq, + ): Promise ⋮---- -export interface SymbolMaxIcebergOrdersFilter { - filterType: 'MAX_NUM_ICEBERG_ORDERS'; - maxNumIcebergOrders: number; -} +submitNewCMOrder( + params: NewPortfolioCMOrderReq, + ): Promise ⋮---- -export interface SymbolMaxPositionFilter { - filterType: 'MAX_POSITION'; - maxPosition: numberInString; -} +submitNewCMConditionalOrder( + params: NewPortfolioCMConditionalOrderReq, + ): Promise ⋮---- -export type SymbolFilter = - | SymbolPriceFilter - | SymbolPercentPriceFilter - | SymbolPercentPriceBySideFilter - | SymbolLegacyMinNotionalFilter - | SymbolLotSizeFilter - | SymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | SymbolMaxOrdersFilter - | SymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter; +submitNewMarginOrder( + params: NewPortfolioMarginOrderReq, + ): Promise ⋮---- -export interface ExchangeMaxNumOrdersFilter { - filterType: 'EXCHANGE_MAX_NUM_ORDERS'; - maxNumOrders: number; -} +submitMarginLoan(params: { asset: string; amount: string }): Promise<{ + tranId: number; + }> ⋮---- -export interface ExchangeMaxAlgoOrdersFilter { - filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +submitMarginRepay(params: { asset: string; amount: string }): Promise<{ + tranId: number; + }> ⋮---- -export type ExchangeFilter = - | ExchangeMaxNumOrdersFilter - | ExchangeMaxAlgoOrdersFilter; +submitNewMarginOCO( + params: NewPortfolioMarginOCOReq, + ): Promise ⋮---- -export type OrderBookPrice = numberInString; -export type OrderBookAmount = numberInString; +cancelUMOrder( + params: CancelPortfolioUMOrderReq, + ): Promise ⋮---- -export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; +cancelAllUMOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -export type OrderBookPriceFormatted = number; -export type OrderBookAmountFormatted = number; -export type OrderBookRowFormatted = [ - OrderBookPriceFormatted, - OrderBookAmountFormatted, -]; +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). + */ +cancelUMConditionalOrder( + params: CancelPortfolioUMConditionalOrderReq, + ): Promise ⋮---- -export interface GenericCodeMsgError { - code: number; - msg: string; -} +cancelUMAlgoOrder( + params: CancelPortfolioUMAlgoOrderReq, + ): Promise ⋮---- -export interface RowsWithTotal { - rows: T[]; - total: number; -} +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). + */ +cancelAllUMConditionalOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -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'; +cancelAllUMAlgoOpenOrders(params: { + symbol: string; + }): Promise ⋮---- -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, - FuturesCoinMLongShortAccountRatioParams, - 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'; +cancelCMOrder( + params: CancelPortfolioCMOrderReq, + ): Promise +⋮---- +cancelAllCMOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -export class CoinMClient extends BaseRestClient +cancelCMConditionalOrder( + params: CancelPortfolioCMConditionalOrderReq, + ): Promise ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, - ) +cancelAllCMConditionalOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise +cancelMarginOrder( + params: CancelPortfolioMarginOrderReq, + ): Promise ⋮---- -/** - * - * Market Data Endpoints - * - **/ +cancelMarginOCO( + params: CancelPortfolioMarginOCOReq, + ): Promise ⋮---- -testConnectivity(): Promise +cancelAllMarginOrders(params: { + symbol: string; + }): Promise ⋮---- -getExchangeInfo(): Promise +modifyUMOrder( + params: ModifyPortfolioUMOrderReq, + ): Promise ⋮---- -getOrderBook(params: OrderBookParams): Promise +modifyCMOrder( + params: ModifyPortfolioCMOrderReq, + ): Promise ⋮---- -getRecentTrades(params: RecentTradesParams): Promise +getUMOrder(params: QueryPortfolioUMOrderReq): Promise ⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, - ): Promise +getAllUMOrders( + params: QueryPortfolioAllUMOrdersReq, + ): Promise ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, - ): Promise +getUMOpenOrder( + params: QueryPortfolioUMOpenOrderReq, + ): Promise +⋮---- +getAllUMOpenOrders(params: { symbol?: string }): Promise ⋮---- /** - * Index Price and Mark Price + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). */ -getMarkPrice(params?: { symbol?: string }): Promise +getAllUMConditionalOrders( + params: QueryPortfolioAllUMConditionalOrdersReq, + ): Promise ⋮---- -getFundingRateHistory( - params?: Partial, - ): Promise +getAllUMAlgoOrders( + params: QueryPortfolioAllUMAlgoOrdersReq, + ): Promise ⋮---- -getFundingRate(params?: { symbol?: string }): Promise +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). + */ +getUMOpenConditionalOrders(params: { + symbol?: string; + }): Promise ⋮---- -getKlines(params: KlinesParams): Promise +getUMAlgoOpenOrders(params?: { + symbol?: string; + }): Promise ⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, - ): Promise +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). + */ +getUMOpenConditionalOrder( + params: QueryPortfolioUMOpenConditionalOrderReq, + ): Promise ⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +getUMAlgoOrder( + params: QueryPortfolioUMAlgoOrderReq, + ): Promise ⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +/** + * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. + */ +getUMConditionalOrderHistory( + params: QueryPortfolioUMConditionalOrderHistoryReq, + ): Promise ⋮---- -getPremiumIndexKlines(params: KlinesParams): Promise +getCMOrder(params: QueryPortfolioCMOrderReq): Promise ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; - pair?: string; - }): Promise +getAllCMOrders( + params: QueryPortfolioAllCMOrdersReq, + ): Promise ⋮---- -getSymbolPriceTicker(params?: { +getCMOpenOrder( + params: QueryPortfolioCMOpenOrderReq, + ): Promise +⋮---- +getAllCMOpenOrders(params: { symbol?: string; pair?: string; - }): Promise + }): Promise ⋮---- -getSymbolOrderBookTicker(params?: { +getCMOpenConditionalOrders(params: { symbol?: string; - pair?: string; - }): Promise + }): Promise ⋮---- -getOpenInterest(params: { symbol: string }): Promise +getCMOpenConditionalOrder(params: { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; + }): Promise ⋮---- -getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise +getAllCMConditionalOrders( + params: QueryPortfolioAllCMConditionalOrdersReq, + ): Promise ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesCoinMLongShortAccountRatioParams, - ): Promise +getCMConditionalOrderHistory( + params: QueryPortfolioCMConditionalOrderHistoryReq, + ): Promise ⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams & { pair?: string }, - ): Promise +getUMForceOrders( + params: QueryPortfolioUMForceOrdersReq, + ): Promise ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, - ): Promise +getCMForceOrders( + params: QueryPortfolioCMForceOrdersReq, + ): Promise ⋮---- -getTakerBuySellVolume( - params: FuturesCoinMTakerBuySellVolumeParams, - ): Promise +getUMOrderModificationHistory( + params: QueryPortfolioUMOrderAmendmentReq, + ): Promise ⋮---- -getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise +getCMOrderModificationHistory( + params: QueryPortfolioCMOrderAmendmentReq, + ): Promise ⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getIndexPriceConstituents(params: { +getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise<{ + rows: PortfolioMarginForceOrder[]; + total: number; + }> +⋮---- +getUMTrades(params: QueryPortfolioUMTradesReq): Promise +⋮---- +getCMTrades(params: QueryPortfolioCMTradesReq): Promise +⋮---- +getUMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > +⋮---- +getCMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > +⋮---- +toggleUMFeeBurn(params: { + feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off + }): Promise<{ code: number; msg: string }> +⋮---- +feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +⋮---- +getUMFeeBurnStatus(): Promise<{ feeBurn: boolean }> +⋮---- +getMarginOrder( + params: QueryPortfolioMarginOrderReq, + ): Promise +⋮---- +getMarginOpenOrders(params: { symbol: string; - }): Promise + }): Promise ⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getQuarterlyContractSettlementPrices(params: { - pair: string; - }): Promise +getAllMarginOrders( + params: QueryPortfolioMarginAllOrdersReq, + ): Promise +⋮---- +getMarginOCO( + params: QueryPortfolioMarginOCOReq, + ): Promise +⋮---- +getAllMarginOCO( + params: QueryPortfolioMarginAllOCOReq, + ): Promise +⋮---- +getMarginOpenOCO(): Promise +⋮---- +getMarginTrades( + params: QueryPortfolioMarginTradesReq, + ): Promise +⋮---- +repayMarginDebt( + params: PortfolioMarginRepayDebtReq, + ): Promise ⋮---- /** * - * Trade Endpoints + * DERIVATIVES - ACCOUNT endpoints * **/ ⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise +getBalance(params?: { asset?: string }): Promise ⋮---- -/** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. - * - * Known issue: `quantity` and `price` should be sent as strings - */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], - ): Promise<(NewOrderResult | NewOrderError)[]> +getAccountInfo(): Promise +⋮---- +getMarginMaxBorrow(params: { asset: string }): Promise<{ + amount: string; // account's currently max borrowable amount with sufficient system availability + borrowLimit: string; // max borrowable amount limited by the account level + }> +⋮---- +amount: string; // account's currently max borrowable amount with sufficient system availability +borrowLimit: string; // max borrowable amount limited by the account level +⋮---- +getMarginMaxWithdraw(params: { asset: string }): Promise<{ + amount: string; // max withdrawable amount + }> +⋮---- +amount: string; // max withdrawable amount ⋮---- -/** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue - */ -modifyOrder( - params: ModifyFuturesOrderParams, - ): Promise +getUMPosition(params?: { symbol?: string }): Promise +⋮---- +getCMPosition(params?: { + marginAsset?: string; + pair?: string; + }): Promise ⋮---- /** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. + * Change UM initial leverage (`POST /papi/v1/um/leverage`). + * `leverage` is an unbounded number here. The maximum is symbol-specific: + * bracket 1 `initialLeverage` from `GET /papi/v1/um/leverageBracket` + * (Binance derivatives changelog 2026-10-09). */ -modifyMultipleOrders( - orders: ModifyFuturesOrderParams[], - ): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> -⋮---- -getOrderModifyHistory( - params: GetOrderModifyHistoryParams, - ): Promise -⋮---- -cancelOrder(params: CancelOrderParams): Promise +updateUMLeverage(params: { symbol: string; leverage: number }): Promise<{ + leverage: number; + maxNotionalValue: string; + symbol: string; + }> ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, - ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +updateCMLeverage(params: { symbol: string; leverage: number }): Promise<{ + leverage: number; + maxQty: string; + symbol: string; + }> ⋮---- -cancelAllOpenOrders(params: { - symbol?: string; - }): Promise +updateUMPositionMode(params: { + dualSidePosition: 'true' | 'false'; + }): Promise<{ + code: number; + msg: string; + }> ⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, - ): Promise +updateCMPositionMode(params: { + dualSidePosition: 'true' | 'false'; + }): Promise<{ + code: number; + msg: string; + }> ⋮---- -getOrder(params: GetOrderParams): Promise +getUMPositionMode(): Promise<{ + dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode + }> ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -getAllOpenOrders(params?: { symbol?: string }): Promise +getCMPositionMode(): Promise<{ + dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode + }> ⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -/** - * - * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) - * Conditional orders migrate to Algo Service on COIN-M - * - **/ +getUMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + notionalCoef: string; + brackets: PortfolioUMLeverageBracket[]; + }[] + > ⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, - ): Promise +getCMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + brackets: PortfolioCMLeverageBracket[]; + }[] + > ⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, - ): Promise +getUMTradingStatus(params?: { + symbol?: string; + }): Promise ⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, - ): Promise +getUMCommissionRate(params: { symbol: string }): Promise<{ + symbol: string; + makerCommissionRate: string; // e.g., "0.0002" for 0.02% + takerCommissionRate: string; // e.g., "0.0004" for 0.04% + }> ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -getAccountTrades( - params: CoinMAccountTradeParams & { orderId?: number }, - ): Promise +getCMCommissionRate(params: { symbol: string }): Promise<{ + symbol: string; + makerCommissionRate: string; // e.g., "0.0002" for 0.02% + takerCommissionRate: string; // e.g., "0.0004" for 0.04% + }> ⋮---- -getPositions(params?: { - marginAsset?: string; - pair?: string; - }): Promise +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -setPositionMode(params: PositionModeParams): Promise +getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise<{ + rows: PortfolioMarginLoanRecord[]; + total: number; + }> ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise<{ + rows: PortfolioMarginRepayRecord[]; + total: number; + }> ⋮---- -setLeverage(params: SetLeverageParams): Promise +getAutoRepayFuturesStatus(): Promise<{ + autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off + }> ⋮---- -getADLQuantileEstimation(params?: { symbol?: string }): Promise +autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, - ): Promise +updateAutoRepayFuturesStatus(params: { + autoRepay: 'true' | 'false'; + }): Promise<{ + msg: string; + }> ⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, - ): Promise -/** - * - * Account Endpoints - * - **/ +getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise<{ + rows: PortfolioMarginInterestRecord[]; + total: number; + }> ⋮---- -getBalance(): Promise +repayFuturesNegativeBalance(): Promise<{ + msg: string; + }> ⋮---- -getAccountCommissionRate(params: { - symbol?: string; - }): Promise +getPortfolioNegativeBalanceInterestHistory( + params?: GetPortfolioInterestHistoryReq, + ): Promise ⋮---- -getAccountInformation(): Promise +autoCollectFunds(): Promise<{ + msg: string; + }> ⋮---- /** - * Notional Bracket for Symbol (NOT "pair") + * Fund collection by asset (`POST /papi/v1/asset-collection`). + * + * Optional `amount` and `futureType` must be sent together. `futureType` + * is the target wallet (`UM`, `CM`, or `OPTION`; `OPTION` is SPAN only). + * If neither is sent, collection behavior is unchanged. */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; - }): Promise +transferAssetFuturesMargin(params: { + asset: string; + amount?: number; + futureType?: 'UM' | 'CM' | 'OPTION'; + }): Promise<{ + msg: string; + }> ⋮---- -// TO ADD: dapi/v1/leverageBracket -// can use dapi/v2/leverageBracket +transferBNB(params: { + amount: string; + transferSide: 'TO_UM' | 'FROM_UM'; + }): Promise<{ + tranId: number; // transaction id + }> ⋮---- -getCurrentPositionMode(): Promise +tranId: number; // transaction id ⋮---- /** - * Query income history (`GET /dapi/v1/income`). + * Query UM income history (`GET /papi/v1/um/income`). * Paginate with `startTime` and `endTime`. `page` is not accepted. */ -getIncomeHistory(params?: GetIncomeHistoryParams): Promise +getUMIncomeHistory( + params?: QueryPortfolioUMIncomeReq, + ): Promise ⋮---- /** - * Get a download id for futures transaction history (`GET /dapi/v1/income/asyn`). - * Limited to 100 requests per month, shared across the web download page, - * REST, USD-M and COIN-M. + * Query CM income history (`GET /papi/v1/cm/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. */ -getDownloadIdForFuturesTransactionHistory(params: { - startTime: number; - endTime: number; - }): Promise<{ - avgCostTimestampOfLast30d: number; - downloadId: string; - }> -⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; - }): Promise +getCMIncomeHistory( + params?: QueryPortfolioCMIncomeReq, + ): Promise ⋮---- -getDownloadIdForFuturesOrderHistory(params: { - startTime: number; - endTime: number; - }): Promise<{ - avgCostTimestampOfLast30d: number; - downloadId: string; +getUMAccount(): Promise<{ + assets: PortfolioUMAccountAsset[]; + positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market }> ⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; - }): Promise +positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market ⋮---- -getDownloadIdForFuturesTradeHistory(params: { - startTime: number; - endTime: number; - }): Promise<{ - avgCostTimestampOfLast30d: number; - downloadId: string; +getCMAccount(): Promise<{ + assets: PortfolioCMAccountAsset[]; + positions: PortfolioCMAccountPosition[]; }> ⋮---- -getFuturesTradeHistoryDownloadLink(params: { - downloadId: string; - }): Promise -⋮---- -/** - * - * Portfolio Margin Endpoints - * - **/ +getUMAccountConfig(): Promise ⋮---- -getClassicPortfolioMarginAccount(params: { - asset: string; - }): Promise +getUMSymbolConfig(params?: { + symbol?: string; + }): Promise ⋮---- -/** - * @deprecated at 6th August, 2024 - **/ -getClassicPortfolioMarginNotionalLimits( - params?: GetClassicPortfolioMarginNotionalLimitParams, - ): Promise<{ - notionalLimits: ClassicPortfolioMarginNotionalLimit[]; +getUMAccountV2(): Promise<{ + assets: PortfolioUMAccountAssetV2[]; + positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market }> ⋮---- -/** - * - * 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 - * - **/ +positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market ⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, - ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> +getUMTradeHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms + }): Promise<{ + avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days + downloadId: string; + }> ⋮---- -/** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, - ): Promise<{ customerId: string; email: string }> +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms ⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, - ): Promise +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days ⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise +getUMTradeDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +getUMOrderHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms + }): Promise<{ + avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days + downloadId: string; + }> ⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms ⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days ⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise +getUMOrderDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- -/** - * - * User Data Stream Endpoints - * - **/ +getUMTransactionHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms + }): Promise<{ + avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days + downloadId: string; + }> ⋮---- -getFuturesUserDataListenKey(): Promise<{ listenKey: string }> +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms ⋮---- -keepAliveFuturesUserDataListenKey(): Promise +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days ⋮---- -closeFuturesUserDataListenKey(): Promise +getUMTransactionDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams + | NewPortfolioUMOrderReq | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +getPMUserDataListenKey(): Promise<{ listenKey: string }> +⋮---- +keepAlivePMUserDataListenKey(): Promise +⋮---- +closePMUserDataListenKey(): Promise ================ -File: src/portfolio-client.ts +File: src/usdm-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'; +/* 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, + GetFuturesAllOrdersParams, + 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, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, NewOCOParams, + numberInString, + OrderBookParams, OrderIdProperty, + RecentTradesParams, + SymbolFromPaginatedRequestFromId, + SymbolPrice, } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { @@ -8875,1228 +8347,1786 @@ import { RestClientOptions, } from './util/requestUtils'; ⋮---- -/** - * REST client for Portfolio Margin APIs (papi) - * - * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info - */ -export class PortfolioClient extends BaseRestClient +export class USDMClient 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 - * - **/ + * + * 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?: { symbol?: string }): Promise +⋮---- +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: { symbol: string }): Promise +⋮---- +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?: { symbol?: string }): Promise +⋮---- +getMultiAssetsModeAssetIndex(params?: { symbol?: string }): Promise +⋮---- +/** + * 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 ⋮---- -testConnectivity(): Promise +modifyMultipleOrders(orders: ModifyOrderParams[]): Promise ⋮---- -signTradFiPerpsContract(): Promise +getOrderModifyHistory( + params: GetFuturesOrderModifyHistoryParams, + ): Promise ⋮---- -/** - * - * DERIVATIVES -TRADE endpoints - * - **/ +cancelOrder(params: CancelOrderParams): Promise ⋮---- -submitNewUMOrder( - params: NewPortfolioUMOrderReq, - ): Promise +cancelMultipleOrders( + params: CancelMultipleOrdersParams, + ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). - */ -submitNewUMConditionalOrder( - params: NewPortfolioUMConditionalOrderReq, - ): Promise +cancelAllOpenOrders(params: { + symbol: string; + }): Promise ⋮---- -submitNewUMAlgoOrder( - params: NewPortfolioUMAlgoOrderReq, - ): Promise +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, + ): Promise ⋮---- -submitNewCMOrder( - params: NewPortfolioCMOrderReq, - ): Promise +getOrder(params: GetOrderParams): Promise ⋮---- -submitNewCMConditionalOrder( - params: NewPortfolioCMConditionalOrderReq, - ): Promise +getAllOrders(params?: GetFuturesAllOrdersParams): Promise ⋮---- -submitNewMarginOrder( - params: NewPortfolioMarginOrderReq, - ): Promise +getAllOpenOrders(params?: { symbol?: string }): Promise ⋮---- -submitMarginLoan(params: { asset: string; amount: string }): Promise<{ - tranId: number; - }> +getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- -submitMarginRepay(params: { asset: string; amount: string }): Promise<{ - tranId: number; - }> +getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- -submitNewMarginOCO( - params: NewPortfolioMarginOCOReq, - ): Promise +getAccountTrades( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, + ): Promise ⋮---- -cancelUMOrder( - params: CancelPortfolioUMOrderReq, - ): Promise +setMarginType(params: SetMarginTypeParams): Promise ⋮---- -cancelAllUMOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> +setPositionMode(params: PositionModeParams): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). + * Change initial leverage (`POST /fapi/v1/leverage`). + * `leverage` is an unbounded number here. The maximum is symbol-specific: + * bracket 1 `initialLeverage` from `GET /fapi/v1/leverageBracket` + * (Binance derivatives changelog 2026-10-09). */ -cancelUMConditionalOrder( - params: CancelPortfolioUMConditionalOrderReq, - ): Promise +setLeverage(params: SetLeverageParams): Promise ⋮---- -cancelUMAlgoOrder( - params: CancelPortfolioUMAlgoOrderReq, - ): Promise +setMultiAssetsMode(params: { + multiAssetsMargin: MultiAssetsMode; + }): Promise +⋮---- +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, + ): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). - */ -cancelAllUMConditionalOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> + * @deprecated + * Use getPositionsV3() instead + **/ +getPositions(params?: Partial): Promise ⋮---- -cancelAllUMAlgoOpenOrders(params: { - symbol: string; - }): Promise +getPositionsV3(params?: { symbol?: string }): Promise ⋮---- -cancelCMOrder( - params: CancelPortfolioCMOrderReq, - ): Promise +getADLQuantileEstimation(params?: { symbol?: string }): Promise ⋮---- -cancelAllCMOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> +getSymbolAdlRisk(params: ⋮---- -cancelCMConditionalOrder( - params: CancelPortfolioCMConditionalOrderReq, - ): Promise +getSymbolAdlRisk(): Promise; ⋮---- -cancelAllCMConditionalOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> +getSymbolAdlRisk(params?: { + symbol?: string; + }): Promise ⋮---- -cancelMarginOrder( - params: CancelPortfolioMarginOrderReq, - ): Promise +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, + ): Promise ⋮---- -cancelMarginOCO( - params: CancelPortfolioMarginOCOReq, - ): Promise +/** + * + * ACCOUNT endpoints - Rest API + * + **/ ⋮---- -cancelAllMarginOrders(params: { - symbol: string; - }): Promise +getBalanceV3(): Promise ⋮---- -modifyUMOrder( - params: ModifyPortfolioUMOrderReq, - ): Promise +/** + * @deprecated + * Use getBalanceV3() instead + **/ +getBalance(): Promise ⋮---- -modifyCMOrder( - params: ModifyPortfolioCMOrderReq, - ): Promise +getAccountInformationV3(): Promise ⋮---- -getUMOrder(params: QueryPortfolioUMOrderReq): Promise +/** + * @deprecated + * Use getAccountInformationV3() instead + **/ +getAccountInformation(): Promise ⋮---- -getAllUMOrders( - params: QueryPortfolioAllUMOrdersReq, - ): Promise +getAccountCommissionRate(params: { + symbol: string; + }): Promise ⋮---- -getUMOpenOrder( - params: QueryPortfolioUMOpenOrderReq, - ): Promise +getFuturesAccountConfig(): Promise ⋮---- -getAllUMOpenOrders(params: { symbol?: string }): Promise +getFuturesSymbolConfig(params: { symbol?: string }): Promise +⋮---- +getUserForceOrders(): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). + * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) */ -getAllUMConditionalOrders( - params: QueryPortfolioAllUMConditionalOrdersReq, - ): Promise +getNotionalAndLeverageBrackets(params?: { + symbol?: string; + }): Promise ⋮---- -getAllUMAlgoOrders( - params: QueryPortfolioAllUMAlgoOrdersReq, - ): Promise +getMultiAssetsMode(): Promise +⋮---- +getCurrentPositionMode(): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). + * Query income history (`GET /fapi/v1/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. */ -getUMOpenConditionalOrders(params: { - symbol?: string; - }): Promise +getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- -getUMAlgoOpenOrders(params?: { +getApiQuantitativeRulesIndicators(params?: { symbol?: string; - }): Promise + }): Promise ⋮---- /** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). + * Get a download id for futures transaction history (`GET /fapi/v1/income/asyn`). + * Limited to 100 requests per month, shared across the web download page, + * REST, USD-M and COIN-M. */ -getUMOpenConditionalOrder( - params: QueryPortfolioUMOpenConditionalOrderReq, - ): Promise +getFuturesTransactionHistoryDownloadId(params: { + startTime: number; + endTime: number; + }): Promise ⋮---- -getUMAlgoOrder( - params: QueryPortfolioUMAlgoOrderReq, - ): Promise +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; + }): Promise ⋮---- -/** - * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. - */ -getUMConditionalOrderHistory( - params: QueryPortfolioUMConditionalOrderHistoryReq, - ): Promise +getFuturesOrderHistoryDownloadId(params: { + startTime: number; + endTime: number; + }): Promise ⋮---- -getCMOrder(params: QueryPortfolioCMOrderReq): Promise +getFuturesOrderHistoryDownloadLink(params: { + downloadId: string; + }): Promise +⋮---- +getFuturesTradeHistoryDownloadId(params: { + startTime: number; + endTime: number; + }): Promise +⋮---- +getFuturesTradeDownloadLink(params: { + downloadId: string; + }): Promise +⋮---- +setBNBBurnEnabled(params: { + feeBurn: 'true' | 'false'; + }): Promise<{ code: number; msg: string }> +⋮---- +getBNBBurnStatus(): Promise<{ + feeBurn: boolean; + }> +⋮---- +signTradFiPerpsAgreement(): Promise<{ code: number; msg: string }> ⋮---- -getAllCMOrders( - params: QueryPortfolioAllCMOrdersReq, - ): Promise +testOrder(params: NewFuturesOrderParams): Promise ⋮---- -getCMOpenOrder( - params: QueryPortfolioCMOpenOrderReq, - ): Promise +/** + * + * Algo Order Endpoints (Effective 2025-12-02) + * Conditional orders migrate to Algo Service + * + **/ ⋮---- -getAllCMOpenOrders(params: { - symbol?: string; - pair?: string; - }): Promise +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, + ): Promise ⋮---- -getCMOpenConditionalOrders(params: { - symbol?: string; - }): Promise +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, + ): Promise ⋮---- -getCMOpenConditionalOrder(params: { +cancelAllAlgoOpenOrders(params: { symbol: string; - strategyId?: number; - newClientStrategyId?: string; - }): Promise + }): Promise ⋮---- -getAllCMConditionalOrders( - params: QueryPortfolioAllCMConditionalOrdersReq, - ): Promise +getAlgoOrder( + params: FuturesQueryAlgoOrderParams, + ): Promise ⋮---- -getCMConditionalOrderHistory( - params: QueryPortfolioCMConditionalOrderHistoryReq, - ): Promise +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, + ): Promise ⋮---- -getUMForceOrders( - params: QueryPortfolioUMForceOrdersReq, - ): Promise +getAllAlgoOrders( + params: FuturesQueryAllAlgoOrdersParams, + ): Promise ⋮---- -getCMForceOrders( - params: QueryPortfolioCMForceOrdersReq, - ): Promise +/** + * + * Convert Endpoints + * + **/ ⋮---- -getUMOrderModificationHistory( - params: QueryPortfolioUMOrderAmendmentReq, - ): Promise +getAllConvertPairs(params?: { + fromAsset?: string; + toAsset?: string; + }): Promise ⋮---- -getCMOrderModificationHistory( - params: QueryPortfolioCMOrderAmendmentReq, - ): Promise +submitConvertQuoteRequest( + params: FuturesConvertQuoteRequest, + ): Promise ⋮---- -getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise<{ - rows: PortfolioMarginForceOrder[]; - total: number; +acceptConvertQuote(params: { quoteId: string }): Promise<{ + orderId: string; + createTime: number; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; }> ⋮---- -getUMTrades(params: QueryPortfolioUMTradesReq): Promise -⋮---- -getCMTrades(params: QueryPortfolioCMTradesReq): Promise -⋮---- -getUMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > -⋮---- -getCMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > +getConvertOrderStatus(params: { + orderId?: string; + quoteId?: string; + }): Promise ⋮---- -toggleUMFeeBurn(params: { - feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off - }): Promise<{ code: number; msg: string }> +/** + * + * Portfolio Margin Pro Endpoints + * + **/ ⋮---- -feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +getPortfolioMarginProAccountInfo(params: { + asset: string; + }): Promise ⋮---- -getUMFeeBurnStatus(): Promise<{ feeBurn: boolean }> +/** + * + * 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 + * + **/ ⋮---- -getMarginOrder( - params: QueryPortfolioMarginOrderReq, - ): Promise +/** + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, + ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> ⋮---- -getMarginOpenOrders(params: { - symbol: string; - }): Promise +/** + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, + ): Promise<{ customerId: string; email: string }> ⋮---- -getAllMarginOrders( - params: QueryPortfolioMarginAllOrdersReq, - ): Promise +/** + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, + ): Promise ⋮---- -getMarginOCO( - params: QueryPortfolioMarginOCOReq, - ): Promise +/** + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise ⋮---- -getAllMarginOCO( - params: QueryPortfolioMarginAllOCOReq, - ): Promise +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- -getMarginOpenOCO(): Promise +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -getMarginTrades( - params: QueryPortfolioMarginTradesReq, - ): Promise +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -repayMarginDebt( - params: PortfolioMarginRepayDebtReq, - ): Promise +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- /** * - * DERIVATIVES - ACCOUNT endpoints + * User Data Stream Endpoints * **/ ⋮---- -getBalance(params?: { asset?: string }): Promise +// USD-M Futures ⋮---- -getAccountInfo(): Promise +getFuturesUserDataListenKey(): Promise<{ listenKey: string }> ⋮---- -getMarginMaxBorrow(params: { asset: string }): Promise<{ - amount: string; // account's currently max borrowable amount with sufficient system availability - borrowLimit: string; // max borrowable amount limited by the account level - }> +keepAliveFuturesUserDataListenKey(): Promise ⋮---- -amount: string; // account's currently max borrowable amount with sufficient system availability -borrowLimit: string; // max borrowable amount limited by the account level +closeFuturesUserDataListenKey(): Promise ⋮---- -getMarginMaxWithdraw(params: { asset: string }): Promise<{ - amount: string; // max withdrawable amount - }> +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, + ): void + +================ +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'; ⋮---- -amount: string; // max withdrawable amount +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'; ⋮---- -getUMPosition(params?: { symbol?: string }): Promise +alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams ⋮---- -getCMPosition(params?: { - marginAsset?: string; - pair?: string; - }): Promise +type WsEventInternalSrc = 'event' | 'function'; ⋮---- -/** - * Change UM initial leverage (`POST /papi/v1/um/leverage`). - * `leverage` is an unbounded number here. The maximum is symbol-specific: - * bracket 1 `initialLeverage` from `GET /papi/v1/um/leverageBracket` - * (Binance derivatives changelog 2026-10-09). - */ -updateUMLeverage(params: { symbol: string; leverage: number }): Promise<{ - leverage: number; - maxNotionalValue: string; - symbol: string; - }> +type WebSocketWithMetadata = WebSocket & { + onping?: (event: unknown) => void; + onpong?: (event: unknown) => void; + wsKey?: WsKey | string; +}; ⋮---- -updateCMLeverage(params: { symbol: string; leverage: number }): Promise<{ - leverage: number; - maxQty: string; - symbol: 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; +} ⋮---- -updateUMPositionMode(params: { - dualSidePosition: 'true' | 'false'; - }): Promise<{ - code: number; - msg: string; - }> +on(event: 'reply', listener: (event: WsResponse) ⋮---- -updateCMPositionMode(params: { - dualSidePosition: 'true' | 'false'; - }): Promise<{ - code: number; - msg: string; - }> +on(event: 'message', listener: (event: WsRawMessage) ⋮---- -getUMPositionMode(): Promise<{ - dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode - }> +on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; ⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode +on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; ⋮---- -getCMPositionMode(): Promise<{ - dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode - }> +on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; ⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode +on( + event: 'open' | 'reconnected', + listener: (event: { + wsKey: WsKey; + ws: WebSocket.Event; + event?: any; + }) => void, + ): this; ⋮---- -getUMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - notionalCoef: string; - brackets: PortfolioUMLeverageBracket[]; - }[] - > +on( + event: 'reconnecting' | 'close', + listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, + ): this; ⋮---- -getCMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - brackets: PortfolioCMLeverageBracket[]; - }[] - > +/** + * @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 ⋮---- -getUMTradingStatus(params?: { - symbol?: string; - }): Promise +constructor( + options: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, + ) ⋮---- -getUMCommissionRate(params: { symbol: string }): Promise<{ - symbol: string; - makerCommissionRate: string; // e.g., "0.0002" for 0.02% - takerCommissionRate: string; // e.g., "0.0004" for 0.04% - }> +// Some defaults: ⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% +// Automatically send an authentication op/request after a connection opens, for private connections. ⋮---- -getCMCommissionRate(params: { symbol: string }): Promise<{ - symbol: string; - makerCommissionRate: string; // e.g., "0.0002" for 0.02% - takerCommissionRate: string; // e.g., "0.0004" for 0.04% - }> +// Individual requests require a signature ⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% +// add default error handling so this doesn't crash node (if the user didn't set a handler) ⋮---- -getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise<{ - rows: PortfolioMarginLoanRecord[]; - total: number; - }> +private getRestClientOptions(): RestClientOptions ⋮---- -getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise<{ - rows: PortfolioMarginRepayRecord[]; - total: number; - }> +public connectToWsUrl( + url: string, + wsKey?: WsKey | string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getAutoRepayFuturesStatus(): Promise<{ - autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off - }> +// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node ⋮---- -autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off +// Add ws connection with key to store ⋮---- -updateAutoRepayFuturesStatus(params: { - autoRepay: 'true' | 'false'; - }): Promise<{ - msg: string; - }> +public tryWsSend(wsKey: WsKey | string, wsMessage: string) ⋮---- -getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise<{ - rows: PortfolioMarginInterestRecord[]; - total: number; - }> +public tryWsPing(wsKey: WsKey | string) ⋮---- -repayFuturesNegativeBalance(): Promise<{ - msg: string; - }> +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -getPortfolioNegativeBalanceInterestHistory( - params?: GetPortfolioInterestHistoryReq, - ): Promise +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -autoCollectFunds(): Promise<{ - msg: string; - }> +private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) ⋮---- -/** - * Fund collection by asset (`POST /papi/v1/asset-collection`). - * - * Optional `amount` and `futureType` must be sent together. `futureType` - * is the target wallet (`UM`, `CM`, or `OPTION`; `OPTION` is SPAN only). - * If neither is sent, collection behavior is unchanged. - */ -transferAssetFuturesMargin(params: { - asset: string; - amount?: number; - futureType?: 'UM' | 'CM' | 'OPTION'; - }): Promise<{ - msg: string; - }> +private onWsClose( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + wsUrl: string, + ) ⋮---- -transferBNB(params: { - amount: string; - transferSide: 'TO_UM' | 'FROM_UM'; - }): Promise<{ - tranId: number; // transaction id - }> +// Clear any timers before we initiate revival ⋮---- -tranId: number; // transaction id +// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states ⋮---- -/** - * Query UM income history (`GET /papi/v1/um/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -getUMIncomeHistory( - params?: QueryPortfolioUMIncomeReq, - ): Promise +private onWsMessage( + event: WebSocket.MessageEvent, + wsKey: WsKey | string, + source: WsEventInternalSrc, + ) ⋮---- -/** - * Query CM income history (`GET /papi/v1/cm/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -getCMIncomeHistory( - params?: QueryPortfolioCMIncomeReq, - ): Promise +// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e ⋮---- -getUMAccount(): Promise<{ - assets: PortfolioUMAccountAsset[]; - positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market - }> +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn ⋮---- -positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market +// emit a separate event for user data messages ⋮---- -getCMAccount(): Promise<{ - assets: PortfolioCMAccountAsset[]; - positions: PortfolioCMAccountPosition[]; - }> +private sendPing(wsKey: WsKey | string, wsUrl: string) ⋮---- -getUMAccountConfig(): Promise +private onWsPing( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + source: WsEventInternalSrc, + ) ⋮---- -getUMSymbolConfig(params?: { - symbol?: string; - }): Promise +private onWsPong( + event: any, + wsKey: WsKey | string, + source: WsEventInternalSrc, + ) ⋮---- -getUMAccountV2(): Promise<{ - assets: PortfolioUMAccountAssetV2[]; - positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market - }> +/** + * 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, + ) ⋮---- -positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market +public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) ⋮---- -getUMTradeHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms - }): Promise<{ - avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days - downloadId: string; - }> +public closeAll(shouldReconnectAfterClose?: boolean) ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +private parseWsError( + context: string, + error: any, + wsKey: WsKey | string, + wsUrl: string, + ) ⋮---- -getUMTradeDownloadLink(params: { - downloadId: string; - }): Promise +private reconnectWithDelay( + wsKey: WsKey | string, + connectionDelayMs: number, + wsUrl: string, + ) ⋮---- -getUMOrderHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms - }): Promise<{ - avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days - downloadId: string; - }> +// We'll set a new one once the new stream respawns, with a diff listenKey in the key ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +private clearTimers(wsKey: WsKey | string) ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +// Send a ping at intervals +private clearPingTimer(wsKey: WsKey | string) ⋮---- -getUMOrderDownloadLink(params: { - downloadId: string; - }): Promise +// Expect a pong within a time limit +private clearPongTimer(wsKey: WsKey | string) ⋮---- -getUMTransactionHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms - }): Promise<{ - avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days - downloadId: string; - }> +// Timer tracking that a reconnect is about to happen / in progress +private clearReconnectTimer(wsKey: WsKey | string) ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +// eslint-disable-next-line @typescript-eslint/no-unused-vars +private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +public getWs(wsKey: WsKey | string): WebSocket | undefined ⋮---- -getUMTransactionDownloadLink(params: { - downloadId: string; - }): Promise +private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) ⋮---- /** - * Validate syntax meets requirements set by binance. Log warning if not. + * Send WS message to subscribe to topics. Use subscribe() to call this. */ -private validateOrderId( - params: - | NewPortfolioUMOrderReq - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, - ): void +private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) ⋮---- /** - * - * User Data Stream Endpoints - * - **/ -getPMUserDataListenKey(): Promise<{ listenKey: string }> -⋮---- -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, - GetFuturesAllOrdersParams, - 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, - 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'; + * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. + */ +private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) ⋮---- -export class USDMClient extends BaseRestClient +/** + * Send WS message to unsubscribe from topics. + */ +public requestListSubscriptions(wsKey: WsKey, requestId: number) ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, +/** + * Send WS message to set property state + */ +public requestSetProperty( + wsKey: WsKey, + property: 'combined' | string, + value: any, + requestId: number, ) ⋮---- /** - * Abstraction required by each client to aid with time sync / drift handling + * Send WS message to get property state */ -async getServerTime(): Promise +public requestGetProperty( + wsKey: WsKey, + property: 'combined' | string, + requestId: number, + ) ⋮---- /** - * - * MARKET DATA endpoints - Rest API - * + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- **/ ⋮---- -testConnectivity(): Promise +private setKeepAliveListenKeyTimer( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, + ) ⋮---- -getExchangeInfo(): Promise +// Set timer to keep WS alive every 50 minutes ⋮---- -getOrderBook(params: OrderBookParams): Promise +// 1000 * 60 ⋮---- -getRpiOrderBook(params: { - symbol: string; - limit?: number; - }): Promise +private sendKeepAliveForMarket( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, + ) ⋮---- -getRecentTrades(params: RecentTradesParams): Promise +private async checkKeepAliveListenKey( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, + ) ⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, - ): Promise +// Simple way to test keep alive failure handling: +// throw new Error(`Fake keep alive failure`); ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, - ): Promise +// code: -1125, +// message: 'This listenKey does not exist.', ⋮---- -getKlines(params: KlinesParams): Promise +// If max failurees reached, tear down and respawn if allowed ⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, - ): Promise +// 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 ⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) ⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) ⋮---- -getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise +private async respawnUserDataStream( + market: WsMarket, + symbol?: string, + isTestnet?: boolean, + respawnAttempt?: number, + ): Promise ⋮---- -getMarkPrice(params: +// 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 ⋮---- -getMarkPrice(): Promise; +// This timer should probably be tracked/singleton ⋮---- -getMarkPrice(params?: { symbol?: string }): Promise +/** + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- + **/ ⋮---- -getFundingRateHistory( - params?: Partial, - ): Promise +/** + * Subscribe to a universal market websocket stream + */ ⋮---- -getFundingRates(): Promise +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -get24hrChangeStatistics(params: +/** + * Subscribe to aggregate trades for a symbol in a market category + */ +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -get24hrChangeStatistics(): Promise; +/** + * 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 ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; - }): Promise +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeBlockTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolPriceTicker(params: +/** + * Subscribe to coin index for a symbol in COINM Futures markets + * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. + */ +public subscribeCoinIndexPrice( + symbol: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolPriceTicker(): Promise; +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; - }): Promise +/** + * 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 ⋮---- -getSymbolPriceTickerV2(params: +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolPriceTickerV2(): Promise; +/** + * Subscribe to klines(candles) for a symbol in a market category + */ +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolPriceTickerV2(params?: { - symbol?: string; - }): Promise +/** + * 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 ⋮---- -getSymbolOrderBookTicker(params: { - symbol: string; - }): Promise; +/** + * 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 ⋮---- -getSymbolOrderBookTicker(): Promise; +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; - }): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllBookTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getQuarterlyContractSettlementPrices(params: { - pair: string; - }): Promise +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getOpenInterest(params: { symbol: string }): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getOpenInterestStatistics( - params: FuturesDataPaginatedParams, - ): Promise +/** + * 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 ⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams, - ): Promise +/** + * 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 ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesDataPaginatedParams, - ): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, - ): Promise +/** + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- -getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise +/** + * Subscribe to aggregate trades for a symbol in spot markets. + */ +public subscribeSpotAggregateTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +/** + * Subscribe to trades for a symbol in spot markets. + */ +public subscribeSpotTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getCompositeSymbolIndex(params?: { symbol?: string }): Promise +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeSpotBlockTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getMultiAssetsModeAssetIndex(params?: { symbol?: string }): Promise +/** + * Subscribe to candles for a symbol in spot markets. + */ +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- /** - * Possibly @deprecated, found only in old docs - **/ -getBasis(params: BasisParams): Promise + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getIndexPriceConstituents(params: { - symbol: string; - }): Promise +/** + * Subscribe to mini 24hr mini ticker in spot markets. + */ +public subscribeSpotAllMini24hrTickers( + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getInsuranceFundBalance(params?: { - symbol?: string; - }): Promise +/** + * Subscribe to 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbol24hrTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getTradingSchedule(): Promise +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** - * - * TRADE endpoints - Rest API - * - **/ + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** - * 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. + * Subscribe to top bid/ask levels for symbol in spot markets. */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], - ): Promise<(NewOrderResult | NewOrderError)[]> +public subscribeSpotPartialBookDepth( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -// Known issue: `quantity` and `price` should be sent as strings, see #523, #526 +/** + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- /** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. + * Supports spot, margin & isolated margin listen keys. */ -modifyOrder( - params: ModifyFuturesOrderParams, - ): Promise +public subscribeSpotUserDataStreamWithListenKey( + listenKey: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): WebSocket | undefined ⋮---- -modifyMultipleOrders(orders: ModifyOrderParams[]): Promise +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -getOrderModifyHistory( - params: GetFuturesOrderModifyHistoryParams, - ): Promise +/** + * 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 ⋮---- -cancelOrder(params: CancelOrderParams): Promise +/** + * Subscribe to margin user data stream - listen key is automatically generated. + */ +public async subscribeMarginUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, - ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -cancelAllOpenOrders(params: { - symbol: string; - }): Promise +/** + * Subscribe to isolated margin user data stream - listen key is automatically generated. + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, - ): Promise +// Start & store timer to keep alive listen key (and handle expiration) +⋮---- +/** + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- -getOrder(params: GetOrderParams): Promise +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeUsdFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -getAllOrders(params?: GetFuturesAllOrdersParams): Promise +// Necessary so client knows this is a reconnect ⋮---- -getAllOpenOrders(params?: { symbol?: string }): Promise +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +/** + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeCoinFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +// Necessary so client knows this is a reconnect ⋮---- -getAccountTrades( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, - ): Promise +// Start & store timer to keep alive listen key (and handle expiration) + +================ +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; ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +export type ExchangeSymbol = string; ⋮---- -setPositionMode(params: PositionModeParams): Promise +export type BooleanString = 'true' | 'false'; +⋮---- +export type BinanceBaseUrlKey = + | 'spot' + | 'spot1' + | 'spot2' + | 'spot3' + | 'spot4' + | 'spottest' + | 'usdmtest' + | 'usdm' + | 'coinm' + | 'coinmtest' + | 'voptions' + | 'voptionstest' + | 'papi' + | 'www'; ⋮---- /** - * Change initial leverage (`POST /fapi/v1/leverage`). - * `leverage` is an unbounded number here. The maximum is symbol-specific: - * bracket 1 `initialLeverage` from `GET /fapi/v1/leverageBracket` - * (Binance derivatives changelog 2026-10-09). - */ -setLeverage(params: SetLeverageParams): Promise + * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. + */ +export type OrderTimeInForce = + | 'GTC' + | 'IOC' + | 'FOK' + | 'GTX' + | 'GTE_GTC' + | 'GTD' + | 'RPI'; ⋮---- -setMultiAssetsMode(params: { - multiAssetsMargin: MultiAssetsMode; - }): Promise +export type StringBoolean = 'TRUE' | 'FALSE'; ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, - ): Promise +export type SideEffects = + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'NO_SIDE_EFFECT' + | 'AUTO_BORROW_REPAY' + | 'NO_SIDE_EFFECT'; ⋮---- /** - * @deprecated - * Use getPositionsV3() instead - **/ -getPositions(params?: Partial): Promise -⋮---- -getPositionsV3(params?: { symbol?: string }): Promise + * 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'; ⋮---- -getADLQuantileEstimation(params?: { symbol?: string }): Promise +export type OrderIdProperty = + | 'newClientOrderId' + | 'newClientStrategyId' + | 'listClientOrderId' + | 'limitClientOrderId' + | 'stopClientOrderId' + | 'clientAlgoId' + | 'aboveClientOrderId' + | 'belowClientOrderId' + | 'workingClientOrderId' + | 'pendingAboveClientOrderId' + | 'pendingBelowClientOrderId' + | 'pendingClientOrderId'; ⋮---- -getSymbolAdlRisk(params: +export type OrderSide = 'BUY' | 'SELL'; ⋮---- -getSymbolAdlRisk(): Promise; +export type OrderStatus = + | 'NEW' + | 'PENDING_NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'EXPIRED_IN_MATCH'; ⋮---- -getSymbolAdlRisk(params?: { - symbol?: string; - }): Promise +export type OrderExecutionType = + | 'NEW' + | 'CANCELED' + | 'REJECTED' + | 'TRADE' + | 'EXPIRED'; ⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, - ): Promise +export type OrderListContingencyType = + | 'OCO' + | 'OTO' + | 'OTOCO' + | 'OPO' + | 'OPOCO'; ⋮---- -/** - * - * ACCOUNT endpoints - Rest API - * - **/ +// listStatusType +export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; ⋮---- -getBalanceV3(): Promise +// listOrderStatus +export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; ⋮---- -/** - * @deprecated - * Use getBalanceV3() instead - **/ -getBalance(): Promise +export type OrderType = + | 'LIMIT' + | 'LIMIT_MAKER' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -getAccountInformationV3(): Promise +export type OrderListOrderType = + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -/** - * @deprecated - * Use getAccountInformationV3() instead - **/ -getAccountInformation(): Promise +export type SelfTradePreventionMode = + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE' + | 'DECREMENT' + | 'TRANSFER'; ⋮---- -getAccountCommissionRate(params: { - symbol: string; - }): Promise +/** Spot expiry reasons. Unknown strings remain supported for forward compatibility. */ +export type SpotExpiryReason = + | 'NONE' + | 'REJECTED' + | 'EXCHANGE_CANCELED' + | 'OCO_TRIGGER' + | 'OTO_PHASE_ONE_EXPIRED' + | 'UNFILLED_IOC_QUANTITY_EXPIRED' + | 'UNFILLED_FOK_ORDER_EXPIRED' + | 'INSUFFICIENT_LIQUIDITY' + | 'EXECUTION_RULE_PRICE_RANGE_EXCEEDED' + | 'EXHAUSTED' + | 'INSUFFICIENT_QUOTE_NOTIONAL_LIMIT' + | (string & Record); +⋮---- +export type SpotEffectiveSelfTradePreventionMode = + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'DECREMENT'; ⋮---- -getFuturesAccountConfig(): Promise +export interface BasicAssetParam { + asset: string; +} ⋮---- -getFuturesSymbolConfig(params: { symbol?: string }): Promise +export interface BasicSymbolParam { + symbol: string; + isIsolated?: StringBoolean; +} ⋮---- -getUserForceOrders(): Promise +export interface SymbolArrayParam { + symbols: string[]; +} ⋮---- -/** - * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) - */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; - }): Promise +export interface BasicAssetPaginatedParams { + asset?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +export interface BasicSymbolPaginatedParams { + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getMultiAssetsMode(): Promise +export interface SymbolPrice { + symbol: string; + price: numberInString; + time?: number; +} ⋮---- -getCurrentPositionMode(): Promise +// used by spot and usdm +export interface OrderBookParams { + symbol: string; + limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; + symbolStatus?: string; +} ⋮---- -/** - * Query income history (`GET /fapi/v1/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -getIncomeHistory(params?: GetIncomeHistoryParams): Promise +export type KlineInterval = + | '1s' + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '3d' + | '1w' + | '1M'; ⋮---- -getApiQuantitativeRulesIndicators(params?: { - symbol?: string; - }): Promise +export interface GetOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Get a download id for futures transaction history (`GET /fapi/v1/income/asyn`). - * Limited to 100 requests per month, shared across the web download page, - * REST, USD-M and COIN-M. - */ -getFuturesTransactionHistoryDownloadId(params: { - startTime: number; - endTime: number; - }): Promise +export interface GetOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; - }): Promise +export interface HistoricalTradesParams { + symbol: string; + limit?: number; + fromId?: number; +} ⋮---- -getFuturesOrderHistoryDownloadId(params: { - startTime: number; - endTime: number; - }): Promise +export interface KlinesParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} ⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; - }): Promise +export type Kline = [ + number, // open time + numberInString, // open + numberInString, // high + numberInString, // low + numberInString, // close + numberInString, // volume + number, // close time + numberInString, // quote asset volume + number, // number of trades + numberInString, // taker buy base asset vol + numberInString, // taker buy quote asset vol + numberInString, // ignore? +]; ⋮---- -getFuturesTradeHistoryDownloadId(params: { - startTime: number; - endTime: number; - }): Promise +number, // open time +numberInString, // open +numberInString, // high +numberInString, // low +numberInString, // close +numberInString, // volume +number, // close time +numberInString, // quote asset volume +number, // number of trades +numberInString, // taker buy base asset vol +numberInString, // taker buy quote asset vol +numberInString, // ignore? ⋮---- -getFuturesTradeDownloadLink(params: { - downloadId: string; - }): Promise +/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ +export type FuturesKline = Kline; +export interface RecentTradesParams { + symbol: string; + limit?: number; +} ⋮---- -setBNBBurnEnabled(params: { - feeBurn: 'true' | 'false'; - }): Promise<{ code: number; msg: string }> +export interface CancelOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -getBNBBurnStatus(): Promise<{ - feeBurn: boolean; - }> +export interface AmendKeepPriorityParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + newQty: numberInString; +} ⋮---- -signTradFiPerpsAgreement(): Promise<{ code: number; msg: string }> +export interface CancelOCOParams { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -testOrder(params: NewFuturesOrderParams): Promise +export interface NewOCOParams { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + limitClientOrderId?: string; + limitStrategyId?: number; + limitStrategyType?: number; + price: number; + limitIcebergQty?: number; + trailingDelta?: number; + stopClientOrderId?: string; + stopPrice: number; + stopStrategyId?: number; + stopStrategyType?: number; + stopLimitPrice?: number; + stopIcebergQty?: number; + stopLimitTimeInForce?: OrderTimeInForce; + newOrderRespType?: OrderResponseType; + /** For isolated margin trading only */ + isIsolated?: StringBoolean; + /** Define a side effect, only for margin trading */ + sideEffectType?: SideEffects; +} ⋮---- -/** - * - * Algo Order Endpoints (Effective 2025-12-02) - * Conditional orders migrate to Algo Service - * - **/ +/** For isolated margin trading only */ ⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, - ): Promise +/** Define a side effect, only for margin trading */ ⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, - ): Promise +export interface NewOrderListParams< + T extends OrderResponseType = OrderResponseType, +> { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + aboveType: OrderListOrderType; + aboveClientOrderId?: string; + aboveIcebergQty?: number; + abovePrice?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + aboveQuoteNotionalLimit?: number; + aboveStopPrice?: number; + aboveTrailingDelta?: number; + aboveTimeInForce?: OrderTimeInForce; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: OrderListOrderType; + belowClientOrderId?: string; + belowIcebergQty?: number; + belowPrice?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + belowQuoteNotionalLimit?: number; + belowStopPrice?: number; + belowTrailingDelta?: number; + belowTimeInForce?: OrderTimeInForce; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: T; + selfTradePreventionMode?: SelfTradePreventionMode; +} ⋮---- -cancelAllAlgoOpenOrders(params: { - symbol: string; - }): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -getAlgoOrder( - params: FuturesQueryAlgoOrderParams, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, - ): Promise +export interface SymbolFromPaginatedRequestFromId { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getAllAlgoOrders( - params: FuturesQueryAllAlgoOrdersParams, - ): Promise +export interface GetAllOrdersParams { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * - * Convert Endpoints - * - **/ +export interface RateLimiter { + rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; + interval: 'SECOND' | 'MINUTE' | 'DAY'; + intervalNum: number; + limit: number; +} ⋮---- -getAllConvertPairs(params?: { - fromAsset?: string; - toAsset?: string; - }): Promise +export interface SymbolPriceFilter { + filterType: 'PRICE_FILTER'; + minPrice: numberInString; + maxPrice: numberInString; + tickSize: numberInString; +} ⋮---- -submitConvertQuoteRequest( - params: FuturesConvertQuoteRequest, - ): Promise +export interface SymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -acceptConvertQuote(params: { quoteId: string }): Promise<{ - orderId: string; - createTime: number; - orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; - }> +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; +} ⋮---- -getConvertOrderStatus(params: { - orderId?: string; - quoteId?: string; - }): Promise +export interface SymbolLotSizeFilter { + filterType: 'LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -/** - * - * Portfolio Margin Pro Endpoints - * - **/ +export interface SymbolMinNotionalFilter { + filterType: 'NOTIONAL'; + minNotional: numberInString; + applyMinToMarket: boolean; + maxNotional: numberInString; + applyMaxToMarket: boolean; + avgPriceMins: number; +} ⋮---- -getPortfolioMarginProAccountInfo(params: { - asset: string; - }): Promise +export interface SymbolIcebergPartsFilter { + filterType: 'ICEBERG_PARTS'; + limit: number; +} ⋮---- -/** - * - * Broker Futures Endpoints - * Possibly @deprecated, found only in old docs - * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker - * - **/ +export interface SymbolMarketLotSizeFilter { + filterType: 'MARKET_LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, - ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> +export interface SymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -/** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, - ): Promise<{ customerId: string; email: string }> +export interface SymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, - ): Promise +export interface SymbolMaxIcebergOrdersFilter { + filterType: 'MAX_NUM_ICEBERG_ORDERS'; + maxNumIcebergOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise +export interface SymbolMaxPositionFilter { + filterType: 'MAX_POSITION'; + maxPosition: numberInString; +} ⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +export type SymbolFilter = + | SymbolPriceFilter + | SymbolPercentPriceFilter + | SymbolPercentPriceBySideFilter + | SymbolLegacyMinNotionalFilter + | SymbolLotSizeFilter + | SymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | SymbolMaxOrdersFilter + | SymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter; ⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise +export interface ExchangeMaxNumOrdersFilter { + filterType: 'EXCHANGE_MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise +export interface ExchangeMaxAlgoOrdersFilter { + filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise +export type ExchangeFilter = + | ExchangeMaxNumOrdersFilter + | ExchangeMaxAlgoOrdersFilter; ⋮---- -/** - * - * User Data Stream Endpoints - * - **/ +export type OrderBookPrice = numberInString; +export type OrderBookAmount = numberInString; ⋮---- -// USD-M Futures +export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; ⋮---- -getFuturesUserDataListenKey(): Promise<{ listenKey: string }> +export type OrderBookPriceFormatted = number; +export type OrderBookAmountFormatted = number; +export type OrderBookRowFormatted = [ + OrderBookPriceFormatted, + OrderBookAmountFormatted, +]; ⋮---- -keepAliveFuturesUserDataListenKey(): Promise +export interface GenericCodeMsgError { + code: number; + msg: string; +} ⋮---- -closeFuturesUserDataListenKey(): Promise +export interface RowsWithTotal { + rows: T[]; + total: number; +} ⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, - ): void +export interface CoinStartEndLimit { + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ================ File: src/types/websockets/ws-api-responses.ts @@ -10114,8 +10144,13 @@ import { OrderSide, OrderTimeInForce, SelfTradePreventionMode, + SpotExpiryReason, } from '../shared'; -import { OrderResponse, SpotNewOrderConditionalFields } from '../spot'; +import { + OrderResponse, + SpotNewOrderConditionalFields, + SpotOrderPreventedMatch, +} from '../spot'; ⋮---- /** * Error response type @@ -10388,6 +10423,7 @@ export interface WSAPIRateLimit { } ⋮---- export interface WSAPIOrder { + quoteNotionalLimit?: numberInString; symbol: string; orderId: number; orderListId: number; @@ -10411,7 +10447,7 @@ export interface WSAPIOrder { preventedMatchId?: number; preventedQuantity?: numberInString; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } ⋮---- /** Present only for expired orders. */ @@ -10523,6 +10559,7 @@ export interface WSAPIOrderTestWithCommission { */ ⋮---- export interface WSAPIOrderCancel { + quoteNotionalLimit?: numberInString; symbol: string; origClientOrderId: string; orderId: number; @@ -10602,7 +10639,7 @@ export interface WSAPIOrderListStatusResponse { orderId: number; clientOrderId: string; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; }[]; } ⋮---- @@ -10612,6 +10649,7 @@ export interface WSAPIOrderListStatusResponse { * SOR response types */ export interface WSAPISOROrderPlaceResponse { + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -10628,7 +10666,7 @@ export interface WSAPISOROrderPlaceResponse { side: string; workingTime: number; /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; fills: { matchType: string; price: string; @@ -10887,7 +10925,7 @@ export interface WSAPISpotOrderRESULT workingTime: number; selfTradePreventionMode: string; /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } ⋮---- /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ @@ -10902,6 +10940,7 @@ export interface WSAPISpotOrderFill { ⋮---- export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { fills: WSAPISpotOrderFill[]; + preventedMatches?: SpotOrderPreventedMatch[]; } ⋮---- export type WSAPISpotOrderResponse = @@ -10936,6 +10975,8 @@ import { OrderTimeInForce, OrderType, SelfTradePreventionMode, + SpotEffectiveSelfTradePreventionMode, + SpotExpiryReason, } from '../shared'; import { AccountUpdateEventType, @@ -11210,7 +11251,10 @@ export interface WsMessageSpotUserDataExecutionReportEventFormatted orderQuoteQty: number; workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; - expiryReason?: string; + expiryReason?: SpotExpiryReason; + /** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ + effectiveSelfTradePreventionMode?: SpotEffectiveSelfTradePreventionMode; + quoteNotionalLimit?: number; trailingDelta?: number; preventedMatchId?: number; trailingTime?: number; @@ -11228,6 +11272,8 @@ export interface WsMessageSpotUserDataExecutionReportEventFormatted preventedExecutionQuoteQty?: number; } ⋮---- +/** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ +⋮---- /** Allocation ID. */ ⋮---- export interface WsMessagePortfolioMarginProAccountUpdateFormatted @@ -11246,8 +11292,12 @@ export interface WsMessagePortfolioMarginProAccountUpdateFormatted export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { eventType: 'serverShutdown'; eventTime: number; + /** Time when the WebSocket session will shut down. */ + shutdownTime?: number; } ⋮---- +/** Time when the WebSocket session will shut down. */ +⋮---- export interface OrderObjectFormatted { symbol: string; orderId: number; @@ -11664,6 +11714,8 @@ import { OrderTimeInForce, OrderType, SelfTradePreventionMode, + SpotEffectiveSelfTradePreventionMode, + SpotExpiryReason, } from '../shared'; import { WsSharedBase } from './ws-general'; ⋮---- @@ -11897,7 +11949,11 @@ export interface WsMessageSpotUserDataExecutionReportEventRaw W: number; V: SelfTradePreventionMode; /** Expiry reason when present (user data executionReport). */ - eR?: string; + eR?: SpotExpiryReason; + /** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ + eV?: SpotEffectiveSelfTradePreventionMode; + /** Present only when the order has a quote notional limit. */ + Qq?: numberInString; d?: number; v?: number; D?: number; @@ -11917,6 +11973,10 @@ export interface WsMessageSpotUserDataExecutionReportEventRaw ⋮---- /** Expiry reason when present (user data executionReport). */ ⋮---- +/** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ +⋮---- +/** Present only when the order has a quote notional limit. */ +⋮---- /** Allocation ID. */ ⋮---- export interface WsMessagePortfolioMarginProAccountUpdateRaw @@ -11935,8 +11995,12 @@ export interface WsMessagePortfolioMarginProAccountUpdateRaw export interface WsMessageWsapiServerShutdownRaw extends WsSharedBase { e: 'serverShutdown'; E: number; + /** Time when the WebSocket session will shut down. */ + T?: number; } ⋮---- +/** Time when the WebSocket session will shut down. */ +⋮---- export interface OrderObjectRaw { s: string; i: number; @@ -14327,3114 +14391,3174 @@ If you want to learn more about integrating with Binance APIs and WebSockets: - Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) ================ -File: src/types/websockets/ws-api-requests.ts +File: src/types/futures.ts ================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderType, - FuturesOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; import { BooleanString, + ExchangeFilter, KlineInterval, numberInString, - OrderResponseType, + OrderBookRow, 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; -} + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SymbolIcebergPartsFilter, + SymbolLotSizeFilter, + SymbolMarketLotSizeFilter, + SymbolMaxIcebergOrdersFilter, + SymbolMaxPositionFilter, + SymbolPriceFilter, +} from './shared'; ⋮---- -export interface WSAPITradesHistoricalRequest { - symbol: string; - fromId?: number; - limit?: number; -} +export type FuturesContractType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; ⋮---- -export interface WSAPIBlockTradesHistoricalRequest { - symbol: string; - fromId: number; +export interface ContinuousContractKlinesParams { + pair: string; + contractType: FuturesContractType; + interval: KlineInterval; + startTime?: number; + endTime?: number; limit?: number; } ⋮---- -export interface WSAPITradesAggregateRequest { - symbol: string; - fromId?: number; +export interface IndexPriceKlinesParams { + pair: string; + interval: KlineInterval; startTime?: number; endTime?: number; limit?: number; } ⋮---- -export interface WSAPIKlinesRequest { +export interface SymbolKlinePaginatedParams { 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' | 'CANCEL_ONLY'; -} -⋮---- -export interface WSAPIReferencePriceRequest { - symbol: string; -} -⋮---- -export interface WSAPIReferencePriceCalculationRequest { +export interface FuturesDataPaginatedParams { symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; -} -⋮---- -/** - * 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; + contractType?: string; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerBookRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; +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; } ⋮---- -/** - * - * Account request types - Spot - * - */ -⋮---- -export interface WSAPIAllOrdersRequest { - symbol: string; - orderId?: 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; - limit?: number; } ⋮---- -export interface WSAPIAllOrderListsRequest { - fromId?: number; +export interface FuturesCoinMLongShortAccountRatioParams { + pair: string; + contractType?: 'PERPETUAL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; startTime?: number; endTime?: number; - limit?: number; } ⋮---- -export interface WSAPIMyTradesRequest { - symbol: string; +export interface GetFuturesAllOrdersParams { + 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 enum EnumDualSideMode { + HedgeMode = 'true', + OneWayMode = 'false', } ⋮---- -export interface WSAPIMyAllocationsRequest { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; +export type DualSideMode = `${EnumDualSideMode}`; +⋮---- +export enum EnumMultiAssetMode { + MultiAssetsMode = 'true', + SingleAssetsMode = 'false', } ⋮---- -/** - * Trading request types - */ -type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; -type SpotPegOffsetType = 'PRICE_LEVEL'; +export type MultiAssetsMode = `${EnumMultiAssetMode}`; ⋮---- -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?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; -} +export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; ⋮---- -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?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - computeCommissionRates?: boolean; - timestamp: number; - recvWindow?: number; -} +export type MarginType = 'ISOLATED' | 'CROSSED'; ⋮---- -export interface WSAPIOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- -export interface WSAPIOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - recvWindow?: number; - timestamp: number; -} +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'; ⋮---- -export interface WSAPIOrderCancelReplaceRequest { +// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. +export interface NewFuturesOrderParams { 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; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesOrderType; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberType; newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; + stopPrice?: numberType; + closePosition?: BooleanString; + activationPrice?: numberType; + callbackRate?: numberType; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: 'ACK' | 'RESULT'; selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; - recvWindow?: number; - timestamp: number; + priceMatch?: PriceMatchMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- -export interface WSAPIOrderAmendKeepPriorityRequest { - symbol: string; - orderId?: number | string; +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +export interface ModifyFuturesOrderParams { + orderId?: number; origClientOrderId?: string; - newClientOrderId?: string; - newQty?: string; - recvWindow?: number; - timestamp: number; + symbol: string; + side: OrderSide; + quantity?: numberType; + price?: numberType; + priceMatch?: PriceMatchMode; + modifyId?: number; + reduceOnly?: BooleanString; } ⋮---- -export interface WSAPIOpenOrdersStatusRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; +export enum EnumPositionMarginChangeType { + AddPositionMargin = 1, + ReducePositionMargin = 0, } ⋮---- -export interface WSAPIOpenOrdersCancelAllRequest { - symbol: string; - recvWindow?: number; - timestamp: number; -} +export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; ⋮---- -/** - * 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 type IncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'SPECIAL_FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR'; ⋮---- -export interface WSAPIOrderListPlaceOCORequest { +export interface CancelMultipleOrdersParams { 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; + orderIdList?: number[]; + origClientOrderIdList?: string[]; } ⋮---- -export interface WSAPIOrderListPlaceOTORequest { +export interface CancelOrdersTimeoutParams { 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; + countdownTime?: 0 | number; } ⋮---- -export interface WSAPIOrderListPlaceOTOCORequest { +export interface SetLeverageParams { 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; + leverage: 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 SetLeverageResult { + leverage: number; + maxNotionalValue: numberInString; + symbol: string; } ⋮---- -export interface WSAPIOrderListPlaceOPOCORequest { +export interface SetMarginTypeParams { 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; + marginType: MarginType; } ⋮---- -export interface WSAPIOrderListStatusRequest { - origClientOrderId?: string; - orderListId?: number; - recvWindow?: number; - timestamp: number; +export interface SetIsolatedMarginParams { + symbol: string; + positionSide?: PositionSide; + amount: number; + type: PositionMarginChangeType; } ⋮---- -export interface WSAPIOrderListCancelRequest { +export interface SetIsolatedMarginResult { + amount: numberInString; + code: 200 | number; + msg: string; + type: 1 | 2; +} +⋮---- +export interface GetPositionMarginChangeHistoryParams { symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; - recvWindow?: number; - timestamp: number; + type?: PositionMarginChangeType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- /** - * SOR request types + * Income history query for `GET /fapi/v1/income` and `GET /dapi/v1/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted. */ -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 interface GetIncomeHistoryParams { + symbol?: string; + incomeType?: IncomeType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { - computeCommissionRates?: boolean; -}; +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; +} ⋮---- /** - * Futures market data request types + * Undocumented USDⓈ-M `exchangeInfo` filter. Not in the published filter schema. + * Observed on live symbols (for example BTCUSDT) with `positionControlSide: "NONE"`. + * connector-python leaves it in `additional_properties`. */ +export interface FuturesSymbolPositionRiskControlFilter { + filterType: 'POSITION_RISK_CONTROL'; + /** + * Undocumented. Observed value: `NONE`. + */ + positionControlSide: string; +} ⋮---- -export interface WSAPIFuturesOrderBookRequest { +/** + * Undocumented. Observed value: `NONE`. + */ +⋮---- +export type FuturesSymbolFilter = + | SymbolPriceFilter + | FuturesSymbolPercentPriceFilter + | SymbolLotSizeFilter + | FuturesSymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | FuturesSymbolMaxOrdersFilter + | FuturesSymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter + | FuturesSymbolPositionRiskControlFilter; +⋮---- +export interface FuturesSymbolExchangeInfo { symbol: string; - limit?: number; + 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 WSAPIFuturesTickerPriceRequest { - symbol?: string; +export interface AggregateFuturesTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; } ⋮---- -export interface WSAPIFuturesTickerBookRequest { - symbol?: string; +export interface MarkPrice { + symbol: string; + markPrice: numberInString; + indexPrice: numberInString; + estimatedSettlePrice: numberInString; + lastFundingRate: numberInString; + interestRate: numberInString; + nextFundingTime: number; + time: number; } ⋮---- -/** - * Futures trading request types - */ -⋮---- -export interface WSAPINewFuturesOrderRequest { +export interface FundingRateHistory { 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; + fundingRate: numberInString; + fundingTime: number; + markPrice: numberInString; + rateType?: 'Regular' | 'Special'; } ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface WSAPIFuturesOrderModifyRequest { +export interface FuturesSymbolOrderBookTicker { 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; - reduceOnly?: BooleanString; - recvWindow?: number; - timestamp: number; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; } ⋮---- -export interface WSAPIFuturesOrderCancelRequest { +export interface OpenInterest { + openInterest: numberInString; symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; + time: number; } ⋮---- -export interface WSAPIFuturesOrderStatusRequest { +export interface HistoricOpenInterest { symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; + sumOpenInterest: string; + sumOpenInterestValue: string; + CMCCirculatingSupply: string; timestamp: number; } ⋮---- -export interface WSAPIFuturesPositionRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; +export interface PositionModeParams { + dualSidePosition: DualSideMode; } ⋮---- -export interface WSAPIFuturesPositionV2Request { - symbol?: string; - recvWindow?: number; - timestamp: number; +export interface ModeChangeResult { + code: 200 | number; + msg: 'success' | string; } ⋮---- -export interface WSAPIAccountInformationRequest { - omitZeroBalances?: boolean; - recvWindow?: number; - timestamp: number; +export interface PositionModeResponse { + dualSidePosition: boolean; } ⋮---- -export interface WSAPIAccountCommissionWSAPIRequest { - symbol: string; +export interface MultiAssetModeResponse { + multiAssetsMargin: boolean; } ⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api - */ -export interface WSAPINewFuturesAlgoOrderRequest { - algoType: FuturesAlgoOrderType; - symbol: string; +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; - 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; + 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; + goodTillDate?: number; } - -================ -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 NewOrderError { + code: number; + msg: string; } ⋮---- -export interface IndexPriceKlinesParams { - pair: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; +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 SymbolKlinePaginatedParams { +export interface ModifyFuturesOrderResult { + orderId: number; symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; + 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 FuturesDataPaginatedParams { +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; - 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; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; } ⋮---- -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 interface CancelAllOpenOrdersResult { + code: 200 | numberInString; + msg: string; } ⋮---- -export interface FuturesCoinMLongShortAccountRatioParams { - pair: string; - contractType?: 'PERPETUAL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; +export interface FuturesAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + marginAvailable: boolean; + updateTime: numberInString; } ⋮---- -export interface GetFuturesAllOrdersParams { - symbol?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; +export interface FuturesCoinMAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + withdrawAvailable: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + updateTime: number; } ⋮---- -export enum EnumDualSideMode { - HedgeMode = 'true', - OneWayMode = 'false', +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 type DualSideMode = `${EnumDualSideMode}`; -⋮---- -export enum EnumMultiAssetMode { - MultiAssetsMode = 'true', - SingleAssetsMode = 'false', +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 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 { +export interface FuturesCoinMAccountPosition { 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 + positionAmt: numberInString; + initialMargin: numberInString; + maintMargin: numberInString; + unrealizedProfit: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + leverage: numberInString; + isolated: boolean; + positionSide: PositionSide; + entryPrice: numberInString; + maxQty: numberInString; + updateTime: number; } ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +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 ModifyFuturesOrderParams { - orderId?: number; - origClientOrderId?: string; - symbol: string; - side: OrderSide; - quantity?: numberType; - price?: numberType; - priceMatch?: PriceMatchMode; - modifyId?: number; - reduceOnly?: BooleanString; +export interface FuturesCoinMAccountInformation { + assets: Omit[]; + positions: FuturesCoinMAccountPosition[]; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; } ⋮---- -export enum EnumPositionMarginChangeType { - AddPositionMargin = 1, - ReducePositionMargin = 0, +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 type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; -⋮---- -export type IncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'SPECIAL_FUNDING_FEE' - | 'COMMISSION' - | 'INSURANCE_CLEAR'; -⋮---- -export interface CancelMultipleOrdersParams { +export interface FuturesPositionV3 { symbol: string; - orderIdList?: number[]; - origClientOrderIdList?: 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 CancelOrdersTimeoutParams { +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; - countdownTime?: 0 | number; + time: number; + pair?: string; + baseQty?: numberInString; + marginAsset?: string; } ⋮---- -export interface SetLeverageParams { +export interface ForceOrderResult { + orderId: number; symbol: string; - leverage: number; + 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 SetLeverageResult { - leverage: number; - maxNotionalValue: numberInString; - symbol: string; +export interface SymbolLeverageBracket { + bracket: number; + initialLeverage: number; + notionalCap: number; + notionalFloor: number; + maintMarginRatio: number; + cum: number; } ⋮---- -export interface SetMarginTypeParams { +export interface SymbolLeverageBracketsResult { symbol: string; - marginType: MarginType; + brackets: SymbolLeverageBracket[]; } ⋮---- -export interface SetIsolatedMarginParams { +export interface UserCommissionRate { symbol: string; - positionSide?: PositionSide; - amount: number; - type: PositionMarginChangeType; + makerCommissionRate: numberInString; + takerCommissionRate: numberInString; + rpiCommissionRate?: numberInString; } ⋮---- -export interface SetIsolatedMarginResult { - amount: numberInString; - code: 200 | number; - msg: string; - type: 1 | 2; +export interface FuturesAccountConfig { + feeTier: number; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + dualSidePosition: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId: number; } ⋮---- -export interface GetPositionMarginChangeHistoryParams { +export interface SymbolConfig { symbol: string; - type?: PositionMarginChangeType; - startTime?: number; - endTime?: number; - limit?: number; + marginType: string; + isAutoAddMargin: string; + leverage: number; + maxNotionalValue: string; } ⋮---- -/** - * Income history query for `GET /fapi/v1/income` and `GET /dapi/v1/income`. - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -export interface GetIncomeHistoryParams { - symbol?: string; - incomeType?: IncomeType; - startTime?: number; - endTime?: number; - limit?: number; +export interface UserForceOrder { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; } ⋮---- -export interface IncomeHistory { - symbol?: string; - incomeType: IncomeType; - income: string; - asset: string; +export interface RebateDataOverview { + brokerId: string; + newTraderRebateCommission: numberInString; + oldTraderRebateCommission: numberInString; + totalTradeUser: number; + unit: string; + totalTradeVol: numberInString; + totalRebateVol: numberInString; 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 SetCancelTimeoutResult { + symbol: string; + countdownTime: numberInString; } ⋮---- -export interface FuturesSymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - limit: number; +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; } ⋮---- -export interface FuturesSymbolMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - notional: numberInString; -} +firstId: number; // First tradeId +lastId: number; // Last tradeId ⋮---- -/** - * Undocumented USDⓈ-M `exchangeInfo` filter. Not in the published filter schema. - * Observed on live symbols (for example BTCUSDT) with `positionControlSide: "NONE"`. - * connector-python leaves it in `additional_properties`. - */ -export interface FuturesSymbolPositionRiskControlFilter { - filterType: 'POSITION_RISK_CONTROL'; - /** - * Undocumented. Observed value: `NONE`. - */ - positionControlSide: string; +export interface OrderAmendmentDetailPrice { + before: numberInString; + after: numberInString; } ⋮---- -/** - * Undocumented. Observed value: `NONE`. - */ +export interface OrderAmendmentDetailQty { + before: numberInString; + after: numberInString; +} ⋮---- -export type FuturesSymbolFilter = - | SymbolPriceFilter - | FuturesSymbolPercentPriceFilter - | SymbolLotSizeFilter - | FuturesSymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | FuturesSymbolMaxOrdersFilter - | FuturesSymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter - | FuturesSymbolPositionRiskControlFilter; +export interface OrderAmendmentDetail { + price: OrderAmendmentDetailPrice; + origQty: OrderAmendmentDetailQty; + count: number; +} ⋮---- -export interface FuturesSymbolExchangeInfo { +export interface OrderAmendment { + amendmentId: number; 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; + orderId: number; + clientOrderId: string; + time: number; + amendment: OrderAmendmentDetail; + modifyId?: 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; +export interface QuarterlyContractSettlementPrice { + deliveryTime: number; + deliveryPrice: number; } ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +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 FuturesOrderBook { - lastUpdateId: number; - E: number; - T: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; +export interface Basis { + indexPrice: string; + contractType: string; + basisRate: string; + futuresPrice: string; + annualizedBasisRate: string; + basis: string; + pair: string; + timestamp: number; } ⋮---- -export interface RawFuturesTrade { - id: number; +export interface IndexPriceConstituent { + exchange: string; + symbol: string; price: numberInString; - qty: numberInString; - quoteQty: numberInString; + weight: numberInString; +} +⋮---- +export interface IndexPriceConstituents { + symbol: string; time: number; - isBuyerMaker: boolean; + constituents: IndexPriceConstituent[]; } ⋮---- -export interface AggregateFuturesTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; +export interface InsuranceFundBalance { + symbols: string[]; + assets: { + asset: string; + marginBalance: string; + updateTime: number; + }[]; } ⋮---- -export interface MarkPrice { +export interface ModifyOrderParams { + orderId?: number; + origClientOrderId?: string; symbol: string; - markPrice: numberInString; - indexPrice: numberInString; - estimatedSettlePrice: numberInString; - lastFundingRate: numberInString; - interestRate: numberInString; - nextFundingTime: number; - time: number; + side: 'SELL' | 'BUY'; + quantity: string; + price: string; + priceMatch?: + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; + modifyId?: number; + reduceOnly?: BooleanString; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FundingRateHistory { +export interface GetFuturesOrderModifyHistoryParams { symbol: string; - fundingRate: numberInString; - fundingTime: number; - markPrice: numberInString; - rateType?: 'Regular' | 'Special'; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface FuturesSymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; +export interface FuturesTradeHistoryDownloadId { + avgCostTimestampOfLast30d: number; + downloadId: string; } ⋮---- -export interface OpenInterest { - openInterest: numberInString; - symbol: string; - time: number; +export interface FuturesTransactionDownloadLink { + downloadId: string; + status: 'completed' | 'processing'; + url: string; + expirationTimestamp: number; + isExpired: boolean | null; } ⋮---- -export interface HistoricOpenInterest { - symbol: string; - sumOpenInterest: string; - sumOpenInterestValue: string; - CMCCirculatingSupply: string; - timestamp: number; +export interface PortfolioMarginProAccountInfo { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; // This field will be ignored in the response } ⋮---- -export interface PositionModeParams { - dualSidePosition: DualSideMode; +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 ModeChangeResult { - code: 200 | number; - msg: 'success' | string; +export interface FuturesConvertQuoteRequest { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + validTime?: '10s' | '30s' | '1m' | '2m'; } ⋮---- -export interface PositionModeResponse { - dualSidePosition: boolean; +export interface FuturesConvertQuote { + quoteId: string; + ratio: string; + inverseRatio: string; + validTimestamp: number; + toAmount: string; + fromAmount: string; } ⋮---- -export interface MultiAssetModeResponse { - multiAssetsMargin: boolean; +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; } ⋮---- -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; +/** + * 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; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - origType: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; + 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; } ⋮---- -export interface NewOrderError { - code: number; - msg: string; -} +clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ ⋮---- -export interface OrderResult { - avgPrice: numberInString; - clientOrderId: string; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; +export interface FuturesAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; + symbol: string; 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; + quantity: numberInString; + algoStatus: FuturesAlgoOrderStatus; + triggerPrice?: numberInString; + price?: numberInString; + icebergQuantity: numberInString | null; selfTradePreventionMode: SelfTradePreventionMode; + workingType: WorkingType; 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; + activatePrice?: numberInString; + callbackRate?: numberInString; + createTime: number; 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; + triggerTime: number; + goodTillDate: number; } ⋮---- -export interface FuturesCoinMAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - withdrawAvailable: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - updateTime: number; +export interface FuturesCancelAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; } ⋮---- -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 FuturesCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; } ⋮---- -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 FuturesCancelAllAlgoOpenOrdersResponse { + code: number; + msg: string; } ⋮---- -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 FuturesQueryAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; } ⋮---- -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 FuturesQueryAlgoOrderResponse + extends FuturesAlgoOrderResponse { + actualOrderId: numberInString; + actualPrice: numberInString; + tpTriggerPrice?: numberInString; + tpPrice?: numberInString; + slTriggerPrice?: numberInString; + slPrice?: numberInString; + tpOrderType?: string; } ⋮---- -export interface FuturesCoinMAccountInformation { - assets: Omit[]; - positions: FuturesCoinMAccountPosition[]; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; +export interface FuturesQueryOpenAlgoOrdersParams { + algoType?: FuturesAlgoOrderType; + symbol?: string; + algoId?: 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; +export interface FuturesQueryAllAlgoOrdersParams { symbol: string; - unRealizedProfit: numberInString; - positionSide: PositionSide; - updateTime: number; + algoId?: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 500; max 1000 } ⋮---- -export interface FuturesPositionV3 { +limit?: number; // Default 500; max 1000 +⋮---- +export interface SymbolAdlRisk { 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; + adlRisk: 'low' | 'medium' | 'high'; 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 TradingSession { + startTime: number; + endTime: number; + type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; } ⋮---- -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; +export interface MarketSchedule { + sessions: TradingSession[]; +} +⋮---- +export interface TradingSchedule { updateTime: number; - cumBase?: numberInString; - pair?: string; - goodTillDate?: number; + marketSchedules: { + EQUITY?: MarketSchedule; + COMMODITY?: MarketSchedule; + KR_EQUITY?: MarketSchedule; + HK_EQUITY?: MarketSchedule; + CN_EQUITY?: MarketSchedule; + FX?: 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.ts +================ +import WebSocket from 'isomorphic-ws'; +⋮---- +import { KlineInterval } from './types/shared'; +import { + Exact, + WsAPIOperationResponseMap, + WsAPITopicRequestParamMap, + WsAPIWsKeyTopicMap, + WsOperation, + WsRequestOperationBinance, +} from './types/websockets/ws-api'; +import { + MessageEventLike, + WSClientConfigurableOptions, + WsMarket, + WsTopic, +} from './types/websockets/ws-general'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient'; +import Beautifier from './util/beautifier'; +import { DefaultLogger } from './util/logger'; +import { signMessage } from './util/node-support'; +import { + appendEventIfMissing, + requiresWSAPINewClientOID, + RestClientOptions, + serialiseParams, + validateWSAPINewClientOID, +} from './util/requestUtils'; +import { neverGuard } from './util/typeGuards'; +import { SignAlgorithm, SignEncodeMethod } from './util/webCryptoAPI'; +import { RestClientCache } from './util/websockets/rest-client-cache'; +import { UserDataStreamManager } from './util/websockets/user-data-stream-manager'; +import { + EVENT_TYPES_USER_DATA, + getLegacyWsKeyContext, + getLegacyWsStoreKeyWithContext, + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getPromiseRefForWSAPIRequest, + getRealWsKeyFromDerivedWsKey, + getTestnetWsKey, + getTopicsPerWSKey, + getWsKeyForProductGroup, + getWsUrl, + getWsURLSuffix, + isPrivateWsTopic, + isWSPingFrameAvailable, + isWSPongFrameAvailable, + MiscUserDataConnectionState, + parseEventTypeFromMessage, + parseRawWsMessage, + resolveUserDataMarketForWsKey, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WSAPIWsKey, + WSConnectionCategory, + WsKey, + WsTopicRequest, +} from './util/websockets/websocket-util'; +import { WSConnectedResult } from './util/websockets/WsStore.types'; +⋮---- +type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +⋮---- +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; } ⋮---- -export interface SymbolLeverageBracket { - bracket: number; - initialLeverage: number; - notionalCap: number; - notionalFloor: number; - maintMarginRatio: number; - cum: number; -} +/** If true, will skip auth requirement for WS API connection */ +⋮---- +/** + * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. + * + * When possible, it will subscribe to all requested topics on a single websocket connection. A list of + * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. + * + * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically + * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. + * + * If any connection is reconnected, the WS client will: + * - Emit the "reconnecting" event when the process begins. + * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a + * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed + * while disconnected. + * + * User data streams will use a dedicated connection per stream for increased resilience. + */ +⋮---- +export class WebsocketClient extends BaseWebsocketClient< +⋮---- +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +⋮---- +/** + * Binance uses native WebSocket ping/pong frames, which cannot be directly used in + * some environents (e.g. most browsers do not support sending raw ping/pong frames). + * + * This disables heartbeats in those environments, if ping/pong frames are unavailable. + * + * Some browsers may still handle these automatically. Some discussion around this can + * be found here: https://stackoverflow.com/questions/10585355/sending-websocket-ping-pong-frame-from-browser + */ +⋮---- +// fn pointers: +⋮---- +protected onWsCloseCleanup(wsKey: WsKey): void +⋮---- +private getUserDataStreamManager(): UserDataStreamManager +⋮---- +private getRestClientOptions(): RestClientOptions +⋮---- +/** + * Request connection of all dependent (public & WS API) websockets in prod, instead of waiting + * for automatic connection by SDK. + * + * For the Binance SDK, this will only open public connections (without auth), but is almost definitely overkill if you're only working with one product group. + */ +public connectAll(): Promise[] +⋮---- +/** + * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if + * you're only working with one product group. + */ +public connectPublic(): Promise[] +⋮---- +/** + * This function serves no purpose in the Binance SDK + */ +public async connectPrivate(): Promise ⋮---- -export interface SymbolLeverageBracketsResult { - symbol: string; - brackets: SymbolLeverageBracket[]; -} +/** + * Ensures the WS API connection is active and ready. + * + * You do not need to call this, but if you call this before making any WS API requests, + * it can accelerate the first request (by preparing the connection in advance). + */ +public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise ⋮---- -export interface UserCommissionRate { - symbol: string; - makerCommissionRate: numberInString; - takerCommissionRate: numberInString; - rpiCommissionRate?: numberInString; -} +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -export interface FuturesAccountConfig { - feeTier: number; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - dualSidePosition: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId: number; -} +/** + * Request subscription to one or more topics. Pass topics as either an array of strings, + * or array of objects (if the topic has parameters). + * + * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. + * + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. + * + * Call `unsubscribe(topics)` to remove topics + */ +public subscribe( + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], + wsKey: WsKey, + ): Promise ⋮---- -export interface SymbolConfig { - symbol: string; - marginType: string; - isAutoAddMargin: string; - leverage: number; - maxNotionalValue: string; -} +/** + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * + * - Requests are automatically routed to the correct websocket connection. + * - These topics will be removed from the topic cache, so they won't be subscribed to again. + */ +public unsubscribe( + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], + wsKey: WsKey, + ) ⋮---- -export interface UserForceOrder { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; -} +/** + * + * + * + * WS API Methods - similar to the REST API, but via WebSockets + * https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information + * + * https://github.com/tiagosiebler/awesome-crypto-examples/wiki/REST-API-vs-WebSockets-vs-WebSocket-API + * + * + * + */ ⋮---- -export interface RebateDataOverview { - brokerId: string; - newTraderRebateCommission: numberInString; - oldTraderRebateCommission: numberInString; - totalTradeUser: number; - unit: string; - totalTradeVol: numberInString; - totalRebateVol: numberInString; - time: number; -} +/** + * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. + * + * WS API Documentation for list of operations and parameters: + * + * - Spot: https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information + * - USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info + * - COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info + * + * + * Returned promise is rejected if: + * - an exception is detected in the reply, OR + * - the connection disconnects for any reason (even if automatic reconnect will happen). + * + * Authentication is automatic. If you didn't request authentication yourself, there might + * be a small delay after your first request, while the SDK automatically authenticates. + * + * Misc options: + * - signRequest: boolean - if included, this request will automatically be signed with the available credentials. + * + * @param wsKey - The connection this event is for. Currently only "v5PrivateTrade" is supported + * for Bybit, since that is the dedicated WS API connection. + * @param operation - The command being sent, e.g. "order.create" to submit a new order. + * @param params - Any request parameters for the command. E.g. `OrderParamsV5` to submit a new + * order. Only send parameters for the request body. Everything else is automatically handled. + * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response + */ ⋮---- -export interface SetCancelTimeoutResult { - symbol: string; - countdownTime: numberInString; -} +// This overload allows the caller to omit the 3rd param, if it isn't required +sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap + TWSParams extends Exact[TWSOperation]>, + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: TWSKey, + operation: TWSOperation, + params?: TWSParams extends void | never ? undefined : TWSParams, + requestFlags?: WSAPIRequestFlags, + ): Promise; ⋮---- -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; -} +// if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap ⋮---- -firstId: number; // First tradeId -lastId: number; // Last tradeId +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact[TWSOperation]>, + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: WsKey, + operation: TWSOperation, + params: TWSParams & { signRequest?: boolean }, + requestFlags?: WSAPIRequestFlags, + ): Promise ⋮---- -export interface OrderAmendmentDetailPrice { - before: numberInString; - after: numberInString; -} +/** + * Spot: + * -> https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information + * -> https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md#public-api-requests + * USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info + * COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info + */ ⋮---- -export interface OrderAmendmentDetailQty { - before: numberInString; - after: numberInString; -} +// If testnet, enforce testnet wskey for WS API calls ⋮---- -export interface OrderAmendmentDetail { - price: OrderAmendmentDetailPrice; - origQty: OrderAmendmentDetailQty; - count: number; -} +// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); ⋮---- -export interface OrderAmendment { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: OrderAmendmentDetail; - modifyId?: number; -} +// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); ⋮---- -export interface QuarterlyContractSettlementPrice { - deliveryTime: number; - deliveryPrice: number; -} +// Some commands don't require authentication. ⋮---- -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; -} +// Only if authOnConnect is enabled (aka using Ed25519 keys) ⋮---- -export interface Basis { - indexPrice: string; - contractType: string; - basisRate: string; - futuresPrice: string; - annualizedBasisRate: string; - basis: string; - pair: string; - timestamp: number; -} +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- -export interface IndexPriceConstituent { - exchange: string; - symbol: string; - price: numberInString; - weight: numberInString; -} +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +⋮---- +/** + * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated + * can introduce a small delay before the actual request is sent, if not connected before that request is + * made. This can lead to a curious race condition, where the request timestamp is before + * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. + * + * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, + * it offsets that timestamp by the delay. + */ ⋮---- -export interface IndexPriceConstituents { - symbol: string; - time: number; - constituents: IndexPriceConstituent[]; -} +// Sign, if needed ⋮---- -export interface InsuranceFundBalance { - symbols: string[]; - assets: { - asset: string; - marginBalance: string; - updateTime: number; - }[]; -} +// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events ⋮---- -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; - reduceOnly?: BooleanString; - recvWindow?: number; - timestamp: number; -} +// Enrich returned promise with request context for easier debugging ⋮---- -export interface GetFuturesOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +// throw e; ⋮---- -export interface FuturesTradeHistoryDownloadId { - avgCostTimestampOfLast30d: number; - downloadId: string; -} +// this.logger.trace( +// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, +// ); ⋮---- -export interface FuturesTransactionDownloadLink { - downloadId: string; - status: 'completed' | 'processing'; - url: string; - expirationTimestamp: number; - isExpired: boolean | null; -} +// Send event. ⋮---- -export interface PortfolioMarginProAccountInfo { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; // This field will be ignored in the response -} +// Return deferred promise, so caller can await this call ⋮---- -maxWithdrawAmount: string; // This field will be ignored in the response +/** + * + * + * Internal methods - not intended for public use + * + * + */ ⋮---- -export interface FuturesConvertPair { - fromAsset: string; - toAsset: string; - fromAssetMinAmount: string; - fromAssetMaxAmount: string; - toAssetMinAmount: string; - toAssetMaxAmount: string; -} +/** + * @returns The WS URL to connect to for this WS key + */ +async getWsUrl( + wsKey: WsKey, + connectionType: 'public' | 'market' | 'private' = 'market', + ): Promise ⋮---- -export interface FuturesConvertQuoteRequest { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - validTime?: '10s' | '30s' | '1m' | '2m'; -} +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, + ): Promise ⋮---- -export interface FuturesConvertQuote { - quoteId: string; - ratio: string; - inverseRatio: string; - validTimestamp: number; - toAmount: string; - fromAmount: string; -} +// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); ⋮---- -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; -} +/** + * Handles request sign, if connection isn't authenticated yet. + * If connection does not need to be authenticated or request doesn't require sign, + * use the requestFlags.authIsOptional flag to skip sign and send the request immediately. + */ +private async signWSAPIRequest( + requestEvent: WsRequestOperationBinance, + requestFlags?: WSAPIRequestFlags, + ): Promise> ⋮---- /** - * Algo Order Types (Effective 2025-12-02) - * USDⓈ-M Futures conditional orders migrate to Algo Service - */ + * Not really needed for most commands on Binance. Their WS API supports + * sending signed WS API commands, but that adds latency to every request. + * + * Instead, this SDK will authenticate once after connecting. All requests + * after authentication can then be sent without sign for maximum speed. + */ ⋮---- -export type FuturesAlgoOrderType = 'CONDITIONAL'; +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise< + WsRequestOperationBinance< + string, + { apiKey: string; signature: string; timestamp: number } + > + > ⋮---- -export type FuturesAlgoConditionalOrderTypes = - | 'STOP_MARKET' - | 'TAKE_PROFIT_MARKET' - | 'STOP' - | 'TAKE_PROFIT' - | 'TRAILING_STOP_MARKET'; +// Note: Only Ed25519 keys are supported for this feature. +// RSA & HMAC keys will automatically sign each individual request instead. ⋮---- -/** - * 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'; +// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. ⋮---- -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; -} +// Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. ⋮---- -clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ +// Note: You still have to specify the timestamp parameter for SIGNED requests. ⋮---- -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; -} +protected sendPingEvent(wsKey: WsKey) ⋮---- -export interface FuturesCancelAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -export interface FuturesCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +⋮---- +protected sendPongEvent(wsKey: WsKey) +⋮---- +// 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) +⋮---- +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +⋮---- +/** + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + */ +protected async getWsRequestEvents( + wsKey: WsKey, + operation: WsOperation, + requests: WsTopicRequest[], + ): Promise>[]> +⋮---- +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- -export interface FuturesCancelAllAlgoOpenOrdersResponse { - code: number; - msg: string; -} +// Cache midflight subs on the req ID +// Enrich response with subs for that req ID ⋮---- -export interface FuturesQueryAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} +protected getPrivateWSKeys(): WsKey[] ⋮---- -export interface FuturesQueryAlgoOrderResponse - extends FuturesAlgoOrderResponse { - actualOrderId: numberInString; - actualPrice: numberInString; - tpTriggerPrice?: numberInString; - tpPrice?: numberInString; - slTriggerPrice?: numberInString; - slPrice?: numberInString; - tpOrderType?: string; -} +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -export interface FuturesQueryOpenAlgoOrdersParams { - algoType?: FuturesAlgoOrderType; - symbol?: string; - algoId?: number; -} +/** + * Determines if a topic is for a private channel, using a hardcoded list of strings + */ +protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- -export interface FuturesQueryAllAlgoOrdersParams { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 500; max 1000 -} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPing(msg: any): boolean ⋮---- -limit?: number; // Default 500; max 1000 +// For binance, all ping/pong events are frame events ⋮---- -export interface SymbolAdlRisk { - symbol: string; - adlRisk: 'low' | 'medium' | 'high'; - updateTime: number; -} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPong(msg: any): boolean ⋮---- -export interface TradingSession { - startTime: number; - endTime: number; - type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; -} +// For binance, all ping/pong events are frame events ⋮---- -export interface MarketSchedule { - sessions: TradingSession[]; -} +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, + ): EmittableEvent[] ⋮---- -export interface TradingSchedule { - updateTime: number; - marketSchedules: { - EQUITY?: MarketSchedule; - COMMODITY?: MarketSchedule; - KR_EQUITY?: MarketSchedule; - HK_EQUITY?: MarketSchedule; - CN_EQUITY?: MarketSchedule; - FX?: MarketSchedule; - }; -} +// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); ⋮---- -export interface RpiOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} +/** + * + * Extract event from JSON + * + */ ⋮---- -E: number; // Message output time -T: number; // Transaction time - -================ -File: src/websocket-client.ts -================ -import WebSocket from 'isomorphic-ws'; +/** + * + * Minor data normalisation & preparation + * + */ ⋮---- -import { KlineInterval } from './types/shared'; -import { - Exact, - WsAPIOperationResponseMap, - WsAPITopicRequestParamMap, - WsAPIWsKeyTopicMap, - WsOperation, - WsRequestOperationBinance, -} from './types/websockets/ws-api'; -import { - MessageEventLike, - WSClientConfigurableOptions, - WsMarket, - WsTopic, -} from './types/websockets/ws-general'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient'; -import Beautifier from './util/beautifier'; -import { DefaultLogger } from './util/logger'; -import { signMessage } from './util/node-support'; -import { - appendEventIfMissing, - requiresWSAPINewClientOID, - RestClientOptions, - serialiseParams, - validateWSAPINewClientOID, -} from './util/requestUtils'; -import { neverGuard } from './util/typeGuards'; -import { SignAlgorithm, SignEncodeMethod } from './util/webCryptoAPI'; -import { RestClientCache } from './util/websockets/rest-client-cache'; -import { UserDataStreamManager } from './util/websockets/user-data-stream-manager'; -import { - EVENT_TYPES_USER_DATA, - getLegacyWsKeyContext, - getLegacyWsStoreKeyWithContext, - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getPromiseRefForWSAPIRequest, - getRealWsKeyFromDerivedWsKey, - getTestnetWsKey, - getTopicsPerWSKey, - getWsKeyForProductGroup, - getWsUrl, - getWsURLSuffix, - isPrivateWsTopic, - isWSPingFrameAvailable, - isWSPongFrameAvailable, - MiscUserDataConnectionState, - parseEventTypeFromMessage, - parseRawWsMessage, - resolveUserDataMarketForWsKey, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WSAPIWsKey, - WSConnectionCategory, - WsKey, - WsTopicRequest, -} from './util/websockets/websocket-util'; -import { WSConnectedResult } from './util/websockets/WsStore.types'; +// ws consumers: { data: ... } +// ws api consumers (user data): { event: ... } +// other responses: { ... } ⋮---- -type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +// First try, the child node ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} +// Second try, the parent ⋮---- -/** If true, will skip auth requirement for WS API connection */ +// Some events don't include the topic (event name) +// This tries to extract and append it, using available context +⋮---- +// This attaches `wsMarket` and `streamName` to incoming events +// If the event is an array, it's attached to each element in the array ⋮---- /** - * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. - * - * When possible, it will subscribe to all requested topics on a single websocket connection. A list of - * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. - * - * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically - * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. - * - * If any connection is reconnected, the WS client will: - * - Emit the "reconnecting" event when the process begins. - * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a - * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed - * while disconnected. - * - * User data streams will use a dedicated connection per stream for increased resilience. - */ + * + * + * Main parsing logic below: + * + * + */ ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +// parsed: JSON.stringify(parsed, null, 2), ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +// WS API response ⋮---- /** - * Binance uses native WebSocket ping/pong frames, which cannot be directly used in - * some environents (e.g. most browsers do not support sending raw ping/pong frames). - * - * This disables heartbeats in those environments, if ping/pong frames are unavailable. - * - * Some browsers may still handle these automatically. Some discussion around this can - * be found here: https://stackoverflow.com/questions/10585355/sending-websocket-ping-pong-frame-from-browser - */ + * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): + * + * { + * result: null, + * id: 1, + * }; + * + * Currently there's no simple way to tell this apart from an actual WS API response with + * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, + * but that will not affect usage. + * + * Unrelated, example wsapi error for reference: + * + { + id: 1, + status: 400, + error: { + code: -1021, + msg: "Timestamp for this request was 1000ms ahead of the server's time." + }, + rateLimits: [ + { + rateLimitType: 'REQUEST_WEIGHT', + interval: 'MINUTE', + intervalNum: 1, + limit: 6000, + count: 4 + } + ], + wsKey: 'mainWSAPI', + isWSAPIResponse: true + } + */ +⋮---- +// This is the counterpart to getPromiseRefForWSAPIRequest +⋮---- +// WS API Exception +⋮---- +// authenticated +⋮---- +// Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests ⋮---- -// fn pointers: +// WS API Success ⋮---- -protected onWsCloseCleanup(wsKey: WsKey): void +// Handle incoming event that listen key expired ⋮---- -private getUserDataStreamManager(): UserDataStreamManager +// handle this how? ⋮---- -private getRestClientOptions(): RestClientOptions +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn +// Automatically leads to triggerCustomReconnectionWorkflow() to handle fresh user data respawn ⋮---- -/** - * Request connection of all dependent (public & WS API) websockets in prod, instead of waiting - * for automatic connection by SDK. - * - * For the Binance SDK, this will only open public connections (without auth), but is almost definitely overkill if you're only working with one product group. - */ -public connectAll(): Promise[] +// Suffix all events for the beautifier, if market is options +// Options has some conflicting keys with different intentions, so will be suffixed ⋮---- -/** - * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if - * you're only working with one product group. - */ -public connectPublic(): Promise[] +// emit an additional event for user data messages ⋮---- -/** - * This function serves no purpose in the Binance SDK - */ -public async connectPrivate(): Promise +// Messages for a subscribed topic all include the "topic" property ⋮---- -/** - * Ensures the WS API connection is active and ready. - * - * You do not need to call this, but if you call this before making any WS API requests, - * it can accelerate the first request (by preparing the connection in advance). - */ -public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise +// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +// Failed request ⋮---- -/** - * Request subscription to one or more topics. Pass topics as either an array of strings, - * or array of objects (if the topic has parameters). - * - * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics - */ -public subscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, - ): Promise +// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, - ) +// Request/reply pattern for authentication success +⋮---- +// In case of catastrophic failure, fallback to noisy emit update ⋮---- /** * * * - * WS API Methods - similar to the REST API, but via WebSockets - * https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information - * - * https://github.com/tiagosiebler/awesome-crypto-examples/wiki/REST-API-vs-WebSockets-vs-WebSocket-API - * - * - * - */ -⋮---- -/** - * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. * - * WS API Documentation for list of operations and parameters: * - * - Spot: https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information - * - USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info - * - COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info + * User Data Streams * * - * Returned promise is rejected if: - * - an exception is detected in the reply, OR - * - the connection disconnects for any reason (even if automatic reconnect will happen). * - * Authentication is automatic. If you didn't request authentication yourself, there might - * be a small delay after your first request, while the SDK automatically authenticates. * - * Misc options: - * - signRequest: boolean - if included, this request will automatically be signed with the available credentials. * - * @param wsKey - The connection this event is for. Currently only "v5PrivateTrade" is supported - * for Bybit, since that is the dedicated WS API connection. - * @param operation - The command being sent, e.g. "order.create" to submit a new order. - * @param params - Any request parameters for the command. E.g. `OrderParamsV5` to submit a new - * order. Only send parameters for the request body. Everything else is automatically handled. - * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response */ ⋮---- -// This overload allows the caller to omit the 3rd param, if it isn't required -sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap - TWSParams extends Exact[TWSOperation]>, - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( - wsKey: TWSKey, - operation: TWSOperation, - params?: TWSParams extends void | never ? undefined : TWSParams, - requestFlags?: WSAPIRequestFlags, - ): Promise; -⋮---- -// if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap +/** + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- + **/ ⋮---- -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact[TWSOperation]>, - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( +/** + * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. + * Supports spot, margin & isolated margin listen keys. + */ +public async subscribeSpotUserDataStreamWithListenKey( wsKey: WsKey, - operation: TWSOperation, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, - ): Promise + listenKey: string, + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- /** - * Spot: - * -> https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information - * -> https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md#public-api-requests - * USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info - * COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info - */ + * Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeSpotUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -// If testnet, enforce testnet wskey for WS API calls +public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise ⋮---- -// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); +public async fetchMarginListenToken(params?: { + symbol?: string; + isIsolated?: boolean; + validity?: number; + }): Promise<{ + token: string; + expirationTime: number; + }> ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); +/** + * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeCrossMarginUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -// Some commands don't require authentication. +public unsubscribeCrossMarginUserDataStream( + wsKey: WsKey = 'main', + ): Promise ⋮---- -// Only if authOnConnect is enabled (aka using Ed25519 keys) +/** + * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +public unsubscribeIsolatedMarginUserDataStream( + symbol: string, + wsKey: WsKey = 'main', + ): Promise ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +/** + * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeMarginRiskUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise +⋮---- +public unsubscribeMarginRiskUserDataStream( + wsKey: WsKey = 'main', + ): Promise ⋮---- /** - * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated - * can introduce a small delay before the actual request is sent, if not connected before that request is - * made. This can lead to a curious race condition, where the request timestamp is before - * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. - * - * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, - * it offsets that timestamp by the delay. - */ + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- -// Sign, if needed +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribeUsdFuturesUserDataStream( + userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate ⋮---- -// Enrich returned promise with request context for easier debugging +// Prevent 'usdm' from being used unintentionally, since this has to be routed via the private endpoints. ⋮---- -// throw e; +public unsubscribeUsdFuturesUserDataStream( + wsKey: WsKey = WS_KEY_MAP.usdmPrivate, + ): Promise ⋮---- -// this.logger.trace( -// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, -// ); +/** + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribeCoinFuturesUserDataStream( + wsKey: WsKey = 'coinm', // coinm | coinmTestnet + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -// Send event. +wsKey: WsKey = 'coinm', // coinm | coinmTestnet ⋮---- -// Return deferred promise, so caller can await this call +public unsubscribeCoinFuturesUserDataStream( + wsKey: WsKey = 'coinm', + ): Promise ⋮---- /** + * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * - * - * Internal methods - not intended for public use - * - * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. */ +public async subscribePortfolioMarginUserDataStream( + wsKey: WsKey = 'portfolioMarginUserData', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise +⋮---- +public unsubscribePortfolioMarginUserDataStream( + wsKey: WsKey = 'portfolioMarginUserData', + ): Promise ⋮---- /** - * @returns The WS URL to connect to for this WS key + * Close an active, dedicated, user data stream connection. + * + * @param wsKey - the connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures. + * @param wsMarket - the product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)). */ -async getWsUrl( +public async closeUserDataStream( wsKey: WsKey, - connectionType: 'public' | 'market' | 'private' = 'market', - ): Promise -⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, - ): Promise + wsMarket: WsMarket, + symbol?: string, + ): Promise ⋮---- -// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); +// built around the assumption in how per-connection listen key wskeys are created +// isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main +// coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm ⋮---- -/** - * Handles request sign, if connection isn't authenticated yet. - * If connection does not need to be authenticated or request doesn't require sign, - * use the requestFlags.authIsOptional flag to skip sign and send the request immediately. - */ -private async signWSAPIRequest( - requestEvent: WsRequestOperationBinance, - requestFlags?: WSAPIRequestFlags, - ): Promise> +protected isCustomReconnectionNeeded(wsKey: string): boolean ⋮---- -/** - * Not really needed for most commands on Binance. Their WS API supports - * sending signed WS API commands, but that adds latency to every request. - * - * Instead, this SDK will authenticate once after connecting. All requests - * after authentication can then be sent without sign for maximum speed. - */ +protected async triggerCustomReconnectionWorkflow( + legacyWsKey: string, + ): Promise ⋮---- -protected async getWsAuthRequestEvent( +private async respawnUserDataStream( wsKey: WsKey, - ): Promise< - WsRequestOperationBinance< - string, - { apiKey: string; signature: string; timestamp: number } - > - > -⋮---- -// Note: Only Ed25519 keys are supported for this feature. -// RSA & HMAC keys will automatically sign each individual request instead. + market: WsMarket, + context: { + symbol?: string; + isTestnet?: boolean; + respawnAttempt?: number; + } = {}, + ): Promise ⋮---- -// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. +// Handle corner case where wsKey is still the derived key for some reason... ⋮---- -// Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. +// 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 ⋮---- -// Note: You still have to specify the timestamp parameter for SIGNED requests. +// Prevent simultaneous timers in same scope ⋮---- -protected sendPingEvent(wsKey: WsKey) +// Execute reconnection workflow after short delay ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +/** + * Subscribe to the European Options user data stream - listen key is automatically generated. + * + * Not supported at this time. Please get in touch if you need this. + */ +// public async subscribeEuropeanOptionsUserData( +// wsKey: WsKey = 'eoptions', +// forceNewConnection?: boolean, +// isReconnecting?: boolean, +// ): Promise { +// try { +// const { listenKey } = await this.restClientCache +// .getEuropeanOptionsClient( +// this.getRestClientOptions(), +// this.options.requestOptions, +// ) +// .getUserDataListenKey(); ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +// const market: WsMarket = 'options'; ⋮---- -protected sendPongEvent(wsKey: WsKey) +// return this.subscribeGeneralUserDataStreamWithListenKey( +// wsKey, +// market, +// listenKey, +// forceNewConnection, +// isReconnecting, +// ); +// } catch (e) { +// this.logger.error('Failed to connect to Options user data', { +// ...WS_LOGGER_CATEGORY, +// error: e, +// }); +// this.emit('exception', { +// functionRef: 'subscribePortfolioMarginUserDataStream()', +// wsKey, +// forceNewConnection, +// isReconnecting, +// error: e?.stack || e, +// }); +// } +// } ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +/** + * + * + * + * + * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. + * + * + * + * + */ ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +/** + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- + **/ ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +/** + * Advanced: Subscribe to a universal market websocket stream + * + * This is NOT recommended unless you're very confident with what you're doing. + */ +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', + ): Promise ⋮---- /** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + * Subscribe to aggregate trades for a symbol in a market category */ -protected async getWsRequestEvents( - wsKey: WsKey, - operation: WsOperation, - requests: WsTopicRequest[], - ): Promise>[]> +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +/** + * 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', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Cache midflight subs on the req ID -// Enrich response with subs for that req ID +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeBlockTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -protected getPrivateWSKeys(): WsKey[] +/** + * Subscribe to coin index for a symbol in COINM Futures markets + * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. + */ +public subscribeCoinIndexPrice( + symbol: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- /** - * Determines if a topic is for a private channel, using a hardcoded list of strings + * Subscribe to mark price for a symbol in a market category */ -protected isPrivateTopicRequest(request: WsTopicRequest): boolean +public subscribeMarkPrice( + symbol: string, + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPing(msg: any): boolean +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// For binance, all ping/pong events are frame events +/** + * Subscribe to klines(candles) for a symbol in a market category + */ +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPong(msg: any): boolean +/** + * 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', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// For binance, all ping/pong events are frame events +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + * Subscribe to index klines(candles) for a symbol in a coinm futures */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, - ): EmittableEvent[] -⋮---- -// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); +public subscribeMarkPriceKlines( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * - * Extract event from JSON - * - */ + * Subscribe to mini 24hr ticker for a symbol in market category. + */ +public subscribeSymbolMini24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * - * Minor data normalisation & preparation - * - */ -⋮---- -// ws consumers: { data: ... } -// ws api consumers (user data): { event: ... } -// other responses: { ... } -⋮---- -// First try, the child node -⋮---- -// Second try, the parent -⋮---- -// Some events don't include the topic (event name) -// This tries to extract and append it, using available context -⋮---- -// This attaches `wsMarket` and `streamName` to incoming events -// If the event is an array, it's attached to each element in the array + * Subscribe to mini 24hr mini ticker in market category. + */ +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * - * - * Main parsing logic below: - * - * - */ -⋮---- -// parsed: JSON.stringify(parsed, null, 2), -⋮---- -// WS API response + * Subscribe to 24hr ticker for a symbol in any market. + */ +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): - * - * { - * result: null, - * id: 1, - * }; - * - * Currently there's no simple way to tell this apart from an actual WS API response with - * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, - * but that will not affect usage. - * - * Unrelated, example wsapi error for reference: - * - { - id: 1, - status: 400, - error: { - code: -1021, - msg: "Timestamp for this request was 1000ms ahead of the server's time." - }, - rateLimits: [ - { - rateLimitType: 'REQUEST_WEIGHT', - interval: 'MINUTE', - intervalNum: 1, - limit: 6000, - count: 4 - } - ], - wsKey: 'mainWSAPI', - isWSAPIResponse: true - } - */ -⋮---- -// This is the counterpart to getPromiseRefForWSAPIRequest -⋮---- -// WS API Exception + * Subscribe to Alpha Trading WebSocket Market Data streams. + * Base URL: wss://nbstream.binance.com/w3w/wsa/stream + */ +public subscribeAlpha(topics: string | string[]): Promise ⋮---- -// authenticated +/** + * Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24) + */ +public subscribeAlphaAllTokensTicker24(): Promise ⋮---- -// Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests +/** + * Subscribe to Alpha aggregate trades for a symbol + * @param symbol e.g. ALPHA_474USDT + */ +public subscribeAlphaAggTrade(symbol: string): Promise ⋮---- -// WS API Success +/** + * Subscribe to Alpha full depth for a symbol + * @param symbol e.g. ALPHA_474USDT + * @param intervalMs 0, 100, or 500 + */ +public subscribeAlphaFulldepth( + symbol: string, + intervalMs: 0 | 100 | 500 = 500, + ): Promise ⋮---- -// Handle incoming event that listen key expired +/** + * Subscribe to Alpha klines for a contract + * @param contractAddress Contract address + * @param chainId Chain ID (e.g. CT_501, 56) + * @param interval 1s, 1m, 5m, 15m, 1h, 4h, 1d + */ +public subscribeAlphaKline( + contractAddress: string, + chainId: string, + interval: '1s' | '1m' | '5m' | '15m' | '1h' | '4h' | '1d', + ): Promise ⋮---- -// handle this how? +/** + * Subscribe to 24hr ticker in any market. + */ +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn -// Automatically leads to triggerCustomReconnectionWorkflow() to handle fresh user data respawn +/** + * 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', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Suffix all events for the beautifier, if market is options -// Options has some conflicting keys with different intentions, so will be suffixed +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// emit an additional event for user data messages +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllBookTickers( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Messages for a subscribed topic all include the "topic" property +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Failed request +/** + * Subscribe to partial book depths (snapshots). + * + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs + */ +public subscribePartialBookDepths( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 100 | 250 | 500 | 1000, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) +/** + * 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 + */ +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// Request/reply pattern for authentication success +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -// In case of catastrophic failure, fallback to noisy emit update +/** + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- /** - * - * - * - * - * - * User Data Streams - * - * - * - * - * + * Subscribe to aggregate trades for a symbol in spot markets. */ +public subscribeSpotAggregateTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ + * Subscribe to trades for a symbol in spot markets. + */ +public subscribeSpotTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. - * Supports spot, margin & isolated margin listen keys. + * Subscribe to block trades for a symbol in spot markets. */ -public async subscribeSpotUserDataStreamWithListenKey( - wsKey: WsKey, - listenKey: string, - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise +public subscribeSpotBlockTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + * Subscribe to candles for a symbol in spot markets. */ -public async subscribeSpotUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise +/** + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -public async fetchMarginListenToken(params?: { - symbol?: string; - isIsolated?: boolean; - validity?: number; - }): Promise<{ - token: string; - expirationTime: number; - }> +/** + * Subscribe to mini 24hr mini ticker in spot markets. + */ +public subscribeSpotAllMini24hrTickers( + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + * Subscribe to 24hr ticker for a symbol in spot markets. */ -public async subscribeCrossMarginUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise +public subscribeSpotSymbol24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -public unsubscribeCrossMarginUserDataStream( - wsKey: WsKey = 'main', - ): Promise +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise ⋮---- /** - * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + * Subscribe to best bid/ask for symbol in spot markets. */ -public async subscribeIsolatedMarginUserDataStream( +public subscribeSpotSymbolBookTicker( symbol: string, - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise + wsKeyOverride?: WsKey, + ): Promise ⋮---- -public unsubscribeIsolatedMarginUserDataStream( +/** + * Subscribe to top bid/ask levels for symbol in spot markets. + */ +public subscribeSpotPartialBookDepth( symbol: string, - wsKey: WsKey = 'main', - ): Promise + levels: 5 | 10 | 20, + updateMs: 1000 | 100 = 1000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- /** - * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + * Subscribe to spot orderbook depth updates to locally manage an order book. */ -public async subscribeMarginRiskUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + wsKeyOverride?: WsKey, + ): Promise + +================ +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'; ⋮---- -public unsubscribeMarginRiskUserDataStream( - wsKey: WsKey = 'main', - ): Promise +/** + * Simple request params with timestamp (required) & recv window (optional) + */ +export type WSAPIRecvWindowTimestamp = { + recvWindow?: number; + timestamp: number; +}; ⋮---- /** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ + * + * Authentication request types + * + */ +export interface WSAPISessionLogonRequest { + timestamp: number; +} ⋮---- /** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribeUsdFuturesUserDataStream( - userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise + * + * General request types + * + */ +export interface WSAPIExchangeInfoRequest { + symbol?: string; + symbols?: string[]; + permissions?: string[]; + showPermissionSets?: boolean; + symbolStatus?: string; +} ⋮---- -userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate +/** + * + * Market data request types + * + */ ⋮---- -// Prevent 'usdm' from being used unintentionally, since this has to be routed via the private endpoints. +export interface WSAPIOrderBookRequest { + symbol: string; + limit?: number; + symbolStatus?: string; +} ⋮---- -public unsubscribeUsdFuturesUserDataStream( - wsKey: WsKey = WS_KEY_MAP.usdmPrivate, - ): Promise +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; +} ⋮---- /** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribeCoinFuturesUserDataStream( - wsKey: WsKey = 'coinm', // coinm | coinmTestnet - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise + * Query execution rules (e.g. PRICE_RANGE). Only one of symbol, symbols, or symbolStatus per request. + */ +export interface WSAPIExecutionRulesRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; +} ⋮---- -wsKey: WsKey = 'coinm', // coinm | coinmTestnet +export interface WSAPIReferencePriceRequest { + symbol: string; +} ⋮---- -public unsubscribeCoinFuturesUserDataStream( - wsKey: WsKey = 'coinm', - ): Promise +export interface WSAPIReferencePriceCalculationRequest { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; +} ⋮---- /** - * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribePortfolioMarginUserDataStream( - wsKey: WsKey = 'portfolioMarginUserData', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, - ): Promise + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITicker24hrRequest { + symbol?: string; + symbols?: string[]; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} ⋮---- -public unsubscribePortfolioMarginUserDataStream( - wsKey: WsKey = 'portfolioMarginUserData', - ): Promise +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerTradingDayRequest { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} ⋮---- /** - * Close an active, dedicated, user data stream connection. - * - * @param wsKey - the connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures. - * @param wsMarket - the product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)). - */ -public async closeUserDataStream( - wsKey: WsKey, - wsMarket: WsMarket, - symbol?: string, - ): Promise + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerRequest { + symbol?: string; + symbols?: string[]; + windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} ⋮---- -// built around the assumption in how per-connection listen key wskeys are created -// isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main -// coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm +windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' ⋮---- -protected isCustomReconnectionNeeded(wsKey: string): boolean +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerPriceRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} ⋮---- -protected async triggerCustomReconnectionWorkflow( - legacyWsKey: string, - ): Promise +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerBookRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} ⋮---- -private async respawnUserDataStream( - wsKey: WsKey, - market: WsMarket, - context: { - symbol?: string; - isTestnet?: boolean; - respawnAttempt?: number; - } = {}, - ): Promise +/** + * + * Account request types - Spot + * + */ ⋮---- -// Handle corner case where wsKey is still the derived key for some reason... +export interface WSAPIAllOrdersRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// 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 +export interface WSAPIAllOrderListsRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// Prevent simultaneous timers in same scope +export interface WSAPIMyTradesRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} ⋮---- -// Execute reconnection workflow after short delay +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; +} ⋮---- /** - * Subscribe to the European Options user data stream - listen key is automatically generated. - * - * Not supported at this time. Please get in touch if you need this. - */ -// public async subscribeEuropeanOptionsUserData( -// wsKey: WsKey = 'eoptions', -// forceNewConnection?: boolean, -// isReconnecting?: boolean, -// ): Promise { -// try { -// const { listenKey } = await this.restClientCache -// .getEuropeanOptionsClient( -// this.getRestClientOptions(), -// this.options.requestOptions, -// ) -// .getUserDataListenKey(); + * Trading request types + */ +type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; +type SpotPegOffsetType = 'PRICE_LEVEL'; ⋮---- -// const market: WsMarket = 'options'; +export interface WSAPINewSpotOrderRequest { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; +} ⋮---- -// return this.subscribeGeneralUserDataStreamWithListenKey( -// wsKey, -// market, -// listenKey, -// forceNewConnection, -// isReconnecting, -// ); -// } catch (e) { -// this.logger.error('Failed to connect to Options user data', { -// ...WS_LOGGER_CATEGORY, -// error: e, -// }); -// this.emit('exception', { -// functionRef: 'subscribePortfolioMarginUserDataStream()', -// wsKey, -// forceNewConnection, -// isReconnecting, -// error: e?.stack || e, -// }); -// } -// } +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * - * - * - * - * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. - * - * - * - * - */ +export interface WSAPIOrderTestRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: numberInString; + newClientOrderId?: string; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + computeCommissionRates?: boolean; + timestamp: number; + recvWindow?: number; +} ⋮---- -/** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Advanced: Subscribe to a universal market websocket stream - * - * This is NOT recommended unless you're very confident with what you're doing. - */ -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', - ): Promise +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; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * 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', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to coin index for a symbol in COINM Futures markets - * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. - */ -public subscribeCoinIndexPrice( - symbol: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface WSAPIOpenOrdersCancelAllRequest { + symbol: string; + recvWindow?: number; + timestamp: number; +} ⋮---- /** - * Subscribe to mark price for a symbol in a market category - */ -public subscribeMarkPrice( - symbol: string, - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, - ): Promise + * 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; +} ⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, - ): Promise +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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + aboveQuoteNotionalLimit?: 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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + belowQuoteNotionalLimit?: numberInString; + belowStopPrice?: numberInString; + belowTrailingDelta?: number; + belowTimeInForce?: string; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * 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', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOrderListPlaceOTORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingQuantity: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOrderListPlaceOTOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: 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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: 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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to Alpha Trading WebSocket Market Data streams. - * Base URL: wss://nbstream.binance.com/w3w/wsa/stream - */ -public subscribeAlpha(topics: string | string[]): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24) - */ -public subscribeAlphaAllTokensTicker24(): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to Alpha aggregate trades for a symbol - * @param symbol e.g. ALPHA_474USDT - */ -public subscribeAlphaAggTrade(symbol: string): Promise +export interface WSAPIOrderListPlaceOPORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: 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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to Alpha full depth for a symbol - * @param symbol e.g. ALPHA_474USDT - * @param intervalMs 0, 100, or 500 - */ -public subscribeAlphaFulldepth( - symbol: string, - intervalMs: 0 | 100 | 500 = 500, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to Alpha klines for a contract - * @param contractAddress Contract address - * @param chainId Chain ID (e.g. CT_501, 56) - * @param interval 1s, 1m, 5m, 15m, 1h, 4h, 1d - */ -public subscribeAlphaKline( - contractAddress: string, - chainId: string, - interval: '1s' | '1m' | '5m' | '15m' | '1h' | '4h' | '1d', - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOrderListPlaceOPOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: 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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: 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; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * 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', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIOrderListCancelRequest { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- /** - * Subscribe to partial book depths (snapshots). - * - * Note: - * - spot only supports 1000ms or 100ms for updateMs - * - futures only support 100, 250 or 500ms for updateMs - */ -public subscribePartialBookDepths( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 100 | 250 | 500 | 1000, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise + * 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; +} ⋮---- -/** - * 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 - */ -public subscribeDiffBookDepth( - symbol: string, - updateMs: 100 | 250 | 500 | 1000 = 100, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise +export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { + computeCommissionRates?: boolean; +}; ⋮---- /** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise + * Futures market data request types + */ ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +export interface WSAPIFuturesOrderBookRequest { + symbol: string; + limit?: number; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; +} ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; +} ⋮---- /** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise + * Futures trading request types + */ ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, - ): Promise +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; +} ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - wsKeyOverride?: WsKey, - ): Promise +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; + reduceOnly?: BooleanString; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise +export interface WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +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; +} ⋮---- /** - * Subscribe to top bid/ask levels for symbol in spot markets. - */ -public subscribeSpotPartialBookDepth( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 1000 | 100 = 1000, - wsKeyOverride?: WsKey, - ): Promise + * 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 ⋮---- /** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - wsKeyOverride?: WsKey, - ): Promise + * 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: README.md @@ -18325,6 +18449,8 @@ import { RateLimiter, SelfTradePreventionMode, SideEffects, + SpotEffectiveSelfTradePreventionMode, + SpotExpiryReason, StringBoolean, SymbolFilter, } from './shared'; @@ -18797,6 +18923,11 @@ export interface ExchangeInfoParams { type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; type SpotPegOffsetType = 'PRICE_LEVEL'; ⋮---- +/** + * From 2026-11-20, BUY limit orders that trade on entry then rest return any lock above + * remaining quantity x limit price to free in the same balance update. Applies to LIMIT GTC, + * triggered STOP_LOSS_LIMIT/TAKE_PROFIT_LIMIT, order-list limits and SOR; icebergs keep the full lock. + */ export interface NewSpotOrderParams< T extends OrderType = OrderType, RT extends OrderResponseType | undefined = OrderResponseType, @@ -18807,6 +18938,8 @@ export interface NewSpotOrderParams< timeInForce?: OrderTimeInForce; quantity?: number; quoteOrderQty?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + quoteNotionalLimit?: number; price?: number; newClientOrderId?: string; strategyId?: number; @@ -18824,6 +18957,8 @@ export interface NewSpotOrderParams< autoRepayAtCancel?: StringBoolean; } ⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; ⋮---- @@ -18935,6 +19070,8 @@ export interface SymbolExchangeInfo { ocoAllowed: boolean; opoAllowed: boolean; quoteOrderQtyMarketAllowed: boolean; + marketQuoteNotionalLimitAllowed?: boolean; + limitQuoteNotionalLimitAllowed?: boolean; allowTrailingStop: boolean; cancelReplaceAllowed: boolean; isSpotTradingAllowed: boolean; @@ -19121,6 +19258,7 @@ export interface OrderResponseACK { ⋮---- /** Conditional fields on POST /api/v3/order RESULT/FULL. Only present when the matching condition is met. */ export interface SpotNewOrderConditionalFields { + quoteNotionalLimit?: numberInString; icebergQty?: numberInString; preventedMatchId?: number; preventedQuantity?: numberInString; @@ -19153,7 +19291,7 @@ export interface OrderResponseResult extends SpotNewOrderConditionalFields { workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } ⋮---- /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ @@ -19166,6 +19304,13 @@ export interface OrderFill { tradeId: number; } ⋮---- +export interface SpotOrderPreventedMatch { + /** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ + effectiveSelfTradePreventionMode?: SpotEffectiveSelfTradePreventionMode; +} +⋮---- +/** Only present on prevented-match reports when the applied STP mode differs from the order's own selfTradePreventionMode. */ +⋮---- export interface OrderResponseFull extends SpotNewOrderConditionalFields { symbol: string; orderId: number; @@ -19187,8 +19332,9 @@ export interface OrderResponseFull extends SpotNewOrderConditionalFields { workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; fills: OrderFill[]; + preventedMatches?: SpotOrderPreventedMatch[]; } ⋮---- /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ @@ -19216,7 +19362,7 @@ export interface OrderListOrder { orderId: number; clientOrderId: string; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } ⋮---- /** Present only for expired orders. */ @@ -19298,6 +19444,7 @@ export interface SORTestOrderResponse { discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. Staff later confirmed this is a multiplier: 0.75 means pay 75% of standard. The FAQ 0.25 example is fictional. ⋮---- export interface CancelSpotOrderResult { + quoteNotionalLimit?: numberInString; symbol: string; origClientOrderId: string; orderId: number; @@ -19376,6 +19523,7 @@ export interface ReplaceSpotOrderResultSuccess< } ⋮---- export interface SpotOrder { + quoteNotionalLimit?: numberInString; symbol: string; orderId: number; orderListId: number; @@ -19396,7 +19544,7 @@ export interface SpotOrder { origQuoteOrderQty: numberInString; selfTradePreventionMode: SelfTradePreventionMode; /** Present only for expired orders. */ - expiryReason?: string; + expiryReason?: SpotExpiryReason; } ⋮---- /** Present only for expired orders. */ @@ -19405,6 +19553,8 @@ export interface SpotAmendKeepPriorityResult { transactTime: number; executionId: number; amendedOrder: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; symbol: string; orderId: number; orderListId: number; @@ -21152,6 +21302,8 @@ export interface NewOrderListOTOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; @@ -21161,6 +21313,8 @@ export interface NewOrderListOTOParams { pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: string; pendingStopPrice?: string; pendingTrailingDelta?: string; pendingQuantity: string; @@ -21170,6 +21324,10 @@ export interface NewOrderListOTOParams { pendingStrategyType?: number; } ⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- export interface NewOrderListOTOResponse { orderListId: number; contingencyType: string; @@ -21184,6 +21342,9 @@ export interface NewOrderListOTOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -21211,6 +21372,8 @@ export interface NewOrderListOTOCOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; @@ -21221,6 +21384,8 @@ export interface NewOrderListOTOCOParams { pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: string; pendingAboveStopPrice?: string; pendingAboveTrailingDelta?: string; pendingAboveIcebergQty?: string; @@ -21230,6 +21395,8 @@ export interface NewOrderListOTOCOParams { pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; pendingBelowClientOrderId?: string; pendingBelowPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: string; pendingBelowStopPrice?: string; pendingBelowTrailingDelta?: string; pendingBelowIcebergQty?: string; @@ -21238,6 +21405,12 @@ export interface NewOrderListOTOCOParams { pendingBelowStrategyType?: number; } ⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- export interface NewOrderListOTOCOResponse { orderListId: number; contingencyType: string; @@ -21252,6 +21425,9 @@ export interface NewOrderListOTOCOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -21280,6 +21456,8 @@ export interface NewOrderListOPOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; @@ -21292,6 +21470,8 @@ export interface NewOrderListOPOParams { pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingQuoteNotionalLimit?: string; pendingStopPrice?: string; pendingTrailingDelta?: string; pendingIcebergQty?: string; @@ -21303,6 +21483,10 @@ export interface NewOrderListOPOParams { pendingPegOffsetValue?: number; } ⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- export interface NewOrderListOPOResponse { orderListId: number; contingencyType: string; @@ -21317,6 +21501,9 @@ export interface NewOrderListOPOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -21345,6 +21532,8 @@ export interface NewOrderListOPOCOParams { workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + workingQuoteNotionalLimit?: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; @@ -21362,6 +21551,8 @@ export interface NewOrderListOPOCOParams { | 'TAKE_PROFIT_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingAboveQuoteNotionalLimit?: string; pendingAboveStopPrice?: string; pendingAboveTrailingDelta?: string; pendingAboveIcebergQty?: string; @@ -21378,6 +21569,8 @@ export interface NewOrderListOPOCOParams { | 'TAKE_PROFIT_LIMIT'; pendingBelowClientOrderId?: string; pendingBelowPrice?: string; + /** BUY only; Binance has not decided when this feature will be enabled. */ + pendingBelowQuoteNotionalLimit?: string; pendingBelowStopPrice?: string; pendingBelowTrailingDelta?: string; pendingBelowIcebergQty?: string; @@ -21389,6 +21582,12 @@ export interface NewOrderListOPOCOParams { pendingBelowPegOffsetValue?: number; } ⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- export interface NewOrderListOPOCOResponse { orderListId: number; contingencyType: string; @@ -21403,6 +21602,9 @@ export interface NewOrderListOPOCOResponse { clientOrderId: string; }[]; orderReports: { + quoteNotionalLimit?: numberInString; + expiryReason?: SpotExpiryReason; + preventedMatches?: SpotOrderPreventedMatch[]; symbol: string; orderId: number; orderListId: number; @@ -26921,7 +27123,7 @@ replaceOrder< /** * 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 + * https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#order-amend-keep-priority-trade */ amendOrderKeepPriority( params: AmendKeepPriorityParams, @@ -29515,7 +29717,7 @@ getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ -getBrokerIfNewSpotUser(): Promise<{ +getBrokerIfNewSpotUser(params: { apiAgentCode: string }): Promise<{ rebateWorking: boolean; ifNewUser: boolean; }> @@ -29532,7 +29734,11 @@ getBrokerSubAccountDepositHistory( * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ -getBrokerUserCustomisedId(market: 'spot' | 'futures') +getBrokerUserCustomisedId( + ...[market, params]: + | [market: 'spot', params: { apiAgentCode: string }] + | [market: 'futures', params: { brokerId: string }] + ) ⋮---- /** * @deprecated, found only in old docs @@ -29790,7 +29996,7 @@ File: package.json ================ { "name": "binance", - "version": "3.6.12", + "version": "3.6.13", "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", From 93b5d07c31bd3eeeb8c22cbde2954e660a97e665 Mon Sep 17 00:00:00 2001 From: JJ-Cro Date: Mon, 16 Nov 2026 18:46:28 +0100 Subject: [PATCH 3/5] fix(v3.6.13): decimal-safe rounding without BigInt; leave legacy and deprecated helpers unchanged - roundToTickSize/roundToStepSize floor via scaled integer math (no BigInt, no deps); handles non-power-of-ten and already-aligned increments (Fixes #695) - Revert legacy subscribeDiffBookDepth changes to upstream (#697 skipped) - Revert deprecated broker helper changes to upstream (#698 skipped) --- src/main-client.ts | 19 +++------- src/util/rounding.ts | 67 ++++++++-------------------------- src/websocket-client-legacy.ts | 7 +--- 3 files changed, 24 insertions(+), 69 deletions(-) diff --git a/src/main-client.ts b/src/main-client.ts index 81c0be1b..cd5f441a 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -4911,11 +4911,11 @@ export class MainClient extends BaseRestClient { * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ - getBrokerIfNewSpotUser(params: { apiAgentCode: string }): Promise<{ + getBrokerIfNewSpotUser(): Promise<{ rebateWorking: boolean; ifNewUser: boolean; }> { - return this.getPrivate('sapi/v1/apiReferral/ifNewUser', params); + return this.getPrivate('sapi/v1/apiReferral/ifNewUser'); } /** @@ -4925,23 +4925,16 @@ export class MainClient extends BaseRestClient { getBrokerSubAccountDepositHistory( params?: GetBrokerSubAccountDepositHistoryParams, ): Promise { - return this.getPrivate('sapi/v1/broker/subAccount/depositHist', params); + return this.getPrivate('sapi/v1/bv1/apiReferral/ifNewUser', params); } /** * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ - getBrokerUserCustomisedId( - ...[market, params]: - | [market: 'spot', params: { apiAgentCode: string }] - | [market: 'futures', params: { brokerId: string }] - ) { + getBrokerUserCustomisedId(market: 'spot' | 'futures') { const prefix = market === 'spot' ? 'sapi' : 'fapi'; - return this.getPrivate( - prefix + '/v1/apiReferral/userCustomization', - params, - ); + return this.getPrivate(prefix + '/v1/apiReferral/userCustomization'); } /** @@ -4951,7 +4944,7 @@ export class MainClient extends BaseRestClient { enableFuturesBrokerSubAccount( params: EnableFuturesBrokerSubAccountParams, ): Promise { - return this.postPrivate('sapi/v1/broker/subAccount/futures', params); + return this.postPrivate('sapi/v1/broker/subAccount', params); } /** diff --git a/src/util/rounding.ts b/src/util/rounding.ts index 229a88d5..77175d39 100644 --- a/src/util/rounding.ts +++ b/src/util/rounding.ts @@ -1,69 +1,34 @@ -/** Parse a decimal, including exponent notation, without floating-point scaling. */ -function parseDecimal(value: string): { coefficient: bigint; scale: number } { - const [mantissa, exponent = '0'] = value.toLowerCase().split('e'); - const fraction = mantissa.split('.')[1] || ''; - return { - coefficient: BigInt(mantissa.replace('.', '')), - scale: fraction.length - Number(exponent), - }; -} - +/** + * Floors a value to a multiple of the increment (tick or step size string, e.g. "0.05000000"). + * Works on scaled integers to avoid float noise. Empty or zero increments return the value unchanged. + */ function floorToIncrement(value: number, increment: string): number { - if (!increment) { - return value; - } - - const decimalIncrement = increment.trim(); - const incrementNumber = Number(decimalIncrement); - if ( - !/^\+?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(decimalIncrement) || - !Number.isFinite(incrementNumber) || - !Number.isFinite(value) - ) { - throw new RangeError( - 'Value must be finite and increment must be a nonnegative decimal', - ); - } - - const step = parseDecimal(decimalIncrement); - if (!Number.isSafeInteger(step.scale)) { - throw new RangeError('Increment exponent is outside the supported range'); - } - - // A zero tick/step disables the corresponding exchange filter. - if (step.coefficient === BigInt(0) || value === 0) { + const incrementNum = parseFloat(increment); + if (!increment || !incrementNum) { return value; } - const amount = parseDecimal(String(value)); - const scale = Math.max(amount.scale, step.scale, 0); - const amountInteger = - amount.coefficient * BigInt('1' + '0'.repeat(scale - amount.scale)); - const stepInteger = - step.coefficient * BigInt('1' + '0'.repeat(scale - step.scale)); - let steps = amountInteger / stepInteger; + // Decimals from the increment string, ignoring trailing zeros (e.g. "0.05000000" → 2) + const decimals = (increment.split('.')[1] || '').replace(/0+$/, '').length; + const factor = 10 ** decimals; - // BigInt division truncates toward zero; preserve mathematical floor for negatives. - if (amountInteger < BigInt(0) && amountInteger % stepInteger !== BigInt(0)) { - steps -= BigInt(1); - } + // toFixed trims float noise (0.29 * 100 = 28.999999999999996) before flooring + const scaledValue = Math.floor(+(value * factor).toFixed(6)); + const scaledIncrement = Math.round(incrementNum * factor); + const floored = Math.floor(scaledValue / scaledIncrement) * scaledIncrement; - return Number(`${steps * stepInteger}e-${scale}`); + return +(floored / factor).toFixed(decimals); } /** - * Floors a price to a multiple of the tick size using decimal arithmetic. - * Empty or zero tick sizes leave it unchanged; invalid sizes or non-finite prices throw RangeError. - * Inputs and the returned number remain subject to JavaScript number precision limits. + * Rounds a price down to a multiple of the symbol's tick size */ export function roundToTickSize(price: number, tickSize: string): number { return floorToIncrement(price, tickSize); } /** - * Floors a quantity to a multiple of the step size using decimal arithmetic. - * Empty or zero step sizes leave it unchanged; invalid sizes or non-finite quantities throw RangeError. - * Inputs and the returned number remain subject to JavaScript number precision limits. + * Rounds a quantity down to a multiple of the symbol's step size */ export function roundToStepSize(quantity: number, stepSize: string): number { return floorToIncrement(quantity, stepSize); diff --git a/src/websocket-client-legacy.ts b/src/websocket-client-legacy.ts index b8c17f7a..1ee7c377 100644 --- a/src/websocket-client-legacy.ts +++ b/src/websocket-client-legacy.ts @@ -1613,7 +1613,7 @@ export class WebsocketClientV1 extends EventEmitter { forceNewConnection?: boolean, ): WebSocket { const lowerCaseSymbol = symbol.toLowerCase(); - const streamName = 'depth'; + const streamName = 'diffBookDepth'; const wsKey = getLegacyWsStoreKeyWithContext( market, 'diffBookDepth', @@ -1621,10 +1621,7 @@ export class WebsocketClientV1 extends EventEmitter { String(updateMs), ); - const updateMsSuffx = - typeof updateMs === 'number' && !(market === 'spot' && updateMs === 1000) - ? `@${updateMs}ms` - : ''; + const updateMsSuffx = typeof updateMs === 'number' ? `@${updateMs}ms` : ''; return this.connectToWsUrl( this.getWsBaseUrl(market, wsKey) + From 686769c263bf220c5d44364b080bb8c6061eb6a2 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 16 Nov 2026 18:47:19 +0100 Subject: [PATCH 4/5] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 78 +- .../enableFuturesBrokerSubAccount.js | 2 +- .../getBrokerSubAccountDepositHistory.js | 2 +- llms.txt | 2182 ++++++++--------- 4 files changed, 1130 insertions(+), 1134 deletions(-) diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 12d3a729..81e5ba01 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -549,45 +549,45 @@ This table includes all endpoints from the official Exchange API docs and corres | [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4871) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | | [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4877) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | | [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4914) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | -| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4925) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | -| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4951) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | -| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4961) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | -| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5002) | | POST | `api/v3/userDataStream` | -| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5006) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | -| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5010) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | -| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5017) | | POST | `sapi/v1/userDataStream` | -| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5021) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5025) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5030) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5038) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5047) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5059) | | POST | `sapi/v1/margin/listen-key` | -| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5063) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5067) | | DELETE | `sapi/v1/margin/listen-key` | -| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5079) | | POST | `sapi/v2/margin/listen-key` | -| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5087) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5095) | | DELETE | `sapi/v2/margin/listen-key` | -| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5099) | | POST | `sapi/v2/margin/uta/listen-key` | -| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5103) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | -| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5107) | | DELETE | `sapi/v2/margin/uta/listen-key` | -| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5115) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | -| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5137) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | -| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5144) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | -| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5153) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | -| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5162) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | -| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5177) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | -| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5186) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | -| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5200) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | -| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5210) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | -| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5219) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | -| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5228) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | -| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5235) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | -| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5242) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | -| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5249) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | -| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5256) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | -| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5273) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | -| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5281) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | -| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5288) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | +| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4925) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | +| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4944) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4954) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | +| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4995) | | POST | `api/v3/userDataStream` | +| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4999) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | +| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5003) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | +| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5010) | | POST | `sapi/v1/userDataStream` | +| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5014) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5018) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5023) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5031) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5040) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5052) | | POST | `sapi/v1/margin/listen-key` | +| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5056) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5060) | | DELETE | `sapi/v1/margin/listen-key` | +| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5072) | | POST | `sapi/v2/margin/listen-key` | +| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5080) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5088) | | DELETE | `sapi/v2/margin/listen-key` | +| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5092) | | POST | `sapi/v2/margin/uta/listen-key` | +| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5096) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | +| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5100) | | DELETE | `sapi/v2/margin/uta/listen-key` | +| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5108) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | +| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5130) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | +| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5137) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | +| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5146) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | +| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5155) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | +| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5170) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | +| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5179) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | +| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5193) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | +| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5203) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | +| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5212) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | +| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5221) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | +| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5228) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | +| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5235) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | +| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5242) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | +| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5249) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | +| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5266) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | +| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5274) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | +| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5281) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | # usdm-client.ts diff --git a/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js b/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js index 169a774b..d3f4698b 100644 --- a/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js +++ b/examples/apidoc/MainClient/enableFuturesBrokerSubAccount.js @@ -4,7 +4,7 @@ import { MainClient } from '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/broker/subAccount/futures +// ENDPOINT: sapi/v1/broker/subAccount // METHOD: POST // PUBLIC: NO diff --git a/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js b/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js index 8042edc4..7fcf832f 100644 --- a/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js +++ b/examples/apidoc/MainClient/getBrokerSubAccountDepositHistory.js @@ -4,7 +4,7 @@ import { MainClient } from '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/broker/subAccount/depositHist +// ENDPOINT: sapi/v1/bv1/apiReferral/ifNewUser // METHOD: GET // PUBLIC: NO diff --git a/llms.txt b/llms.txt index 6d721e2d..80bac8cc 100644 --- a/llms.txt +++ b/llms.txt @@ -3517,6 +3517,11 @@ High level summary for some of the available examples, but check the folder for - `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: .nvmrc +================ +v24.22.3 + ================ File: examples/Rest/Futures/rest-future-bracket-order.ts ================ @@ -5251,11 +5256,6 @@ private handleWSReconnectedEvent(params: { wsKey: WsKey }) ⋮---- // Queue resubscribe workflow -================ -File: .nvmrc -================ -v24.22.3 - ================ File: src/types/portfolio-margin.ts ================ @@ -8860,1273 +8860,1273 @@ private validateOrderId( ): void ================ -File: src/websocket-client-legacy.ts +File: src/types/shared.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; +// 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; ⋮---- -on( - event: 'error', - listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, - ): this; +export type ExchangeSymbol = string; ⋮---- -on( - event: 'open' | 'reconnected', - listener: (event: { - wsKey: WsKey; - ws: WebSocket.Event; - event?: any; - }) => void, - ): this; +export type BooleanString = 'true' | 'false'; ⋮---- -on( - event: 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; +export type BinanceBaseUrlKey = + | 'spot' + | 'spot1' + | 'spot2' + | 'spot3' + | 'spot4' + | 'spottest' + | 'usdmtest' + | 'usdm' + | 'coinm' + | 'coinmtest' + | 'voptions' + | 'voptionstest' + | 'papi' + | 'www'; ⋮---- /** - * @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. + * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. */ -export class WebsocketClientV1 extends EventEmitter -⋮---- -constructor( - options: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, - ) +export type OrderTimeInForce = + | 'GTC' + | 'IOC' + | 'FOK' + | 'GTX' + | 'GTE_GTC' + | 'GTD' + | 'RPI'; ⋮---- -// Some defaults: +export type StringBoolean = 'TRUE' | 'FALSE'; ⋮---- -// Automatically send an authentication op/request after a connection opens, for private connections. +export type SideEffects = + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'NO_SIDE_EFFECT' + | 'AUTO_BORROW_REPAY' + | 'NO_SIDE_EFFECT'; ⋮---- -// Individual requests require a signature +/** + * 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'; ⋮---- -// add default error handling so this doesn't crash node (if the user didn't set a handler) +export type OrderIdProperty = + | 'newClientOrderId' + | 'newClientStrategyId' + | 'listClientOrderId' + | 'limitClientOrderId' + | 'stopClientOrderId' + | 'clientAlgoId' + | 'aboveClientOrderId' + | 'belowClientOrderId' + | 'workingClientOrderId' + | 'pendingAboveClientOrderId' + | 'pendingBelowClientOrderId' + | 'pendingClientOrderId'; ⋮---- -private getRestClientOptions(): RestClientOptions +export type OrderSide = 'BUY' | 'SELL'; ⋮---- -public connectToWsUrl( - url: string, - wsKey?: WsKey | string, - forceNewConnection?: boolean, - ): WebSocket +export type OrderStatus = + | 'NEW' + | 'PENDING_NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'EXPIRED_IN_MATCH'; ⋮---- -// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node +export type OrderExecutionType = + | 'NEW' + | 'CANCELED' + | 'REJECTED' + | 'TRADE' + | 'EXPIRED'; ⋮---- -// Add ws connection with key to store +export type OrderListContingencyType = + | 'OCO' + | 'OTO' + | 'OTOCO' + | 'OPO' + | 'OPOCO'; ⋮---- -public tryWsSend(wsKey: WsKey | string, wsMessage: string) +// listStatusType +export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; ⋮---- -public tryWsPing(wsKey: WsKey | string) +// listOrderStatus +export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +export type OrderType = + | 'LIMIT' + | 'LIMIT_MAKER' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +export type OrderListOrderType = + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) +export type SelfTradePreventionMode = + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE' + | 'DECREMENT' + | 'TRANSFER'; ⋮---- -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 +/** Spot expiry reasons. Unknown strings remain supported for forward compatibility. */ +export type SpotExpiryReason = + | 'NONE' + | 'REJECTED' + | 'EXCHANGE_CANCELED' + | 'OCO_TRIGGER' + | 'OTO_PHASE_ONE_EXPIRED' + | 'UNFILLED_IOC_QUANTITY_EXPIRED' + | 'UNFILLED_FOK_ORDER_EXPIRED' + | 'INSUFFICIENT_LIQUIDITY' + | 'EXECUTION_RULE_PRICE_RANGE_EXCEEDED' + | 'EXHAUSTED' + | 'INSUFFICIENT_QUOTE_NOTIONAL_LIMIT' + | (string & Record); ⋮---- -// emit a separate event for user data messages +export type SpotEffectiveSelfTradePreventionMode = + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'DECREMENT'; ⋮---- -private sendPing(wsKey: WsKey | string, wsUrl: string) +export interface BasicAssetParam { + asset: string; +} ⋮---- -private onWsPing( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - source: WsEventInternalSrc, - ) +export interface BasicSymbolParam { + symbol: string; + isIsolated?: StringBoolean; +} ⋮---- -private onWsPong( - event: any, - wsKey: WsKey | string, - source: WsEventInternalSrc, - ) +export interface SymbolArrayParam { + symbols: string[]; +} ⋮---- -/** - * 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, - ) +export interface BasicAssetPaginatedParams { + asset?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +export interface BasicSymbolPaginatedParams { + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) +export interface SymbolPrice { + symbol: string; + price: numberInString; + time?: number; +} ⋮---- -public closeAll(shouldReconnectAfterClose?: boolean) +// used by spot and usdm +export interface OrderBookParams { + symbol: string; + limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; + symbolStatus?: string; +} ⋮---- -public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) +export type KlineInterval = + | '1s' + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '3d' + | '1w' + | '1M'; ⋮---- -private parseWsError( - context: string, - error: any, - wsKey: WsKey | string, - wsUrl: string, - ) +export interface GetOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -private reconnectWithDelay( - wsKey: WsKey | string, - connectionDelayMs: number, - wsUrl: string, - ) +export interface GetOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// We'll set a new one once the new stream respawns, with a diff listenKey in the key +export interface HistoricalTradesParams { + symbol: string; + limit?: number; + fromId?: number; +} ⋮---- -private clearTimers(wsKey: WsKey | string) +export interface KlinesParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: WsKey | string) +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? +]; ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: WsKey | string) +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? ⋮---- -// Timer tracking that a reconnect is about to happen / in progress -private clearReconnectTimer(wsKey: WsKey | string) +/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ +export type FuturesKline = Kline; +export interface RecentTradesParams { + symbol: string; + limit?: number; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string +export interface CancelOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -public getWs(wsKey: WsKey | string): WebSocket | undefined +export interface AmendKeepPriorityParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + newQty: numberInString; +} ⋮---- -private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) +export interface CancelOCOParams { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -/** - * Send WS message to subscribe to topics. Use subscribe() to call this. - */ -private requestSubscribeTopics(wsKey: WsKey | string, topics: 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; +} ⋮---- -/** - * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. - */ -private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) +/** For isolated margin trading only */ ⋮---- -/** - * Send WS message to unsubscribe from topics. - */ -public requestListSubscriptions(wsKey: WsKey, requestId: number) +/** Define a side effect, only for margin trading */ ⋮---- -/** - * 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, - ) +export interface NewOrderListParams< + T extends OrderResponseType = OrderResponseType, +> { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + aboveType: OrderListOrderType; + aboveClientOrderId?: string; + aboveIcebergQty?: number; + abovePrice?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + aboveQuoteNotionalLimit?: number; + aboveStopPrice?: number; + aboveTrailingDelta?: number; + aboveTimeInForce?: OrderTimeInForce; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: OrderListOrderType; + belowClientOrderId?: string; + belowIcebergQty?: number; + belowPrice?: number; + /** BUY only; Binance has not decided when this feature will be enabled. */ + belowQuoteNotionalLimit?: number; + belowStopPrice?: number; + belowTrailingDelta?: number; + belowTimeInForce?: OrderTimeInForce; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: T; + selfTradePreventionMode?: SelfTradePreventionMode; +} ⋮---- -/** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -private setKeepAliveListenKeyTimer( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -// Set timer to keep WS alive every 50 minutes +export interface SymbolFromPaginatedRequestFromId { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// 1000 * 60 +export interface GetAllOrdersParams { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -private sendKeepAliveForMarket( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +export interface RateLimiter { + rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; + interval: 'SECOND' | 'MINUTE' | 'DAY'; + intervalNum: number; + limit: number; +} ⋮---- -private async checkKeepAliveListenKey( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +export interface SymbolPriceFilter { + filterType: 'PRICE_FILTER'; + minPrice: numberInString; + maxPrice: numberInString; + tickSize: numberInString; +} ⋮---- -// Simple way to test keep alive failure handling: -// throw new Error(`Fake keep alive failure`); +export interface SymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -// code: -1125, -// message: 'This listenKey does not exist.', +export interface SymbolPercentPriceBySideFilter { + filterType: 'PERCENT_PRICE_BY_SIDE'; + bidMultiplierUp: numberInString; + bidMultiplierDown: numberInString; + askMultiplierUp: numberInString; + askMultiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -// If max failurees reached, tear down and respawn if allowed +export interface SymbolLegacyMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + minNotional: numberInString; + applyToMarket: boolean; + avgPriceMins: number; +} ⋮---- -// 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 +export interface SymbolLotSizeFilter { + filterType: 'LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) +export interface SymbolMinNotionalFilter { + filterType: 'NOTIONAL'; + minNotional: numberInString; + applyMinToMarket: boolean; + maxNotional: numberInString; + applyMaxToMarket: boolean; + avgPriceMins: number; +} ⋮---- -private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) +export interface SymbolIcebergPartsFilter { + filterType: 'ICEBERG_PARTS'; + limit: number; +} ⋮---- -private async respawnUserDataStream( - market: WsMarket, - symbol?: string, - isTestnet?: boolean, - respawnAttempt?: number, - ): Promise +export interface SymbolMarketLotSizeFilter { + filterType: 'MARKET_LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -// 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 +export interface SymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -// This timer should probably be tracked/singleton +export interface SymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ +export interface SymbolMaxIcebergOrdersFilter { + filterType: 'MAX_NUM_ICEBERG_ORDERS'; + maxNumIcebergOrders: number; +} ⋮---- -/** - * Subscribe to a universal market websocket stream - */ +export interface SymbolMaxPositionFilter { + filterType: 'MAX_POSITION'; + maxPosition: numberInString; +} ⋮---- -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export type SymbolFilter = + | SymbolPriceFilter + | SymbolPercentPriceFilter + | SymbolPercentPriceBySideFilter + | SymbolLegacyMinNotionalFilter + | SymbolLotSizeFilter + | SymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | SymbolMaxOrdersFilter + | SymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter; ⋮---- -/** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface ExchangeMaxNumOrdersFilter { + filterType: 'EXCHANGE_MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -/** - * 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 +export interface ExchangeMaxAlgoOrdersFilter { + filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeBlockTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +export type ExchangeFilter = + | ExchangeMaxNumOrdersFilter + | ExchangeMaxAlgoOrdersFilter; ⋮---- -/** - * Subscribe to coin index for a symbol in COINM Futures markets - * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. - */ -public subscribeCoinIndexPrice( - symbol: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, - ): WebSocket +export type OrderBookPrice = numberInString; +export type OrderBookAmount = numberInString; ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; ⋮---- -/** - * 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 +export type OrderBookPriceFormatted = number; +export type OrderBookAmountFormatted = number; +export type OrderBookRowFormatted = [ + OrderBookPriceFormatted, + OrderBookAmountFormatted, +]; ⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, - ): WebSocket +export interface GenericCodeMsgError { + code: number; + msg: string; +} ⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface RowsWithTotal { + rows: T[]; + total: number; +} ⋮---- -/** - * 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 +export interface CoinStartEndLimit { + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} + +================ +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'; ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +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'; ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +type WsEventInternalSrc = 'event' | 'function'; ⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +type WebSocketWithMetadata = WebSocket & { + onping?: (event: unknown) => void; + onpong?: (event: unknown) => void; + wsKey?: WsKey | string; +}; ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +on(event: 'reply', listener: (event: WsResponse) ⋮---- -/** - * 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 +on(event: 'message', listener: (event: WsRawMessage) ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +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; ⋮---- /** - * 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 + * @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 ⋮---- -/** - * 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 +constructor( + options: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, + ) ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +// Some defaults: ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +// Automatically send an authentication op/request after a connection opens, for private connections. ⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +// Individual requests require a signature ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +// add default error handling so this doesn't crash node (if the user didn't set a handler) ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +private getRestClientOptions(): RestClientOptions ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, +public connectToWsUrl( + url: string, + wsKey?: WsKey | string, forceNewConnection?: boolean, ): WebSocket ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - forceNewConnection?: boolean, - ): WebSocket +// Add ws connection with key to store ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +public tryWsSend(wsKey: WsKey | string, wsMessage: string) ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket +public tryWsPing(wsKey: WsKey | string) ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -/** - * 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 +private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) ⋮---- -/** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - forceNewConnection?: boolean, - ): WebSocket +private onWsClose( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + wsUrl: string, + ) ⋮---- -/** - * 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 +// Clear any timers before we initiate revival ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states ⋮---- -/** - * 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 +private onWsMessage( + event: WebSocket.MessageEvent, + wsKey: WsKey | string, + source: WsEventInternalSrc, + ) ⋮---- -/** - * Subscribe to margin user data stream - listen key is automatically generated. - */ -public async subscribeMarginUserDataStream( - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn ⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +// emit a separate event for user data messages ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +private sendPing(wsKey: WsKey | string, wsUrl: string) ⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ +private onWsPing( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + source: WsEventInternalSrc, + ) +⋮---- +private onWsPong( + event: any, + wsKey: WsKey | string, + source: WsEventInternalSrc, + ) ⋮---- /** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. + * If closed, trigger a reconnect immediately */ -public async subscribeUsdFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +private executeReconnectableClose( + wsKey: WsKey | string, + reason: string, + wsUrl: string, + ) ⋮---- -// Necessary so client knows this is a reconnect +public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +public closeAll(shouldReconnectAfterClose?: boolean) ⋮---- -/** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeCoinFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) ⋮---- -// Necessary so client knows this is a reconnect +private parseWsError( + context: string, + error: any, + wsKey: WsKey | string, + wsUrl: string, + ) ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) - -================ -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; +private reconnectWithDelay( + wsKey: WsKey | string, + connectionDelayMs: number, + wsUrl: string, + ) ⋮---- -export type ExchangeSymbol = string; +// We'll set a new one once the new stream respawns, with a diff listenKey in the key ⋮---- -export type BooleanString = 'true' | 'false'; +private clearTimers(wsKey: WsKey | string) ⋮---- -export type BinanceBaseUrlKey = - | 'spot' - | 'spot1' - | 'spot2' - | 'spot3' - | 'spot4' - | 'spottest' - | 'usdmtest' - | 'usdm' - | 'coinm' - | 'coinmtest' - | 'voptions' - | 'voptionstest' - | 'papi' - | 'www'; +// 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) ⋮---- /** - * 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' - | 'RPI'; + * Send WS message to subscribe to topics. Use subscribe() to call this. + */ +private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) ⋮---- -export type StringBoolean = 'TRUE' | 'FALSE'; +/** + * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. + */ +private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) ⋮---- -export type SideEffects = - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'NO_SIDE_EFFECT' - | 'AUTO_BORROW_REPAY' - | 'NO_SIDE_EFFECT'; +/** + * Send WS message to unsubscribe from topics. + */ +public requestListSubscriptions(wsKey: WsKey, requestId: number) ⋮---- /** - * 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'; + * Send WS message to set property state + */ +public requestSetProperty( + wsKey: WsKey, + property: 'combined' | string, + value: any, + requestId: number, + ) ⋮---- -export type OrderIdProperty = - | 'newClientOrderId' - | 'newClientStrategyId' - | 'listClientOrderId' - | 'limitClientOrderId' - | 'stopClientOrderId' - | 'clientAlgoId' - | 'aboveClientOrderId' - | 'belowClientOrderId' - | 'workingClientOrderId' - | 'pendingAboveClientOrderId' - | 'pendingBelowClientOrderId' - | 'pendingClientOrderId'; +/** + * Send WS message to get property state + */ +public requestGetProperty( + wsKey: WsKey, + property: 'combined' | string, + requestId: number, + ) ⋮---- -export type OrderSide = 'BUY' | 'SELL'; +/** + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- + **/ ⋮---- -export type OrderStatus = - | 'NEW' - | 'PENDING_NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED' - | 'EXPIRED_IN_MATCH'; +private setKeepAliveListenKeyTimer( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, + ) ⋮---- -export type OrderExecutionType = - | 'NEW' - | 'CANCELED' - | 'REJECTED' - | 'TRADE' - | 'EXPIRED'; +// Set timer to keep WS alive every 50 minutes ⋮---- -export type OrderListContingencyType = - | 'OCO' - | 'OTO' - | 'OTOCO' - | 'OPO' - | 'OPOCO'; +// 1000 * 60 ⋮---- -// listStatusType -export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; +private sendKeepAliveForMarket( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, + ) ⋮---- -// listOrderStatus -export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; +private async checkKeepAliveListenKey( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, + ) ⋮---- -export type OrderType = - | 'LIMIT' - | 'LIMIT_MAKER' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +// Simple way to test keep alive failure handling: +// throw new Error(`Fake keep alive failure`); ⋮---- -export type OrderListOrderType = - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +// code: -1125, +// message: 'This listenKey does not exist.', ⋮---- -export type SelfTradePreventionMode = - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE' - | 'DECREMENT' - | 'TRANSFER'; +// If max failurees reached, tear down and respawn if allowed ⋮---- -/** Spot expiry reasons. Unknown strings remain supported for forward compatibility. */ -export type SpotExpiryReason = - | 'NONE' - | 'REJECTED' - | 'EXCHANGE_CANCELED' - | 'OCO_TRIGGER' - | 'OTO_PHASE_ONE_EXPIRED' - | 'UNFILLED_IOC_QUANTITY_EXPIRED' - | 'UNFILLED_FOK_ORDER_EXPIRED' - | 'INSUFFICIENT_LIQUIDITY' - | 'EXECUTION_RULE_PRICE_RANGE_EXCEEDED' - | 'EXHAUSTED' - | 'INSUFFICIENT_QUOTE_NOTIONAL_LIMIT' - | (string & Record); +// 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 ⋮---- -export type SpotEffectiveSelfTradePreventionMode = - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'DECREMENT'; +// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) ⋮---- -export interface BasicAssetParam { - asset: string; -} +private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) ⋮---- -export interface BasicSymbolParam { - symbol: string; - isIsolated?: StringBoolean; -} +private async respawnUserDataStream( + market: WsMarket, + symbol?: string, + isTestnet?: boolean, + respawnAttempt?: number, + ): Promise ⋮---- -export interface SymbolArrayParam { - symbols: string[]; -} +// 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 ⋮---- -export interface BasicAssetPaginatedParams { - asset?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -export interface BasicSymbolPaginatedParams { - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +// This timer should probably be tracked/singleton ⋮---- -export interface SymbolPrice { - symbol: string; - price: numberInString; - time?: number; -} +/** + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- + **/ ⋮---- -// used by spot and usdm -export interface OrderBookParams { - symbol: string; - limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; - symbolStatus?: string; -} +/** + * Subscribe to a universal market websocket stream + */ ⋮---- -export type KlineInterval = - | '1s' - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '3d' - | '1w' - | '1M'; +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface GetOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Subscribe to aggregate trades for a symbol in a market category + */ +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface GetOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * 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 ⋮---- -export interface HistoricalTradesParams { - symbol: string; - limit?: number; - fromId?: number; -} +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeBlockTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface KlinesParams { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} +/** + * Subscribe to coin index for a symbol in COINM Futures markets + * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. + */ +public subscribeCoinIndexPrice( + symbol: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -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? -]; +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -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? +/** + * 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 ⋮---- -/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ -export type FuturesKline = Kline; -export interface RecentTradesParams { - symbol: string; - limit?: number; -} +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface CancelOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Subscribe to klines(candles) for a symbol in a market category + */ +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface AmendKeepPriorityParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - newQty: numberInString; -} +/** + * 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 ⋮---- -export interface CancelOCOParams { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -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; -} +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeMarkPriceKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -/** For isolated margin trading only */ +/** + * Subscribe to mini 24hr ticker for a symbol in market category. + */ +public subscribeSymbolMini24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -/** Define a side effect, only for margin trading */ +/** + * Subscribe to mini 24hr mini ticker in market category. + */ +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface NewOrderListParams< - T extends OrderResponseType = OrderResponseType, -> { - symbol: string; - listClientOrderId?: string; - side: OrderSide; - quantity: number; - aboveType: OrderListOrderType; - aboveClientOrderId?: string; - aboveIcebergQty?: number; - abovePrice?: number; - /** BUY only; Binance has not decided when this feature will be enabled. */ - aboveQuoteNotionalLimit?: number; - aboveStopPrice?: number; - aboveTrailingDelta?: number; - aboveTimeInForce?: OrderTimeInForce; - aboveStrategyId?: number; - aboveStrategyType?: number; - belowType: OrderListOrderType; - belowClientOrderId?: string; - belowIcebergQty?: number; - belowPrice?: number; - /** BUY only; Binance has not decided when this feature will be enabled. */ - belowQuoteNotionalLimit?: number; - belowStopPrice?: number; - belowTrailingDelta?: number; - belowTimeInForce?: OrderTimeInForce; - belowStrategyId?: number; - belowStrategyType?: number; - newOrderRespType?: T; - selfTradePreventionMode?: SelfTradePreventionMode; -} +/** + * Subscribe to 24hr ticker for a symbol in any market. + */ +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -/** BUY only; Binance has not decided when this feature will be enabled. */ +/** + * Subscribe to 24hr ticker in any market. + */ +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -/** BUY only; Binance has not decided when this feature will be enabled. */ +/** + * 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 ⋮---- -export interface SymbolFromPaginatedRequestFromId { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * 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 ⋮---- -export interface GetAllOrdersParams { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeSpotBlockTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface RateLimiter { - rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; - interval: 'SECOND' | 'MINUTE' | 'DAY'; - intervalNum: number; - limit: number; -} +/** + * Subscribe to candles for a symbol in spot markets. + */ +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface SymbolPriceFilter { - filterType: 'PRICE_FILTER'; - minPrice: numberInString; - maxPrice: numberInString; - tickSize: numberInString; -} +/** + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface SymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - avgPriceMins: number; -} +/** + * Subscribe to mini 24hr mini ticker in spot markets. + */ +public subscribeSpotAllMini24hrTickers( + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface SymbolPercentPriceBySideFilter { - filterType: 'PERCENT_PRICE_BY_SIDE'; - bidMultiplierUp: numberInString; - bidMultiplierDown: numberInString; - askMultiplierUp: numberInString; - askMultiplierDown: numberInString; - avgPriceMins: number; -} +/** + * Subscribe to 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbol24hrTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface SymbolLegacyMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - minNotional: numberInString; - applyToMarket: boolean; - avgPriceMins: number; -} +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket ⋮---- -export interface SymbolLotSizeFilter { - filterType: 'LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface SymbolMinNotionalFilter { - filterType: 'NOTIONAL'; - minNotional: numberInString; - applyMinToMarket: boolean; - maxNotional: numberInString; - applyMaxToMarket: boolean; - avgPriceMins: number; -} +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket ⋮---- -export interface SymbolIcebergPartsFilter { - filterType: 'ICEBERG_PARTS'; - limit: number; -} +/** + * 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 ⋮---- -export interface SymbolMarketLotSizeFilter { - filterType: 'MARKET_LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +/** + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -export interface SymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - maxNumOrders: number; -} +/** + * 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 ⋮---- -export interface SymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -export interface SymbolMaxIcebergOrdersFilter { - filterType: 'MAX_NUM_ICEBERG_ORDERS'; - maxNumIcebergOrders: number; -} +/** + * 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 ⋮---- -export interface SymbolMaxPositionFilter { - filterType: 'MAX_POSITION'; - maxPosition: numberInString; -} +/** + * Subscribe to margin user data stream - listen key is automatically generated. + */ +public async subscribeMarginUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -export type SymbolFilter = - | SymbolPriceFilter - | SymbolPercentPriceFilter - | SymbolPercentPriceBySideFilter - | SymbolLegacyMinNotionalFilter - | SymbolLotSizeFilter - | SymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | SymbolMaxOrdersFilter - | SymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter; +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -export interface ExchangeMaxNumOrdersFilter { - filterType: 'EXCHANGE_MAX_NUM_ORDERS'; - maxNumOrders: number; -} +/** + * Subscribe to isolated margin user data stream - listen key is automatically generated. + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -export interface ExchangeMaxAlgoOrdersFilter { - filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -export type ExchangeFilter = - | ExchangeMaxNumOrdersFilter - | ExchangeMaxAlgoOrdersFilter; +/** + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- -export type OrderBookPrice = numberInString; -export type OrderBookAmount = numberInString; +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeUsdFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; +// Necessary so client knows this is a reconnect ⋮---- -export type OrderBookPriceFormatted = number; -export type OrderBookAmountFormatted = number; -export type OrderBookRowFormatted = [ - OrderBookPriceFormatted, - OrderBookAmountFormatted, -]; +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -export interface GenericCodeMsgError { - code: number; - msg: string; -} +/** + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeCoinFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -export interface RowsWithTotal { - rows: T[]; - total: number; -} +// Necessary so client knows this is a reconnect ⋮---- -export interface CoinStartEndLimit { - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +// Start & store timer to keep alive listen key (and handle expiration) ================ File: src/types/websockets/ws-api-responses.ts @@ -29717,7 +29717,7 @@ getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ -getBrokerIfNewSpotUser(params: { apiAgentCode: string }): Promise<{ +getBrokerIfNewSpotUser(): Promise<{ rebateWorking: boolean; ifNewUser: boolean; }> @@ -29734,11 +29734,7 @@ getBrokerSubAccountDepositHistory( * @deprecated, found only in old docs * Use EXCHANGE LINK endpoints instead **/ -getBrokerUserCustomisedId( - ...[market, params]: - | [market: 'spot', params: { apiAgentCode: string }] - | [market: 'futures', params: { brokerId: string }] - ) +getBrokerUserCustomisedId(market: 'spot' | 'futures') ⋮---- /** * @deprecated, found only in old docs From 4236bb808532d4c41016ad92835a80829ee303c2 Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Thu, 19 Nov 2026 17:40:38 +0100 Subject: [PATCH 5/5] test(v3.6.13): unit tests for rounding helpers (#695) --- test/util/rounding.test.ts | 151 +++++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 test/util/rounding.test.ts diff --git a/test/util/rounding.test.ts b/test/util/rounding.test.ts new file mode 100644 index 00000000..782487cf --- /dev/null +++ b/test/util/rounding.test.ts @@ -0,0 +1,151 @@ +import { roundToStepSize, roundToTickSize } from '../../src/util/rounding'; + +describe.each([ + { name: 'roundToTickSize', round: roundToTickSize }, + { name: 'roundToStepSize', round: roundToStepSize }, +])('$name', ({ round }) => { + describe('issue #695', () => { + it.each<[number, string, number]>([ + [1.23, '0.05', 1.2], + [1.23, '0.05000000', 1.2], + [23, '10', 20], + [3.5, '2.5', 2.5], + [0.3, '0.1', 0.3], + [0.29, '0.01', 0.29], + ])( + 'should round %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('classic floating-point cases', () => { + it.each<[number, string, number]>([ + [0.30000000000000004, '0.1', 0.3], + [1.1, '0.1', 1.1], + [0.0009, '0.0003', 0.0009], + [4.35, '0.01', 4.35], + [4.35, '0.01000000', 4.35], + ])( + 'should round %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('power-of-ten increments', () => { + it.each<[number, string, number]>([ + [1.23456, '0.01', 1.23], + [1.23456, '0.001', 1.234], + [17.89, '1', 17], + [17.89, '1.00000000', 17], + [178.9, '10', 170], + [0.123, '0.10', 0.1], + ])( + 'should round %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('non-power-of-ten increments', () => { + it.each<[number, string, number]>([ + [1.3, '0.25', 1.25], + [1.74, '0.25', 1.5], + [19.99, '0.5', 19.5], + [17, '5', 15], + [0.04, '0.05', 0], + ])( + 'should round %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('already aligned values', () => { + it.each<[number, string, number]>([ + [4.35, '0.01', 4.35], + [1.25, '0.05', 1.25], + [2.5, '2.5', 2.5], + [20, '10', 20], + [0.0003, '0.0001', 0.0003], + ])( + 'should keep %p with increment %p at %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('floor direction', () => { + it.each<[number, string, number]>([ + [4.349, '0.01', 4.34], + [1.2999, '0.05', 1.25], + [9.99, '5', 5], + [0.009, '0.01', 0], + ])( + 'should floor %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('very small steps', () => { + it.each<[number, string, number]>([ + [0.123456789, '0.00000001', 0.12345678], + [0.00000005, '0.00000001', 0.00000005], + ])( + 'should round %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('large values', () => { + it.each<[number, string, number]>([ + [65432.129, '0.01', 65432.12], + [123456789.987, '0.001', 123456789.987], + [98765.4, '0.5', 98765], + ])( + 'should round %p with increment %p to %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('edge contract', () => { + it.each<[number, string, number]>([ + [5.55, '', 5.55], + [5.55, '0', 5.55], + [5.55, '0.00000000', 5.55], + [0, '0.05', 0], + ])( + 'should keep %p with increment %p at %p', + (value, increment, expected) => { + expect(round(value, increment)).toBe(expected); + }, + ); + }); + + describe('number output without float noise', () => { + it.each<[number, string, string]>([ + [0.3, '0.1', '0.3'], + [1.23, '0.05', '1.2'], + [0.29, '0.01', '0.29'], + ])( + 'should format %p with increment %p as %p', + (value, increment, expected) => { + const result = round(value, increment); + expect(typeof result).toBe('number'); + expect(String(result)).toBe(expected); + }, + ); + }); +});