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/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 91d34e34..81e5ba01 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` | 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/llms.txt b/llms.txt index c324c03c..80bac8cc 100644 --- a/llms.txt +++ b/llms.txt @@ -3517,6 +3517,20 @@ 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 +================ +import { + FuturesNewAlgoOrderParams, + NewFuturesOrderParams, + USDMClient, +} from '../../../src/index'; + ================ File: src/types/websockets/ws-api.ts ================ @@ -3917,7 +3931,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 +4202,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,3082 +5257,3081 @@ private handleWSReconnectedEvent(params: { wsKey: WsKey }) // Queue resubscribe workflow ================ -File: src/websocket-client-legacy.ts +File: src/types/portfolio-margin.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'; +// Enums +export type PMStrategyType = + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; ⋮---- -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'; +export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- -alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams +export type PMPriceMatch = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; ⋮---- -type WsEventInternalSrc = 'event' | 'function'; +export type PMSelfTradePreventionMode = + | 'NONE' + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH'; ⋮---- -type WebSocketWithMetadata = WebSocket & { - onping?: (event: unknown) => void; - onpong?: (event: unknown) => void; - wsKey?: WsKey | string; -}; +export type PMMarginOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -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; +export type PMMarginSideEffectType = + | 'NO_SIDE_EFFECT' + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'AUTO_BORROW_REPAY'; +⋮---- +export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +⋮---- +export interface NewPortfolioUMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; // Cannot be sent in Hedge Mode + price?: string; + newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ + newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK + priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- -on(event: 'reply', listener: (event: WsResponse) +positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode ⋮---- -on(event: 'message', listener: (event: WsRawMessage) +reduceOnly?: boolean; // Cannot be sent in Hedge Mode ⋮---- -on( - event: 'formattedMessage', - listener: (event: WsFormattedMessage) => void, - ): this; +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 ⋮---- -on( - event: 'formattedUserDataMessage', - listener: (event: WsUserDataEvents) => void, - ): this; +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -on( - event: 'error', - listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, - ): this; +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; +} ⋮---- -on( - event: 'open' | 'reconnected', - listener: (event: { - wsKey: WsKey; - ws: WebSocket.Event; - event?: any; - }) => void, - ): this; +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; +} ⋮---- -on( - event: 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; +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; +} ⋮---- -/** - * @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 PortfolioUMAlgoType = 'CONDITIONAL'; ⋮---- -constructor( - options: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, - ) +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; +} ⋮---- -// Some defaults: +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; +} ⋮---- -// Automatically send an authentication op/request after a connection opens, for private connections. +export interface CancelPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -// Individual requests require a signature +export interface PortfolioUMCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} ⋮---- -// add default error handling so this doesn't crash node (if the user didn't set a handler) +export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { + code: number; + msg: string; +} ⋮---- -private getRestClientOptions(): RestClientOptions +export interface QueryPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -public connectToWsUrl( - url: string, - wsKey?: WsKey | string, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioAllUMAlgoOrdersReq { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node +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'; +} ⋮---- -// Add ws connection with key to store +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; +} ⋮---- -public tryWsSend(wsKey: WsKey | string, wsMessage: string) +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; +} ⋮---- -public tryWsPing(wsKey: WsKey | string) +export interface NewPortfolioCMConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + pair: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; +} ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +export interface MarginOrderFill { + price: string; + qty: string; + commission: string; + commissionAsset: 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) +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; +} ⋮---- -private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) +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[]; +} ⋮---- -private onWsClose( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - wsUrl: string, - ) +export interface PortfolioMarginOCOOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -// Clear any timers before we initiate revival +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; +} ⋮---- -// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states +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; +} ⋮---- -private onWsMessage( - event: WebSocket.MessageEvent, - wsKey: WsKey | string, - source: WsEventInternalSrc, - ) +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[]; +} ⋮---- -// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e +// Add new interfaces for canceling UM orders +export interface CancelPortfolioUMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn +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; +} ⋮---- -// emit a separate event for user data messages +export interface CancelPortfolioUMConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -private sendPing(wsKey: WsKey | string, wsUrl: string) +export interface PortfolioUMCancelConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate: number; + priceMatch: PMPriceMatch; +} ⋮---- -private onWsPing( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - source: WsEventInternalSrc, - ) +export interface CancelPortfolioCMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -private onWsPong( - event: any, - wsKey: WsKey | string, - source: WsEventInternalSrc, - ) +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; +} ⋮---- -/** - * 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 CancelPortfolioCMConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) +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; +} ⋮---- -public closeAll(shouldReconnectAfterClose?: boolean) +export interface CancelPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) +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 parseWsError( - context: string, - error: any, - wsKey: WsKey | string, - wsUrl: string, - ) +export interface CancelPortfolioMarginOCOReq { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -private reconnectWithDelay( - wsKey: WsKey | string, - connectionDelayMs: number, - wsUrl: string, - ) +export interface PortfolioMarginOCOCancelOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -// We'll set a new one once the new stream respawns, with a diff listenKey in the key +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 clearTimers(wsKey: WsKey | string) +export interface PortfolioMarginOCOCancelResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOCancelOrder[]; + orderReports: PortfolioMarginOCOCancelOrderReport[]; +} ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: WsKey | string) +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; +} ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: WsKey | string) +export interface PortfolioMarginCancelAllOrdersOCOReport { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOCancelOrder[]; + orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; +} ⋮---- -// Timer tracking that a reconnect is about to happen / in progress -private clearReconnectTimer(wsKey: WsKey | string) +export type PortfolioMarginCancelAllOrdersResponse = + | PortfolioMarginCancelAllOrdersOrderReport + | PortfolioMarginCancelAllOrdersOCOReport; ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string +export interface ModifyPortfolioUMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: string; + price: string; + orderId?: number; + origClientOrderId?: string; + priceMatch?: PMPriceMatch; + modifyId?: number; +} ⋮---- -public getWs(wsKey: WsKey | string): WebSocket | undefined +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; +} ⋮---- -private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) +export interface ModifyPortfolioCMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: string; + price: string; + orderId?: number; + origClientOrderId?: string; + modifyId?: number; +} ⋮---- -/** - * Send WS message to subscribe to topics. Use subscribe() to call this. - */ -private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) +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; +} ⋮---- -/** - * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. - */ -private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) +export interface QueryPortfolioUMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Send WS message to unsubscribe from topics. - */ -public requestListSubscriptions(wsKey: WsKey, requestId: number) +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; +} ⋮---- -/** - * Send WS message to set property state - */ -public requestSetProperty( - wsKey: WsKey, - property: 'combined' | string, - value: any, - requestId: number, - ) +export interface QueryPortfolioAllUMOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Send WS message to get property state - */ -public requestGetProperty( - wsKey: WsKey, - property: 'combined' | string, - requestId: number, - ) +export interface QueryPortfolioUMOpenOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ +export interface QueryPortfolioAllUMConditionalOrdersReq { + symbol?: string; + strategyId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -private setKeepAliveListenKeyTimer( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +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; +} ⋮---- -// Set timer to keep WS alive every 50 minutes +export interface QueryPortfolioUMOpenConditionalOrderReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -// 1000 * 60 +export interface QueryPortfolioUMConditionalOrderHistoryReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -private sendKeepAliveForMarket( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +export interface QueryPortfolioCMOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -private async checkKeepAliveListenKey( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, - ) +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; +} ⋮---- -// Simple way to test keep alive failure handling: -// throw new Error(`Fake keep alive failure`); +export interface QueryPortfolioAllCMOrdersReq { + symbol: string; + pair?: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// code: -1125, -// message: 'This listenKey does not exist.', +export interface QueryPortfolioCMOpenOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -// If max failurees reached, tear down and respawn if allowed +export interface QueryPortfolioAllCMConditionalOrdersReq { + symbol?: string; + strategyId?: number; + startTime?: number; + endTime?: number; + limit?: 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 -⋮---- -// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) +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; +} ⋮---- -private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) +export interface QueryPortfolioCMConditionalOrderHistoryReq { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; +} ⋮---- -private async respawnUserDataStream( - market: WsMarket, - symbol?: string, - isTestnet?: boolean, - respawnAttempt?: number, - ): Promise +export interface PortfolioCMConditionalHistoryOrder + extends PortfolioCMConditionalOrder { + priceMatch: PMPriceMatch; +} ⋮---- -// 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 QueryPortfolioUMForceOrdersReq { + symbol?: string; + autoCloseType?: PMAutoCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// This timer should probably be tracked/singleton +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; +} ⋮---- -/** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ +export interface QueryPortfolioCMForceOrdersReq { + symbol?: string; + autoCloseType?: PMAutoCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to a universal market websocket stream - */ +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; +} ⋮---- -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioUMOrderAmendmentReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioUMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: 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 PortfolioUMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioUMOrderAmendment; + priceMatch: PMPriceMatch; + modifyId?: number; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeBlockTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioCMOrderAmendmentReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + 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 interface PortfolioCMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface PortfolioCMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioCMOrderAmendment; + modifyId?: 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 QueryPortfolioMarginForceOrdersReq { + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 +} ⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, - ): WebSocket +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 ⋮---- -/** - * 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 PortfolioMarginForceOrder { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + updatedTime: 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 -⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +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 index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - 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 mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - 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 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 50; max 1000 ⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - 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 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 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 best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - 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 best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - 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 subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioMarginAllOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} ⋮---- -/** - * 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 +limit?: number; // Default 500; max 500 ⋮---- -/** - * 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 +export interface QueryPortfolioMarginOCOReq { + orderListId?: number; // Either orderListId or origClientOrderId must be provided + origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, - ): WebSocket +orderListId?: number; // Either orderListId or origClientOrderId must be provided +origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +export interface PortfolioMarginOCOQueryOrder { + symbol: string; + orderId: number; + clientOrderId: string; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +export interface PortfolioMarginOCO { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOQueryOrder[]; +} ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +export interface QueryPortfolioMarginAllOCOReq { + fromId?: number; // If supplied, neither startTime or endTime can be provided + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +fromId?: number; // If supplied, neither startTime or endTime can be provided ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, - ): WebSocket +limit?: number; // Default 500; max 500 ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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 +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - forceNewConnection?: boolean, - ): WebSocket +fromId?: number; // TradeId to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +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; +} ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket +export interface PortfolioMarginRepayDebtReq { + asset: string; + amount?: string; + specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - forceNewConnection?: boolean, - ): WebSocket +specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket +export interface PortfolioMarginRepayDebtResponse { + amount: string; + asset: string; + specifyRepayAssets: string[]; + updateTime: number; + success: boolean; +} ⋮---- /** - * 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 + * + * DERIVATIVES - ACCOUNT endpoints + * + **/ ⋮---- -/** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - forceNewConnection?: boolean, - ): WebSocket +export type PMAccountStatus = + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; ⋮---- -/** - * 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 type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; +export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +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; +} ⋮---- -/** - * 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 +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 ⋮---- -/** - * Subscribe to margin user data stream - listen key is automatically generated. - */ -public async subscribeMarginUserDataStream( - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): 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; +} ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +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 ⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +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 +} ⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ +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 ⋮---- -/** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeUsdFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, - ): Promise +accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD ⋮---- -// Necessary so client knows this is a reconnect +virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +totalMarginOpenLoss: string; // in USD margin open order +updateTime: number; // last update time ⋮---- -/** - * 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 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; +} ⋮---- -// Necessary so client knows this is a reconnect +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; +} ⋮---- -// 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 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 type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +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 type PMPriceMatch = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; +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 type PMSelfTradePreventionMode = - | 'NONE' - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH'; +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 type PMMarginOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +export interface PortfolioTradingIndicator { + isLocked: boolean; + plannedRecoverTime: number; + indicator: PMIndicatorType; + value: number; + triggerValue: number; +} ⋮---- -export type PMMarginSideEffectType = - | 'NO_SIDE_EFFECT' - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'AUTO_BORROW_REPAY'; +export interface PortfolioTradingStatus { + indicators: { + [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" + }; + updateTime: number; +} ⋮---- -export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" ⋮---- -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 PortfolioMarginLoanRecord { + txId: number; + asset: string; + principal: string; + timestamp: number; + status: PMMarginLoanStatus; } ⋮---- -positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode +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 +} ⋮---- -reduceOnly?: boolean; // Cannot be sent in Hedge Mode +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 ⋮---- -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 +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 +} ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +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 NewPortfolioUMOrderResponse { - clientOrderId: string; - cumQty: string; - cumQuote?: string; - executedQty: string; - orderId: number; - avgPrice?: string; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate?: number; - updateTime: number; - priceMatch: PMPriceMatch; +export interface PortfolioMarginRepayRecord { + amount: string; // Total amount repaid + asset: string; + interest: string; // Interest repaid + principal: string; // Principal repaid + status: PMMarginLoanStatus; + txId: number; } ⋮---- -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; -} +amount: string; // Total amount repaid ⋮---- -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; +interest: string; // Interest repaid +principal: string; // Principal repaid +⋮---- +export interface GetMarginInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago } ⋮---- -export type PortfolioUMAlgoType = 'CONDITIONAL'; +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 NewPortfolioUMAlgoOrderReq { - algoType: PortfolioUMAlgoType; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - type: PMStrategyType; - timeInForce?: string; - quantity?: string; - price?: string; - triggerPrice?: string; - workingType?: PMWorkingType; - priceMatch?: PMPriceMatch; - closePosition?: string; - priceProtect?: string; - reduceOnly?: string; - activatePrice?: string; - callbackRate?: string; - clientAlgoId?: string; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; -} +export 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 ⋮---- -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; -} +| '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 CancelPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; +export interface PortfolioMarginInterestRecord { + txId: number; + interestAccuredTime: number; + asset: string; + rawAsset: string; + principal: string; + interest: string; + interestRate: string; + type: PMInterestType; } ⋮---- -export interface PortfolioUMCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; +export interface GetPortfolioInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; // Default: 10, Max: 100 } ⋮---- -export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { - code: number; - msg: string; -} +size?: number; // Default: 10, Max: 100 ⋮---- -export interface QueryPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; +export interface PortfolioNegativeBalanceInterestRecord { + asset: string; + interest: string; // interest amount + interestAccuredTime: number; + interestRate: string; // daily interest rate + principal: string; } ⋮---- -export interface QueryPortfolioAllUMAlgoOrdersReq { - symbol: string; - algoId?: number; +interest: string; // interest amount +⋮---- +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'; +⋮---- +/** + * 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; + limit?: number; // Default 100; max 1000 } ⋮---- -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'; -} +limit?: number; // Default 100; max 1000 ⋮---- -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 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 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; -} +symbol: string; // trade symbol, if existing ⋮---- -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; -} +income: string; // income amount +asset: string; // income asset +info: string; // extra information ⋮---- -export interface MarginOrderFill { - price: string; - qty: string; - commission: string; - commissionAsset: string; +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'; +⋮---- +/** + * 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 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; -} +limit?: number; // Default 100; max 1000 ⋮---- -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 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 interface PortfolioMarginOCOOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +symbol: string; // trade symbol, if existing ⋮---- -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; -} +income: string; // income amount +asset: string; // income asset +info: string; // extra information ⋮---- -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; +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 } ⋮---- -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[]; +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 } ⋮---- -// Add new interfaces for canceling UM orders -export interface CancelPortfolioUMOrderReq { - 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 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'; +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 CancelPortfolioUMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +symbol: string; // symbol name +positionAmt: string; // position amount ⋮---- -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; +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode +⋮---- +maxQty: string; // maximum quantity of base asset +⋮---- +export interface PortfolioUMAccountConfig { + feeTier: number; // account commission tier + canTrade: boolean; // if can trade + canDeposit: boolean; // if can transfer in asset + canWithdraw: boolean; // if can transfer out asset + dualSidePosition: boolean; + updateTime: number; // reserved property + multiAssetsMargin: boolean; + tradeGroupId: number; } ⋮---- -export interface CancelPortfolioCMOrderReq { +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; - orderId?: number; - origClientOrderId?: string; + marginType: 'CROSSED' | 'ISOLATED'; + isAutoAddMargin: string; // "true" or "false" as string + leverage: number; + maxNotionalValue: string; } ⋮---- -export interface PortfolioCMCancelOrderResponse { - avgPrice?: string; - clientOrderId: string; - cumQty: string; - cumBase?: string; - executedQty: string; - orderId: number; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - pair: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} -⋮---- -export interface CancelPortfolioCMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} -⋮---- -export interface PortfolioCMCancelConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; -} -⋮---- -export interface CancelPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; -} -⋮---- -export interface PortfolioMarginCancelOrderResponse { - symbol: string; - orderId: number; - origClientOrderId: string; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; -} -⋮---- -export interface CancelPortfolioMarginOCOReq { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} -⋮---- -export interface PortfolioMarginOCOCancelOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} -⋮---- -export interface PortfolioMarginOCOCancelOrderReport { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: 'STOP_LOSS_LIMIT' | 'LIMIT_MAKER'; - side: 'BUY' | 'SELL'; - stopPrice?: string; -} +isAutoAddMargin: string; // "true" or "false" as string ⋮---- -export interface PortfolioMarginOCOCancelResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginOCOCancelOrderReport[]; +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 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; -} +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 PortfolioMarginCancelAllOrdersOCOReport { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; +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 type PortfolioMarginCancelAllOrdersResponse = - | PortfolioMarginCancelAllOrdersOrderReport - | PortfolioMarginCancelAllOrdersOCOReport; +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 ModifyPortfolioUMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - priceMatch?: PMPriceMatch; - modifyId?: 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 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; -} +status: 'completed' | 'processing'; // Enum: completed, processing +url: string; // The link is mapped to download id ⋮---- -export interface ModifyPortfolioCMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - modifyId?: number; -} +notified: boolean; // ignore +expirationTimestamp: number; // The link would expire after this timestamp ⋮---- -export interface PortfolioCMModifyOrderResponse { - orderId: number; - symbol: string; - pair: string; - status: string; - clientOrderId: string; - price: string; - avgPrice?: string; - origQty: string; - executedQty: string; - cumQty: string; - cumBase?: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - origType: 'LIMIT'; - updateTime: number; - modifyId?: number; +export interface PortfolioTradFiPerpsContractSignResponse { + code: number; + msg: string; } + +================ +File: src/coinm-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; ⋮---- -export interface QueryPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +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 PortfolioUMOrder { - avgPrice: string; - clientOrderId: string; - cumQuote: string; - executedQty: string; - orderId: number; - origQty: string; - origType: 'LIMIT' | 'MARKET'; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - status: string; - symbol: string; - time: number; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +export class CoinMClient extends BaseRestClient ⋮---- -export interface QueryPortfolioAllUMOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, + ) ⋮---- -export interface QueryPortfolioUMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- -export interface QueryPortfolioAllUMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * + * Market Data Endpoints + * + **/ ⋮---- -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; -} +testConnectivity(): Promise ⋮---- -export interface QueryPortfolioUMOpenConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +getExchangeInfo(): Promise ⋮---- -export interface QueryPortfolioUMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +getOrderBook(params: OrderBookParams): Promise ⋮---- -export interface QueryPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +getRecentTrades(params: RecentTradesParams): Promise ⋮---- -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; -} +getHistoricalTrades( + params: HistoricalTradesParams, + ): Promise ⋮---- -export interface QueryPortfolioAllCMOrdersReq { - symbol: string; - pair?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, + ): Promise ⋮---- -export interface QueryPortfolioCMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Index Price and Mark Price + */ +getMarkPrice(params?: { symbol?: string }): Promise ⋮---- -export interface QueryPortfolioAllCMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +getFundingRateHistory( + params?: Partial, + ): Promise ⋮---- -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; -} +getFundingRate(params?: { symbol?: string }): Promise ⋮---- -export interface QueryPortfolioCMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +getKlines(params: KlinesParams): Promise ⋮---- -export interface PortfolioCMConditionalHistoryOrder - extends PortfolioCMConditionalOrder { - priceMatch: PMPriceMatch; -} +getContinuousContractKlines( + params: ContinuousContractKlinesParams, + ): Promise ⋮---- -export interface QueryPortfolioUMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- -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; -} +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -export interface QueryPortfolioCMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} +getPremiumIndexKlines(params: KlinesParams): Promise ⋮---- -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; -} +get24hrChangeStatistics(params?: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -export interface QueryPortfolioUMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getSymbolPriceTicker(params?: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -export interface PortfolioUMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} +getSymbolOrderBookTicker(params?: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -export interface PortfolioUMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioUMOrderAmendment; - priceMatch: PMPriceMatch; - modifyId?: number; -} +getOpenInterest(params: { symbol: string }): Promise ⋮---- -export interface QueryPortfolioCMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise ⋮---- -export interface PortfolioCMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} +getTopTradersLongShortAccountRatio( + params: FuturesCoinMLongShortAccountRatioParams, + ): Promise ⋮---- -export interface PortfolioCMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioCMOrderAmendment; - modifyId?: number; -} +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams & { pair?: string }, + ): Promise ⋮---- -export interface QueryPortfolioMarginForceOrdersReq { - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 -} +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, + ): Promise ⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 +getTakerBuySellVolume( + params: FuturesCoinMTakerBuySellVolumeParams, + ): Promise ⋮---- -export interface PortfolioMarginForceOrder { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - updatedTime: number; -} +getCompositeSymbolIndex(params: FuturesCoinMBasisParams): 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 -} +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getIndexPriceConstituents(params: { + symbol: string; + }): Promise ⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getQuarterlyContractSettlementPrices(params: { + pair: 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; -} +/** + * + * Trade Endpoints + * + **/ ⋮---- -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 -} +submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 50; max 1000 +/** + * 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 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; -} +/** + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + */ +modifyOrder( + params: ModifyFuturesOrderParams, + ): Promise ⋮---- -export interface 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) -} +/** + * 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)[]> ⋮---- -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) +getOrderModifyHistory( + params: GetOrderModifyHistoryParams, + ): Promise ⋮---- -export interface QueryPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +cancelOrder(params: CancelOrderParams): 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; -} +cancelMultipleOrders( + params: CancelMultipleOrdersParams, + ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- -export interface QueryPortfolioMarginAllOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; // Default 500; max 500 -} +cancelAllOpenOrders(params: { + symbol?: string; + }): Promise ⋮---- -limit?: number; // Default 500; max 500 +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, + ): Promise ⋮---- -export interface QueryPortfolioMarginOCOReq { - orderListId?: number; // Either orderListId or origClientOrderId must be provided - origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided -} +getOrder(params: GetOrderParams): Promise ⋮---- -orderListId?: number; // Either orderListId or origClientOrderId must be provided -origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +getAllOrders(params: GetAllOrdersParams): Promise ⋮---- -export interface PortfolioMarginOCOQueryOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +getAllOpenOrders(params?: { symbol?: string }): Promise ⋮---- -export interface PortfolioMarginOCO { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOQueryOrder[]; -} +getCurrentOpenOrder(params: GetOrderParams): 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 -} +/** + * + * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) + * Conditional orders migrate to Algo Service on COIN-M + * + **/ ⋮---- -fromId?: number; // If supplied, neither startTime or endTime can be provided +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, + ): Promise ⋮---- -limit?: number; // Default 500; max 500 +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, + ): 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 -} +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, + ): Promise ⋮---- -fromId?: number; // TradeId to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 +getForceOrders(params?: GetForceOrdersParams): 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; -} +getAccountTrades( + params: CoinMAccountTradeParams & { orderId?: number }, + ): Promise ⋮---- -export interface PortfolioMarginRepayDebtReq { - asset: string; - amount?: string; - specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas -} +getPositions(params?: { + marginAsset?: string; + pair?: string; + }): Promise ⋮---- -specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas +setPositionMode(params: PositionModeParams): Promise ⋮---- -export interface PortfolioMarginRepayDebtResponse { - amount: string; - asset: string; - specifyRepayAssets: string[]; - updateTime: number; - success: boolean; -} +setMarginType(params: SetMarginTypeParams): Promise ⋮---- -/** - * - * DERIVATIVES - ACCOUNT endpoints - * - **/ +setLeverage(params: SetLeverageParams): Promise ⋮---- -export type PMAccountStatus = - | 'NORMAL' - | 'MARGIN_CALL' - | 'SUPPLY_MARGIN' - | 'REDUCE_ONLY' - | 'ACTIVE_LIQUIDATION' - | 'FORCE_LIQUIDATION' - | 'BANKRUPTED'; +getADLQuantileEstimation(params?: { symbol?: string }): Promise ⋮---- -export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; -export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, + ): 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; -} +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, + ): Promise +/** + * + * Account Endpoints + * + **/ ⋮---- -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 +getBalance(): 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; -} +getAccountCommissionRate(params: { + symbol?: string; + }): 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 +getAccountInformation(): Promise ⋮---- -export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; +/** + * Notional Bracket for Symbol (NOT "pair") + */ +getNotionalAndLeverageBrackets(params?: { + symbol?: string; + }): 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 -} +// TO ADD: dapi/v1/leverageBracket +// can use dapi/v2/leverageBracket ⋮---- -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 +getCurrentPositionMode(): Promise ⋮---- -accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD +/** + * Query income history (`GET /dapi/v1/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- -virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD +/** + * 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; + }> ⋮---- -totalMarginOpenLoss: string; // in USD margin open order -updateTime: number; // last update time +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; + }): 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; -} +getDownloadIdForFuturesOrderHistory(params: { + startTime: number; + endTime: number; + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- -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; -} +getFuturesOrderHistoryDownloadLink(params: { + downloadId: 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 -} +getDownloadIdForFuturesTradeHistory(params: { + startTime: number; + endTime: number; + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: 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 +getFuturesTradeHistoryDownloadLink(params: { + downloadId: string; + }): 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 -} +/** + * + * Portfolio Margin Endpoints + * + **/ ⋮---- -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 +getClassicPortfolioMarginAccount(params: { + asset: string; + }): Promise ⋮---- -export interface PortfolioTradingIndicator { - isLocked: boolean; - plannedRecoverTime: number; - indicator: PMIndicatorType; - value: number; - triggerValue: number; -} +/** + * @deprecated at 6th August, 2024 + **/ +getClassicPortfolioMarginNotionalLimits( + params?: GetClassicPortfolioMarginNotionalLimitParams, + ): Promise<{ + notionalLimits: ClassicPortfolioMarginNotionalLimit[]; + }> ⋮---- -export interface PortfolioTradingStatus { - indicators: { - [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" - }; - updateTime: 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 + * + **/ ⋮---- -[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" +/** + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, + ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> ⋮---- -export interface PortfolioMarginLoanRecord { - txId: number; - asset: string; - principal: string; - timestamp: number; - status: PMMarginLoanStatus; -} +/** + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, + ): Promise<{ customerId: string; email: 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 -} +/** + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, + ): 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 +/** + * @deprecated + **/ +getBrokerUserCustomId(brokerId: 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 -} +/** + * @deprecated + **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): 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 +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -export interface PortfolioMarginRepayRecord { - amount: string; // Total amount repaid - asset: string; - interest: string; // Interest repaid - principal: string; // Principal repaid - status: PMMarginLoanStatus; - txId: number; -} +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -amount: string; // Total amount repaid +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, + ): Promise ⋮---- -interest: string; // Interest repaid -principal: string; // Principal repaid +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -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 -} +getFuturesUserDataListenKey(): Promise<{ listenKey: 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 +keepAliveFuturesUserDataListenKey(): 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 +closeFuturesUserDataListenKey(): Promise ⋮---- -| '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 +/** + * 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'; ⋮---- -export interface PortfolioMarginInterestRecord { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset: string; - principal: string; - interest: string; - interestRate: string; - type: PMInterestType; -} +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'; ⋮---- -export interface GetPortfolioInterestHistoryReq { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; // Default: 10, Max: 100 -} +/** + * REST client for Portfolio Margin APIs (papi) + * + * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info + */ +export class PortfolioClient extends BaseRestClient ⋮---- -size?: number; // Default: 10, Max: 100 +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, + ) ⋮---- -export interface PortfolioNegativeBalanceInterestRecord { - asset: string; - interest: string; // interest amount - interestAccuredTime: number; - interestRate: string; // daily interest rate - principal: string; -} +getClientId(): BinanceBaseUrlKey ⋮---- -interest: string; // interest amount +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- -interestRate: string; // daily interest rate +/** + * + * Misc Endpoints + * + **/ ⋮---- -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'; +testConnectivity(): Promise +⋮---- +signTradFiPerpsContract(): Promise ⋮---- /** - * 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 -} + * + * DERIVATIVES -TRADE endpoints + * + **/ ⋮---- -limit?: number; // Default 100; max 1000 +submitNewUMOrder( + params: NewPortfolioUMOrderReq, + ): Promise ⋮---- -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 -} +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). + */ +submitNewUMConditionalOrder( + params: NewPortfolioUMConditionalOrderReq, + ): Promise ⋮---- -symbol: string; // trade symbol, if existing +submitNewUMAlgoOrder( + params: NewPortfolioUMAlgoOrderReq, + ): Promise ⋮---- -income: string; // income amount -asset: string; // income asset -info: string; // extra information +submitNewCMOrder( + params: NewPortfolioCMOrderReq, + ): Promise ⋮---- -tranId: string; // transaction id -tradeId: string; // trade id, if existing +submitNewCMConditionalOrder( + params: NewPortfolioCMConditionalOrderReq, + ): Promise ⋮---- -export type CMIncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'FUNDING_FEE' - | 'REALIZED_PNL' - | 'COMMISSION' - | 'INSURANCE_CLEAR' - | 'DELIVERED_SETTELMENT'; +submitNewMarginOrder( + params: NewPortfolioMarginOrderReq, + ): 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 -} +submitMarginLoan(params: { asset: string; amount: string }): Promise<{ + tranId: number; + }> ⋮---- -limit?: number; // Default 100; max 1000 +submitMarginRepay(params: { asset: string; amount: string }): Promise<{ + tranId: number; + }> ⋮---- -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 -} +submitNewMarginOCO( + params: NewPortfolioMarginOCOReq, + ): Promise ⋮---- -symbol: string; // trade symbol, if existing +cancelUMOrder( + params: CancelPortfolioUMOrderReq, + ): Promise ⋮---- -income: string; // income amount -asset: string; // income asset -info: string; // extra information +cancelAllUMOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -tranId: string; // transaction id -tradeId: string; // trade id, if existing +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). + */ +cancelUMConditionalOrder( + params: CancelPortfolioUMConditionalOrderReq, + ): Promise ⋮---- -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 -} +cancelUMAlgoOrder( + params: CancelPortfolioUMAlgoOrderReq, + ): Promise ⋮---- -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 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 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 -} +cancelAllUMAlgoOpenOrders(params: { + symbol: string; + }): 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 +cancelCMOrder( + params: CancelPortfolioCMOrderReq, + ): 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 -} +cancelAllCMOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -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 +cancelCMConditionalOrder( + params: CancelPortfolioCMConditionalOrderReq, + ): 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; -} +cancelAllCMConditionalOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- -symbol: string; // symbol name -positionAmt: string; // position amount +cancelMarginOrder( + params: CancelPortfolioMarginOrderReq, + ): Promise ⋮---- -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode +cancelMarginOCO( + params: CancelPortfolioMarginOCOReq, + ): Promise ⋮---- -maxQty: string; // maximum quantity of base asset +cancelAllMarginOrders(params: { + symbol: string; + }): 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; -} +modifyUMOrder( + params: ModifyPortfolioUMOrderReq, + ): Promise ⋮---- -feeTier: number; // account commission tier -canTrade: boolean; // if can trade -canDeposit: boolean; // if can transfer in asset -canWithdraw: boolean; // if can transfer out asset +modifyCMOrder( + params: ModifyPortfolioCMOrderReq, + ): Promise ⋮---- -updateTime: number; // reserved property +getUMOrder(params: QueryPortfolioUMOrderReq): Promise ⋮---- -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 -} +getAllUMOrders( + params: QueryPortfolioAllUMOrdersReq, + ): Promise ⋮---- -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 +getUMOpenOrder( + params: QueryPortfolioUMOpenOrderReq, + ): Promise ⋮---- -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; -} +getAllUMOpenOrders(params: { symbol?: string }): Promise ⋮---- -status: 'completed' | 'processing'; // Enum: completed, processing -url: string; // The link is mapped to download id +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). + */ +getAllUMConditionalOrders( + params: QueryPortfolioAllUMConditionalOrdersReq, + ): Promise ⋮---- -notified: boolean; // ignore -expirationTimestamp: number; // The link would expire after this timestamp +getAllUMAlgoOrders( + params: QueryPortfolioAllUMAlgoOrdersReq, + ): Promise ⋮---- -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; +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). + */ +getUMOpenConditionalOrders(params: { + symbol?: string; + }): Promise ⋮---- -export type ExchangeSymbol = string; +getUMAlgoOpenOrders(params?: { + symbol?: string; + }): Promise ⋮---- -export type BooleanString = 'true' | 'false'; +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). + */ +getUMOpenConditionalOrder( + params: QueryPortfolioUMOpenConditionalOrderReq, + ): Promise ⋮---- -export type BinanceBaseUrlKey = - | 'spot' - | 'spot1' - | 'spot2' - | 'spot3' - | 'spot4' - | 'spottest' - | 'usdmtest' - | 'usdm' - | 'coinm' - | 'coinmtest' - | 'voptions' - | 'voptionstest' - | 'papi' - | 'www'; +getUMAlgoOrder( + params: QueryPortfolioUMAlgoOrderReq, + ): 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'; + * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. + */ +getUMConditionalOrderHistory( + params: QueryPortfolioUMConditionalOrderHistoryReq, + ): Promise ⋮---- -export type StringBoolean = 'TRUE' | 'FALSE'; +getCMOrder(params: QueryPortfolioCMOrderReq): Promise ⋮---- -export type SideEffects = - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'NO_SIDE_EFFECT' - | 'AUTO_BORROW_REPAY' - | 'NO_SIDE_EFFECT'; +getAllCMOrders( + params: QueryPortfolioAllCMOrdersReq, + ): 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'; +getCMOpenOrder( + params: QueryPortfolioCMOpenOrderReq, + ): Promise ⋮---- -export type OrderIdProperty = - | 'newClientOrderId' - | 'newClientStrategyId' - | 'listClientOrderId' - | 'limitClientOrderId' - | 'stopClientOrderId' - | 'clientAlgoId' - | 'aboveClientOrderId' - | 'belowClientOrderId' - | 'workingClientOrderId' - | 'pendingAboveClientOrderId' - | 'pendingBelowClientOrderId' - | 'pendingClientOrderId'; +getAllCMOpenOrders(params: { + symbol?: string; + pair?: string; + }): Promise ⋮---- -export type OrderSide = 'BUY' | 'SELL'; +getCMOpenConditionalOrders(params: { + symbol?: string; + }): Promise ⋮---- -export type OrderStatus = - | 'NEW' - | 'PENDING_NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED' - | 'EXPIRED_IN_MATCH'; +getCMOpenConditionalOrder(params: { + symbol: string; + strategyId?: number; + newClientStrategyId?: string; + }): Promise ⋮---- -export type OrderExecutionType = - | 'NEW' - | 'CANCELED' - | 'REJECTED' - | 'TRADE' - | 'EXPIRED'; +getAllCMConditionalOrders( + params: QueryPortfolioAllCMConditionalOrdersReq, + ): Promise ⋮---- -export type OrderListContingencyType = - | 'OCO' - | 'OTO' - | 'OTOCO' - | 'OPO' - | 'OPOCO'; +getCMConditionalOrderHistory( + params: QueryPortfolioCMConditionalOrderHistoryReq, + ): Promise ⋮---- -// listStatusType -export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; +getUMForceOrders( + params: QueryPortfolioUMForceOrdersReq, + ): Promise ⋮---- -// listOrderStatus -export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; +getCMForceOrders( + params: QueryPortfolioCMForceOrdersReq, + ): Promise ⋮---- -export type OrderType = - | 'LIMIT' - | 'LIMIT_MAKER' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +getUMOrderModificationHistory( + params: QueryPortfolioUMOrderAmendmentReq, + ): Promise ⋮---- -export type OrderListOrderType = - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +getCMOrderModificationHistory( + params: QueryPortfolioCMOrderAmendmentReq, + ): Promise ⋮---- -export type SelfTradePreventionMode = - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE' - | 'DECREMENT' - | 'TRANSFER'; +getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise<{ + rows: PortfolioMarginForceOrder[]; + total: number; + }> ⋮---- -export interface BasicAssetParam { - asset: string; -} +getUMTrades(params: QueryPortfolioUMTradesReq): Promise ⋮---- -export interface BasicSymbolParam { - symbol: string; - isIsolated?: StringBoolean; -} +getCMTrades(params: QueryPortfolioCMTradesReq): Promise ⋮---- -export interface SymbolArrayParam { - symbols: string[]; -} +getUMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > ⋮---- -export interface BasicAssetPaginatedParams { - asset?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -export interface BasicSymbolPaginatedParams { - symbol?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getCMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > ⋮---- -export interface SymbolPrice { - symbol: string; - price: numberInString; - time?: number; -} +toggleUMFeeBurn(params: { + feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off + }): Promise<{ code: number; msg: string }> ⋮---- -// used by spot and usdm -export interface OrderBookParams { - symbol: string; - limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; - symbolStatus?: string; -} +feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off ⋮---- -export type KlineInterval = - | '1s' - | '1m' - | '3m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '3d' - | '1w' - | '1M'; +getUMFeeBurnStatus(): Promise<{ feeBurn: boolean }> ⋮---- -export interface GetOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +getMarginOrder( + params: QueryPortfolioMarginOrderReq, + ): Promise ⋮---- -export interface GetOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getMarginOpenOrders(params: { + symbol: string; + }): Promise ⋮---- -export interface HistoricalTradesParams { - symbol: string; - limit?: number; - fromId?: number; -} +getAllMarginOrders( + params: QueryPortfolioMarginAllOrdersReq, + ): Promise ⋮---- -export interface KlinesParams { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} +getMarginOCO( + params: QueryPortfolioMarginOCOReq, + ): 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? -]; +getAllMarginOCO( + params: QueryPortfolioMarginAllOCOReq, + ): 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? +getMarginOpenOCO(): Promise ⋮---- -/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ -export type FuturesKline = Kline; -export interface RecentTradesParams { - symbol: string; - limit?: number; -} +getMarginTrades( + params: QueryPortfolioMarginTradesReq, + ): Promise ⋮---- -export interface CancelOrderParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +repayMarginDebt( + params: PortfolioMarginRepayDebtReq, + ): Promise ⋮---- -export interface AmendKeepPriorityParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - newQty: numberInString; -} +/** + * + * DERIVATIVES - ACCOUNT endpoints + * + **/ ⋮---- -export interface CancelOCOParams { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} +getBalance(params?: { asset?: string }): 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; -} +getAccountInfo(): Promise ⋮---- -/** For isolated margin trading only */ +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 + }> ⋮---- -/** Define a side effect, only for margin trading */ +amount: string; // account's currently max borrowable amount with sufficient system availability +borrowLimit: string; // max borrowable amount limited by the account level ⋮---- -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; -} +getMarginMaxWithdraw(params: { asset: string }): Promise<{ + amount: string; // max withdrawable amount + }> ⋮---- -export interface SymbolFromPaginatedRequestFromId { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +amount: string; // max withdrawable amount ⋮---- -export interface GetAllOrdersParams { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +getUMPosition(params?: { symbol?: string }): Promise ⋮---- -export interface RateLimiter { - rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; - interval: 'SECOND' | 'MINUTE' | 'DAY'; - intervalNum: number; - limit: number; -} +getCMPosition(params?: { + marginAsset?: string; + pair?: string; + }): Promise ⋮---- -export interface SymbolPriceFilter { - filterType: 'PRICE_FILTER'; - minPrice: numberInString; - maxPrice: numberInString; - tickSize: numberInString; -} +/** + * 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; + }> ⋮---- -export interface SymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - avgPriceMins: number; -} +updateCMLeverage(params: { symbol: string; leverage: number }): Promise<{ + leverage: number; + maxQty: string; + symbol: string; + }> ⋮---- -export interface SymbolPercentPriceBySideFilter { - filterType: 'PERCENT_PRICE_BY_SIDE'; - bidMultiplierUp: numberInString; - bidMultiplierDown: numberInString; - askMultiplierUp: numberInString; - askMultiplierDown: numberInString; - avgPriceMins: number; -} +updateUMPositionMode(params: { + dualSidePosition: 'true' | 'false'; + }): Promise<{ + code: number; + msg: string; + }> ⋮---- -export interface SymbolLegacyMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - minNotional: numberInString; - applyToMarket: boolean; - avgPriceMins: number; -} +updateCMPositionMode(params: { + dualSidePosition: 'true' | 'false'; + }): Promise<{ + code: number; + msg: string; + }> ⋮---- -export interface SymbolLotSizeFilter { - filterType: 'LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +getUMPositionMode(): Promise<{ + dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode + }> ⋮---- -export interface SymbolMinNotionalFilter { - filterType: 'NOTIONAL'; - minNotional: numberInString; - applyMinToMarket: boolean; - maxNotional: numberInString; - applyMaxToMarket: boolean; - avgPriceMins: number; -} +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -export interface SymbolIcebergPartsFilter { - filterType: 'ICEBERG_PARTS'; - limit: number; -} +getCMPositionMode(): Promise<{ + dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode + }> ⋮---- -export interface SymbolMarketLotSizeFilter { - filterType: 'MARKET_LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; -} +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -export interface SymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - maxNumOrders: number; -} +getUMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + notionalCoef: string; + brackets: PortfolioUMLeverageBracket[]; + }[] + > ⋮---- -export interface SymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +getCMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + brackets: PortfolioCMLeverageBracket[]; + }[] + > ⋮---- -export interface SymbolMaxIcebergOrdersFilter { - filterType: 'MAX_NUM_ICEBERG_ORDERS'; - maxNumIcebergOrders: number; -} +getUMTradingStatus(params?: { + symbol?: string; + }): Promise ⋮---- -export interface SymbolMaxPositionFilter { - filterType: 'MAX_POSITION'; - maxPosition: numberInString; -} +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% + }> ⋮---- -export type SymbolFilter = - | SymbolPriceFilter - | SymbolPercentPriceFilter - | SymbolPercentPriceBySideFilter - | SymbolLegacyMinNotionalFilter - | SymbolLotSizeFilter - | SymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | SymbolMaxOrdersFilter - | SymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter; +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -export interface ExchangeMaxNumOrdersFilter { - filterType: 'EXCHANGE_MAX_NUM_ORDERS'; - maxNumOrders: number; -} +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% + }> ⋮---- -export interface ExchangeMaxAlgoOrdersFilter { - filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; - maxNumAlgoOrders: number; -} +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -export type ExchangeFilter = - | ExchangeMaxNumOrdersFilter - | ExchangeMaxAlgoOrdersFilter; +getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise<{ + rows: PortfolioMarginLoanRecord[]; + total: number; + }> ⋮---- -export type OrderBookPrice = numberInString; -export type OrderBookAmount = numberInString; +getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise<{ + rows: PortfolioMarginRepayRecord[]; + total: number; + }> ⋮---- -export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; +getAutoRepayFuturesStatus(): Promise<{ + autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off + }> ⋮---- -export type OrderBookPriceFormatted = number; -export type OrderBookAmountFormatted = number; -export type OrderBookRowFormatted = [ - OrderBookPriceFormatted, - OrderBookAmountFormatted, -]; +autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off ⋮---- -export interface GenericCodeMsgError { - code: number; - msg: string; -} +updateAutoRepayFuturesStatus(params: { + autoRepay: 'true' | 'false'; + }): Promise<{ + msg: string; + }> ⋮---- -export interface RowsWithTotal { - rows: T[]; - total: number; -} +getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise<{ + rows: PortfolioMarginInterestRecord[]; + total: number; + }> ⋮---- -export interface CoinStartEndLimit { - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} - -================ -File: src/coinm-client.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; +repayFuturesNegativeBalance(): Promise<{ + msg: string; + }> ⋮---- -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, +getPortfolioNegativeBalanceInterestHistory( + params?: GetPortfolioInterestHistoryReq, + ): Promise +⋮---- +autoCollectFunds(): Promise<{ + msg: 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; + }> +⋮---- +transferBNB(params: { + amount: string; + transferSide: 'TO_UM' | 'FROM_UM'; + }): Promise<{ + tranId: number; // transaction id + }> +⋮---- +tranId: number; // transaction id +⋮---- +/** + * Query UM income history (`GET /papi/v1/um/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getUMIncomeHistory( + params?: QueryPortfolioUMIncomeReq, + ): Promise +⋮---- +/** + * Query CM income history (`GET /papi/v1/cm/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getCMIncomeHistory( + params?: QueryPortfolioCMIncomeReq, + ): Promise +⋮---- +getUMAccount(): Promise<{ + assets: PortfolioUMAccountAsset[]; + positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market + }> +⋮---- +positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market +⋮---- +getCMAccount(): Promise<{ + assets: PortfolioCMAccountAsset[]; + positions: PortfolioCMAccountPosition[]; + }> +⋮---- +getUMAccountConfig(): Promise +⋮---- +getUMSymbolConfig(params?: { + symbol?: string; + }): Promise +⋮---- +getUMAccountV2(): Promise<{ + assets: PortfolioUMAccountAssetV2[]; + positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market + }> +⋮---- +positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market +⋮---- +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; + }> +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMTradeDownloadLink(params: { + downloadId: string; + }): Promise +⋮---- +getUMOrderHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms + }): Promise<{ + avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days + downloadId: string; + }> +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMOrderDownloadLink(params: { + downloadId: string; + }): Promise +⋮---- +getUMTransactionHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms + }): Promise<{ + avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days + downloadId: string; + }> +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMTransactionDownloadLink(params: { + downloadId: string; + }): Promise +⋮---- +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewPortfolioUMOrderReq + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, + ): void +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +getPMUserDataListenKey(): Promise<{ 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, - GetAllOrdersParams, - GetOrderModifyHistoryParams, GetOrderParams, HistoricalTradesParams, Kline, KlinesParams, NewOCOParams, + numberInString, OrderBookParams, OrderIdProperty, RecentTradesParams, @@ -8334,7 +8340,6 @@ import { } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { - asArray, generateNewOrderId, getOrderIdPrefix, getServerTimeEndpoint, @@ -8342,7 +8347,7 @@ import { RestClientOptions, } from './util/requestUtils'; ⋮---- -export class CoinMClient extends BaseRestClient +export class USDMClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, @@ -8356,7 +8361,7 @@ async getServerTime(): Promise ⋮---- /** * - * Market Data Endpoints + * MARKET DATA endpoints - Rest API * **/ ⋮---- @@ -8366,6 +8371,11 @@ getExchangeInfo(): Promise ⋮---- getOrderBook(params: OrderBookParams): Promise ⋮---- +getRpiOrderBook(params: { + symbol: string; + limit?: number; + }): Promise +⋮---- getRecentTrades(params: RecentTradesParams): Promise ⋮---- getHistoricalTrades( @@ -8376,17 +8386,6 @@ getAggregateTrades( params: SymbolFromPaginatedRequestFromId, ): Promise ⋮---- -/** - * Index Price and Mark Price - */ -getMarkPrice(params?: { symbol?: string }): Promise -⋮---- -getFundingRateHistory( - params?: Partial, - ): Promise -⋮---- -getFundingRate(params?: { symbol?: string }): Promise -⋮---- getKlines(params: KlinesParams): Promise ⋮---- getContinuousContractKlines( @@ -8397,78 +8396,120 @@ getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -getPremiumIndexKlines(params: KlinesParams): Promise +getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; - pair?: string; - }): Promise +getMarkPrice(params: ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; - pair?: string; - }): Promise +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; - pair?: string; - }): Promise + }): Promise ⋮---- -getOpenInterest(params: { symbol: string }): Promise +getQuarterlyContractSettlementPrices(params: { + pair: string; + }): Promise ⋮---- -getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise +getOpenInterest(params: { symbol: string }): Promise ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesCoinMLongShortAccountRatioParams, - ): Promise +getOpenInterestStatistics( + params: FuturesDataPaginatedParams, + ): Promise ⋮---- getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams & { pair?: string }, + params: FuturesDataPaginatedParams, ): Promise ⋮---- -getGlobalLongShortAccountRatio( +getTopTradersLongShortAccountRatio( params: FuturesDataPaginatedParams, ): Promise ⋮---- -getTakerBuySellVolume( - params: FuturesCoinMTakerBuySellVolumeParams, +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, ): Promise ⋮---- -getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise +getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise +⋮---- +getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +⋮---- +getCompositeSymbolIndex(params?: { symbol?: string }): Promise +⋮---- +getMultiAssetsModeAssetIndex(params?: { symbol?: string }): Promise ⋮---- /** - * possibly @deprecated - * Only in old documentation, not in new one + * Possibly @deprecated, found only in old docs **/ +getBasis(params: BasisParams): Promise +⋮---- getIndexPriceConstituents(params: { symbol: string; }): Promise ⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getQuarterlyContractSettlementPrices(params: { - pair: string; - }): Promise +getInsuranceFundBalance(params?: { + symbol?: string; + }): Promise +⋮---- +getTradingSchedule(): Promise ⋮---- /** * - * Trade Endpoints + * 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. + * 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 + * 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[], +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 */ @@ -8476,16 +8517,11 @@ modifyOrder( params: ModifyFuturesOrderParams, ): Promise ⋮---- -/** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. - */ -modifyMultipleOrders( - orders: ModifyFuturesOrderParams[], - ): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> +modifyMultipleOrders(orders: ModifyOrderParams[]): Promise ⋮---- getOrderModifyHistory( - params: GetOrderModifyHistoryParams, - ): Promise + params: GetFuturesOrderModifyHistoryParams, + ): Promise ⋮---- cancelOrder(params: CancelOrderParams): Promise ⋮---- @@ -8494,7 +8530,7 @@ cancelMultipleOrders( ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- cancelAllOpenOrders(params: { - symbol?: string; + symbol: string; }): Promise ⋮---- // Auto-cancel all open orders @@ -8504,149 +8540,224 @@ setCancelOrdersOnTimeout( ⋮---- getOrder(params: GetOrderParams): Promise ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +getAllOrders(params?: GetFuturesAllOrdersParams): Promise ⋮---- getAllOpenOrders(params?: { symbol?: string }): Promise ⋮---- getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- -/** - * - * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) - * Conditional orders migrate to Algo Service on COIN-M - * - **/ -⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, - ): Promise -⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, - ): Promise -⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, - ): Promise -⋮---- getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- getAccountTrades( - params: CoinMAccountTradeParams & { orderId?: number }, - ): Promise + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, + ): Promise ⋮---- -getPositions(params?: { - marginAsset?: string; - pair?: string; - }): Promise +setMarginType(params: SetMarginTypeParams): Promise ⋮---- setPositionMode(params: PositionModeParams): Promise ⋮---- -setMarginType(params: SetMarginTypeParams): Promise -⋮---- +/** + * 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 ⋮---- -getADLQuantileEstimation(params?: { symbol?: string }): Promise +setMultiAssetsMode(params: { + multiAssetsMargin: MultiAssetsMode; + }): Promise ⋮---- setIsolatedPositionMargin( params: SetIsolatedMarginParams, ): Promise ⋮---- +/** + * @deprecated + * Use getPositionsV3() instead + **/ +getPositions(params?: Partial): Promise +⋮---- +getPositionsV3(params?: { symbol?: string }): Promise +⋮---- +getADLQuantileEstimation(params?: { symbol?: string }): Promise +⋮---- +getSymbolAdlRisk(params: +⋮---- +getSymbolAdlRisk(): Promise; +⋮---- +getSymbolAdlRisk(params?: { + symbol?: string; + }): Promise +⋮---- getPositionMarginChangeHistory( params: GetPositionMarginChangeHistoryParams, ): Promise +⋮---- /** * - * Account Endpoints + * ACCOUNT endpoints - Rest API * **/ ⋮---- -getBalance(): Promise +getBalanceV3(): Promise +⋮---- +/** + * @deprecated + * Use getBalanceV3() instead + **/ +getBalance(): Promise +⋮---- +getAccountInformationV3(): Promise +⋮---- +/** + * @deprecated + * Use getAccountInformationV3() instead + **/ +getAccountInformation(): Promise ⋮---- getAccountCommissionRate(params: { - symbol?: string; + symbol: string; }): Promise ⋮---- -getAccountInformation(): Promise +getFuturesAccountConfig(): Promise +⋮---- +getFuturesSymbolConfig(params: { symbol?: string }): Promise +⋮---- +getUserForceOrders(): Promise ⋮---- /** - * Notional Bracket for Symbol (NOT "pair") + * 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 + }): Promise ⋮---- -// TO ADD: dapi/v1/leverageBracket -// can use dapi/v2/leverageBracket +getMultiAssetsMode(): Promise ⋮---- getCurrentPositionMode(): Promise ⋮---- /** - * Query income history (`GET /dapi/v1/income`). + * Query income history (`GET /fapi/v1/income`). * Paginate with `startTime` and `endTime`. `page` is not accepted. */ getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- +getApiQuantitativeRulesIndicators(params?: { + symbol?: string; + }): Promise +⋮---- /** - * Get a download id for futures transaction history (`GET /dapi/v1/income/asyn`). + * 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. */ -getDownloadIdForFuturesTransactionHistory(params: { +getFuturesTransactionHistoryDownloadId(params: { startTime: number; endTime: number; - }): Promise<{ - avgCostTimestampOfLast30d: number; - downloadId: string; - }> + }): Promise ⋮---- getFuturesTransactionHistoryDownloadLink(params: { downloadId: string; - }): Promise + }): Promise ⋮---- -getDownloadIdForFuturesOrderHistory(params: { +getFuturesOrderHistoryDownloadId(params: { startTime: number; endTime: number; - }): Promise<{ - avgCostTimestampOfLast30d: number; - downloadId: string; - }> + }): Promise ⋮---- getFuturesOrderHistoryDownloadLink(params: { downloadId: string; - }): Promise + }): Promise ⋮---- -getDownloadIdForFuturesTradeHistory(params: { +getFuturesTradeHistoryDownloadId(params: { startTime: number; endTime: number; - }): Promise<{ - avgCostTimestampOfLast30d: number; + }): Promise +⋮---- +getFuturesTradeDownloadLink(params: { downloadId: string; + }): Promise +⋮---- +setBNBBurnEnabled(params: { + feeBurn: 'true' | 'false'; + }): Promise<{ code: number; msg: string }> +⋮---- +getBNBBurnStatus(): Promise<{ + feeBurn: boolean; }> ⋮---- -getFuturesTradeHistoryDownloadLink(params: { - downloadId: string; - }): Promise +signTradFiPerpsAgreement(): Promise<{ code: number; msg: string }> +⋮---- +testOrder(params: NewFuturesOrderParams): Promise ⋮---- /** * - * Portfolio Margin Endpoints - * + * Algo Order Endpoints (Effective 2025-12-02) + * Conditional orders migrate to Algo Service + * **/ ⋮---- -getClassicPortfolioMarginAccount(params: { - asset: string; - }): Promise +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, + ): Promise +⋮---- +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, + ): Promise +⋮---- +cancelAllAlgoOpenOrders(params: { + symbol: string; + }): Promise +⋮---- +getAlgoOrder( + params: FuturesQueryAlgoOrderParams, + ): Promise +⋮---- +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, + ): Promise +⋮---- +getAllAlgoOrders( + params: FuturesQueryAllAlgoOrdersParams, + ): Promise ⋮---- /** - * @deprecated at 6th August, 2024 + * + * Convert Endpoints + * **/ -getClassicPortfolioMarginNotionalLimits( - params?: GetClassicPortfolioMarginNotionalLimitParams, - ): Promise<{ - notionalLimits: ClassicPortfolioMarginNotionalLimit[]; +⋮---- +getAllConvertPairs(params?: { + fromAsset?: string; + toAsset?: string; + }): Promise +⋮---- +submitConvertQuoteRequest( + params: FuturesConvertQuoteRequest, + ): Promise +⋮---- +acceptConvertQuote(params: { quoteId: string }): Promise<{ + orderId: string; + createTime: number; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; }> ⋮---- +getConvertOrderStatus(params: { + orderId?: string; + quoteId?: string; + }): Promise +⋮---- +/** + * + * Portfolio Margin Pro Endpoints + * + **/ +⋮---- +getPortfolioMarginProAccountInfo(params: { + asset: string; + }): Promise +⋮---- /** * * Broker Futures Endpoints @@ -8727,6 +8838,8 @@ getBrokerTradeDetail( * **/ ⋮---- +// USD-M Futures +⋮---- getFuturesUserDataListenKey(): Promise<{ listenKey: string }> ⋮---- keepAliveFuturesUserDataListenKey(): Promise @@ -8747,1392 +8860,1314 @@ private validateOrderId( ): void ================ -File: src/portfolio-client.ts +File: src/types/shared.ts ================ -import { AxiosRequestConfig } from 'axios'; -⋮---- -import { - CancelPortfolioCMConditionalOrderReq, - CancelPortfolioCMOrderReq, - CancelPortfolioMarginOCOReq, - CancelPortfolioMarginOrderReq, - CancelPortfolioUMAlgoOrderReq, - CancelPortfolioUMConditionalOrderReq, - CancelPortfolioUMOrderReq, - DownloadLinkResponse, - GetMarginInterestHistoryReq, - GetMarginLoanRecordsReq, - GetMarginRepayRecordsReq, - GetPortfolioInterestHistoryReq, - ModifyPortfolioCMOrderReq, - ModifyPortfolioUMOrderReq, - NewPortfolioCMConditionalOrderReq, - NewPortfolioCMConditionalOrderResponse, - NewPortfolioCMOrderReq, - NewPortfolioCMOrderResponse, - NewPortfolioConditionalOrderResponse, - NewPortfolioMarginOCOReq, - NewPortfolioMarginOCOResponse, - NewPortfolioMarginOrderReq, - NewPortfolioMarginOrderResponse, - NewPortfolioUMAlgoOrderReq, - NewPortfolioUMConditionalOrderReq, - NewPortfolioUMOrderReq, - NewPortfolioUMOrderResponse, - PortfolioAccountInformation, - PortfolioADLQuantile, - PortfolioBalance, - PortfolioCMAccountAsset, - PortfolioCMAccountPosition, - PortfolioCMCancelConditionalOrderResponse, - PortfolioCMCancelOrderResponse, - PortfolioCMConditionalHistoryOrder, - PortfolioCMConditionalOrder, - PortfolioCMForceOrder, - PortfolioCMIncome, - PortfolioCMLeverageBracket, - PortfolioCMModifyOrderResponse, - PortfolioCMOrder, - PortfolioCMOrderModificationHistory, - PortfolioCMPosition, - PortfolioCMTrade, - PortfolioMarginCancelAllOrdersResponse, - PortfolioMarginCancelOrderResponse, - PortfolioMarginForceOrder, - PortfolioMarginInterestRecord, - PortfolioMarginLoanRecord, - PortfolioMarginOCO, - PortfolioMarginOCOCancelResponse, - PortfolioMarginOrder, - PortfolioMarginRepayDebtReq, - PortfolioMarginRepayDebtResponse, - PortfolioMarginRepayRecord, - PortfolioMarginTrade, - PortfolioNegativeBalanceInterestRecord, - PortfolioTradFiPerpsContractSignResponse, - PortfolioTradingStatus, - PortfolioUMAccountAsset, - PortfolioUMAccountAssetV2, - PortfolioUMAccountConfig, - PortfolioUMAccountPosition, - PortfolioUMAccountPositionV2, - PortfolioUMAlgoOrder, - PortfolioUMCancelAlgoOrderResponse, - PortfolioUMCancelAllUMAlgoOpenOrdersResponse, - PortfolioUMCancelConditionalOrderResponse, - PortfolioUMCancelOrderResponse, - PortfolioUMConditionalOrder, - PortfolioUMForceOrder, - PortfolioUMIncome, - PortfolioUMLeverageBracket, - PortfolioUMModifyOrderResponse, - PortfolioUMOrder, - PortfolioUMOrderModificationHistory, - PortfolioUMPosition, - PortfolioUMSymbolConfig, - PortfolioUMTrade, - QueryPortfolioAllCMConditionalOrdersReq, - QueryPortfolioAllCMOrdersReq, - QueryPortfolioAllUMAlgoOrdersReq, - QueryPortfolioAllUMConditionalOrdersReq, - QueryPortfolioAllUMOrdersReq, - QueryPortfolioCMConditionalOrderHistoryReq, - QueryPortfolioCMForceOrdersReq, - QueryPortfolioCMIncomeReq, - QueryPortfolioCMOpenOrderReq, - QueryPortfolioCMOrderAmendmentReq, - QueryPortfolioCMOrderReq, - QueryPortfolioCMTradesReq, - QueryPortfolioMarginAllOCOReq, - QueryPortfolioMarginAllOrdersReq, - QueryPortfolioMarginForceOrdersReq, - QueryPortfolioMarginOCOReq, - QueryPortfolioMarginOrderReq, - QueryPortfolioMarginTradesReq, - QueryPortfolioUMAlgoOrderReq, - QueryPortfolioUMConditionalOrderHistoryReq, - QueryPortfolioUMForceOrdersReq, - QueryPortfolioUMIncomeReq, - QueryPortfolioUMOpenConditionalOrderReq, - QueryPortfolioUMOpenOrderReq, - QueryPortfolioUMOrderAmendmentReq, - QueryPortfolioUMOrderReq, - QueryPortfolioUMTradesReq, -} from './types/portfolio-margin'; -import { - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - NewOCOParams, - OrderIdProperty, -} from './types/shared'; -import BaseRestClient from './util/BaseRestClient'; -import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, -} from './util/requestUtils'; -⋮---- -/** - * REST client for Portfolio Margin APIs (papi) - * - * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info - */ -export class PortfolioClient extends BaseRestClient +// 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; ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, - ) +export type ExchangeSymbol = string; ⋮---- -getClientId(): BinanceBaseUrlKey +export type BooleanString = 'true' | 'false'; ⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise +export type BinanceBaseUrlKey = + | 'spot' + | 'spot1' + | 'spot2' + | 'spot3' + | 'spot4' + | 'spottest' + | 'usdmtest' + | 'usdm' + | 'coinm' + | 'coinmtest' + | 'voptions' + | 'voptionstest' + | 'papi' + | 'www'; ⋮---- /** - * - * Misc Endpoints - * - **/ + * 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'; ⋮---- -testConnectivity(): Promise +export type StringBoolean = 'TRUE' | 'FALSE'; ⋮---- -signTradFiPerpsContract(): Promise +export type SideEffects = + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'NO_SIDE_EFFECT' + | 'AUTO_BORROW_REPAY' + | 'NO_SIDE_EFFECT'; ⋮---- /** - * - * DERIVATIVES -TRADE endpoints - * - **/ -⋮---- -submitNewUMOrder( - params: NewPortfolioUMOrderReq, - ): Promise -⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). - */ -submitNewUMConditionalOrder( - params: NewPortfolioUMConditionalOrderReq, - ): Promise -⋮---- -submitNewUMAlgoOrder( - params: NewPortfolioUMAlgoOrderReq, - ): Promise + * 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'; ⋮---- -submitNewCMOrder( - params: NewPortfolioCMOrderReq, - ): Promise +export type OrderIdProperty = + | 'newClientOrderId' + | 'newClientStrategyId' + | 'listClientOrderId' + | 'limitClientOrderId' + | 'stopClientOrderId' + | 'clientAlgoId' + | 'aboveClientOrderId' + | 'belowClientOrderId' + | 'workingClientOrderId' + | 'pendingAboveClientOrderId' + | 'pendingBelowClientOrderId' + | 'pendingClientOrderId'; ⋮---- -submitNewCMConditionalOrder( - params: NewPortfolioCMConditionalOrderReq, - ): Promise +export type OrderSide = 'BUY' | 'SELL'; ⋮---- -submitNewMarginOrder( - params: NewPortfolioMarginOrderReq, - ): Promise +export type OrderStatus = + | 'NEW' + | 'PENDING_NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'EXPIRED_IN_MATCH'; ⋮---- -submitMarginLoan(params: { asset: string; amount: string }): Promise<{ - tranId: number; - }> +export type OrderExecutionType = + | 'NEW' + | 'CANCELED' + | 'REJECTED' + | 'TRADE' + | 'EXPIRED'; ⋮---- -submitMarginRepay(params: { asset: string; amount: string }): Promise<{ - tranId: number; - }> +export type OrderListContingencyType = + | 'OCO' + | 'OTO' + | 'OTOCO' + | 'OPO' + | 'OPOCO'; ⋮---- -submitNewMarginOCO( - params: NewPortfolioMarginOCOReq, - ): Promise +// listStatusType +export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; ⋮---- -cancelUMOrder( - params: CancelPortfolioUMOrderReq, - ): Promise +// listOrderStatus +export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; ⋮---- -cancelAllUMOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> +export type OrderType = + | 'LIMIT' + | 'LIMIT_MAKER' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). - */ -cancelUMConditionalOrder( - params: CancelPortfolioUMConditionalOrderReq, - ): Promise +export type OrderListOrderType = + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -cancelUMAlgoOrder( - params: CancelPortfolioUMAlgoOrderReq, - ): Promise +export type SelfTradePreventionMode = + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE' + | 'DECREMENT' + | 'TRANSFER'; ⋮---- -/** - * @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; - }> +/** 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'; ⋮---- -cancelAllUMAlgoOpenOrders(params: { - symbol: string; - }): Promise +export interface BasicAssetParam { + asset: string; +} ⋮---- -cancelCMOrder( - params: CancelPortfolioCMOrderReq, - ): Promise +export interface BasicSymbolParam { + symbol: string; + isIsolated?: StringBoolean; +} ⋮---- -cancelAllCMOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> +export interface SymbolArrayParam { + symbols: string[]; +} ⋮---- -cancelCMConditionalOrder( - params: CancelPortfolioCMConditionalOrderReq, - ): Promise +export interface BasicAssetPaginatedParams { + asset?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +export interface BasicSymbolPaginatedParams { + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -cancelAllCMConditionalOrders(params: { symbol: string }): Promise<{ - code: number; - msg: string; - }> +export interface SymbolPrice { + symbol: string; + price: numberInString; + time?: number; +} ⋮---- -cancelMarginOrder( - params: CancelPortfolioMarginOrderReq, - ): Promise +// used by spot and usdm +export interface OrderBookParams { + symbol: string; + limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; + symbolStatus?: string; +} ⋮---- -cancelMarginOCO( - params: CancelPortfolioMarginOCOReq, - ): Promise +export type KlineInterval = + | '1s' + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '3d' + | '1w' + | '1M'; ⋮---- -cancelAllMarginOrders(params: { - symbol: string; - }): Promise +export interface GetOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -modifyUMOrder( - params: ModifyPortfolioUMOrderReq, - ): Promise +export interface GetOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -modifyCMOrder( - params: ModifyPortfolioCMOrderReq, - ): Promise +export interface HistoricalTradesParams { + symbol: string; + limit?: number; + fromId?: number; +} ⋮---- -getUMOrder(params: QueryPortfolioUMOrderReq): Promise +export interface KlinesParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} ⋮---- -getAllUMOrders( - params: QueryPortfolioAllUMOrdersReq, - ): 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? +]; ⋮---- -getUMOpenOrder( - params: QueryPortfolioUMOpenOrderReq, - ): 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? ⋮---- -getAllUMOpenOrders(params: { symbol?: string }): Promise +/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ +export type FuturesKline = Kline; +export interface RecentTradesParams { + symbol: string; + limit?: number; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). - */ -getAllUMConditionalOrders( - params: QueryPortfolioAllUMConditionalOrdersReq, - ): Promise +export interface CancelOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -getAllUMAlgoOrders( - params: QueryPortfolioAllUMAlgoOrdersReq, - ): Promise +export interface AmendKeepPriorityParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + newQty: numberInString; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). - */ -getUMOpenConditionalOrders(params: { - symbol?: string; - }): Promise +export interface CancelOCOParams { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -getUMAlgoOpenOrders(params?: { - symbol?: string; - }): 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; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). - */ -getUMOpenConditionalOrder( - params: QueryPortfolioUMOpenConditionalOrderReq, - ): Promise +/** For isolated margin trading only */ ⋮---- -getUMAlgoOrder( - params: QueryPortfolioUMAlgoOrderReq, - ): Promise +/** Define a side effect, only for margin trading */ ⋮---- -/** - * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. - */ -getUMConditionalOrderHistory( - params: QueryPortfolioUMConditionalOrderHistoryReq, - ): 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; +} ⋮---- -getCMOrder(params: QueryPortfolioCMOrderReq): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -getAllCMOrders( - params: QueryPortfolioAllCMOrdersReq, - ): Promise +/** BUY only; Binance has not decided when this feature will be enabled. */ ⋮---- -getCMOpenOrder( - params: QueryPortfolioCMOpenOrderReq, - ): Promise +export interface SymbolFromPaginatedRequestFromId { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getAllCMOpenOrders(params: { - symbol?: string; - pair?: string; - }): Promise +export interface GetAllOrdersParams { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getCMOpenConditionalOrders(params: { - symbol?: string; - }): Promise +export interface RateLimiter { + rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; + interval: 'SECOND' | 'MINUTE' | 'DAY'; + intervalNum: number; + limit: number; +} ⋮---- -getCMOpenConditionalOrder(params: { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; - }): Promise +export interface SymbolPriceFilter { + filterType: 'PRICE_FILTER'; + minPrice: numberInString; + maxPrice: numberInString; + tickSize: numberInString; +} ⋮---- -getAllCMConditionalOrders( - params: QueryPortfolioAllCMConditionalOrdersReq, - ): Promise +export interface SymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -getCMConditionalOrderHistory( - params: QueryPortfolioCMConditionalOrderHistoryReq, - ): Promise +export interface SymbolPercentPriceBySideFilter { + filterType: 'PERCENT_PRICE_BY_SIDE'; + bidMultiplierUp: numberInString; + bidMultiplierDown: numberInString; + askMultiplierUp: numberInString; + askMultiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -getUMForceOrders( - params: QueryPortfolioUMForceOrdersReq, - ): Promise +export interface SymbolLegacyMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + minNotional: numberInString; + applyToMarket: boolean; + avgPriceMins: number; +} ⋮---- -getCMForceOrders( - params: QueryPortfolioCMForceOrdersReq, - ): Promise +export interface SymbolLotSizeFilter { + filterType: 'LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -getUMOrderModificationHistory( - params: QueryPortfolioUMOrderAmendmentReq, - ): Promise +export interface SymbolMinNotionalFilter { + filterType: 'NOTIONAL'; + minNotional: numberInString; + applyMinToMarket: boolean; + maxNotional: numberInString; + applyMaxToMarket: boolean; + avgPriceMins: number; +} ⋮---- -getCMOrderModificationHistory( - params: QueryPortfolioCMOrderAmendmentReq, - ): Promise +export interface SymbolIcebergPartsFilter { + filterType: 'ICEBERG_PARTS'; + limit: number; +} ⋮---- -getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise<{ - rows: PortfolioMarginForceOrder[]; - total: number; - }> +export interface SymbolMarketLotSizeFilter { + filterType: 'MARKET_LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -getUMTrades(params: QueryPortfolioUMTradesReq): Promise +export interface SymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -getCMTrades(params: QueryPortfolioCMTradesReq): Promise +export interface SymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -getUMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > +export interface SymbolMaxIcebergOrdersFilter { + filterType: 'MAX_NUM_ICEBERG_ORDERS'; + maxNumIcebergOrders: number; +} ⋮---- -getCMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > +export interface SymbolMaxPositionFilter { + filterType: 'MAX_POSITION'; + maxPosition: numberInString; +} ⋮---- -toggleUMFeeBurn(params: { - feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off - }): Promise<{ code: number; msg: string }> +export type SymbolFilter = + | SymbolPriceFilter + | SymbolPercentPriceFilter + | SymbolPercentPriceBySideFilter + | SymbolLegacyMinNotionalFilter + | SymbolLotSizeFilter + | SymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | SymbolMaxOrdersFilter + | SymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter; ⋮---- -feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +export interface ExchangeMaxNumOrdersFilter { + filterType: 'EXCHANGE_MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -getUMFeeBurnStatus(): Promise<{ feeBurn: boolean }> +export interface ExchangeMaxAlgoOrdersFilter { + filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -getMarginOrder( - params: QueryPortfolioMarginOrderReq, - ): Promise +export type ExchangeFilter = + | ExchangeMaxNumOrdersFilter + | ExchangeMaxAlgoOrdersFilter; ⋮---- -getMarginOpenOrders(params: { - symbol: string; - }): Promise +export type OrderBookPrice = numberInString; +export type OrderBookAmount = numberInString; ⋮---- -getAllMarginOrders( - params: QueryPortfolioMarginAllOrdersReq, - ): Promise +export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; ⋮---- -getMarginOCO( - params: QueryPortfolioMarginOCOReq, - ): Promise +export type OrderBookPriceFormatted = number; +export type OrderBookAmountFormatted = number; +export type OrderBookRowFormatted = [ + OrderBookPriceFormatted, + OrderBookAmountFormatted, +]; ⋮---- -getAllMarginOCO( - params: QueryPortfolioMarginAllOCOReq, - ): Promise +export interface GenericCodeMsgError { + code: number; + msg: string; +} ⋮---- -getMarginOpenOCO(): Promise +export interface RowsWithTotal { + rows: T[]; + total: number; +} ⋮---- -getMarginTrades( - params: QueryPortfolioMarginTradesReq, - ): Promise +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'; ⋮---- -repayMarginDebt( - params: PortfolioMarginRepayDebtReq, - ): Promise +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'; ⋮---- -/** - * - * DERIVATIVES - ACCOUNT endpoints - * - **/ +alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams ⋮---- -getBalance(params?: { asset?: string }): Promise +type WsEventInternalSrc = 'event' | 'function'; ⋮---- -getAccountInfo(): Promise +type WebSocketWithMetadata = WebSocket & { + onping?: (event: unknown) => void; + onpong?: (event: unknown) => void; + wsKey?: WsKey | 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 - }> +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; +} ⋮---- -amount: string; // account's currently max borrowable amount with sufficient system availability -borrowLimit: string; // max borrowable amount limited by the account level +on(event: 'reply', listener: (event: WsResponse) ⋮---- -getMarginMaxWithdraw(params: { asset: string }): Promise<{ - amount: string; // max withdrawable amount - }> +on(event: 'message', listener: (event: WsRawMessage) ⋮---- -amount: string; // max withdrawable amount +on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; ⋮---- -getUMPosition(params?: { symbol?: string }): Promise +on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; ⋮---- -getCMPosition(params?: { - marginAsset?: string; - pair?: string; - }): Promise +on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; ⋮---- -/** - * 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; - }> +on( + event: 'open' | 'reconnected', + listener: (event: { + wsKey: WsKey; + ws: WebSocket.Event; + event?: any; + }) => void, + ): this; ⋮---- -updateCMLeverage(params: { symbol: string; leverage: number }): Promise<{ - leverage: number; - maxQty: string; - symbol: string; - }> +on( + event: 'reconnecting' | 'close', + listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, + ): this; ⋮---- -updateUMPositionMode(params: { - dualSidePosition: 'true' | 'false'; - }): Promise<{ - code: number; - msg: string; - }> +/** + * @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 ⋮---- -updateCMPositionMode(params: { - dualSidePosition: 'true' | 'false'; - }): Promise<{ - code: number; - msg: string; - }> +constructor( + options: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, + ) ⋮---- -getUMPositionMode(): Promise<{ - dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode - }> +// Some defaults: ⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode -⋮---- -getCMPositionMode(): Promise<{ - dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode - }> +// Automatically send an authentication op/request after a connection opens, for private connections. ⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode +// Individual requests require a signature ⋮---- -getUMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - notionalCoef: string; - brackets: PortfolioUMLeverageBracket[]; - }[] - > +// add default error handling so this doesn't crash node (if the user didn't set a handler) ⋮---- -getCMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - brackets: PortfolioCMLeverageBracket[]; - }[] - > +private getRestClientOptions(): RestClientOptions ⋮---- -getUMTradingStatus(params?: { - symbol?: string; - }): Promise +public connectToWsUrl( + url: string, + wsKey?: WsKey | string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -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% - }> +// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node ⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% +// Add ws connection with key to store ⋮---- -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% - }> +public tryWsSend(wsKey: WsKey | string, wsMessage: string) ⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% +public tryWsPing(wsKey: WsKey | string) ⋮---- -getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise<{ - rows: PortfolioMarginLoanRecord[]; - total: number; - }> +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise<{ - rows: PortfolioMarginRepayRecord[]; - total: number; - }> +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -getAutoRepayFuturesStatus(): Promise<{ - autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off - }> +private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) ⋮---- -autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off +private onWsClose( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + wsUrl: string, + ) ⋮---- -updateAutoRepayFuturesStatus(params: { - autoRepay: 'true' | 'false'; - }): Promise<{ - msg: string; - }> +// Clear any timers before we initiate revival ⋮---- -getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise<{ - rows: PortfolioMarginInterestRecord[]; - total: number; - }> +// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states ⋮---- -repayFuturesNegativeBalance(): Promise<{ - msg: string; - }> +private onWsMessage( + event: WebSocket.MessageEvent, + wsKey: WsKey | string, + source: WsEventInternalSrc, + ) ⋮---- -getPortfolioNegativeBalanceInterestHistory( - params?: GetPortfolioInterestHistoryReq, - ): Promise +// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e ⋮---- -autoCollectFunds(): Promise<{ - msg: string; - }> +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn ⋮---- -/** - * 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; - }> +// emit a separate event for user data messages ⋮---- -transferBNB(params: { - amount: string; - transferSide: 'TO_UM' | 'FROM_UM'; - }): Promise<{ - tranId: number; // transaction id - }> +private sendPing(wsKey: WsKey | string, wsUrl: string) ⋮---- -tranId: number; // transaction id +private onWsPing( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + source: WsEventInternalSrc, + ) ⋮---- -/** - * Query UM income history (`GET /papi/v1/um/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -getUMIncomeHistory( - params?: QueryPortfolioUMIncomeReq, - ): Promise +private onWsPong( + event: any, + wsKey: WsKey | string, + source: WsEventInternalSrc, + ) ⋮---- /** - * Query CM income history (`GET /papi/v1/cm/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. + * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. + * If closed, trigger a reconnect immediately */ -getCMIncomeHistory( - params?: QueryPortfolioCMIncomeReq, - ): Promise -⋮---- -getUMAccount(): Promise<{ - assets: PortfolioUMAccountAsset[]; - positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market - }> -⋮---- -positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market -⋮---- -getCMAccount(): Promise<{ - assets: PortfolioCMAccountAsset[]; - positions: PortfolioCMAccountPosition[]; - }> -⋮---- -getUMAccountConfig(): Promise +private executeReconnectableClose( + wsKey: WsKey | string, + reason: string, + wsUrl: string, + ) ⋮---- -getUMSymbolConfig(params?: { - symbol?: string; - }): Promise +public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) ⋮---- -getUMAccountV2(): Promise<{ - assets: PortfolioUMAccountAssetV2[]; - positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market - }> +public closeAll(shouldReconnectAfterClose?: boolean) ⋮---- -positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market +public closeWs(ws: WebSocket, 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; - }> +private parseWsError( + context: string, + error: any, + wsKey: WsKey | string, + wsUrl: string, + ) ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +private reconnectWithDelay( + wsKey: WsKey | string, + connectionDelayMs: number, + wsUrl: string, + ) ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +// We'll set a new one once the new stream respawns, with a diff listenKey in the key ⋮---- -getUMTradeDownloadLink(params: { - downloadId: string; - }): Promise +private clearTimers(wsKey: WsKey | 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; - }> +// Send a ping at intervals +private clearPingTimer(wsKey: WsKey | string) ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +// Expect a pong within a time limit +private clearPongTimer(wsKey: WsKey | string) ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +// Timer tracking that a reconnect is about to happen / in progress +private clearReconnectTimer(wsKey: WsKey | string) ⋮---- -getUMOrderDownloadLink(params: { - downloadId: string; - }): Promise +// eslint-disable-next-line @typescript-eslint/no-unused-vars +private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): 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; - }> +public getWs(wsKey: WsKey | string): WebSocket | undefined ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +/** + * Send WS message to subscribe to topics. Use subscribe() to call this. + */ +private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) ⋮---- -getUMTransactionDownloadLink(params: { - downloadId: string; - }): Promise +/** + * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. + */ +private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) ⋮---- /** - * Validate syntax meets requirements set by binance. Log warning if not. + * Send WS message to unsubscribe from topics. */ -private validateOrderId( - params: - | NewPortfolioUMOrderReq - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, - ): void +public requestListSubscriptions(wsKey: WsKey, requestId: number) ⋮---- /** - * - * 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'; -⋮---- -export class USDMClient extends BaseRestClient -⋮---- -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 -⋮---- -getSymbolPriceTicker(params: -⋮---- -getSymbolPriceTicker(): Promise; -⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; - }): Promise -⋮---- -getSymbolPriceTickerV2(params: -⋮---- -getSymbolPriceTickerV2(): Promise; -⋮---- -getSymbolPriceTickerV2(params?: { - symbol?: string; - }): Promise +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeBlockTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolOrderBookTicker(params: { - symbol: string; - }): Promise; +/** + * 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 ⋮---- -getSymbolOrderBookTicker(): Promise; +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -getSymbolOrderBookTicker(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 ⋮---- -getQuarterlyContractSettlementPrices(params: { - pair: string; - }): Promise +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getOpenInterest(params: { symbol: string }): 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 ⋮---- -getOpenInterestStatistics( - params: FuturesDataPaginatedParams, - ): 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 ⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams, - ): Promise +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesDataPaginatedParams, - ): Promise +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeMarkPriceKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, - ): Promise +/** + * Subscribe to mini 24hr ticker for a symbol in market category. + */ +public subscribeSymbolMini24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise +/** + * Subscribe to mini 24hr mini ticker in market category. + */ +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +/** + * Subscribe to 24hr ticker for a symbol in any market. + */ +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getCompositeSymbolIndex(params?: { symbol?: string }): Promise +/** + * Subscribe to 24hr ticker in any market. + */ +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getMultiAssetsModeAssetIndex(params?: { symbol?: string }): Promise +/** + * 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 ⋮---- /** - * Possibly @deprecated, found only in old docs - **/ -getBasis(params: BasisParams): Promise + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getIndexPriceConstituents(params: { - symbol: string; - }): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllBookTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getInsuranceFundBalance(params?: { - symbol?: string; - }): Promise +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getTradingSchedule(): Promise +/** + * 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). * - * TRADE endpoints - Rest API + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs * - **/ -⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise + * 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 ⋮---- /** - * 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. + * Subscribe to orderbook depth updates to locally manage an order book. * - * 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. + * 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 */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], - ): Promise<(NewOrderResult | NewOrderError)[]> -⋮---- -// Known issue: `quantity` and `price` should be sent as strings, see #523, #526 +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- /** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + * Subscribe to best bid/ask for all symbols in spot markets. */ -modifyOrder( - params: ModifyFuturesOrderParams, - ): Promise -⋮---- -modifyMultipleOrders(orders: ModifyOrderParams[]): Promise -⋮---- -getOrderModifyHistory( - params: GetFuturesOrderModifyHistoryParams, - ): Promise +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, + ): WebSocket ⋮---- -cancelOrder(params: CancelOrderParams): Promise +/** + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, - ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> -⋮---- -cancelAllOpenOrders(params: { - symbol: string; - }): Promise -⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, - ): Promise -⋮---- -getOrder(params: GetOrderParams): Promise -⋮---- -getAllOrders(params?: GetFuturesAllOrdersParams): Promise -⋮---- -getAllOpenOrders(params?: { symbol?: string }): Promise -⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +/** + * Subscribe to aggregate trades for a symbol in spot markets. + */ +public subscribeSpotAggregateTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +/** + * Subscribe to trades for a symbol in spot markets. + */ +public subscribeSpotTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getAccountTrades( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, - ): Promise +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeSpotBlockTrades( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +/** + * Subscribe to candles for a symbol in spot markets. + */ +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -setPositionMode(params: PositionModeParams): Promise +/** + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- /** - * 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). + * Subscribe to mini 24hr mini ticker in spot markets. */ -setLeverage(params: SetLeverageParams): Promise +public subscribeSpotAllMini24hrTickers( + forceNewConnection?: boolean, + ): WebSocket ⋮---- -setMultiAssetsMode(params: { - multiAssetsMargin: MultiAssetsMode; - }): Promise +/** + * Subscribe to 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbol24hrTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, - ): Promise +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** - * @deprecated - * Use getPositionsV3() instead - **/ -getPositions(params?: Partial): Promise + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getPositionsV3(params?: { symbol?: string }): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket ⋮---- -getADLQuantileEstimation(params?: { symbol?: string }): Promise +/** + * 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 ⋮---- -getSymbolAdlRisk(params: +/** + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, + ): WebSocket ⋮---- -getSymbolAdlRisk(): Promise; +/** + * 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 ⋮---- -getSymbolAdlRisk(params?: { - symbol?: string; - }): Promise +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, - ): 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 ⋮---- /** - * - * ACCOUNT endpoints - Rest API - * - **/ + * Subscribe to margin user data stream - listen key is automatically generated. + */ +public async subscribeMarginUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -getBalanceV3(): Promise +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * @deprecated - * Use getBalanceV3() instead - **/ -getBalance(): Promise + * Subscribe to isolated margin user data stream - listen key is automatically generated. + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -getAccountInformationV3(): Promise +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * @deprecated - * Use getAccountInformationV3() instead + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- **/ -getAccountInformation(): Promise -⋮---- -getAccountCommissionRate(params: { - symbol: string; - }): Promise ⋮---- -getFuturesAccountConfig(): Promise +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. + */ +public async subscribeUsdFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -getFuturesSymbolConfig(params: { symbol?: string }): Promise +// Necessary so client knows this is a reconnect ⋮---- -getUserForceOrders(): Promise +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; - }): Promise +public async subscribeCoinFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, + ): Promise ⋮---- -getMultiAssetsMode(): Promise +// Necessary so client knows this is a reconnect ⋮---- -getCurrentPositionMode(): Promise +// Start & store timer to keep alive listen key (and handle expiration) + +================ +File: src/types/websockets/ws-api-responses.ts +================ +import type { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures.js'; +import { + numberInString, + OrderSide, + OrderTimeInForce, + SelfTradePreventionMode, + SpotExpiryReason, +} from '../shared'; +import { + OrderResponse, + SpotNewOrderConditionalFields, + SpotOrderPreventedMatch, +} from '../spot'; ⋮---- /** - * Query income history (`GET /fapi/v1/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -getIncomeHistory(params?: GetIncomeHistoryParams): Promise + * Error response type + */ +export interface ErrorResponse { + code: number; + msg: string; +} ⋮---- -getApiQuantitativeRulesIndicators(params?: { - symbol?: string; - }): Promise -⋮---- -/** - * 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 -⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; - }): Promise -⋮---- -getFuturesOrderHistoryDownloadId(params: { - startTime: number; - endTime: number; - }): Promise -⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; - }): Promise -⋮---- -getFuturesTradeHistoryDownloadId(params: { - startTime: number; - endTime: number; - }): Promise -⋮---- -getFuturesTradeDownloadLink(params: { - downloadId: string; - }): Promise -⋮---- -setBNBBurnEnabled(params: { - feeBurn: 'true' | 'false'; - }): Promise<{ code: number; msg: string }> -⋮---- -getBNBBurnStatus(): Promise<{ - feeBurn: boolean; - }> -⋮---- -signTradFiPerpsAgreement(): Promise<{ code: number; msg: string }> -⋮---- -testOrder(params: NewFuturesOrderParams): Promise -⋮---- -/** - * - * Algo Order Endpoints (Effective 2025-12-02) - * Conditional orders migrate to Algo Service - * - **/ -⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, - ): Promise -⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, - ): Promise -⋮---- -cancelAllAlgoOpenOrders(params: { - symbol: string; - }): Promise -⋮---- -getAlgoOrder( - params: FuturesQueryAlgoOrderParams, - ): Promise -⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, - ): Promise -⋮---- -getAllAlgoOrders( - params: FuturesQueryAllAlgoOrdersParams, - ): Promise -⋮---- -/** - * - * Convert Endpoints - * - **/ -⋮---- -getAllConvertPairs(params?: { - fromAsset?: string; - toAsset?: string; - }): Promise -⋮---- -submitConvertQuoteRequest( - params: FuturesConvertQuoteRequest, - ): Promise -⋮---- -acceptConvertQuote(params: { quoteId: string }): Promise<{ - orderId: string; - createTime: number; - orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; - }> -⋮---- -getConvertOrderStatus(params: { - orderId?: string; - quoteId?: string; - }): Promise -⋮---- -/** - * - * Portfolio Margin Pro Endpoints - * - **/ -⋮---- -getPortfolioMarginProAccountInfo(params: { - asset: string; - }): Promise -⋮---- -/** - * - * Broker Futures Endpoints - * Possibly @deprecated, found only in old docs - * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker - * - **/ -⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, - ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> -⋮---- -/** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, - ): Promise<{ customerId: string; email: string }> -⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, - ): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise -⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, - ): Promise -⋮---- -/** - * - * User Data Stream Endpoints - * - **/ -⋮---- -// USD-M Futures -⋮---- -getFuturesUserDataListenKey(): Promise<{ listenKey: string }> -⋮---- -keepAliveFuturesUserDataListenKey(): Promise -⋮---- -closeFuturesUserDataListenKey(): Promise -⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, - ): void - -================ -File: src/types/websockets/ws-api-responses.ts -================ -import type { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures.js'; -import { - numberInString, - OrderSide, - OrderTimeInForce, - SelfTradePreventionMode, -} from '../shared'; -import { OrderResponse, SpotNewOrderConditionalFields } from '../spot'; -⋮---- -/** - * Error response type - */ -export interface ErrorResponse { - code: number; - msg: string; -} -⋮---- -export interface WSAPISessionStatus { - apiKey: string; - authorizedSince: number; - connectedSince: number; - returnRateLimits: boolean; - serverTime: number; - userDataStream: boolean; -} +export interface WSAPISessionStatus { + apiKey: string; + authorizedSince: number; + connectedSince: number; + returnRateLimits: boolean; + serverTime: number; + userDataStream: boolean; +} ⋮---- /** * General response types @@ -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,2394 +14391,1634 @@ 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, + OrderStatus, OrderTimeInForce, OrderType, + RateLimiter, SelfTradePreventionMode, -} from '../shared'; + SymbolIcebergPartsFilter, + SymbolLotSizeFilter, + SymbolMarketLotSizeFilter, + SymbolMaxIcebergOrdersFilter, + SymbolMaxPositionFilter, + SymbolPriceFilter, +} from './shared'; ⋮---- -/** - * Simple request params with timestamp (required) & recv window (optional) - */ -export type WSAPIRecvWindowTimestamp = { - recvWindow?: number; - timestamp: number; -}; +export type FuturesContractType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; ⋮---- -/** - * - * Authentication request types - * - */ -export interface WSAPISessionLogonRequest { - timestamp: number; +export interface ContinuousContractKlinesParams { + pair: string; + contractType: FuturesContractType; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -/** - * - * General request types - * - */ -export interface WSAPIExchangeInfoRequest { - symbol?: string; - symbols?: string[]; - permissions?: string[]; - showPermissionSets?: boolean; - symbolStatus?: string; +export interface IndexPriceKlinesParams { + pair: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -/** - * - * Market data request types - * - */ -⋮---- -export interface WSAPIOrderBookRequest { +export interface SymbolKlinePaginatedParams { symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; limit?: number; - symbolStatus?: string; } ⋮---- -export interface WSAPITradesRecentRequest { +export interface FuturesDataPaginatedParams { symbol: string; + contractType?: string; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface WSAPITradesHistoricalRequest { - symbol: string; - fromId?: number; +export interface FuturesCoinMTakerBuySellVolumeParams { + pair: string; + contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface WSAPIBlockTradesHistoricalRequest { - symbol: string; - fromId: number; +export interface FuturesCoinMBasisParams { + pair: string; + contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface WSAPITradesAggregateRequest { - symbol: string; - 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 WSAPIKlinesRequest { - symbol: string; - interval: KlineInterval; +export interface GetFuturesAllOrdersParams { + symbol?: string; + orderId?: number; startTime?: number; endTime?: number; - timeZone?: string; limit?: number; } ⋮---- -export interface WSAPIAvgPriceRequest { - symbol: string; +export enum EnumDualSideMode { + HedgeMode = 'true', + OneWayMode = 'false', } ⋮---- -/** - * 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 type DualSideMode = `${EnumDualSideMode}`; ⋮---- -export interface WSAPIReferencePriceRequest { - symbol: string; +export enum EnumMultiAssetMode { + MultiAssetsMode = 'true', + SingleAssetsMode = 'false', } ⋮---- -export interface WSAPIReferencePriceCalculationRequest { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; -} +export type MultiAssetsMode = `${EnumMultiAssetMode}`; ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITicker24hrRequest { - symbol?: string; - symbols?: string[]; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} +export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerTradingDayRequest { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} +export type MarginType = 'ISOLATED' | 'CROSSED'; ⋮---- -/** - * 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; -} +export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- -windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' +export type FuturesOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerPriceRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} +export type PriceMatchMode = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerBookRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; +// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. +export interface NewFuturesOrderParams { + symbol: string; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesOrderType; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberType; + newClientOrderId?: string; + stopPrice?: numberType; + closePosition?: BooleanString; + activationPrice?: numberType; + callbackRate?: numberType; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: 'ACK' | 'RESULT'; + selfTradePreventionMode?: SelfTradePreventionMode; + priceMatch?: PriceMatchMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- -/** - * - * Account request types - Spot - * - */ +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -export interface WSAPIAllOrdersRequest { - symbol: string; +export interface ModifyFuturesOrderParams { orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; + origClientOrderId?: string; + symbol: string; + side: OrderSide; + quantity?: numberType; + price?: numberType; + priceMatch?: PriceMatchMode; + modifyId?: number; + reduceOnly?: BooleanString; } ⋮---- -export interface WSAPIAllOrderListsRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; +export enum EnumPositionMarginChangeType { + AddPositionMargin = 1, + ReducePositionMargin = 0, } ⋮---- -export interface WSAPIMyTradesRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} +export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; ⋮---- -export interface WSAPIMyPreventedMatchesRequest { +export type IncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'SPECIAL_FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR'; +⋮---- +export interface CancelMultipleOrdersParams { symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; + orderIdList?: number[]; + origClientOrderIdList?: string[]; } ⋮---- -export interface WSAPIMyAllocationsRequest { +export interface CancelOrdersTimeoutParams { symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; + countdownTime?: 0 | number; } ⋮---- -/** - * Trading request types - */ -type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; -type SpotPegOffsetType = 'PRICE_LEVEL'; -⋮---- -export interface WSAPINewSpotOrderRequest { +export interface SetLeverageParams { 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; + leverage: number; } ⋮---- -export interface WSAPIOrderTestRequest { +export interface SetLeverageResult { + leverage: number; + maxNotionalValue: numberInString; 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 interface WSAPIOrderStatusRequest { +export interface SetMarginTypeParams { symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; + marginType: MarginType; } ⋮---- -export interface WSAPIOrderCancelRequest { +export interface SetIsolatedMarginParams { symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - recvWindow?: number; - timestamp: number; + positionSide?: PositionSide; + amount: number; + type: PositionMarginChangeType; } ⋮---- -export interface WSAPIOrderCancelReplaceRequest { - symbol: string; - cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; - cancelOrderId?: number; - cancelOrigClientOrderId?: string; - cancelNewClientOrderId?: string; - side: 'BUY' | 'SELL'; - type: string; - timeInForce?: string; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; - recvWindow?: number; - timestamp: number; +export interface SetIsolatedMarginResult { + amount: numberInString; + code: 200 | number; + msg: string; + type: 1 | 2; } ⋮---- -export interface WSAPIOrderAmendKeepPriorityRequest { +export interface GetPositionMarginChangeHistoryParams { symbol: string; - orderId?: number | string; - origClientOrderId?: string; - newClientOrderId?: string; - newQty?: string; - recvWindow?: number; - timestamp: number; + type?: PositionMarginChangeType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface WSAPIOpenOrdersStatusRequest { +/** + * 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; - recvWindow?: number; - timestamp: number; + incomeType?: IncomeType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface WSAPIOpenOrdersCancelAllRequest { - symbol: string; - recvWindow?: number; - timestamp: number; +export interface IncomeHistory { + symbol?: string; + incomeType: IncomeType; + income: string; + asset: string; + time: number; + info: string; + tranId: number; + tradeId: string; } ⋮---- -/** - * 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 ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; +⋮---- +export interface GetForceOrdersParams { + symbol?: string; + autoCloseType?: ForceOrderCloseType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface WSAPIOrderListPlaceOCORequest { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: numberInString; - listClientOrderId?: string; - aboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - aboveClientOrderId?: string; - aboveIcebergQty?: numberInString; - abovePrice?: numberInString; - aboveStopPrice?: numberInString; - aboveTrailingDelta?: number; - aboveTimeInForce?: string; - aboveStrategyId?: number; - aboveStrategyType?: number; - belowType: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - belowClientOrderId?: string; - belowIcebergQty?: numberInString; - belowPrice?: numberInString; - belowStopPrice?: numberInString; - belowTrailingDelta?: number; - belowTimeInForce?: string; - belowStrategyId?: number; - belowStrategyType?: number; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - recvWindow?: number; - timestamp: number; +export 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 WSAPIOrderListPlaceOTORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: numberInString; - pendingStopPrice?: numberInString; - pendingTrailingDelta?: numberInString; - pendingQuantity: numberInString; - pendingIcebergQty?: numberInString; - pendingTimeInForce?: string; - pendingStrategyId?: number; - pendingStrategyType?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOTOCORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: number | string; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: numberInString; - pendingAboveStopPrice?: numberInString; - pendingAboveTrailingDelta?: numberInString; - pendingAboveIcebergQty?: numberInString; - pendingAboveTimeInForce?: string; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingBelowType: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: numberInString; - pendingBelowStopPrice?: numberInString; - pendingBelowTrailingDelta?: numberInString; - pendingBelowIcebergQty?: numberInString; - pendingBelowTimeInForce?: string; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOPORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: numberInString; - pendingStopPrice?: numberInString; - pendingTrailingDelta?: numberInString; - pendingIcebergQty?: numberInString; - pendingTimeInForce?: string; - pendingStrategyId?: number; - pendingStrategyType?: number; - pendingPegPriceType?: string; - pendingPegOffsetType?: string; - pendingPegOffsetValue?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOPOCORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingSide: 'BUY' | 'SELL'; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: numberInString; - pendingAboveStopPrice?: numberInString; - pendingAboveTrailingDelta?: numberInString; - pendingAboveIcebergQty?: numberInString; - pendingAboveTimeInForce?: string; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingAbovePegPriceType?: string; - pendingAbovePegOffsetType?: string; - pendingAbovePegOffsetValue?: number; - pendingBelowType?: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: numberInString; - pendingBelowStopPrice?: numberInString; - pendingBelowTrailingDelta?: numberInString; - pendingBelowIcebergQty?: numberInString; - pendingBelowTimeInForce?: string; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - pendingBelowPegPriceType?: string; - pendingBelowPegOffsetType?: string; - pendingBelowPegOffsetValue?: number; - recvWindow?: number; - timestamp: number; +export interface FuturesSymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + limit: number; } ⋮---- -export interface WSAPIOrderListStatusRequest { - origClientOrderId?: string; - orderListId?: number; - recvWindow?: number; - timestamp: number; +export interface FuturesSymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + limit: number; } ⋮---- -export interface WSAPIOrderListCancelRequest { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; - recvWindow?: number; - timestamp: number; +export interface FuturesSymbolMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + notional: numberInString; } ⋮---- /** - * SOR 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 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 FuturesSymbolPositionRiskControlFilter { + filterType: 'POSITION_RISK_CONTROL'; + /** + * Undocumented. Observed value: `NONE`. + */ + positionControlSide: string; } ⋮---- -export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { - computeCommissionRates?: boolean; -}; -⋮---- /** - * Futures market data request types - */ + * Undocumented. Observed value: `NONE`. + */ ⋮---- -export interface WSAPIFuturesOrderBookRequest { +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; } ⋮---- -export interface WSAPIFuturesTickerPriceRequest { - symbol?: string; -} +underlyingType: 'COIN' | 'INDEX'; // No other known values +underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc ⋮---- -export interface WSAPIFuturesTickerBookRequest { - symbol?: string; +export interface FuturesExchangeInfo { + exchangeFilters: ExchangeFilter[]; + rateLimits: RateLimiter[]; + serverTime: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any[]; + symbols: FuturesSymbolExchangeInfo[]; + timezone: string; } ⋮---- -/** - * Futures trading request types - */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -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; +export interface FuturesOrderBook { + lastUpdateId: number; + E: number; + T: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; } ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface WSAPIFuturesOrderModifyRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - side: 'BUY' | 'SELL'; - quantity: numberInString; +export interface RawFuturesTrade { + id: number; 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; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; } ⋮---- -export interface WSAPIFuturesOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; +export interface AggregateFuturesTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; } ⋮---- -export interface WSAPIFuturesOrderStatusRequest { +export interface MarkPrice { symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesPositionRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; + markPrice: numberInString; + indexPrice: numberInString; + estimatedSettlePrice: numberInString; + lastFundingRate: numberInString; + interestRate: numberInString; + nextFundingTime: number; + time: number; } ⋮---- -export interface WSAPIFuturesPositionV2Request { - symbol?: string; - recvWindow?: number; - timestamp: number; +export interface FundingRateHistory { + symbol: string; + fundingRate: numberInString; + fundingTime: number; + markPrice: numberInString; + rateType?: 'Regular' | 'Special'; } ⋮---- -export interface WSAPIAccountInformationRequest { - omitZeroBalances?: boolean; - recvWindow?: number; - timestamp: number; +export interface FuturesSymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; } ⋮---- -export interface WSAPIAccountCommissionWSAPIRequest { +export interface OpenInterest { + openInterest: numberInString; symbol: string; + time: number; } ⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api - */ -export interface WSAPINewFuturesAlgoOrderRequest { - algoType: FuturesAlgoOrderType; +export interface HistoricOpenInterest { 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; + sumOpenInterest: string; + sumOpenInterestValue: string; + CMCCirculatingSupply: string; 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; +export interface PositionModeParams { + dualSidePosition: DualSideMode; } - -================ -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 ModeChangeResult { + code: 200 | number; + msg: 'success' | string; +} ⋮---- -export interface ContinuousContractKlinesParams { - pair: string; - contractType: FuturesContractType; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; +export interface PositionModeResponse { + dualSidePosition: boolean; } ⋮---- -export interface IndexPriceKlinesParams { - pair: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; +export interface MultiAssetModeResponse { + multiAssetsMargin: boolean; } ⋮---- -export interface SymbolKlinePaginatedParams { +export interface NewOrderResult { + clientOrderId: string; + cumQty: numberInString; + cumQuote?: numberInString; + executedQty: numberInString; + orderId: number; + avgPrice?: numberInString; + origQty: numberInString; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + origType: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + goodTillDate?: number; } ⋮---- -export interface FuturesDataPaginatedParams { - symbol: string; - contractType?: string; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMTakerBuySellVolumeParams { - pair: string; - contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMBasisParams { - pair: string; - contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export 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 GetFuturesAllOrdersParams { - symbol?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export enum EnumDualSideMode { - HedgeMode = 'true', - OneWayMode = 'false', -} -⋮---- -export type DualSideMode = `${EnumDualSideMode}`; -⋮---- -export enum EnumMultiAssetMode { - MultiAssetsMode = 'true', - SingleAssetsMode = 'false', +export interface NewOrderError { + code: number; + msg: string; } ⋮---- -export type MultiAssetsMode = `${EnumMultiAssetMode}`; -⋮---- -export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; -⋮---- -export type MarginType = 'ISOLATED' | 'CROSSED'; -⋮---- -export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; -⋮---- -export type FuturesOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; -⋮---- -export type PriceMatchMode = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; -⋮---- -// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. -export interface NewFuturesOrderParams { - symbol: string; +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; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + time: number; + timeInForce: OrderTimeInForce; 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 + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + goodTillDate: number; + cumBase?: numberInString; + pair?: string; } ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface ModifyFuturesOrderParams { - orderId?: number; - origClientOrderId?: 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; - quantity?: numberType; - price?: numberType; - priceMatch?: PriceMatchMode; + positionSide: PositionSide; + stopPrice: numberInString; + workingType: WorkingType; + priceProtect: boolean; + origType: FuturesOrderType; + updateTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; modifyId?: number; - reduceOnly?: BooleanString; -} -⋮---- -export enum EnumPositionMarginChangeType { - AddPositionMargin = 1, - ReducePositionMargin = 0, } ⋮---- -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 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; - orderIdList?: number[]; - origClientOrderIdList?: string[]; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; } ⋮---- -export interface CancelOrdersTimeoutParams { - symbol: string; - countdownTime?: 0 | number; +export interface CancelAllOpenOrdersResult { + code: 200 | numberInString; + msg: string; } ⋮---- -export interface SetLeverageParams { - symbol: string; - leverage: number; +export interface FuturesAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + marginAvailable: boolean; + updateTime: numberInString; } ⋮---- -export interface SetLeverageResult { - leverage: number; - maxNotionalValue: numberInString; - symbol: string; +export interface FuturesCoinMAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + withdrawAvailable: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + updateTime: number; } ⋮---- -export interface SetMarginTypeParams { - symbol: string; - marginType: MarginType; +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 SetIsolatedMarginParams { +export interface FuturesAccountPosition { symbol: string; - positionSide?: PositionSide; - amount: number; - type: PositionMarginChangeType; + 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 SetIsolatedMarginResult { - amount: numberInString; - code: 200 | number; - msg: string; - type: 1 | 2; +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 GetPositionMarginChangeHistoryParams { +export interface FuturesAccountInformation { + feeTier: numberInString; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + updateTime: numberInString; + multiAssetsMargin: boolean; + totalInitialMargin: numberInString; + totalMaintMargin: numberInString; + totalWalletBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalMarginBalance: numberInString; + totalPositionInitialMargin: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalCrossWalletBalance: numberInString; + totalCrossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + assets: FuturesAccountAsset[]; + positions: FuturesAccountPosition[]; +} +⋮---- +export interface FuturesCoinMAccountInformation { + assets: Omit[]; + positions: FuturesCoinMAccountPosition[]; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; +} +⋮---- +export interface FuturesPosition { + entryPrice: numberInString; + marginType: 'isolated' | 'cross'; + isAutoAddMargin: 'false' | 'true'; + isolatedMargin: numberInString; + leverage: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + maxNotionalValue: numberInString; + positionAmt: numberInString; + notional: numberInString; + isolatedWallet: numberInString; symbol: string; - type?: PositionMarginChangeType; - startTime?: number; - endTime?: number; - limit?: number; + unRealizedProfit: numberInString; + positionSide: PositionSide; + updateTime: number; } ⋮---- -/** - * 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 FuturesPositionV3 { + symbol: string; + positionSide: PositionSide; + positionAmt: numberInString; + entryPrice: numberInString; + breakEvenPrice: numberInString; + markPrice: numberInString; + unRealizedProfit: numberInString; + liquidationPrice: numberInString; + isolatedMargin: numberInString; + notional: numberInString; + marginAsset: string; + isolatedWallet: numberInString; + initialMargin: numberInString; + maintMargin: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + adl: number; + bidNotional: numberInString; + askNotional: numberInString; + updateTime: number; } ⋮---- -export interface IncomeHistory { - symbol?: string; - incomeType: IncomeType; - income: string; - asset: string; +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; - info: string; - tranId: number; - tradeId: string; + pair?: string; + baseQty?: numberInString; + marginAsset?: string; } ⋮---- -export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; +export interface ForceOrderResult { + orderId: number; + symbol: string; + status: OrderStatus; + clientOrderId: string; + price: numberInString; + avgPrice: numberInString; + origQty: numberInString; + executedQty: numberInString; + cumQuote: numberInString; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + reduceOnly: boolean; + closePosition: boolean; + side: OrderSide; + stopPrice: numberInString; + workingType: WorkingType; + origType: FuturesOrderType; + time: number; + updateTime: number; + cumBase?: numberInString; + pair?: string; + goodTillDate?: number; +} ⋮---- -export interface GetForceOrdersParams { - symbol?: string; - autoCloseType?: ForceOrderCloseType; - startTime?: number; - endTime?: number; - limit?: number; +export interface SymbolLeverageBracket { + bracket: number; + initialLeverage: number; + notionalCap: number; + notionalFloor: number; + maintMarginRatio: number; + cum: number; } ⋮---- -export type ContactType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; +export interface SymbolLeverageBracketsResult { + symbol: string; + brackets: SymbolLeverageBracket[]; +} ⋮---- -export type ContractStatus = - | 'PENDING_TRADING' - | 'TRADING' - | 'PRE_DELIVERING' - | 'DELIVERING' - | 'DELIVERED' - | 'CANCELLED' - | 'PRE_SETTLE' - | 'SETTLING' - | 'CLOSE'; +export interface UserCommissionRate { + symbol: string; + makerCommissionRate: numberInString; + takerCommissionRate: numberInString; + rpiCommissionRate?: numberInString; +} ⋮---- -export interface FuturesSymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - multiplierDecimal: numberInString; +export interface FuturesAccountConfig { + feeTier: number; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + dualSidePosition: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId: number; } ⋮---- -export interface FuturesSymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - limit: number; +export interface SymbolConfig { + symbol: string; + marginType: string; + isAutoAddMargin: string; + leverage: number; + maxNotionalValue: string; } ⋮---- -export interface FuturesSymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; +export interface UserForceOrder { + rateLimitType: string; + interval: string; + intervalNum: number; limit: number; } ⋮---- -export interface FuturesSymbolMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - notional: numberInString; +export interface RebateDataOverview { + brokerId: string; + newTraderRebateCommission: numberInString; + oldTraderRebateCommission: numberInString; + totalTradeUser: number; + unit: string; + totalTradeVol: numberInString; + totalRebateVol: numberInString; + time: number; } ⋮---- -/** - * 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 SetCancelTimeoutResult { + symbol: string; + countdownTime: numberInString; } ⋮---- -/** - * Undocumented. Observed value: `NONE`. - */ -⋮---- -export type FuturesSymbolFilter = - | SymbolPriceFilter - | FuturesSymbolPercentPriceFilter - | SymbolLotSizeFilter - | FuturesSymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | FuturesSymbolMaxOrdersFilter - | FuturesSymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter - | FuturesSymbolPositionRiskControlFilter; -⋮---- -export interface FuturesSymbolExchangeInfo { +export interface ChangeStats24hr { 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; + 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; } ⋮---- -underlyingType: 'COIN' | 'INDEX'; // No other known values -underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc +firstId: number; // First tradeId +lastId: number; // Last tradeId ⋮---- -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 OrderAmendmentDetailPrice { + before: numberInString; + after: numberInString; } ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface OrderAmendmentDetailQty { + before: numberInString; + after: numberInString; +} ⋮---- -export interface FuturesOrderBook { - lastUpdateId: number; - E: number; - T: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; +export interface OrderAmendmentDetail { + price: OrderAmendmentDetailPrice; + origQty: OrderAmendmentDetailQty; + count: number; } ⋮---- -export interface RawFuturesTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; +export interface OrderAmendment { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; time: number; - isBuyerMaker: boolean; + amendment: OrderAmendmentDetail; + modifyId?: number; } ⋮---- -export interface AggregateFuturesTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; +export interface QuarterlyContractSettlementPrice { + deliveryTime: number; + deliveryPrice: number; } ⋮---- -export interface MarkPrice { - symbol: string; - markPrice: numberInString; - indexPrice: numberInString; - estimatedSettlePrice: numberInString; - lastFundingRate: numberInString; - interestRate: numberInString; - nextFundingTime: number; - time: number; +export interface BasisParams { + pair: string; + contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface FundingRateHistory { - symbol: string; - fundingRate: numberInString; - fundingTime: number; - markPrice: numberInString; - rateType?: 'Regular' | 'Special'; +export interface Basis { + indexPrice: string; + contractType: string; + basisRate: string; + futuresPrice: string; + annualizedBasisRate: string; + basis: string; + pair: string; + timestamp: number; } ⋮---- -export interface FuturesSymbolOrderBookTicker { +export interface IndexPriceConstituent { + exchange: string; symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; + price: numberInString; + weight: numberInString; } ⋮---- -export interface OpenInterest { - openInterest: numberInString; +export interface IndexPriceConstituents { symbol: string; time: number; + constituents: IndexPriceConstituent[]; } ⋮---- -export interface HistoricOpenInterest { +export interface InsuranceFundBalance { + symbols: string[]; + assets: { + asset: string; + marginBalance: string; + updateTime: number; + }[]; +} +⋮---- +export interface ModifyOrderParams { + orderId?: number; + origClientOrderId?: string; symbol: string; - sumOpenInterest: string; - sumOpenInterestValue: string; - CMCCirculatingSupply: 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; } ⋮---- -export interface PositionModeParams { - dualSidePosition: DualSideMode; +export interface GetFuturesOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface ModeChangeResult { - code: 200 | number; - msg: 'success' | string; +export interface FuturesTradeHistoryDownloadId { + avgCostTimestampOfLast30d: number; + downloadId: string; } ⋮---- -export interface PositionModeResponse { - dualSidePosition: boolean; +export interface FuturesTransactionDownloadLink { + downloadId: string; + status: 'completed' | 'processing'; + url: string; + expirationTimestamp: number; + isExpired: boolean | null; } ⋮---- -export interface MultiAssetModeResponse { - multiAssetsMargin: boolean; +export interface PortfolioMarginProAccountInfo { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; // This field will be ignored in the response } ⋮---- -export interface NewOrderResult { - clientOrderId: string; - cumQty: numberInString; - cumQuote?: numberInString; - executedQty: numberInString; - orderId: number; - avgPrice?: numberInString; - origQty: numberInString; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - origType: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - goodTillDate?: number; +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 NewOrderError { - code: number; - msg: string; +export interface FuturesConvertQuoteRequest { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + validTime?: '10s' | '30s' | '1m' | '2m'; } ⋮---- -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 FuturesConvertQuote { + quoteId: string; + ratio: string; + inverseRatio: string; + validTimestamp: number; + toAmount: string; + fromAmount: string; } ⋮---- -export interface ModifyFuturesOrderResult { - orderId: number; +export interface FuturesConvertOrderStatus { + orderId: string; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; +} +⋮---- +/** + * Algo Order Types (Effective 2025-12-02) + * USDⓈ-M Futures conditional orders migrate to Algo Service + */ +⋮---- +export type FuturesAlgoOrderType = 'CONDITIONAL'; +⋮---- +export type FuturesAlgoConditionalOrderTypes = + | 'STOP_MARKET' + | 'TAKE_PROFIT_MARKET' + | 'STOP' + | 'TAKE_PROFIT' + | 'TRAILING_STOP_MARKET'; +⋮---- +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update + */ +export type FuturesAlgoOrderStatus = + | 'NEW' + | 'CANCELED' + | 'TRIGGERING' + | 'TRIGGERED' + | 'FINISHED' + | 'REJECTED' + | 'EXPIRED'; +⋮---- +export interface FuturesNewAlgoOrderParams { + algoType: FuturesAlgoOrderType; symbol: string; - 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; + 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 CancelFuturesOrderResult { - clientOrderId: string; - cumQty: numberInString; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; +clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ +⋮---- +export interface FuturesAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; + symbol: string; side: OrderSide; positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; 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; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + activatePrice?: numberInString; + callbackRate?: numberInString; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; } ⋮---- -export interface CancelAllOpenOrdersResult { - code: 200 | numberInString; - msg: string; +export interface FuturesCancelAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; } ⋮---- -export interface FuturesAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - marginAvailable: boolean; - updateTime: numberInString; +export interface FuturesCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; } ⋮---- -export interface FuturesCoinMAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - withdrawAvailable: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - updateTime: number; +export interface FuturesCancelAllAlgoOpenOrdersResponse { + code: number; + msg: 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 FuturesQueryAlgoOrderParams { + algoId?: number; + clientAlgoId?: 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 FuturesQueryAlgoOrderResponse + extends FuturesAlgoOrderResponse { + actualOrderId: numberInString; + actualPrice: numberInString; + tpTriggerPrice?: numberInString; + tpPrice?: numberInString; + slTriggerPrice?: numberInString; + slPrice?: numberInString; + tpOrderType?: 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 FuturesQueryOpenAlgoOrdersParams { + algoType?: FuturesAlgoOrderType; + symbol?: string; + algoId?: number; } ⋮---- -export interface FuturesAccountInformation { - feeTier: numberInString; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - updateTime: numberInString; - multiAssetsMargin: boolean; - totalInitialMargin: numberInString; - totalMaintMargin: numberInString; - totalWalletBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalMarginBalance: numberInString; - totalPositionInitialMargin: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalCrossWalletBalance: numberInString; - totalCrossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - assets: FuturesAccountAsset[]; - positions: FuturesAccountPosition[]; +export interface FuturesQueryAllAlgoOrdersParams { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 500; max 1000 } ⋮---- -export interface FuturesCoinMAccountInformation { - assets: Omit[]; - positions: FuturesCoinMAccountPosition[]; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; -} +limit?: number; // Default 500; max 1000 ⋮---- -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 SymbolAdlRisk { symbol: string; - unRealizedProfit: numberInString; - positionSide: PositionSide; + adlRisk: 'low' | 'medium' | 'high'; updateTime: number; } ⋮---- -export interface FuturesPositionV3 { - symbol: string; - positionSide: PositionSide; - positionAmt: numberInString; - entryPrice: numberInString; - breakEvenPrice: numberInString; - markPrice: numberInString; - unRealizedProfit: numberInString; - liquidationPrice: numberInString; - isolatedMargin: numberInString; - notional: numberInString; - marginAsset: string; - isolatedWallet: numberInString; - initialMargin: numberInString; - maintMargin: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - adl: number; - bidNotional: numberInString; - askNotional: numberInString; - updateTime: number; +export interface TradingSession { + startTime: number; + endTime: number; + type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; } ⋮---- -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 MarketSchedule { + sessions: TradingSession[]; } ⋮---- -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 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 SymbolLeverageBracket { - bracket: number; - initialLeverage: number; - notionalCap: number; - notionalFloor: number; - maintMarginRatio: number; - cum: number; +export interface RpiOrderBook { + lastUpdateId: number; + E: number; // Message output time + T: number; // Transaction time + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; } ⋮---- -export interface SymbolLeverageBracketsResult { - symbol: string; - brackets: SymbolLeverageBracket[]; -} +E: number; // Message output time +T: number; // Transaction time + +================ +File: src/websocket-client.ts +================ +import WebSocket from 'isomorphic-ws'; ⋮---- -export interface UserCommissionRate { - symbol: string; - makerCommissionRate: numberInString; - takerCommissionRate: numberInString; - rpiCommissionRate?: numberInString; -} +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'; ⋮---- -export interface FuturesAccountConfig { - feeTier: number; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - dualSidePosition: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId: number; +type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +⋮---- +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; } ⋮---- -export interface SymbolConfig { - symbol: string; - marginType: string; - isAutoAddMargin: string; - leverage: number; - maxNotionalValue: string; -} -⋮---- -export interface UserForceOrder { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; -} -⋮---- -export interface RebateDataOverview { - brokerId: string; - newTraderRebateCommission: numberInString; - oldTraderRebateCommission: numberInString; - totalTradeUser: number; - unit: string; - totalTradeVol: numberInString; - totalRebateVol: numberInString; - time: number; -} -⋮---- -export interface SetCancelTimeoutResult { - symbol: string; - countdownTime: numberInString; -} -⋮---- -export interface ChangeStats24hr { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First tradeId - lastId: number; // Last tradeId - count: number; -} +/** If true, will skip auth requirement for WS API connection */ ⋮---- -firstId: number; // First tradeId -lastId: number; // Last tradeId +/** + * 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 interface OrderAmendmentDetailPrice { - before: numberInString; - after: numberInString; -} +export class WebsocketClient extends BaseWebsocketClient< ⋮---- -export interface OrderAmendmentDetailQty { - before: numberInString; - after: numberInString; -} +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- -export interface OrderAmendmentDetail { - price: OrderAmendmentDetailPrice; - origQty: OrderAmendmentDetailQty; - count: number; -} +/** + * 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 + */ ⋮---- -export interface OrderAmendment { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: OrderAmendmentDetail; - modifyId?: number; -} +// fn pointers: ⋮---- -export interface QuarterlyContractSettlementPrice { - deliveryTime: number; - deliveryPrice: number; -} +protected onWsCloseCleanup(wsKey: WsKey): void ⋮---- -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; -} +private getUserDataStreamManager(): UserDataStreamManager ⋮---- -export interface Basis { - indexPrice: string; - contractType: string; - basisRate: string; - futuresPrice: string; - annualizedBasisRate: string; - basis: string; - pair: string; - timestamp: number; -} +private getRestClientOptions(): RestClientOptions ⋮---- -export interface IndexPriceConstituent { - exchange: string; - symbol: string; - price: numberInString; - weight: numberInString; -} +/** + * 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[] ⋮---- -export interface IndexPriceConstituents { - symbol: string; - time: number; - constituents: IndexPriceConstituent[]; -} +/** + * 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[] ⋮---- -export interface InsuranceFundBalance { - symbols: string[]; - assets: { - asset: string; - marginBalance: string; - updateTime: number; - }[]; -} +/** + * This function serves no purpose in the Binance SDK + */ +public async connectPrivate(): Promise ⋮---- -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; -} +/** + * 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 GetFuturesOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -export interface FuturesTradeHistoryDownloadId { - avgCostTimestampOfLast30d: number; - downloadId: string; -} +/** + * 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 FuturesTransactionDownloadLink { - downloadId: string; - status: 'completed' | 'processing'; - url: string; - expirationTimestamp: number; - isExpired: boolean | null; -} +/** + * 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 PortfolioMarginProAccountInfo { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; // This field will be ignored in the response -} +/** + * + * + * + * 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 + * + * + * + */ ⋮---- -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; -} +/** + * 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 FuturesConvertQuoteRequest { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - validTime?: '10s' | '30s' | '1m' | '2m'; -} +// 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 FuturesConvertQuote { - quoteId: string; - ratio: string; - inverseRatio: string; - validTimestamp: number; - toAmount: string; - fromAmount: string; -} +// if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap ⋮---- -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; -} +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 ⋮---- /** - * Algo Order Types (Effective 2025-12-02) - * USDⓈ-M Futures conditional orders migrate to Algo Service - */ -⋮---- -export type FuturesAlgoOrderType = 'CONDITIONAL'; + * 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 type FuturesAlgoConditionalOrderTypes = - | 'STOP_MARKET' - | 'TAKE_PROFIT_MARKET' - | 'STOP' - | 'TAKE_PROFIT' - | 'TRAILING_STOP_MARKET'; +// If testnet, enforce testnet wskey for WS API calls ⋮---- -/** - * 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'; +// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); ⋮---- -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; -} +// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); ⋮---- -clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ +// Some commands don't require authentication. ⋮---- -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; -} +// Only if authOnConnect is enabled (aka using Ed25519 keys) ⋮---- -export interface FuturesCancelAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- -export interface FuturesCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- -export interface FuturesCancelAllAlgoOpenOrdersResponse { - code: number; - msg: string; -} +/** + * 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 FuturesQueryAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} +// Sign, if needed ⋮---- -export interface FuturesQueryAlgoOrderResponse - extends FuturesAlgoOrderResponse { - actualOrderId: numberInString; - actualPrice: numberInString; - tpTriggerPrice?: numberInString; - tpPrice?: numberInString; - slTriggerPrice?: numberInString; - slPrice?: numberInString; - tpOrderType?: string; -} +// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events ⋮---- -export interface FuturesQueryOpenAlgoOrdersParams { - algoType?: FuturesAlgoOrderType; - symbol?: string; - algoId?: number; -} +// Enrich returned promise with request context for easier debugging ⋮---- -export interface FuturesQueryAllAlgoOrdersParams { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 500; max 1000 -} +// throw e; ⋮---- -limit?: number; // Default 500; max 1000 +// this.logger.trace( +// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, +// ); ⋮---- -export interface SymbolAdlRisk { - symbol: string; - adlRisk: 'low' | 'medium' | 'high'; - updateTime: number; -} +// Send event. ⋮---- -export interface TradingSession { - startTime: number; - endTime: number; - type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; -} +// Return deferred promise, so caller can await this call ⋮---- -export interface MarketSchedule { - sessions: TradingSession[]; -} +/** + * + * + * Internal methods - not intended for public use + * + * + */ ⋮---- -export interface TradingSchedule { - updateTime: number; - marketSchedules: { - EQUITY?: MarketSchedule; - COMMODITY?: MarketSchedule; - KR_EQUITY?: MarketSchedule; - HK_EQUITY?: MarketSchedule; - CN_EQUITY?: MarketSchedule; - FX?: MarketSchedule; - }; -} +/** + * @returns The WS URL to connect to for this WS key + */ +async getWsUrl( + wsKey: WsKey, + connectionType: 'public' | 'market' | 'private' = 'market', + ): Promise ⋮---- -export interface RpiOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, + ): Promise ⋮---- -E: number; // Message output time -T: number; // Transaction time - -================ -File: src/websocket-client.ts -================ -import WebSocket from 'isomorphic-ws'; +// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); ⋮---- -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'; +/** + * 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> ⋮---- -type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +/** + * 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 interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise< + WsRequestOperationBinance< + string, + { apiKey: string; signature: string; timestamp: number } + > + > ⋮---- -/** If true, will skip auth requirement for WS API connection */ +// Note: Only Ed25519 keys are supported for this feature. +// RSA & HMAC keys will automatically sign each individual request instead. ⋮---- -/** - * 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. - */ +// 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 class WebsocketClient extends BaseWebsocketClient< +// 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. ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +// Note: You still have to specify the timestamp parameter for SIGNED requests. ⋮---- -/** - * 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 - */ +protected sendPingEvent(wsKey: WsKey) ⋮---- -// fn pointers: +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -protected onWsCloseCleanup(wsKey: WsKey): void +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -private getUserDataStreamManager(): UserDataStreamManager +protected sendPongEvent(wsKey: WsKey) ⋮---- -private getRestClientOptions(): RestClientOptions +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -/** - * 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[] +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -/** - * 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[] +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** - * This function serves no purpose in the Binance SDK + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ -public async connectPrivate(): Promise +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 +⋮---- +// Cache midflight subs on the req ID +// Enrich response with subs for that req ID +⋮---- +protected getPrivateWSKeys(): WsKey[] +⋮---- +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** - * 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). + * Determines if a topic is for a private channel, using a hardcoded list of strings */ -public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise +protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPing(msg: any): boolean +⋮---- +// For binance, all ping/pong events are frame events +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPong(msg: any): boolean +⋮---- +// For binance, all ping/pong events are frame events ⋮---- /** - * Request subscription to one or more topics. Pass topics as either an array of strings, - * or array of objects (if the topic has parameters). - * - * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ -public subscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], +protected resolveEmittableEvents( wsKey: WsKey, - ): Promise + event: MessageEventLike, + ): EmittableEvent[] +⋮---- +// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); ⋮---- /** - * 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, - ) -⋮---- -/** - * - * - * - * 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 - * - * - * 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 -⋮---- -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 -⋮---- -/** - * 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 - */ -⋮---- -// If testnet, enforce testnet wskey for WS API calls -⋮---- -// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); -⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); -⋮---- -// Some commands don't require authentication. -⋮---- -// Only if authOnConnect is enabled (aka using Ed25519 keys) -⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); -⋮---- -// 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. - */ -⋮---- -// Sign, if needed -⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events -⋮---- -// Enrich returned promise with request context for easier debugging -⋮---- -// throw e; -⋮---- -// this.logger.trace( -// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, -// ); -⋮---- -// Send event. -⋮---- -// Return deferred promise, so caller can await this call -⋮---- -/** - * - * - * Internal methods - not intended for public use - * - * - */ -⋮---- -/** - * @returns The WS URL to connect to for this WS key - */ -async getWsUrl( - wsKey: WsKey, - connectionType: 'public' | 'market' | 'private' = 'market', - ): Promise -⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, - ): Promise -⋮---- -// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); -⋮---- -/** - * 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> -⋮---- -/** - * 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 getWsAuthRequestEvent( - 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. -⋮---- -// 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. -⋮---- -// 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. -⋮---- -// Note: You still have to specify the timestamp parameter for SIGNED requests. -⋮---- -protected sendPingEvent(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) -⋮---- -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 -⋮---- -// Cache midflight subs on the req ID -// Enrich response with subs for that req ID -⋮---- -protected getPrivateWSKeys(): WsKey[] -⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean -⋮---- -/** - * Determines if a topic is for a private channel, using a hardcoded list of strings - */ -protected isPrivateTopicRequest(request: WsTopicRequest): boolean -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPing(msg: any): boolean -⋮---- -// For binance, all ping/pong events are frame events -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPong(msg: any): boolean -⋮---- -// For binance, all ping/pong events are frame events -⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, - ): EmittableEvent[] -⋮---- -// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); -⋮---- -/** - * - * Extract event from JSON - * - */ + * + * Extract event from JSON + * + */ ⋮---- /** * @@ -17335,106 +16639,926 @@ public subscribeDiffBookDepth( ): Promise ⋮---- /** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, - ): Promise + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ +⋮---- +/** + * Subscribe to aggregate trades for a symbol in spot markets. + */ +public subscribeSpotAggregateTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to trades for a symbol in spot markets. + */ +public subscribeSpotTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeSpotBlockTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to candles for a symbol in spot markets. + */ +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to mini 24hr mini ticker in spot markets. + */ +public subscribeSpotAllMini24hrTickers( + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbol24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise +⋮---- +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise +⋮---- +/** + * 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 +⋮---- +/** + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +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'; +⋮---- +/** + * Simple request params with timestamp (required) & recv window (optional) + */ +export type WSAPIRecvWindowTimestamp = { + recvWindow?: number; + timestamp: number; +}; +⋮---- +/** + * + * Authentication request types + * + */ +export interface WSAPISessionLogonRequest { + timestamp: number; +} +⋮---- +/** + * + * General request types + * + */ +export interface WSAPIExchangeInfoRequest { + symbol?: string; + symbols?: string[]; + permissions?: string[]; + showPermissionSets?: boolean; + symbolStatus?: string; +} +⋮---- +/** + * + * Market data request types + * + */ +⋮---- +export interface WSAPIOrderBookRequest { + symbol: string; + limit?: number; + symbolStatus?: string; +} +⋮---- +export interface WSAPITradesRecentRequest { + symbol: string; + limit?: number; +} +⋮---- +export interface WSAPITradesHistoricalRequest { + symbol: string; + fromId?: number; + limit?: number; +} +⋮---- +export interface WSAPIBlockTradesHistoricalRequest { + symbol: string; + fromId: number; + limit?: number; +} +⋮---- +export interface WSAPITradesAggregateRequest { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIKlinesRequest { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} +⋮---- +export interface WSAPIAvgPriceRequest { + symbol: string; +} +⋮---- +/** + * Query execution rules (e.g. PRICE_RANGE). Only one of symbol, symbols, or symbolStatus per request. + */ +export interface WSAPIExecutionRulesRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; +} +⋮---- +export interface WSAPIReferencePriceRequest { + symbol: string; +} +⋮---- +export interface WSAPIReferencePriceCalculationRequest { + 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; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerBookRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} +⋮---- +/** + * + * Account request types - Spot + * + */ +⋮---- +export interface WSAPIAllOrdersRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIAllOrderListsRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyTradesRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyPreventedMatchesRequest { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyAllocationsRequest { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; +} +⋮---- +/** + * Trading request types + */ +type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; +type SpotPegOffsetType = 'PRICE_LEVEL'; +⋮---- +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; +} +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +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; +} +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +export interface WSAPIOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelReplaceRequest { + symbol: string; + cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; + cancelOrderId?: number; + cancelOrigClientOrderId?: string; + cancelNewClientOrderId?: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + /** 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; +} +⋮---- +/** BUY only; Binance has not decided when this feature will be enabled. */ +⋮---- +export interface WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersCancelAllRequest { + symbol: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * Order list request types + */ +export interface WSAPIOrderListPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + price: numberInString; + quantity: numberInString; + listClientOrderId?: string; + limitClientOrderId?: string; + limitIcebergQty?: numberInString; + limitStrategyId?: number; + limitStrategyType?: number; + stopPrice?: numberInString; + trailingDelta?: number; + stopClientOrderId?: string; + stopLimitPrice?: numberInString; + stopLimitTimeInForce?: string; + stopIcebergQty?: numberInString; + stopStrategyId?: number; + stopStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOCORequest { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: numberInString; + listClientOrderId?: string; + aboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + aboveClientOrderId?: string; + aboveIcebergQty?: numberInString; + abovePrice?: numberInString; + /** 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; +} +⋮---- +/** 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 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; +} +⋮---- +/** 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 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; +} +⋮---- +/** 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 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; +} +⋮---- +/** 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 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; +} +⋮---- +/** 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 WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListCancelRequest { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * SOR request types + */ +export interface WSAPISOROrderPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + price?: numberInString; + quantity: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: string; + timestamp: number; + recvWindow?: number; +} ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { + computeCommissionRates?: boolean; +}; ⋮---- /** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise + * Futures market data request types + */ ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesOrderBookRequest { + symbol: string; + limit?: number; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; +} ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; +} ⋮---- /** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise + * Futures trading request types + */ ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - 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 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(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 best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - wsKeyOverride?: WsKey, - ): Promise +export interface WSAPIFuturesOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesPositionRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesPositionV2Request { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIAccountInformationRequest { + omitZeroBalances?: boolean; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIAccountCommissionWSAPIRequest { + symbol: string; +} ⋮---- /** - * 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, @@ -29790,7 +29992,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", 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..cd5f441a 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 { 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..77175d39 100644 --- a/src/util/rounding.ts +++ b/src/util/rounding.ts @@ -1,43 +1,35 @@ /** - * Rounds a price to the correct number of decimal places based on the symbol's tick size + * 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. */ -export function roundToTickSize(price: number, tickSize: string): number { - if (!tickSize) { - return price; +function floorToIncrement(value: number, increment: string): number { + const incrementNum = parseFloat(increment); + if (!increment || !incrementNum) { + return value; } - // 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); - } + // 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; - // Round to the nearest tick - const tickSizeNum = parseFloat(tickSize); - const rounded = Math.floor(price / tickSizeNum) * tickSizeNum; + // 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; - // Format with correct precision - return +rounded.toFixed(precision); + return +(floored / factor).toFixed(decimals); } /** - * Rounds a quantity to the correct step size + * Rounds a price down to a multiple of the symbol's tick size */ -export function roundToStepSize(quantity: number, stepSize: string): number { - if (!stepSize) { - return quantity; - } - - // Calculate precision from step size - const precision = stepSize.indexOf('1') - 1; - if (precision < 0) { - return Math.floor(quantity); - } - - // Round to the nearest step - const stepSizeNum = parseFloat(stepSize); - const rounded = Math.floor(quantity / stepSizeNum) * stepSizeNum; +export function roundToTickSize(price: number, tickSize: string): number { + return floorToIncrement(price, tickSize); +} - // Format with correct precision - return +rounded.toFixed(precision); +/** + * 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/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); + }, + ); + }); +});