From f2de3e4e0245b9e9bb19766c06b3cad4daac57d7 Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Mon, 2 Nov 2026 09:04:57 +0100 Subject: [PATCH 1/6] feat(v3.6.12): support CANCEL_ONLY symbol status filters - Add CANCEL_ONLY to Spot REST and WebSocket execution rules and reference price calculation filters. - Add keyless regression tests for all supported filter values and omitted filters. - Bump package and lockfile versions from 3.6.11 to 3.6.12. --- package-lock.json | 4 +- package.json | 2 +- src/main-client.ts | 2 +- src/types/spot.ts | 2 +- src/types/websockets/ws-api-requests.ts | 4 +- test/spot/symbolStatus.test.ts | 68 +++++++++++++++++++++++++ 6 files changed, 75 insertions(+), 7 deletions(-) create mode 100644 test/spot/symbolStatus.test.ts diff --git a/package-lock.json b/package-lock.json index 561a49f0..fd6840f8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "binance", - "version": "3.6.11", + "version": "3.6.12", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "binance", - "version": "3.6.11", + "version": "3.6.12", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 8a779399..857926fc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "binance", - "version": "3.6.11", + "version": "3.6.12", "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 a03929a8..68e31ff6 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -870,7 +870,7 @@ export class MainClient extends BaseRestClient { getReferencePriceCalculation(params: { symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; }): Promise { return this.get('api/v3/referencePrice/calculation', params); } diff --git a/src/types/spot.ts b/src/types/spot.ts index 0112b71c..479d6970 100644 --- a/src/types/spot.ts +++ b/src/types/spot.ts @@ -698,7 +698,7 @@ export interface SpotExecutionRulesResponse { export interface SpotExecutionRulesParams { symbol?: string; symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; } /** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ diff --git a/src/types/websockets/ws-api-requests.ts b/src/types/websockets/ws-api-requests.ts index 78714cd4..ed2cf346 100644 --- a/src/types/websockets/ws-api-requests.ts +++ b/src/types/websockets/ws-api-requests.ts @@ -103,7 +103,7 @@ export interface WSAPIAvgPriceRequest { export interface WSAPIExecutionRulesRequest { symbol?: string; symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; } export interface WSAPIReferencePriceRequest { @@ -112,7 +112,7 @@ export interface WSAPIReferencePriceRequest { export interface WSAPIReferencePriceCalculationRequest { symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; } /** diff --git a/test/spot/symbolStatus.test.ts b/test/spot/symbolStatus.test.ts new file mode 100644 index 00000000..0138871a --- /dev/null +++ b/test/spot/symbolStatus.test.ts @@ -0,0 +1,68 @@ +import { MainClient, WebsocketAPIClient } from '../../src/index'; +import { WS_KEY_MAP } from '../../src/util/websockets/websocket-util'; + +describe.each(['TRADING', 'HALT', 'BREAK', 'CANCEL_ONLY', undefined] as const)( + 'Spot symbolStatus filter: %s', + (symbolStatus) => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('forwards the REST execution rules filter', async () => { + const client = new MainClient(); + const getSpy = jest.spyOn(client, 'get').mockResolvedValue({}); + + await client.getExecutionRules({ symbolStatus }); + + expect(getSpy).toHaveBeenCalledWith('api/v3/executionRules', { + symbolStatus, + }); + }); + + it('forwards the REST reference price calculation filter', async () => { + const client = new MainClient(); + const getSpy = jest.spyOn(client, 'get').mockResolvedValue({}); + const params = { symbol: 'BTCUSDT', symbolStatus }; + + await client.getReferencePriceCalculation(params); + + expect(getSpy).toHaveBeenCalledWith( + 'api/v3/referencePrice/calculation', + params, + ); + }); + + it('forwards the WebSocket execution rules filter without authentication', async () => { + const client = new WebsocketAPIClient(); + const sendSpy = jest + .spyOn(client.getWSClient(), 'sendWSAPIRequest') + .mockResolvedValue({}); + + await client.getSpotExecutionRules({ symbolStatus }); + + expect(sendSpy).toHaveBeenCalledWith( + WS_KEY_MAP.mainWSAPI, + 'executionRules', + { symbolStatus }, + { authIsOptional: true }, + ); + }); + + it('forwards the WebSocket reference price calculation filter without authentication', async () => { + const client = new WebsocketAPIClient(); + const sendSpy = jest + .spyOn(client.getWSClient(), 'sendWSAPIRequest') + .mockResolvedValue({}); + const params = { symbol: 'BTCUSDT', symbolStatus }; + + await client.getSpotReferencePriceCalculation(params); + + expect(sendSpy).toHaveBeenCalledWith( + WS_KEY_MAP.mainWSAPI, + 'referencePrice.calculation', + params, + { authIsOptional: true }, + ); + }); + }, +); From 62ef65f9e5dba8fc5ef1bc45ff90a70eb87688d9 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 2 Nov 2026 11:33:56 +0100 Subject: [PATCH 2/6] chore: regenerate endpoint docs and examples --- llms.txt | 8431 +++++++++++++++++++++++++++--------------------------- 1 file changed, 4217 insertions(+), 4214 deletions(-) diff --git a/llms.txt b/llms.txt index 8bd28118..c1b43c25 100644 --- a/llms.txt +++ b/llms.txt @@ -1762,2428 +1762,2429 @@ const optionsExpiration = '260128'; // YYMMDD // wsClient.subscribeContractInfoStream('coinm'); ================ -File: examples/WebSockets/WS-API/ws-api-client.ts +File: examples/WebSockets/Public/ws-usdm-market.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -// or -// import { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } from 'binance'; -// or -// const { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } = require('binance'); -⋮---- -import { DefaultLogger, WebsocketAPIClient } from '../../../src'; +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- -/** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. - */ +// or, with the npm package +/* +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from 'binance'; +*/ ⋮---- -// returned by binance, generated using the publicKey (above) -// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; -// Your Ed25519 private key is passed as the "secret" -// const secret = privateKey; +// Without typescript: +// const logger = { ⋮---- -// function attachEventHandlers( -// wsClient: TWSClient, -// ): void { -// /** -// * General event handlers for monitoring the WebsocketClient -// */ -// wsClient.on('message', (data) => { -// // console.log('raw message received ', JSON.stringify(data)); -// }); -// wsClient.on('response', (data) => { -// // console.log('ws response: ', JSON.stringify(data)); -// }); -// wsClient.on('open', (data) => { -// console.log('ws connected', data.wsKey); -// }); -// wsClient.on('reconnecting', ({ wsKey }) => { -// console.log('ws automatically reconnecting.... ', wsKey); -// }); -// wsClient.on('reconnected', (data) => { -// console.log('ws has reconnected ', data?.wsKey); -// }); -// wsClient.on('authenticated', (data) => { -// console.log('ws has authenticated ', data?.wsKey); -// }); -// wsClient.on('exception', (data) => { -// console.error('ws exception: ', JSON.stringify(data)); -// }); +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; // } ⋮---- -async function main() +// Optional: when enabled, the SDK will try to format incoming data into more readable objects. +// Beautified data is emitted via the "formattedMessage" event ⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: -// trace: (...params) => console.log(new Date(), 'trace', ...params), +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -// Enforce testnet ws connections, regardless of supplied wsKey -// testnet: true, +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -// Note: unless you set this to false, the SDK will automatically call -// the `subscribeUserDataStream()` method again if reconnected (if you called it before): -// resubscribeUserDataStreamAfterReconnect: true, +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: -// attachEventListeners: false +// console.log('log rawMessage: ', data); ⋮---- -// Optional, attach basic event handlers, so nothing is left unhandled -// attachEventHandlers(wsClient.getWSClient()); +// Formatted data that has gone through the beautifier ⋮---- -// Optional, if you see RECV Window errors, you can use this to manage time issues. -// ! However, make sure you sync your system clock first! -// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow -// wsClient.setTimeOffsetMs(-5000); +// console.log('log formattedMessage: ', data); ⋮---- -// Optional. Can be used to prepare a connection before sending commands. -// Can be done as part of a bootstrapping workflow, to reduce initial latency when sending the first command -// await wsClient.getWSClient().connectWSAPI(WS_KEY_MAP.mainWSAPI); +/** + * Optional: we've included type-guards for many formatted websocket topics. + * + * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). + */ +// if (isWsAggTradeFormatted(data)) { +// console.log('log agg trade: ', data); +// return; +// } ⋮---- -// SPOT - Market data requests +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -// SPOT - Trading requests +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -// SPOT - Account requests +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -// FUTURES - Market data requests +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -// FUTURES - Trading requests +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -// FUTURES - Account requests +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -// Start executing the example workflow - -================ -File: examples/WebSockets/WS-API/ws-api-raw-promises.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - DefaultLogger, - WebsocketClient, - WS_KEY_MAP, - WSAPIWsKey, -} from '../../../src/index'; +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClient, WSAPIWsKey } from 'binance'; +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -// testnet: true, +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- -logger, // Optional: inject a custom logger +/** + * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. + * + * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. + * + * The WsKey is a reference to the connection that this topic should be routed to. + * WS_KEY_MAP is a complete enum with all the available WsKey values. + * + * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data + */ +⋮---- +// Uses the regular market feeds WS URL dedicated to USDM Futures: wss://fstream.binance.com/market/stream ⋮---- /** - * General event handlers for monitoring the WebsocketClient - */ + * Subscribe to each available type of USDM Derivatives market topic, the new way + */ ⋮---- -// WS API responses can be processed here too, but that is optional -// console.log('ws response: ', JSON.stringify(data)); +// Aggregate Trade Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams ⋮---- -async function main() +// Mark Price Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream ⋮---- -/** - * - * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send - * your first command. That connection will then be reused for every command you send, unless the connection drops - then - * it will automatically be replaced with a healthy connection. - * - * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection - * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands (using the connectWSAPI() method shown below). This is optional. - * - */ +// Mark Price Stream for All market +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market ⋮---- -/** - * Websockets (with their unique URLs) are tracked using the concept of a "WsKey". - * - * This WsKey identifies the "main" WS API connection URL (e.g. for spot & margin markets): - * wss://ws-api.binance.com:443/ws-api/v3 - * - * Other notable keys: - * - mainWSAPI2: alternative for "main" - * - mainWSAPITestnet: "main" testnet - * - usdmWSAPI: usdm futures - * - usdmWSAPITestnet: usdm futures testnet - * - coinmWSAPI: coinm futures - * - coinmWSAPITestnet: coinm futures testnet - */ +// Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams ⋮---- -// Note: if you set "testnet: true" in the config, this will automatically resolve to WS_KEY_MAP.mainWSAPITestnet (you can keep using mainWSAPI). +// Continuous Contract Kline/Candlestick Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams +'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER ⋮---- -// Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! -// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow -// wsClient.setTimeOffsetMs(-5000); +// Individual Symbol Mini Ticker Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream +'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE ⋮---- -// Optional, see above. Can be used to prepare a connection before sending commands. This is not required and will happen automatically -// await wsClient.connectWSAPI(WS_API_WS_KEY); +// All Market Mini Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream +'!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD ⋮---- -// rateLimits: wsAPIResponse.result.rateLimits, -// symbols: wsAPIResponse.result.symbols, +// Individual Symbol Ticker Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams ⋮---- -// Start executing the example workflow - -================ -File: src/index.ts -================ - - -================ -File: .gitignore -================ -.vscode/ -.idea/ -.nyc_output/ -node_modules/ -util/config.js -coverage/ -yarn-error.log -lib/* -testfile.ts -privaterepotracker -restClientRegex.ts -.DS_Store -dist -localtest.ts -repomix.sh -doc -*.pem - -================ -File: .jshintrc -================ -{ - "esversion": 8, - "asi": true, - "laxbreak": true, - "predef": [ "-Promise" ] -} - -================ -File: .npmignore -================ -.gitignore -coverage/ -test/ -util/ -.vscode/ -.eslintrc.js -.travis.yml -.mocharc.json -.prettierrc - -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" -} - -================ -File: CHANGELOG.md -================ -# Binance API - -## 2.0.14 -- Update values thrown by exception parser. - -## 2.0.13 -- Expose time sync offset getter/setter in base client. `getTimeOffset()/setTimeOffest(value)`. -- Add handler to signMessage method, falling back to browser equivalent if method is not a function (react/preact/#141). - -## 2.0.12 -- Increase default timeout for websocket pong heartbeats to 7500ms. - -## 2.0.11 -- Fix APIs that use the DELETE method. - -## 2.0.9-10 -- Fix typo in websocket types. -- Fix missing type properties for ws messages. - -## 2.0.8 -- Emit `reconnected` events for reconnected user data stream. - -## 2.0.6 -- Fix symbol & margin asset types for futures user data updated position event. - -## 2.0.5 -- Refine types for user data websocket events (futures) - -## 2.0.4 -- Disable 'silly' logger category by default to reduce ping/pong noise. -- Expand ws support to other API categories. -- Expand beautifier support for other WS messages. - -## 2.0.3 -- Expand main-client APIs. -- Expand usdm-client APIs. - -## 2.0.2 -- Fix getAccountInformation main endpoint. -- Fix a few missing APIs. -- Refactor SpotClient->MainClient. SpotClient will be deprecated in future (MainClient is the same, just a different name). -- Fix build errors from incorrect module imports. - -## 2.0.0 - -- Introduction for typescript with strong types on most request parameters & responses. - - NPM package includes transpiled framework & type declarations. - - Supports both typescript and vanilla node.js projects. - - REST requests and responses include detailed types, though some may still be missing. - - Raw and beautified WS events include detailed types, though some may still be missing. -- Introduction for webpack. - - To generate a browser bundle clone & build the library then run webpack using `npm run pack`. -- Introduction for integration tests via jest on all REST clients. - - Tests are executed automatically to avoid unintended breaking changes on release. - - Real API calls are made to validate integration. -- Complete networking overhaul using [axios](https://github.com/axios/axios). - - Small & modern framework. Significant reduction in dependencies via deprecation of `request`. - - Support for proxies and [other axios-supported functionality](https://github.com/axios/axios#request-config). - - Support for backend (node) and frontend (browser) requests. -- Complete overhaul in websockets client. - - Websocket events are still (optionally) beautified consistently with how the previous library worked. - - New event-driven architecture. - - Support for USDM Futures. More to come in a future release. - - Automatic connection monitoring, with automatic reconnect if the connection goes stale. - - Automatic userData connection monitoring, with automatic refresh and respawn if previous listen key expires or the connection closes unexpectedly. -- Complete overhaul in REST client. - - Revamped spot client (see [spot-client](./src/spot-client.ts)). - - Introduction of [usdm-client](./src/usdm-client.ts) for USDM Futures. -- Passive tracking & storage of API limit states (IP request weight & order weight). - - Parsed automatically via response headers when any request is made, if header is detected. - - See `getRateLimitStates()` to query the last seen weights on any of the REST clients. -- Smarter time-sync to handle common recvWindow latency issues (optional, default on). - -### 2.0.0-beta.4 - -- Breaking change: refactor most options to camel case (instead of underscore separation). -- Add optional beautifier support for REST responses (parses known numbers stored as strings into numbers). - -### 2.0.0-beta.5-8 - -- Breaking change: refactor spot getAllCoinsInformation to getBalances(). -- Fix POST request format to www-form-urlencoded. - - - - - -================ -File: eslint.config.cjs -================ - - -================ -File: index.js -================ - +// All Market Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream +'!ticker@arr', // DOESNT EXIST AS TYPE GUARD +⋮---- +// Liquidation Order Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams +⋮---- +// Liquidation Order Stream for All market +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams +⋮---- +// Composite Index Symbol Information Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams +⋮---- +'btcusdt@compositeIndex', // DOESNT EXIST AS TYPE GUARD +// Contract Info Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream +'!contractInfo', // DOESNT EXIST AS TYPE GUARD +⋮---- +// Multi-Assets Mode Asset Index Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index +'!assetIndex@arr', // DOESNT EXIST AS TYPE GUARD +⋮---- +// /** +// * +// * For those that used the Node.js Binance SDK before the v3 release, you can +// * still subscribe to available market topics the "old" way, for convenience +// * when migrating from the old WebsocketClient to the new multiplex client): +// * +// */ +⋮---- +// wsClient.subscribeAggregateTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(symbol, 'spot'); +// wsClient.subscribeTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(coinMSymbol, 'coinm'); +// wsClient.subscribeCoinIndexPrice(coinMSymbol2); +// wsClient.subscribeAllBookTickers('usdm'); +// wsClient.subscribeSpotKline(symbol, '1m'); +// wsClient.subscribeMarkPrice(symbol, 'usdm'); +// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMarketMarkPrice('usdm'); +// wsClient.subscribeAllMarketMarkPrice('coinm'); +// wsClient.subscribeKlines(symbol, '1m', 'usdm'); +// wsClient.subscribeContinuousContractKlines( +// symbol, +// 'perpetual', +// '1m', +// 'usdm', +// ); +// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); +// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMini24hrTickers('spot'); +// wsClient.subscribeAllMini24hrTickers('usdm'); +// wsClient.subscribeAllMini24hrTickers('coinm'); +// wsClient.subscribeAll24hrTickers('spot'); +// wsClient.subscribeAll24hrTickers('usdm'); +// wsClient.subscribeAll24hrTickers('coinm'); +// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); +// wsClient.subscribeAllLiquidationOrders('usdm'); +// wsClient.subscribeAllLiquidationOrders('coinm'); +// wsClient.subscribeSpotSymbol24hrTicker(symbol); +// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); +// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); +// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); +// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); +// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); +// wsClient.subscribeContractInfoStream('usdm'); +// wsClient.subscribeContractInfoStream('coinm'); ================ -File: jest.config.ts +File: examples/WebSockets/Public/ws-usdm-public.ts ================ -/** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from '../../../src'; ⋮---- -import type { Config } from 'jest'; +// or, with the npm package +/* +import { + DefaultLogger, + isWsDiffBookDepthEventFormatted, + isWsPartialBookDepthEventFormatted, + WebsocketClient, + WS_KEY_MAP, +} from 'binance'; +*/ ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +// Without typescript: +// const logger = { ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +// A simple way to suppress heartbeats but receive all other traces +// if (params[0].includes('ping') || params[0].includes('pong')) { +// return; +// } ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +// Optional: when enabled, the SDK will try to format incoming data into more readable objects. +// Beautified data is emitted via the "formattedMessage" event ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- -// Indicates whether the coverage information should be collected while executing the test +// Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +// console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- -// The directory where Jest should output its coverage files +// console.log('log rawMessage: ', data); ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +// Formatted data that has gone through the beautifier ⋮---- -// Indicates which provider should be used to instrument code for coverage +// console.log('log formattedMessage: ', data); ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +/** + * Optional: we've included type-guards for many formatted websocket topics. + * + * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). + */ +// if (isWsAggTradeFormatted(data)) { +// console.log('log agg trade: ', data); +// return; +// } ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +// // For one symbol +// if (isWsFormattedMarkPriceUpdateEvent(data)) { +// console.log('log mark price: ', data); +// return; +// } ⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, +// // for many symbols +// if (isWsFormattedMarkPriceUpdateArray(data)) { +// console.log('log mark prices: ', data); +// return; +// } ⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, +// if (isWsFormattedKline(data)) { +// console.log('log kline: ', data); +// return; +// } ⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, +// if (isWsFormattedTrade(data)) { +// return console.log('log trade: ', data); +// } ⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], +// if (isWsFormattedForceOrder(data)) { +// return console.log('log force order: ', data); +// } ⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, +// if (isWsFormatted24hrTickerArray(data)) { +// return console.log('log 24hr ticker array: ', data); +// } ⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, +// if (isWsFormattedRollingWindowTickerArray(data)) { +// return console.log('log rolling window ticker array: ', data); +// } ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +// if (isWsFormatted24hrTicker(data)) { +// return console.log('log 24hr ticker: ', data); +// } ⋮---- -// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. -// maxWorkers: "50%", +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +// No action needed here, unless you need to query the REST API after being reconnected. ⋮---- -// An array of file extensions your modules use -// moduleFileExtensions: [ -// "js", -// "mjs", -// "cjs", -// "jsx", -// "ts", -// "tsx", -// "json", -// "node" -// ], +/** + * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. + * + * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. + * + * The WsKey is a reference to the connection that this topic should be routed to. + * WS_KEY_MAP is a complete enum with all the available WsKey values. + * + * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data + */ ⋮---- -// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module -// moduleNameMapper: {}, +// Uses the high-frequency order book & core public feeds WS URL dedicated to USDM Futures: +// wss://fstream.binance.com/public/stream ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +/** + * Subscribe to each available type of USDM Derivatives market topic, the new way + */ ⋮---- -// Activates notifications for test results -// notify: false, +// Individual Symbol Book Ticker Streams +// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +// All Book Tickers Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream +'!bookTicker', // DOESNT EXIST AS TYPE GUARD +// Partial Book Depth Streams +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams ⋮---- -// A preset that is used as a base for Jest's configuration -// preset: undefined, +// Diff. Book Depth Stream +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams ⋮---- -// Run tests from one or more projects -// projects: undefined, +// /** +// * +// * For those that used the Node.js Binance SDK before the v3 release, you can +// * still subscribe to available market topics the "old" way, for convenience +// * when migrating from the old WebsocketClient to the new multiplex client): +// * +// */ ⋮---- -// Use this configuration option to add custom reporters to Jest -// reporters: undefined, +// wsClient.subscribeAggregateTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(symbol, 'spot'); +// wsClient.subscribeTrades(symbol, 'usdm'); +// wsClient.subscribeTrades(coinMSymbol, 'coinm'); +// wsClient.subscribeCoinIndexPrice(coinMSymbol2); +// wsClient.subscribeAllBookTickers('usdm'); +// wsClient.subscribeSpotKline(symbol, '1m'); +// wsClient.subscribeMarkPrice(symbol, 'usdm'); +// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMarketMarkPrice('usdm'); +// wsClient.subscribeAllMarketMarkPrice('coinm'); +// wsClient.subscribeKlines(symbol, '1m', 'usdm'); +// wsClient.subscribeContinuousContractKlines( +// symbol, +// 'perpetual', +// '1m', +// 'usdm', +// ); +// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); +// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 +// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); +// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); +// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); +// wsClient.subscribeAllMini24hrTickers('spot'); +// wsClient.subscribeAllMini24hrTickers('usdm'); +// wsClient.subscribeAllMini24hrTickers('coinm'); +// wsClient.subscribeAll24hrTickers('spot'); +// wsClient.subscribeAll24hrTickers('usdm'); +// wsClient.subscribeAll24hrTickers('coinm'); +// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); +// wsClient.subscribeAllLiquidationOrders('usdm'); +// wsClient.subscribeAllLiquidationOrders('coinm'); +// wsClient.subscribeSpotSymbol24hrTicker(symbol); +// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); +// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); +// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); +// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); +// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); +// wsClient.subscribeContractInfoStream('usdm'); +// wsClient.subscribeContractInfoStream('coinm'); + +================ +File: examples/WebSockets/WS-API/ws-api-client.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +// or +// import { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } from 'binance'; +// or +// const { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } = require('binance'); ⋮---- -// Automatically reset mock state before every test -// resetMocks: false, +import { DefaultLogger, WebsocketAPIClient } from '../../../src'; ⋮---- -// Reset the module registry before running each individual test -// resetModules: false, +/** + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. + */ ⋮---- -// A path to a custom resolver -// resolver: undefined, +// returned by binance, generated using the publicKey (above) +// const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; +// Your Ed25519 private key is passed as the "secret" +// const secret = privateKey; ⋮---- -// Automatically restore mock state and implementation before every test -// restoreMocks: false, +// function attachEventHandlers( +// wsClient: TWSClient, +// ): void { +// /** +// * General event handlers for monitoring the WebsocketClient +// */ +// wsClient.on('message', (data) => { +// // console.log('raw message received ', JSON.stringify(data)); +// }); +// wsClient.on('response', (data) => { +// // console.log('ws response: ', JSON.stringify(data)); +// }); +// wsClient.on('open', (data) => { +// console.log('ws connected', data.wsKey); +// }); +// wsClient.on('reconnecting', ({ wsKey }) => { +// console.log('ws automatically reconnecting.... ', wsKey); +// }); +// wsClient.on('reconnected', (data) => { +// console.log('ws has reconnected ', data?.wsKey); +// }); +// wsClient.on('authenticated', (data) => { +// console.log('ws has authenticated ', data?.wsKey); +// }); +// wsClient.on('exception', (data) => { +// console.error('ws exception: ', JSON.stringify(data)); +// }); +// } ⋮---- -// The root directory that Jest should scan for tests and modules within -// rootDir: undefined, +async function main() ⋮---- -// A list of paths to directories that Jest should use to search for files in -// roots: [ -// "" -// ], +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: +// trace: (...params) => console.log(new Date(), 'trace', ...params), ⋮---- -// Allows you to use a custom runner instead of Jest's default test runner -// runner: "jest-runner", +// Enforce testnet ws connections, regardless of supplied wsKey +// testnet: true, ⋮---- -// The paths to modules that run some code to configure or set up the testing environment before each test -// setupFiles: [], +// Note: unless you set this to false, the SDK will automatically call +// the `subscribeUserDataStream()` method again if reconnected (if you called it before): +// resubscribeUserDataStreamAfterReconnect: true, ⋮---- -// A list of paths to modules that run some code to configure or set up the testing framework before each test -// setupFilesAfterEnv: [], +// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: +// attachEventListeners: false ⋮---- -// The number of seconds after which a test is considered as slow and reported as such in the results. -// slowTestThreshold: 5, +// Optional, attach basic event handlers, so nothing is left unhandled +// attachEventHandlers(wsClient.getWSClient()); ⋮---- -// A list of paths to snapshot serializer modules Jest should use for snapshot testing -// snapshotSerializers: [], +// Optional, if you see RECV Window errors, you can use this to manage time issues. +// ! However, make sure you sync your system clock first! +// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow +// wsClient.setTimeOffsetMs(-5000); ⋮---- -// The test environment that will be used for testing -// testEnvironment: "jest-environment-node", +// Optional. Can be used to prepare a connection before sending commands. +// Can be done as part of a bootstrapping workflow, to reduce initial latency when sending the first command +// await wsClient.getWSClient().connectWSAPI(WS_KEY_MAP.mainWSAPI); ⋮---- -// Options that will be passed to the testEnvironment -// testEnvironmentOptions: {}, +// SPOT - Market data requests ⋮---- -// Adds a location field to test results -// testLocationInResults: false, +// SPOT - Trading requests ⋮---- -// The glob patterns Jest uses to detect test files +// SPOT - Account requests ⋮---- -// "**/__tests__/**/*.[jt]s?(x)", +// FUTURES - Market data requests ⋮---- -// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped -// testPathIgnorePatterns: [ -// "/node_modules/" -// ], +// FUTURES - Trading requests ⋮---- -// The regexp pattern or array of patterns that Jest uses to detect test files -// testRegex: [], +// FUTURES - Account requests ⋮---- -// This option allows the use of a custom results processor -// testResultsProcessor: undefined, +// Start executing the example workflow + +================ +File: examples/WebSockets/WS-API/ws-api-raw-promises.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + DefaultLogger, + WebsocketClient, + WS_KEY_MAP, + WSAPIWsKey, +} from '../../../src/index'; ⋮---- -// This option allows use of a custom test runner -// testRunner: "jest-circus/runner", +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClient, WSAPIWsKey } from 'binance'; ⋮---- -// A map from regular expressions to paths to transformers -// transform: undefined, +// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: ⋮---- -// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation -// transformIgnorePatterns: [ -// "/node_modules/", -// "\\.pnp\\.[^\\/]+$" -// ], +// testnet: true, ⋮---- -// Prevents import esm module error from v1 axios release, issue #5026 +logger, // Optional: inject a custom logger ⋮---- -// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them -// unmockedModulePathPatterns: undefined, +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -// Indicates whether each individual test should be reported during the run -// verbose: undefined, -verbose: true, // report individual test +// WS API responses can be processed here too, but that is optional +// console.log('ws response: ', JSON.stringify(data)); ⋮---- -// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode -// watchPathIgnorePatterns: [], +async function main() ⋮---- -// Whether to use watchman for file crawling -// watchman: true, +/** + * + * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send + * your first command. That connection will then be reused for every command you send, unless the connection drops - then + * it will automatically be replaced with a healthy connection. + * + * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection + * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands (using the connectWSAPI() method shown below). This is optional. + * + */ +⋮---- +/** + * Websockets (with their unique URLs) are tracked using the concept of a "WsKey". + * + * This WsKey identifies the "main" WS API connection URL (e.g. for spot & margin markets): + * wss://ws-api.binance.com:443/ws-api/v3 + * + * Other notable keys: + * - mainWSAPI2: alternative for "main" + * - mainWSAPITestnet: "main" testnet + * - usdmWSAPI: usdm futures + * - usdmWSAPITestnet: usdm futures testnet + * - coinmWSAPI: coinm futures + * - coinmWSAPITestnet: coinm futures testnet + */ +⋮---- +// Note: if you set "testnet: true" in the config, this will automatically resolve to WS_KEY_MAP.mainWSAPITestnet (you can keep using mainWSAPI). +⋮---- +// Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! +// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow +// wsClient.setTimeOffsetMs(-5000); +⋮---- +// Optional, see above. Can be used to prepare a connection before sending commands. This is not required and will happen automatically +// await wsClient.connectWSAPI(WS_API_WS_KEY); +⋮---- +// rateLimits: wsAPIResponse.result.rateLimits, +// symbols: wsAPIResponse.result.symbols, +⋮---- +// Start executing the example workflow ================ -File: jsconfig.json +File: examples/WebSockets/README.md ================ -{ - "compilerOptions": { - "target": "ES6", - "module": "commonjs" - }, - "exclude": [ - "node_modules", - "**/node_modules/*", - "coverage", - "doc" - ] -} +# Binance WebSocket Streams -================ -File: LICENSE.md -================ -Copyright 2025 Tiago Siebler +This Node.js, JavaScript & TypeScript SDK for Binance has complete support for all available WebSocket capabilities of Binance's API offering. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +## Capabilities -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +These WebSocket capabilities are split into two key groups: -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +1. WebSocket Consumers: + - Subscribe to market data & receive realtime updates. + - Subscribe to private account data & receive realtime updates (generally called the user data stream). +2. WebSocket API: + - Send requests & commands over a persistent WebSocket (WSAPI) connection. E.g. Submit an order. + - Subscribe to private account data & receive realtime updates (generally called the user data stream), over a persistent WebSocket (WSAPI) connection. Note: + - This was previously available without the WebSocket API, via a mechanic involving a temporary listenKey. + - In recent updates, the WebSocket API supports subscribing to the user data stream (private updates). + - In some cases, this is the only way to subsrcibe to the user data stream (e.g. in Spot markets). + +## Architecture + +### WebsocketClient + +This SDK has all WebSocket capabilities integrated in the dedicated class called the `WebsocketClient`. This can be imported from the package directly. This all-in-one class handles all aspects of Binance's WebSocket capabilities, across all subdomains & endpoints. It also includes the raw capabilities to support integration with the WebSocket API. Subscriptions, heartbeats and connection recovery after disconnect - these are all included automatically. + +If the answer to any of these is yes, you should be using the WebsocketClient: + +- You want to subscribe to & receive realtime updates for public market data. +- You want raw control over how & where WebSocket API commands are sent. + +If you are looking for a more convenient integration with Binance's WebSocket API, you should look at the `WebsocketAPIClient`. + +### WebsocketAPIClient + +This is a utility class built over the WebsocketClient to especially provide a more convenient way of using Binance's WebSocket API. While WebSockets are asynchronous by design, the WebsocketAPIClient provides a way to send WebSocket API commands and await the result. All commands are wrapped in a promise and internal event tracking ensures promises are resolved or rejected as part of the command life cycle. + +This utility class in this SDK allows you to integrate the WebSocket API in the same way that you would integrate a REST API. Make a request and await the result. + +As of early 2026, some of the user data streams are also only available via the WebSocket API streams. This has been integrated into the WebsocketAPIClient and is available with a number of user data methods, depending on the product group. Some references: + +- Spot: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` +- Margin: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.marginUserData)` +- USDM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.usdmWSAPI)` +- CoinM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.coinmWSAPI)` + +## Key Features + +### Base URL Split & Migration + +On 06/03/2026, Binance announced a routing upgrade to their USDM Futures WebSocket System, titled: "Binance USDⓈ-M Futures WebSocket System Upgrade Notice (2026-03-06)". + +#### Key Highlights: + +- Introduction of three dedicated WebSocket base URLs: + - Public (high-frequency public market data) + - wss://fstream.binance.com/public + - Market (regular market data) + - wss://fstream.binance.com/market + - Private (user data streams) + - wss://fstream.binance.com/private +- New endpoints are supported immediately upon this announcement. +- Legacy WebSocket URLs will be permanently retired on 2026-04-23. +- Documentation including endpoint & stream mapping: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data + +#### Binance JavaScript SDK Support + +All three dedicated WebSocket base URLs are supported. Each with their own unique WsKey, used to track each unique connection. + +Continue to subscribe to market data as before with the dedicated subscribe method, but ensure to provide the connection key depending on the type of market data you are consuming. + +Minimal examples: + +```typescript +// ... + +// For public (high-frequency public data) +const wsKeyUsdmPublic = WS_KEY_MAP.usdmPublic; +wsClient.subscribe(['btcusdt@bookTicker', 'btcusdt@depth'], wsKeyUsdmPublic); + +// For market (regular market data) +const wsKeyUsdmMarket = WS_KEY_MAP.usdmMarket; +wsClient.subscribe(['btcusdt@aggTrade', 'btcusdt@forceOrder'], wsKeyUsdmMarket); + +// For user data, continue using the subscribe user data stream method as before. +// The SDK will automatically route to the "private" endpoint for USDM Futures: +wsClient.subscribeUsdFuturesUserDataStream(); +``` + +#### Legacy `wsClient.subscribe*()` methods + +If you're using any of the per-topic convenience methods, such as `wsClient.subscribeAggregateTrades(...)`, no change is required. The SDK will automatically route the topic subscription request to the appropriate WS URL. + +## Further Reading + +For detailed examples, refer to the examples in this folder, as well as the following documentation: + +- Binance JavaScript SDK QuickStart Guide: https://siebly.io/sdk/binance/javascript +- Binance JavaScript SDK Readme: https://www.npmjs.com/package/binance ================ -File: tsconfig.build.json +File: src/index.ts +================ + + +================ +File: .jshintrc ================ { - "extends": "./tsconfig.json", - "exclude": [ - "node_modules", - "test", - "dist", - "**/*spec.ts", - "**/*test.ts", - "jest.config.ts" - ] + "esversion": 8, + "asi": true, + "laxbreak": true, + "predef": [ "-Promise" ] } ================ -File: tsconfig.json +File: .npmignore ================ -{ - "compileOnSave": true, - "compilerOptions": { - "allowJs": true, - "target": "es6", - "module": "commonjs", - "moduleResolution": "node", - "declaration": true, - "removeComments": false, - "noEmitOnError": true, - "noImplicitAny": false, - "strictNullChecks": true, - "skipLibCheck": true, - "sourceMap": true, - "esModuleInterop": true, - "lib": ["es2017", "dom"], - "baseUrl": ".", - "outDir": "lib" - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"] -} +.gitignore +coverage/ +test/ +util/ +.vscode/ +.eslintrc.js +.travis.yml +.mocharc.json +.prettierrc ================ -File: tsconfig.linting.json +File: .prettierrc ================ { - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "outDir": "dist/cjs", - "target": "esnext", - "rootDir": "../", - "allowJs": true - }, - "include": [ - "src/**/*.*", - "test/**/*.*", - "examples/**/*.*", - ".eslintrc.cjs", - "jest.config.ts", - "webpack/webpack.config.ts" - ] + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" } ================ -File: src/types/coin.ts +File: CHANGELOG.md ================ -import { FuturesContractType, PositionSide } from './futures'; -import { numberInString, OrderSide } from './shared'; +# Binance API + +## 2.0.14 +- Update values thrown by exception parser. + +## 2.0.13 +- Expose time sync offset getter/setter in base client. `getTimeOffset()/setTimeOffest(value)`. +- Add handler to signMessage method, falling back to browser equivalent if method is not a function (react/preact/#141). + +## 2.0.12 +- Increase default timeout for websocket pong heartbeats to 7500ms. + +## 2.0.11 +- Fix APIs that use the DELETE method. + +## 2.0.9-10 +- Fix typo in websocket types. +- Fix missing type properties for ws messages. + +## 2.0.8 +- Emit `reconnected` events for reconnected user data stream. + +## 2.0.6 +- Fix symbol & margin asset types for futures user data updated position event. + +## 2.0.5 +- Refine types for user data websocket events (futures) + +## 2.0.4 +- Disable 'silly' logger category by default to reduce ping/pong noise. +- Expand ws support to other API categories. +- Expand beautifier support for other WS messages. + +## 2.0.3 +- Expand main-client APIs. +- Expand usdm-client APIs. + +## 2.0.2 +- Fix getAccountInformation main endpoint. +- Fix a few missing APIs. +- Refactor SpotClient->MainClient. SpotClient will be deprecated in future (MainClient is the same, just a different name). +- Fix build errors from incorrect module imports. + +## 2.0.0 + +- Introduction for typescript with strong types on most request parameters & responses. + - NPM package includes transpiled framework & type declarations. + - Supports both typescript and vanilla node.js projects. + - REST requests and responses include detailed types, though some may still be missing. + - Raw and beautified WS events include detailed types, though some may still be missing. +- Introduction for webpack. + - To generate a browser bundle clone & build the library then run webpack using `npm run pack`. +- Introduction for integration tests via jest on all REST clients. + - Tests are executed automatically to avoid unintended breaking changes on release. + - Real API calls are made to validate integration. +- Complete networking overhaul using [axios](https://github.com/axios/axios). + - Small & modern framework. Significant reduction in dependencies via deprecation of `request`. + - Support for proxies and [other axios-supported functionality](https://github.com/axios/axios#request-config). + - Support for backend (node) and frontend (browser) requests. +- Complete overhaul in websockets client. + - Websocket events are still (optionally) beautified consistently with how the previous library worked. + - New event-driven architecture. + - Support for USDM Futures. More to come in a future release. + - Automatic connection monitoring, with automatic reconnect if the connection goes stale. + - Automatic userData connection monitoring, with automatic refresh and respawn if previous listen key expires or the connection closes unexpectedly. +- Complete overhaul in REST client. + - Revamped spot client (see [spot-client](./src/spot-client.ts)). + - Introduction of [usdm-client](./src/usdm-client.ts) for USDM Futures. +- Passive tracking & storage of API limit states (IP request weight & order weight). + - Parsed automatically via response headers when any request is made, if header is detected. + - See `getRateLimitStates()` to query the last seen weights on any of the REST clients. +- Smarter time-sync to handle common recvWindow latency issues (optional, default on). + +### 2.0.0-beta.4 + +- Breaking change: refactor most options to camel case (instead of underscore separation). +- Add optional beautifier support for REST responses (parses known numbers stored as strings into numbers). + +### 2.0.0-beta.5-8 + +- Breaking change: refactor spot getAllCoinsInformation to getBalances(). +- Fix POST request format to www-form-urlencoded. + + + + + +================ +File: eslint.config.cjs +================ + + +================ +File: index.js +================ + + +================ +File: jest.config.ts +================ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ ⋮---- -export interface PositionRisk { - symbol: string; - positionAmt: numberInString; - entryPrice: numberInString; - markPrice: numberInString; - unRealizedProfit: numberInString; - liquidationPrice: numberInString; - leverage: numberInString; - maxQty: numberInString; - marginType: string; - isolatedMargin: numberInString; - isAutoAddMargin: boolean; - positionSide: PositionSide; - updateTime: number; -} +import type { Config } from 'jest'; ⋮---- -export interface CoinMOpenInterest { - symbol: string; - pair: string; - openInterest: numberInString; - contractType: FuturesContractType; - time: number; -} -export type SymbolOrPair = - | { pair: string; symbol?: never } - | { pair?: never; symbol: string }; +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- -export interface CoinMSymbolOrderBookTicker { - symbol: string; - pair: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; -} +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, ⋮---- -export interface CoinMPaginatedRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- -export interface CoinMAccountTradeParamsWithPair extends CoinMPaginatedRequest { - pair: string; - symbol?: never; - fromId?: never; -} +// Automatically clear mock calls, instances, contexts and results before every test ⋮---- -export interface CoinMAccountTradeParamsWithSymbol - extends CoinMPaginatedRequest { - symbol: string; - pair?: never; -} +// Indicates whether the coverage information should be collected while executing the test ⋮---- -export interface CoinMAccountTradeParamsWithFromId - extends CoinMPaginatedRequest { - fromId: number; - startTime?: never; - endTime?: never; -} +// An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- -export type CoinMAccountTradeParams = - | CoinMAccountTradeParamsWithSymbol - | CoinMAccountTradeParamsWithPair - | CoinMAccountTradeParamsWithFromId; +// The directory where Jest should output its coverage files ⋮---- -export interface CoinMPositionTrade { - symbol: string; - id: number; - orderId: number; - pair: string; - side: OrderSide; - price: numberInString; - qty: numberInString; - realizedPnl: numberInString; - marginAsset: string; - baseQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - positionSide: PositionSide; - buyer: boolean; - maker: boolean; - quoteQty?: numberInString; -} +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -export interface FundingRate { - symbol: string; - adjustedFundingRateCap: string; - adjustedFundingRateFloor: string; - fundingIntervalHours: number; - disclaimer: boolean; -} +// Indicates which provider should be used to instrument code for coverage ⋮---- -export interface GetClassicPortfolioMarginNotionalLimitParams { - symbol?: string; - pair?: string; -} +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], ⋮---- -export interface ClassicPortfolioMarginNotionalLimit { - symbol: string; - pair: string; - notionalLimit: string; -} +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, ⋮---- -export interface ClassicPortfolioMarginAccount { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; -} +// A path to a custom dependency extractor +// dependencyExtractor: undefined, ⋮---- -export interface FuturesTransactionHistoryDownloadLink { - downloadId: string; - status: string; - url: string; - notified: boolean; - expirationTimestamp: number; - isExpired: boolean | null; -} - -================ -File: webpack/webpack.config.js -================ -function generateConfig(name) +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, ⋮---- -// Node.js core modules not available in browsers -// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], ⋮---- -// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, ⋮---- -// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. - -================ -File: .npmrc -================ -min-release-age=30 -save-exact=true - -================ -File: examples/Rest/Futures/rest-usdm-order-sl.ts -================ -import { FuturesNewAlgoOrderParams, USDMClient } from '../../../src/index'; +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, ⋮---- -// or -// import { FuturesNewAlgoOrderParams, USDMClient } from 'binance'; +// A set of global variables that need to be available in all test environments +// globals: {}, ⋮---- -async function start() +// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. +// maxWorkers: "50%", ⋮---- -// Hedge Mode example: find each open hedge position and replace its SL. - -================ -File: examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts -================ -// or -// import { -// DefaultLogger, -// isWsFormattedFuturesUserDataEvent, -// isWsFormattedSpotUserDataEvent, -// isWsFormattedSpotUserDataExecutionReport, -// isWsFormattedUserDataEvent, -// WebsocketClient, -// WsUserDataEvents, -// } from 'binance'; +// An array of directory names to be searched recursively up from the requiring module's location +// moduleDirectories: [ +// "node_modules" +// ], ⋮---- -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotUserDataEvent, - isWsFormattedSpotUserDataExecutionReport, - isWsFormattedUserDataEvent, - WebsocketClient, - WsConnectionStateEnum, - WsUserDataEvents, -} from '../../../src/index'; +// An array of file extensions your modules use +// moduleFileExtensions: [ +// "js", +// "mjs", +// "cjs", +// "jsx", +// "ts", +// "tsx", +// "json", +// "node" +// ], ⋮---- -// Optional, hook and customise logging behavior +// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module +// moduleNameMapper: {}, ⋮---- -// testnet: true, +// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader +// modulePathIgnorePatterns: [], ⋮---- -// wsClient.on('message', (data) => { -// console.log('raw message received ', JSON.stringify(data, null, 2)); -// }); +// Activates notifications for test results +// notify: false, ⋮---- -function onUserDataEvent(data: WsUserDataEvents) +// An enum that specifies notification mode. Requires { notify: true } +// notifyMode: "failure-change", ⋮---- -// the market denotes which API category it came from -// if (data.wsMarket.includes('spot')) { +// A preset that is used as a base for Jest's configuration +// preset: undefined, ⋮---- -// or use a type guard, if one exists (PRs welcome) +// Run tests from one or more projects +// projects: undefined, ⋮---- -// The wsKey can be parsed to determine the type of message (what websocket it came from) -// if (!Array.isArray(data) && data.wsKey.includes('userData')) { -// return onUserDataEvent(data); -// } +// Use this configuration option to add custom reporters to Jest +// reporters: undefined, ⋮---- -// or use a type guard if available +// Automatically reset mock state before every test +// resetMocks: false, ⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +// Reset the module registry before running each individual test +// resetModules: false, ⋮---- -// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: -// - fetch balances -// - fetch positions -// - fetch orders +// A path to a custom resolver +// resolver: undefined, ⋮---- -/** - * This example demonstrates subscribing to the user data stream via the - * listen key workflow. - * - * Note: the listen key workflow is deprecated for "spot" markets. Use the - * WebSocket API `userDataStream.subscribe` workflow instead (only available - * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. - * - * Each method below opens a dedicated WS connection attached to an automatically - * fetched listen key (a session for your user data stream). - * - * Once subscribed, you don't need to do anything else. Listen-key keep-alive, refresh, reconnects, etc are all automatically handled by the SDK. - */ +// Automatically restore mock state and implementation before every test +// restoreMocks: false, ⋮---- -/** - * Note: for spot markets, the listen key workflow is deprecated. Use the - * WebSocket API `userDataStream.subscribe` workflow instead (only available - * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. - */ -// Deprecated, see above: wsClient.subscribeSpotUserDataStream(); -// Deprecated, see above: wsClient.subscribeSpotUserDataStream('main2'); -// Deprecated, see above: wsClient.subscribeCrossMarginUserDataStream(); -// Deprecated, see above: wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDC'); +// The root directory that Jest should scan for tests and modules within +// rootDir: undefined, ⋮---- -/** - * Futures - */ +// A list of paths to directories that Jest should use to search for files in +// roots: [ +// "" +// ], ⋮---- -// Example 5: usdm futures +// Allows you to use a custom runner instead of Jest's default test runner +// runner: "jest-runner", ⋮---- -// Example 6: coinm futures +// The paths to modules that run some code to configure or set up the testing environment before each test +// setupFiles: [], ⋮---- -// Example 7: portfolio margin +// A list of paths to modules that run some code to configure or set up the testing framework before each test +// setupFilesAfterEnv: [], ⋮---- -// Example 8: portfolio margin pro +// The number of seconds after which a test is considered as slow and reported as such in the results. +// slowTestThreshold: 5, ⋮---- -// after 15 seconds, kill user data connections one by one (or all at once) +// A list of paths to snapshot serializer modules Jest should use for snapshot testing +// snapshotSerializers: [], ⋮---- -// console.log('killing all connections at once'); -// wsClient.closeAll(); +// The test environment that will be used for testing +// testEnvironment: "jest-environment-node", ⋮---- -// or: +// Options that will be passed to the testEnvironment +// testEnvironmentOptions: {}, ⋮---- -// console.log('killing all connections'); -// wsClient.closeAll(); -// Example 5: usdm futures +// Adds a location field to test results +// testLocationInResults: false, ⋮---- -// Example 6: coinm futures +// The glob patterns Jest uses to detect test files ⋮---- -// // Example 7: portfolio margin -// wsClient.unsubscribePortfolioMarginUserDataStream(); -// // Example 8: portfolio margin pro -// wsClient.unsubscribePortfolioMarginUserDataStream( -// 'portfolioMarginProUserData', -// ); +// "**/__tests__/**/*.[jt]s?(x)", ⋮---- -// after 20 seconds, list the remaining open connections - -================ -File: examples/WebSockets/Public/ws-usdm-market.ts -================ -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from '../../../src'; +// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped +// testPathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// or, with the npm package -/* -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from 'binance'; -*/ +// The regexp pattern or array of patterns that Jest uses to detect test files +// testRegex: [], ⋮---- -// Without typescript: -// const logger = { +// This option allows the use of a custom results processor +// testResultsProcessor: undefined, ⋮---- -// A simple way to suppress heartbeats but receive all other traces -// if (params[0].includes('ping') || params[0].includes('pong')) { -// return; -// } +// This option allows use of a custom test runner +// testRunner: "jest-circus/runner", ⋮---- -// Optional: when enabled, the SDK will try to format incoming data into more readable objects. -// Beautified data is emitted via the "formattedMessage" event +// A map from regular expressions to paths to transformers +// transform: undefined, ⋮---- -logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation +// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation +// transformIgnorePatterns: [ +// "/node_modules/", +// "\\.pnp\\.[^\\/]+$" +// ], ⋮---- -// Raw unprocessed incoming data, e.g. if you have the beautifier disabled +// Prevents import esm module error from v1 axios release, issue #5026 ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them +// unmockedModulePathPatterns: undefined, ⋮---- -// console.log('log rawMessage: ', data); +// Indicates whether each individual test should be reported during the run +// verbose: undefined, +verbose: true, // report individual test ⋮---- -// Formatted data that has gone through the beautifier +// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode +// watchPathIgnorePatterns: [], ⋮---- -// console.log('log formattedMessage: ', data); +// Whether to use watchman for file crawling +// watchman: true, + +================ +File: jsconfig.json +================ +{ + "compilerOptions": { + "target": "ES6", + "module": "commonjs" + }, + "exclude": [ + "node_modules", + "**/node_modules/*", + "coverage", + "doc" + ] +} + +================ +File: LICENSE.md +================ +Copyright 2025 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================ +File: tsconfig.build.json +================ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules", + "test", + "dist", + "**/*spec.ts", + "**/*test.ts", + "jest.config.ts" + ] +} + +================ +File: tsconfig.json +================ +{ + "compileOnSave": true, + "compilerOptions": { + "allowJs": true, + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "declaration": true, + "removeComments": false, + "noEmitOnError": true, + "noImplicitAny": false, + "strictNullChecks": true, + "skipLibCheck": true, + "sourceMap": true, + "esModuleInterop": true, + "lib": ["es2017", "dom"], + "baseUrl": ".", + "outDir": "lib" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"] +} + +================ +File: tsconfig.linting.json +================ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext", + "rootDir": "../", + "allowJs": true + }, + "include": [ + "src/**/*.*", + "test/**/*.*", + "examples/**/*.*", + ".eslintrc.cjs", + "jest.config.ts", + "webpack/webpack.config.ts" + ] +} + +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts +================ +// or +// import { +// DefaultLogger, +// isWsFormattedFuturesUserDataEvent, +// isWsFormattedSpotUserDataEvent, +// isWsFormattedSpotUserDataExecutionReport, +// isWsFormattedUserDataEvent, +// WebsocketClient, +// WsUserDataEvents, +// } from 'binance'; ⋮---- -/** - * Optional: we've included type-guards for many formatted websocket topics. - * - * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). - */ -// if (isWsAggTradeFormatted(data)) { -// console.log('log agg trade: ', data); -// return; -// } +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotUserDataEvent, + isWsFormattedSpotUserDataExecutionReport, + isWsFormattedUserDataEvent, + WebsocketClient, + WsConnectionStateEnum, + WsUserDataEvents, +} from '../../../src/index'; ⋮---- -// // For one symbol -// if (isWsFormattedMarkPriceUpdateEvent(data)) { -// console.log('log mark price: ', data); -// return; -// } +// Optional, hook and customise logging behavior ⋮---- -// // for many symbols -// if (isWsFormattedMarkPriceUpdateArray(data)) { -// console.log('log mark prices: ', data); -// return; -// } +// testnet: true, ⋮---- -// if (isWsFormattedKline(data)) { -// console.log('log kline: ', data); -// return; -// } +// wsClient.on('message', (data) => { +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// }); ⋮---- -// if (isWsFormattedTrade(data)) { -// return console.log('log trade: ', data); -// } +function onUserDataEvent(data: WsUserDataEvents) ⋮---- -// if (isWsFormattedForceOrder(data)) { -// return console.log('log force order: ', data); -// } +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { ⋮---- -// if (isWsFormatted24hrTickerArray(data)) { -// return console.log('log 24hr ticker array: ', data); -// } +// or use a type guard, if one exists (PRs welcome) ⋮---- -// if (isWsFormattedRollingWindowTickerArray(data)) { -// return console.log('log rolling window ticker array: ', data); +// The wsKey can be parsed to determine the type of message (what websocket it came from) +// if (!Array.isArray(data) && data.wsKey.includes('userData')) { +// return onUserDataEvent(data); // } ⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } +// or use a type guard if available ⋮---- // response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. +// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: +// - fetch balances +// - fetch positions +// - fetch orders ⋮---- /** - * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. - * - * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. - * - * The WsKey is a reference to the connection that this topic should be routed to. - * WS_KEY_MAP is a complete enum with all the available WsKey values. - * - * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data - */ + * This example demonstrates subscribing to the user data stream via the + * listen key workflow. + * + * Note: the listen key workflow is deprecated for "spot" markets. Use the + * WebSocket API `userDataStream.subscribe` workflow instead (only available + * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + * + * Each method below opens a dedicated WS connection attached to an automatically + * fetched listen key (a session for your user data stream). + * + * Once subscribed, you don't need to do anything else. Listen-key keep-alive, refresh, reconnects, etc are all automatically handled by the SDK. + */ ⋮---- -// Uses the regular market feeds WS URL dedicated to USDM Futures: wss://fstream.binance.com/market/stream +/** + * Note: for spot markets, the listen key workflow is deprecated. Use the + * WebSocket API `userDataStream.subscribe` workflow instead (only available + * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + */ +// Deprecated, see above: wsClient.subscribeSpotUserDataStream(); +// Deprecated, see above: wsClient.subscribeSpotUserDataStream('main2'); +// Deprecated, see above: wsClient.subscribeCrossMarginUserDataStream(); +// Deprecated, see above: wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDC'); ⋮---- /** - * Subscribe to each available type of USDM Derivatives market topic, the new way - */ + * Futures + */ ⋮---- -// Aggregate Trade Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams +// Example 5: usdm futures ⋮---- -// Mark Price Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream +// Example 6: coinm futures ⋮---- -// Mark Price Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market +// Example 7: portfolio margin ⋮---- -// Kline/Candlestick Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams +// Example 8: portfolio margin pro ⋮---- -// Continuous Contract Kline/Candlestick Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams -'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER +// after 15 seconds, kill user data connections one by one (or all at once) ⋮---- -// Individual Symbol Mini Ticker Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream -'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE +// console.log('killing all connections at once'); +// wsClient.closeAll(); ⋮---- -// All Market Mini Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream -'!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD -⋮---- -// Individual Symbol Ticker Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams -⋮---- -// All Market Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream -'!ticker@arr', // DOESNT EXIST AS TYPE GUARD -⋮---- -// Liquidation Order Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams -⋮---- -// Liquidation Order Stream for All market -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams -⋮---- -// Composite Index Symbol Information Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams -⋮---- -'btcusdt@compositeIndex', // DOESNT EXIST AS TYPE GUARD -// Contract Info Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream -'!contractInfo', // DOESNT EXIST AS TYPE GUARD +// or: ⋮---- -// Multi-Assets Mode Asset Index Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index -'!assetIndex@arr', // DOESNT EXIST AS TYPE GUARD +// console.log('killing all connections'); +// wsClient.closeAll(); +// Example 5: usdm futures ⋮---- -// /** -// * -// * For those that used the Node.js Binance SDK before the v3 release, you can -// * still subscribe to available market topics the "old" way, for convenience -// * when migrating from the old WebsocketClient to the new multiplex client): -// * -// */ +// Example 6: coinm futures ⋮---- -// wsClient.subscribeAggregateTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(symbol, 'spot'); -// wsClient.subscribeTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(coinMSymbol, 'coinm'); -// wsClient.subscribeCoinIndexPrice(coinMSymbol2); -// wsClient.subscribeAllBookTickers('usdm'); -// wsClient.subscribeSpotKline(symbol, '1m'); -// wsClient.subscribeMarkPrice(symbol, 'usdm'); -// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMarketMarkPrice('usdm'); -// wsClient.subscribeAllMarketMarkPrice('coinm'); -// wsClient.subscribeKlines(symbol, '1m', 'usdm'); -// wsClient.subscribeContinuousContractKlines( -// symbol, -// 'perpetual', -// '1m', -// 'usdm', +// // Example 7: portfolio margin +// wsClient.unsubscribePortfolioMarginUserDataStream(); +// // Example 8: portfolio margin pro +// wsClient.unsubscribePortfolioMarginUserDataStream( +// 'portfolioMarginProUserData', // ); -// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); -// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMini24hrTickers('spot'); -// wsClient.subscribeAllMini24hrTickers('usdm'); -// wsClient.subscribeAllMini24hrTickers('coinm'); -// wsClient.subscribeAll24hrTickers('spot'); -// wsClient.subscribeAll24hrTickers('usdm'); -// wsClient.subscribeAll24hrTickers('coinm'); -// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); -// wsClient.subscribeAllLiquidationOrders('usdm'); -// wsClient.subscribeAllLiquidationOrders('coinm'); -// wsClient.subscribeSpotSymbol24hrTicker(symbol); -// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); -// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); -// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); -// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); -// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); -// wsClient.subscribeContractInfoStream('usdm'); -// wsClient.subscribeContractInfoStream('coinm'); +⋮---- +// after 20 seconds, list the remaining open connections ================ -File: examples/WebSockets/Public/ws-usdm-public.ts +File: src/types/websockets/ws-general.ts ================ -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from '../../../src'; +import { AxiosRequestConfig } from 'axios'; +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; ⋮---- -// or, with the npm package -/* -import { - DefaultLogger, - isWsDiffBookDepthEventFormatted, - isWsPartialBookDepthEventFormatted, - WebsocketClient, - WS_KEY_MAP, -} from 'binance'; -*/ +import { RestClientOptions } from '../../util/requestUtils'; +import { WsKey } from '../../util/websockets/websocket-util'; ⋮---- -// Without typescript: -// const logger = { +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} ⋮---- -// A simple way to suppress heartbeats but receive all other traces -// if (params[0].includes('ping') || params[0].includes('pong')) { -// return; -// } +export function isMessageEvent(msg: unknown): msg is MessageEventLike ⋮---- -// Optional: when enabled, the SDK will try to format incoming data into more readable objects. -// Beautified data is emitted via the "formattedMessage" event +export type WsMarket = + | 'spot' + | 'spotTestnet' + | 'crossMargin' + | 'isolatedMargin' + | 'riskDataMargin' + | 'usdm' + | 'usdmTestnet' + | 'coinm' + | 'coinmTestnet' + | 'options' + | 'optionsTestnet' + | 'portfoliom' + | 'alpha'; ⋮---- -logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation +export interface WsSharedBase { + wsMarket: WsMarket; + wsKey: WsKey; + streamName: string; +} ⋮---- -// Raw unprocessed incoming data, e.g. if you have the beautifier disabled +export interface WsResponse { + type: 'message'; + data: { + result: boolean | string[] | null; + id: number; + isWSAPIResponse: boolean; + wsKey: WsKey; + }; +} ⋮---- -// console.log('raw message received ', JSON.stringify(data, null, 2)); +// Same as inverse futures +export type WsPublicInverseTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'klineV2'; ⋮---- -// console.log('log rawMessage: ', data); +export type WsPublicUSDTPerpTopic = + | 'orderBookL2_25' + | 'orderBookL2_200' + | 'trade' + | 'insurance' + | 'instrument_info' + | 'kline'; ⋮---- -// Formatted data that has gone through the beautifier +export type WsPublicSpotV1Topic = + | 'trade' + | 'realtimes' + | 'kline' + | 'mergedDepth' + | 'diffDepth'; ⋮---- -// console.log('log formattedMessage: ', data); +export type WsPublicSpotV2Topic = 'depth' | 'kline' | 'trade' | 'realtimes'; ⋮---- -/** - * Optional: we've included type-guards for many formatted websocket topics. - * - * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). - */ -// if (isWsAggTradeFormatted(data)) { -// console.log('log agg trade: ', data); -// return; -// } +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data +export type WsPublicUSDMTopic = 'bookTicker' | 'depth'; ⋮---- -// // For one symbol -// if (isWsFormattedMarkPriceUpdateEvent(data)) { -// console.log('log mark price: ', data); -// return; -// } +// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#market-regular-market-data +export type WsMarketUSDMTopic = + | 'aggTrade' + | 'markPrice' + | 'kline' + | 'continuousKline' + | 'miniTicker' + | 'ticker' + | 'forceOrder' + | 'compositeIndex' + | 'contractInfo' + | 'assetIndex'; ⋮---- -// // for many symbols -// if (isWsFormattedMarkPriceUpdateArray(data)) { -// console.log('log mark prices: ', data); -// return; -// } +export type WsPublicTopics = + | WsPublicInverseTopic + | WsPublicUSDTPerpTopic + | WsPublicSpotV1Topic + | WsPublicSpotV2Topic + | WsMarketUSDMTopic + | WsPublicUSDMTopic + | string; ⋮---- -// if (isWsFormattedKline(data)) { -// console.log('log kline: ', data); -// return; -// } +// Same as inverse futures +export type WsPrivateInverseTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order'; ⋮---- -// if (isWsFormattedTrade(data)) { -// return console.log('log trade: ', data); -// } +export type WsPrivateUSDTPerpTopic = + | 'position' + | 'execution' + | 'order' + | 'stop_order' + | 'wallet'; ⋮---- -// if (isWsFormattedForceOrder(data)) { -// return console.log('log force order: ', data); -// } +export type WsPrivateSpotTopic = + | 'outboundAccountInfo' + | 'executionReport' + | 'ticketInfo'; ⋮---- -// if (isWsFormatted24hrTickerArray(data)) { -// return console.log('log 24hr ticker array: ', data); -// } +export type WsPrivateTopic = + | WsPrivateInverseTopic + | WsPrivateUSDTPerpTopic + | WsPrivateSpotTopic + | string; ⋮---- -// if (isWsFormattedRollingWindowTickerArray(data)) { -// return console.log('log rolling window ticker array: ', data); -// } -⋮---- -// if (isWsFormatted24hrTicker(data)) { -// return console.log('log 24hr ticker: ', data); -// } -⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -⋮---- -// No action needed here, unless you need to query the REST API after being reconnected. -⋮---- -/** - * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. - * - * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. - * - * The WsKey is a reference to the connection that this topic should be routed to. - * WS_KEY_MAP is a complete enum with all the available WsKey values. - * - * The following topics are routed to the "market" endpoint for USDM Futures market data, as per the following documentation: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data - */ -⋮---- -// Uses the high-frequency order book & core public feeds WS URL dedicated to USDM Futures: -// wss://fstream.binance.com/public/stream -⋮---- -/** - * Subscribe to each available type of USDM Derivatives market topic, the new way - */ -⋮---- -// Individual Symbol Book Ticker Streams -// https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams -⋮---- -// All Book Tickers Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream -'!bookTicker', // DOESNT EXIST AS TYPE GUARD -// Partial Book Depth Streams -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams -⋮---- -// Diff. Book Depth Stream -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams -⋮---- -// /** -// * -// * For those that used the Node.js Binance SDK before the v3 release, you can -// * still subscribe to available market topics the "old" way, for convenience -// * when migrating from the old WebsocketClient to the new multiplex client): -// * -// */ +export type WsTopic = WsPublicTopics | WsPrivateTopic; ⋮---- -// wsClient.subscribeAggregateTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(symbol, 'spot'); -// wsClient.subscribeTrades(symbol, 'usdm'); -// wsClient.subscribeTrades(coinMSymbol, 'coinm'); -// wsClient.subscribeCoinIndexPrice(coinMSymbol2); -// wsClient.subscribeAllBookTickers('usdm'); -// wsClient.subscribeSpotKline(symbol, '1m'); -// wsClient.subscribeMarkPrice(symbol, 'usdm'); -// wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMarketMarkPrice('usdm'); -// wsClient.subscribeAllMarketMarkPrice('coinm'); -// wsClient.subscribeKlines(symbol, '1m', 'usdm'); -// wsClient.subscribeContinuousContractKlines( -// symbol, -// 'perpetual', -// '1m', -// 'usdm', -// ); -// wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); -// wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 -// wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); -// wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); -// wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); -// wsClient.subscribeAllMini24hrTickers('spot'); -// wsClient.subscribeAllMini24hrTickers('usdm'); -// wsClient.subscribeAllMini24hrTickers('coinm'); -// wsClient.subscribeAll24hrTickers('spot'); -// wsClient.subscribeAll24hrTickers('usdm'); -// wsClient.subscribeAll24hrTickers('coinm'); -// wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); -// wsClient.subscribeAllLiquidationOrders('usdm'); -// wsClient.subscribeAllLiquidationOrders('coinm'); -// wsClient.subscribeSpotSymbol24hrTicker(symbol); -// wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); -// wsClient.subscribeAllRollingWindowTickers('spot', '1d'); -// wsClient.subscribeSymbolBookTicker(symbol, 'spot'); -// wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); -// wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); -// wsClient.subscribeContractInfoStream('usdm'); -// wsClient.subscribeContractInfoStream('coinm'); - -================ -File: examples/WebSockets/README.md -================ -# Binance WebSocket Streams - -This Node.js, JavaScript & TypeScript SDK for Binance has complete support for all available WebSocket capabilities of Binance's API offering. - -## Capabilities - -These WebSocket capabilities are split into two key groups: - -1. WebSocket Consumers: - - Subscribe to market data & receive realtime updates. - - Subscribe to private account data & receive realtime updates (generally called the user data stream). -2. WebSocket API: - - Send requests & commands over a persistent WebSocket (WSAPI) connection. E.g. Submit an order. - - Subscribe to private account data & receive realtime updates (generally called the user data stream), over a persistent WebSocket (WSAPI) connection. Note: - - This was previously available without the WebSocket API, via a mechanic involving a temporary listenKey. - - In recent updates, the WebSocket API supports subscribing to the user data stream (private updates). - - In some cases, this is the only way to subsrcibe to the user data stream (e.g. in Spot markets). - -## Architecture - -### WebsocketClient - -This SDK has all WebSocket capabilities integrated in the dedicated class called the `WebsocketClient`. This can be imported from the package directly. This all-in-one class handles all aspects of Binance's WebSocket capabilities, across all subdomains & endpoints. It also includes the raw capabilities to support integration with the WebSocket API. Subscriptions, heartbeats and connection recovery after disconnect - these are all included automatically. - -If the answer to any of these is yes, you should be using the WebsocketClient: - -- You want to subscribe to & receive realtime updates for public market data. -- You want raw control over how & where WebSocket API commands are sent. - -If you are looking for a more convenient integration with Binance's WebSocket API, you should look at the `WebsocketAPIClient`. - -### WebsocketAPIClient - -This is a utility class built over the WebsocketClient to especially provide a more convenient way of using Binance's WebSocket API. While WebSockets are asynchronous by design, the WebsocketAPIClient provides a way to send WebSocket API commands and await the result. All commands are wrapped in a promise and internal event tracking ensures promises are resolved or rejected as part of the command life cycle. - -This utility class in this SDK allows you to integrate the WebSocket API in the same way that you would integrate a REST API. Make a request and await the result. - -As of early 2026, some of the user data streams are also only available via the WebSocket API streams. This has been integrated into the WebsocketAPIClient and is available with a number of user data methods, depending on the product group. Some references: - -- Spot: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` -- Margin: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.marginUserData)` -- USDM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.usdmWSAPI)` -- CoinM Futures: `wsApiClient.subscribeUserDataStream(WS_KEY_MAP.coinmWSAPI)` - -## Key Features - -### Base URL Split & Migration - -On 06/03/2026, Binance announced a routing upgrade to their USDM Futures WebSocket System, titled: "Binance USDⓈ-M Futures WebSocket System Upgrade Notice (2026-03-06)". - -#### Key Highlights: - -- Introduction of three dedicated WebSocket base URLs: - - Public (high-frequency public market data) - - wss://fstream.binance.com/public - - Market (regular market data) - - wss://fstream.binance.com/market - - Private (user data streams) - - wss://fstream.binance.com/private -- New endpoints are supported immediately upon this announcement. -- Legacy WebSocket URLs will be permanently retired on 2026-04-23. -- Documentation including endpoint & stream mapping: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data - -#### Binance JavaScript SDK Support - -All three dedicated WebSocket base URLs are supported. Each with their own unique WsKey, used to track each unique connection. +export interface WSClientConfigurableOptions { + /** Your API key */ + api_key?: string; -Continue to subscribe to market data as before with the dedicated subscribe method, but ensure to provide the connection key depending on the type of market data you are consuming. + /** Your API secret */ + api_secret?: string; -Minimal examples: + beautify?: boolean; -```typescript -// ... + /** + * If true, log a warning if the beautifier is missing anything for an event + */ + beautifyWarnIfMissing?: boolean; -// For public (high-frequency public data) -const wsKeyUsdmPublic = WS_KEY_MAP.usdmPublic; -wsClient.subscribe(['btcusdt@bookTicker', 'btcusdt@depth'], wsKeyUsdmPublic); + /** + * Set to `true` to connect to Binance's testnet environment. + * + * Notes: + * - Not all WebSocket categories support testnet. + * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets + */ + testnet?: boolean; -// For market (regular market data) -const wsKeyUsdmMarket = WS_KEY_MAP.usdmMarket; -wsClient.subscribe(['btcusdt@aggTrade', 'btcusdt@forceOrder'], wsKeyUsdmMarket); + /** + * Set to `true` to use Binance's demo trading WebSocket endpoints. + * Demo trading uses real market data but simulated trading. + * More info: https://demo.binance.com/ + * + * Notes: + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + */ + demoTrading?: boolean; -// For user data, continue using the subscribe user data stream method as before. -// The SDK will automatically route to the "private" endpoint for USDM Futures: -wsClient.subscribeUsdFuturesUserDataStream(); -``` + /** + * Default: false. If true, use market maker endpoints when available. + * Eligible for high-frequency trading users who have enrolled and qualified + * in at least one of the Futures Liquidity Provider Programs. + * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + */ + useMMSubdomain?: boolean; -#### Legacy `wsClient.subscribe*()` methods + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; -If you're using any of the per-topic convenience methods, such as `wsClient.subscribeAggregateTrades(...)`, no change is required. The SDK will automatically route the topic subscription request to the appropriate WS URL. + // Disable ping/pong ws heartbeat mechanism (not recommended) + disableHeartbeat?: boolean; -## Further Reading + /** How often to check if the connection is alive */ + pingInterval?: number; -For detailed examples, refer to the examples in this folder, as well as the following documentation: + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; -- Binance JavaScript SDK QuickStart Guide: https://siebly.io/sdk/binance/javascript -- Binance JavaScript SDK Readme: https://www.npmjs.com/package/binance + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; -================ -File: examples/README.md -================ -# Binance API - Examples + restOptions?: RestClientOptions; -This folder contains ready to go examples demonstrating various aspects of this API implementation, written in TypeScript (but they are compatible with pure JavaScript projects). + requestOptions?: AxiosRequestConfig; -Found something difficult to implement? Contribute to these examples and help others! + wsOptions?: { + protocols?: string[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); -## Getting started + wsUrl?: string; -- Clone the project (or download it as a zip, or install the module in your own project `npm install binance`). -- Edit the sample as needed (some samples require edits, e.g API keys or import statements to import from npm, not src). -- Execute the sample using tsx: `tsx examples/REST/rest-spot-public.ts`. + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ + customSignMessageFn?: (message: string, secret: string) => Promise; -Samples that refer to API credentials using `process.env.API_KEY_COM` can be spawned with environment variables. Unix/macOS example: -``` -API_KEY_COM='apikeypastedhere' API_SECRET_COM='apisecretpastedhere' tsx "examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts" -``` - -Or edit the example directly to hardcode your API keys. - -### WebSockets - -All examples relating to WebSockets can be found in the [examples/WebSockets](./WebSockets/) folder. High level summary of available examples: - -#### Consumers - -These are purely for receiving data from Binance's WebSockets (market data, account updates, etc). - -##### Market Data - -These examples demonstrate subscribing to & receiving market data from Binance's WebSockets: - -- ws-public.ts - - Demonstration on general usage of the WebSocket client to subscribe to / unsubscribe from one or more market data topics. -- ws-public-spot-orderbook.ts - - Subscribing to orderbook events for multiple symbols in spot markets. -- ws-public-spot-trades.ts - - Subscribing to raw trades for multiple symbols in spot markets. -- ws-unsubscribe.ts - - Subscribing to a list of topics, and then unsubscribing from a few topics in that list. -- ws-public-usdm-funding.ts - - Simple example subscribing to a general topic, and how to process incoming events to only extract funding rates from those events. - -##### Account Data - -These examples demonstrate receiving account update events from Binance's WebSockets: - -- ws-userdata-listenkey.ts - - Demonstration on subscribing to various user data streams (spot, margin, futures), - - Handling incoming user data events - - Using provided type guards to determine which product group the user data event is for (spot, margin, futures, etc). -- ws-userdata-listenKey-testnet.ts - - Similar to above, but on testnet. -- ws-userdata-connection-safety.ts - - Demonstration on extra safety around the first user data stream connection. - - Note: this is overkill in most situations... - -##### WebSocket API - -These examples demonstrate how to send commands using Binance's WebSocket API (e.g. submitting orders). Very similar to the REST API, but using a persisted WebSocket connection instead of HTTP requests. - -- ws-api-client.ts - - Demonstration of using Binance's WebSocket API in Node.js/JavaScript/TypeScript, using the WebsocketAPIClient. - - This WebsocketAPIClient is very similar to a REST client, with one method per available command (endpoint) and fully typed requests & responses. - - Routing is automatically handled via the WebsocketClient, including authentication and connection persistence. Just call the functions you need - the SDK does the rest. - - From a usage perspective, it feels like a REST API - you can await responses just like a HTTP request. -- ws-api-raw-promises.ts - - More verbose usage of the WebSocket API using the `sendWSAPIRequest()` method. - - The `WebsocketAPIClient` uses this method too, so in most cases it is simple to just use the `WebsocketAPIClient` instead. -- ws-userdata-wsapi.ts - - The listenKey workflow for the user data stream is deprecated (in spot markets). - - This example demonstrates how to subscribe to the user data stream in spot markets, without a listen key, using the WebSocket API. - -##### Misc Workflows - -These are miscellaneous examples that cover one or more of the above categories: - -- ws-close.ts - - Closing the (old listen-key driven) user data stream. - - Unsubscribing from various topics. -- ws-proxy-socks.ts - - Using WebSockets over a SOCKS proxy. -- deprecated-ws-public.ts - - -### REST APIs - -All examples relating to REST APIs can be found in the [examples/REST](./REST/) folder. Most examples are named around functionality & product group. Any examples with "private" involve API calls relating to your account (such as changing settings or submitting orders, etc), - -High level summary for some of the available examples, but check the folder for a complete list: - -#### REST USDM Examples - -- `rest-future-bracket-order.ts` Creates an entry order plus a passive reduce-only TP limit order and an SL Algo Service order. -- `rest-usdm-order.ts` Creates a single entry order using `submitNewOrder`. -- `rest-usdm-order-sl.ts` Modifies a Hedge Mode LONG stop-loss order using Algo Service orders. - -================ -File: src/types/websockets/ws-api.ts -================ -import { WS_KEY_MAP, WsKey } from '../../util/websockets/websocket-util'; -import { FuturesExchangeInfo } from '../futures'; -import { - ExchangeInfo, - SpotExecutionRulesResponse, - SpotReferencePriceCalculationResponse, - SpotReferencePriceResult, -} from '../spot'; -import { - WSAPIAccountCommissionWSAPIRequest, - WSAPIAccountInformationRequest, - WSAPIAllOrderListsRequest, - WSAPIAllOrdersRequest, - WSAPIAvgPriceRequest, - WSAPIBlockTradesHistoricalRequest, - WSAPIExchangeInfoRequest, - WSAPIExecutionRulesRequest, - WSAPIFuturesAlgoOrderCancelRequest, - WSAPIFuturesOrderBookRequest, - WSAPIFuturesOrderCancelRequest, - WSAPIFuturesOrderModifyRequest, - WSAPIFuturesOrderStatusRequest, - WSAPIFuturesTickerBookRequest, - WSAPIFuturesTickerPriceRequest, - WSAPIKlinesRequest, - WSAPIMyAllocationsRequest, - WSAPIMyPreventedMatchesRequest, - WSAPIMyTradesRequest, - WSAPINewFuturesAlgoOrderRequest, - WSAPINewFuturesOrderRequest, - WSAPINewSpotOrderRequest, - WSAPIOpenOrdersCancelAllRequest, - WSAPIOpenOrdersStatusRequest, - WSAPIOrderAmendKeepPriorityRequest, - WSAPIOrderBookRequest, - WSAPIOrderCancelReplaceRequest, - WSAPIOrderCancelRequest, - WSAPIOrderListCancelRequest, - WSAPIOrderListPlaceOCORequest, - WSAPIOrderListPlaceOPOCORequest, - WSAPIOrderListPlaceOPORequest, - WSAPIOrderListPlaceOTOCORequest, - WSAPIOrderListPlaceOTORequest, - WSAPIOrderListPlaceRequest, - WSAPIOrderListStatusRequest, - WSAPIOrderStatusRequest, - WSAPIOrderTestRequest, - WSAPIRecvWindowTimestamp, - WSAPIReferencePriceCalculationRequest, - WSAPIReferencePriceRequest, - WSAPISessionLogonRequest, - WSAPISOROrderPlaceRequest, - WSAPISOROrderTestRequest, - WSAPITicker24hrRequest, - WSAPITickerBookRequest, - WSAPITickerPriceRequest, - WSAPITickerRequest, - WSAPITickerTradingDayRequest, - WSAPITradesAggregateRequest, - WSAPITradesHistoricalRequest, - WSAPITradesRecentRequest, -} from './ws-api-requests'; -import { - WSAPIAccountCommission, - WSAPIAccountInformation, - WSAPIAggregateTrade, - WSAPIAllocation, - WSAPIAvgPrice, - WSAPIBlockTrade, - WSAPIBookTicker, - WSAPIFullTicker, - WSAPIFuturesAccountBalanceItem, - WSAPIFuturesAccountStatus, - WSAPIFuturesAlgoOrder, - WSAPIFuturesAlgoOrderCancelResponse, - WSAPIFuturesBookTicker, - WSAPIFuturesOrder, - WSAPIFuturesOrderBook, - WSAPIFuturesPosition, - WSAPIFuturesPositionV2, - WSAPIFuturesPriceTicker, - WSAPIKline, - WSAPIMiniTicker, - WSAPIOrder, - WSAPIOrderBook, - WSAPIOrderCancel, - WSAPIOrderCancelReplaceResponse, - WSAPIOrderListCancelResponse, - WSAPIOrderListPlaceResponse, - WSAPIOrderListStatusResponse, - WSAPIOrderTestResponse, - WSAPIOrderTestWithCommission, - WSAPIPreventedMatch, - WSAPIPriceTicker, - WSAPIRateLimit, - WSAPIServerTime, - WSAPISessionStatus, - WSAPISOROrderPlaceResponse, - WSAPISOROrderTestResponse, - WSAPISOROrderTestResponseWithCommission, - WSAPISpotOrderResponse, - WSAPITrade, -} from './ws-api-responses'; + /** + * Optional custom JSON parser used for incoming WS messages. + * Defaults to JSON.parse. + */ + customParseJSONFn?: (raw: string) => object; +} ⋮---- -/** - * Standard WS commands (for consumers) - */ -export type WsOperation = - | 'SUBSCRIBE' - | 'UNSUBSCRIBE' - | 'LIST_SUBSCRIPTIONS' - | 'SET_PROPERTY' - | 'GET_PROPERTY'; +/** Your API key */ ⋮---- -/** - * WS API commands (for sending requests via WS) - */ +/** Your API secret */ ⋮---- -//// General commands +/** + * If true, log a warning if the beautifier is missing anything for an event + */ ⋮---- -//// Market data commands +/** + * Set to `true` to connect to Binance's testnet environment. + * + * Notes: + * - Not all WebSocket categories support testnet. + * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets + */ ⋮---- -//// Account commands -// Spot +/** + * Set to `true` to use Binance's demo trading WebSocket endpoints. + * Demo trading uses real market data but simulated trading. + * More info: https://demo.binance.com/ + * + * Notes: + * - If demo trading, `testnet` should be set to false! + * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + */ ⋮---- -// Futures +/** + * Default: false. If true, use market maker endpoints when available. + * Eligible for high-frequency trading users who have enrolled and qualified + * in at least one of the Futures Liquidity Provider Programs. + * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + */ ⋮---- -//// Trading commands +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- -// Order list commands +// Disable ping/pong ws heartbeat mechanism (not recommended) ⋮---- -// SOR commands +/** How often to check if the connection is alive */ ⋮---- -// user data stream +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -export interface WSAPIUserDataListenKeyRequest { - apiKey: string; - listenKey: string; -} +/** Delay in milliseconds before respawning the connection */ ⋮---- -export type WsAPIOperation = (typeof WS_API_Operations)[number]; +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -export interface WsRequestOperationBinance< - TWSTopic extends string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - TWSParams extends object = any, -> { - method: WsOperation | WsAPIOperation; - params?: (TWSTopic | string | number)[] | TWSParams; +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ +⋮---- +/** + * Optional custom JSON parser used for incoming WS messages. + * Defaults to JSON.parse. + */ +⋮---- +/** + * WS configuration that's always defined, regardless of user configuration + * (usually comes from defaults if there's no user-provided values) + */ +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + pongTimeout: number; + pingInterval: number; + reconnectTimeout: number; + recvWindow: number; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequestsIndividually: boolean; +} + +================ +File: src/types/coin.ts +================ +import { FuturesContractType, PositionSide } from './futures'; +import { numberInString, OrderSide } from './shared'; +⋮---- +export interface PositionRisk { + symbol: string; + positionAmt: numberInString; + entryPrice: numberInString; + markPrice: numberInString; + unRealizedProfit: numberInString; + liquidationPrice: numberInString; + leverage: numberInString; + maxQty: numberInString; + marginType: string; + isolatedMargin: numberInString; + isAutoAddMargin: boolean; + positionSide: PositionSide; + updateTime: number; +} +⋮---- +export interface CoinMOpenInterest { + symbol: string; + pair: string; + openInterest: numberInString; + contractType: FuturesContractType; + time: number; +} +export type SymbolOrPair = + | { pair: string; symbol?: never } + | { pair?: never; symbol: string }; +⋮---- +export interface CoinMSymbolOrderBookTicker { + symbol: string; + pair: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; +} +⋮---- +export interface CoinMPaginatedRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface CoinMAccountTradeParamsWithPair extends CoinMPaginatedRequest { + pair: string; + symbol?: never; + fromId?: never; +} +⋮---- +export interface CoinMAccountTradeParamsWithSymbol + extends CoinMPaginatedRequest { + symbol: string; + pair?: never; +} +⋮---- +export interface CoinMAccountTradeParamsWithFromId + extends CoinMPaginatedRequest { + fromId: number; + startTime?: never; + endTime?: never; +} +⋮---- +export type CoinMAccountTradeParams = + | CoinMAccountTradeParamsWithSymbol + | CoinMAccountTradeParamsWithPair + | CoinMAccountTradeParamsWithFromId; +⋮---- +export interface CoinMPositionTrade { + symbol: string; id: number; + orderId: number; + pair: string; + side: OrderSide; + price: numberInString; + qty: numberInString; + realizedPnl: numberInString; + marginAsset: string; + baseQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + positionSide: PositionSide; + buyer: boolean; + maker: boolean; + quoteQty?: numberInString; } ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface FundingRate { + symbol: string; + adjustedFundingRateCap: string; + adjustedFundingRateFloor: string; + fundingIntervalHours: number; + disclaimer: boolean; +} ⋮---- -export interface WSAPIResponse { - /** Auto-generated */ - id: string; - - status: number; - result: TResponseData; - rateLimits: { - rateLimitType: 'REQUEST_WEIGHT'; - interval: 'MINUTE'; - intervalNum: number; - limit: number; - count: number; - }[]; - - wsKey: WsKey; - isWSAPIResponse: boolean; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - request?: any; +export interface GetClassicPortfolioMarginNotionalLimitParams { + symbol?: string; + pair?: string; } ⋮---- -/** Auto-generated */ +export interface ClassicPortfolioMarginNotionalLimit { + symbol: string; + pair: string; + notionalLimit: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface ClassicPortfolioMarginAccount { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; +} ⋮---- -export type Exact = { - // This part says: if there's any key that's not in T, it's an error - // This conflicts sometimes for some reason... - // [K: string]: never; -} & { - [K in keyof T]: T[K]; -}; +export interface FuturesTransactionHistoryDownloadLink { + downloadId: string; + status: string; + url: string; + notified: boolean; + expirationTimestamp: number; + isExpired: boolean | null; +} + +================ +File: webpack/webpack.config.js +================ +function generateConfig(name) ⋮---- -// This part says: if there's any key that's not in T, it's an error -// This conflicts sometimes for some reason... -// [K: string]: never; +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -/** - * List of operations supported for this WsKey (connection) - */ -export interface WsAPIWsKeyTopicMap { - [WS_KEY_MAP.main]: WsOperation; - [WS_KEY_MAP.main2]: WsOperation; - [WS_KEY_MAP.main3]: WsOperation; +// Node.js core modules not available in browsers +// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers +⋮---- +// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. +⋮---- +// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. - [WS_KEY_MAP.mainTestnetPublic]: WsOperation; - [WS_KEY_MAP.mainTestnetUserData]: WsOperation; +================ +File: .gitignore +================ +.vscode/ +.idea/ +.nyc_output/ +node_modules/ +util/config.js +coverage/ +yarn-error.log +lib/* +testfile.ts +privaterepotracker +restClientRegex.ts +.DS_Store +dist +localtest.ts +repomix.sh +doc +*.pem +.env - [WS_KEY_MAP.marginRiskUserData]: WsOperation; - [WS_KEY_MAP.marginUserData]: WsAPIOperation; - [WS_KEY_MAP.usdm]: WsOperation; - [WS_KEY_MAP.usdmTestnet]: WsOperation; +================ +File: .npmrc +================ +min-release-age=30 +save-exact=true - [WS_KEY_MAP.coinm]: WsOperation; - [WS_KEY_MAP.coinm2]: WsOperation; - [WS_KEY_MAP.coinmTestnet]: WsOperation; - [WS_KEY_MAP.eoptions]: WsOperation; - [WS_KEY_MAP.portfolioMarginUserData]: WsOperation; - [WS_KEY_MAP.portfolioMarginProUserData]: WsOperation; +================ +File: examples/Rest/Futures/rest-usdm-order-sl.ts +================ +import { FuturesNewAlgoOrderParams, USDMClient } from '../../../src/index'; +⋮---- +// or +// import { FuturesNewAlgoOrderParams, USDMClient } from 'binance'; +⋮---- +async function start() +⋮---- +// Hedge Mode example: find each open hedge position and replace its SL. - [WS_KEY_MAP.alpha]: WsOperation; +================ +File: examples/README.md +================ +# Binance API - Examples - [WS_KEY_MAP.mainWSAPI]: WsAPIOperation; - [WS_KEY_MAP.mainWSAPI2]: WsAPIOperation; - [WS_KEY_MAP.mainWSAPITestnet]: WsAPIOperation; +This folder contains ready to go examples demonstrating various aspects of this API implementation, written in TypeScript (but they are compatible with pure JavaScript projects). - [WS_KEY_MAP.usdmWSAPI]: WsAPIOperation; - [WS_KEY_MAP.usdmWSAPITestnet]: WsAPIOperation; +Found something difficult to implement? Contribute to these examples and help others! - [WS_KEY_MAP.coinmWSAPI]: WsAPIOperation; - [WS_KEY_MAP.coinmWSAPITestnet]: WsAPIOperation; -} -⋮---- -export type WsAPIFuturesWsKey = - | typeof WS_KEY_MAP.usdmWSAPI - | typeof WS_KEY_MAP.usdmWSAPITestnet; -⋮---- -/** - * Request parameters expected per operation. - * - * - Each "key" here is the name of the command/operation. - * - Each "value" here has the parameters required for the command. - * - * Make sure to add new topics to WS_API_Operations and the response param map too. - */ -export interface WsAPITopicRequestParamMap { - SUBSCRIBE: never; - UNSUBSCRIBE: never; - LIST_SUBSCRIPTIONS: never; - SET_PROPERTY: never; - GET_PROPERTY: never; +## Getting started - /** - * Authentication commands & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ - 'session.logon': WSAPISessionLogonRequest; - 'session.status': void; - 'session.logout': void; +- Clone the project (or download it as a zip, or install the module in your own project `npm install binance`). +- Edit the sample as needed (some samples require edits, e.g API keys or import statements to import from npm, not src). +- Execute the sample using tsx: `tsx examples/REST/rest-spot-public.ts`. - /** - * General requests & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ - ping: void; - time: void; +Samples that refer to API credentials using `process.env.API_KEY_COM` can be spawned with environment variables. Unix/macOS example: +``` +API_KEY_COM='apikeypastedhere' API_SECRET_COM='apisecretpastedhere' tsx "examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts" +``` - exchangeInfo: void | WSAPIExchangeInfoRequest; +Or edit the example directly to hardcode your API keys. - /** - * Market data requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ - depth: TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesOrderBookRequest - : WSAPIOrderBookRequest; - 'trades.recent': WSAPITradesRecentRequest; - 'trades.historical': WSAPITradesHistoricalRequest; - 'blockTrades.historical': WSAPIBlockTradesHistoricalRequest; - 'trades.aggregate': WSAPITradesAggregateRequest; - klines: WSAPIKlinesRequest; - uiKlines: WSAPIKlinesRequest; - avgPrice: WSAPIAvgPriceRequest; - executionRules: void | WSAPIExecutionRulesRequest; - referencePrice: WSAPIReferencePriceRequest; - 'referencePrice.calculation': WSAPIReferencePriceCalculationRequest; - 'ticker.24hr': void | WSAPITicker24hrRequest; - 'ticker.tradingDay': WSAPITickerTradingDayRequest; - ticker: WSAPITickerRequest; - 'ticker.price': void | TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesTickerPriceRequest | undefined - : WSAPITickerPriceRequest | undefined; - 'ticker.book': void | TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesTickerBookRequest | undefined - : WSAPITickerBookRequest | undefined; +### WebSockets - /** - * Account requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ +All examples relating to WebSockets can be found in the [examples/WebSockets](./WebSockets/) folder. High level summary of available examples: - 'account.status': - | void - | (TWSKey extends WsAPIFuturesWsKey - ? WSAPIRecvWindowTimestamp - : WSAPIAccountInformationRequest); +#### Consumers - 'account.rateLimits.orders': void | WSAPIRecvWindowTimestamp; +These are purely for receiving data from Binance's WebSockets (market data, account updates, etc). - allOrders: WSAPIAllOrdersRequest; +##### Market Data - allOrderLists: void | WSAPIAllOrderListsRequest; +These examples demonstrate subscribing to & receiving market data from Binance's WebSockets: - myTrades: WSAPIMyTradesRequest; +- ws-public.ts + - Demonstration on general usage of the WebSocket client to subscribe to / unsubscribe from one or more market data topics. +- ws-public-spot-orderbook.ts + - Subscribing to orderbook events for multiple symbols in spot markets. +- ws-public-spot-trades.ts + - Subscribing to raw trades for multiple symbols in spot markets. +- ws-unsubscribe.ts + - Subscribing to a list of topics, and then unsubscribing from a few topics in that list. +- ws-public-usdm-funding.ts + - Simple example subscribing to a general topic, and how to process incoming events to only extract funding rates from those events. - myPreventedMatches: WSAPIMyPreventedMatchesRequest; +##### Account Data - myAllocations: WSAPIMyAllocationsRequest; +These examples demonstrate receiving account update events from Binance's WebSockets: - 'account.commission': WSAPIAccountCommissionWSAPIRequest; +- ws-userdata-listenkey.ts + - Demonstration on subscribing to various user data streams (spot, margin, futures), + - Handling incoming user data events + - Using provided type guards to determine which product group the user data event is for (spot, margin, futures, etc). +- ws-userdata-listenKey-testnet.ts + - Similar to above, but on testnet. +- ws-userdata-connection-safety.ts + - Demonstration on extra safety around the first user data stream connection. + - Note: this is overkill in most situations... - /** - * Futures account requests & parameters: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ - 'account.position': WSAPIRecvWindowTimestamp; +##### WebSocket API - 'v2/account.position': WSAPIRecvWindowTimestamp; +These examples demonstrate how to send commands using Binance's WebSocket API (e.g. submitting orders). Very similar to the REST API, but using a persisted WebSocket connection instead of HTTP requests. - 'account.balance': WSAPIRecvWindowTimestamp; +- ws-api-client.ts + - Demonstration of using Binance's WebSocket API in Node.js/JavaScript/TypeScript, using the WebsocketAPIClient. + - This WebsocketAPIClient is very similar to a REST client, with one method per available command (endpoint) and fully typed requests & responses. + - Routing is automatically handled via the WebsocketClient, including authentication and connection persistence. Just call the functions you need - the SDK does the rest. + - From a usage perspective, it feels like a REST API - you can await responses just like a HTTP request. +- ws-api-raw-promises.ts + - More verbose usage of the WebSocket API using the `sendWSAPIRequest()` method. + - The `WebsocketAPIClient` uses this method too, so in most cases it is simple to just use the `WebsocketAPIClient` instead. +- ws-userdata-wsapi.ts + - The listenKey workflow for the user data stream is deprecated (in spot markets). + - This example demonstrates how to subscribe to the user data stream in spot markets, without a listen key, using the WebSocket API. - 'v2/account.balance': WSAPIRecvWindowTimestamp; +##### Misc Workflows - 'v2/account.status': WSAPIRecvWindowTimestamp; +These are miscellaneous examples that cover one or more of the above categories: - /** - * Trading requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ - 'order.place': (TWSKey extends WsAPIFuturesWsKey - ? WSAPINewFuturesOrderRequest - : WSAPINewSpotOrderRequest) & { - timestamp?: number; - }; - 'order.test': WSAPIOrderTestRequest; - 'order.status': TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesOrderStatusRequest - : WSAPIOrderStatusRequest; - 'order.cancel': TWSKey extends WsAPIFuturesWsKey - ? WSAPIFuturesOrderCancelRequest - : WSAPIOrderCancelRequest; - 'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures - 'order.cancelReplace': WSAPIOrderCancelReplaceRequest; - 'order.amend.keepPriority': WSAPIOrderAmendKeepPriorityRequest; - 'openOrders.status': WSAPIOpenOrdersStatusRequest; - 'openOrders.cancelAll': WSAPIOpenOrdersCancelAllRequest; +- ws-close.ts + - Closing the (old listen-key driven) user data stream. + - Unsubscribing from various topics. +- ws-proxy-socks.ts + - Using WebSockets over a SOCKS proxy. +- deprecated-ws-public.ts - 'algoOrder.place': WSAPINewFuturesAlgoOrderRequest; - 'algoOrder.cancel': WSAPIFuturesAlgoOrderCancelRequest; - /** - * Order list requests & parameters: - */ - 'orderList.place': WSAPIOrderListPlaceRequest; - 'orderList.place.oco': WSAPIOrderListPlaceOCORequest; - 'orderList.place.oto': WSAPIOrderListPlaceOTORequest; - 'orderList.place.otoco': WSAPIOrderListPlaceOTOCORequest; - 'orderList.place.opo': WSAPIOrderListPlaceOPORequest; - 'orderList.place.opoco': WSAPIOrderListPlaceOPOCORequest; - 'orderList.status': WSAPIOrderListStatusRequest; - 'orderList.cancel': WSAPIOrderListCancelRequest; +### REST APIs - 'openOrderLists.status': WSAPIRecvWindowTimestamp; +All examples relating to REST APIs can be found in the [examples/REST](./REST/) folder. Most examples are named around functionality & product group. Any examples with "private" involve API calls relating to your account (such as changing settings or submitting orders, etc), - /** - * SOR requests & parameters: - */ - 'sor.order.place': WSAPISOROrderPlaceRequest; - 'sor.order.test': WSAPISOROrderTestRequest; +High level summary for some of the available examples, but check the folder for a complete list: - /** - * User data stream: - * - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests - * - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - * - * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. - */ - 'userDataStream.start': { apiKey: string }; - 'userDataStream.ping': WSAPIUserDataListenKeyRequest; - 'userDataStream.stop': WSAPIUserDataListenKeyRequest; - 'userDataStream.subscribe': void; - 'userDataStream.subscribe.signature': { timestamp: number }; - 'userDataStream.unsubscribe': void; +#### REST USDM Examples - /** - * User data streams, margin: - */ - 'userDataStream.subscribe.listenToken': { listenToken: string }; -} -⋮---- -/** - * Authentication commands & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ -⋮---- -/** - * General requests & parameters: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ -⋮---- -/** - * Market data requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ -⋮---- -/** - * Account requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ -⋮---- -/** - * Futures account requests & parameters: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ -⋮---- -/** - * Trading requests & parameters: - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ -⋮---- -'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures +- `rest-future-bracket-order.ts` Creates an entry order plus a passive reduce-only TP limit order and an SL Algo Service order. +- `rest-usdm-order.ts` Creates a single entry order using `submitNewOrder`. +- `rest-usdm-order-sl.ts` Modifies a Hedge Mode LONG stop-loss order using Algo Service orders. + +================ +File: src/types/websockets/ws-api.ts +================ +import { WS_KEY_MAP, WsKey } from '../../util/websockets/websocket-util'; +import { FuturesExchangeInfo } from '../futures'; +import { + ExchangeInfo, + SpotExecutionRulesResponse, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, +} from '../spot'; +import { + WSAPIAccountCommissionWSAPIRequest, + WSAPIAccountInformationRequest, + WSAPIAllOrderListsRequest, + WSAPIAllOrdersRequest, + WSAPIAvgPriceRequest, + WSAPIBlockTradesHistoricalRequest, + WSAPIExchangeInfoRequest, + WSAPIExecutionRulesRequest, + WSAPIFuturesAlgoOrderCancelRequest, + WSAPIFuturesOrderBookRequest, + WSAPIFuturesOrderCancelRequest, + WSAPIFuturesOrderModifyRequest, + WSAPIFuturesOrderStatusRequest, + WSAPIFuturesTickerBookRequest, + WSAPIFuturesTickerPriceRequest, + WSAPIKlinesRequest, + WSAPIMyAllocationsRequest, + WSAPIMyPreventedMatchesRequest, + WSAPIMyTradesRequest, + WSAPINewFuturesAlgoOrderRequest, + WSAPINewFuturesOrderRequest, + WSAPINewSpotOrderRequest, + WSAPIOpenOrdersCancelAllRequest, + WSAPIOpenOrdersStatusRequest, + WSAPIOrderAmendKeepPriorityRequest, + WSAPIOrderBookRequest, + WSAPIOrderCancelReplaceRequest, + WSAPIOrderCancelRequest, + WSAPIOrderListCancelRequest, + WSAPIOrderListPlaceOCORequest, + WSAPIOrderListPlaceOPOCORequest, + WSAPIOrderListPlaceOPORequest, + WSAPIOrderListPlaceOTOCORequest, + WSAPIOrderListPlaceOTORequest, + WSAPIOrderListPlaceRequest, + WSAPIOrderListStatusRequest, + WSAPIOrderStatusRequest, + WSAPIOrderTestRequest, + WSAPIRecvWindowTimestamp, + WSAPIReferencePriceCalculationRequest, + WSAPIReferencePriceRequest, + WSAPISessionLogonRequest, + WSAPISOROrderPlaceRequest, + WSAPISOROrderTestRequest, + WSAPITicker24hrRequest, + WSAPITickerBookRequest, + WSAPITickerPriceRequest, + WSAPITickerRequest, + WSAPITickerTradingDayRequest, + WSAPITradesAggregateRequest, + WSAPITradesHistoricalRequest, + WSAPITradesRecentRequest, +} from './ws-api-requests'; +import { + WSAPIAccountCommission, + WSAPIAccountInformation, + WSAPIAggregateTrade, + WSAPIAllocation, + WSAPIAvgPrice, + WSAPIBlockTrade, + WSAPIBookTicker, + WSAPIFullTicker, + WSAPIFuturesAccountBalanceItem, + WSAPIFuturesAccountStatus, + WSAPIFuturesAlgoOrder, + WSAPIFuturesAlgoOrderCancelResponse, + WSAPIFuturesBookTicker, + WSAPIFuturesOrder, + WSAPIFuturesOrderBook, + WSAPIFuturesPosition, + WSAPIFuturesPositionV2, + WSAPIFuturesPriceTicker, + WSAPIKline, + WSAPIMiniTicker, + WSAPIOrder, + WSAPIOrderBook, + WSAPIOrderCancel, + WSAPIOrderCancelReplaceResponse, + WSAPIOrderListCancelResponse, + WSAPIOrderListPlaceResponse, + WSAPIOrderListStatusResponse, + WSAPIOrderTestResponse, + WSAPIOrderTestWithCommission, + WSAPIPreventedMatch, + WSAPIPriceTicker, + WSAPIRateLimit, + WSAPIServerTime, + WSAPISessionStatus, + WSAPISOROrderPlaceResponse, + WSAPISOROrderTestResponse, + WSAPISOROrderTestResponseWithCommission, + WSAPISpotOrderResponse, + WSAPITrade, +} from './ws-api-responses'; ⋮---- /** - * Order list requests & parameters: - */ + * Standard WS commands (for consumers) + */ +export type WsOperation = + | 'SUBSCRIBE' + | 'UNSUBSCRIBE' + | 'LIST_SUBSCRIPTIONS' + | 'SET_PROPERTY' + | 'GET_PROPERTY'; ⋮---- /** - * SOR requests & parameters: - */ + * WS API commands (for sending requests via WS) + */ ⋮---- -/** - * User data stream: - * - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests - * - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - * - * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. - */ +//// General commands ⋮---- -/** - * User data streams, margin: - */ +//// Market data commands ⋮---- -/** - * Response structure expected for each operation - * - * - Each "key" here is a command/request supported by the WS API - * - Each "value" here is the response schema for that command. - */ -export interface WsAPIOperationResponseMap { - [key: string]: unknown; +//// Account commands +// Spot +⋮---- +// Futures +⋮---- +//// Trading commands +⋮---- +// Order list commands +⋮---- +// SOR commands +⋮---- +// user data stream +⋮---- +export interface WSAPIUserDataListenKeyRequest { + apiKey: string; + listenKey: string; +} +⋮---- +export type WsAPIOperation = (typeof WS_API_Operations)[number]; +⋮---- +export interface WsRequestOperationBinance< + TWSTopic extends string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + TWSParams extends object = any, +> { + method: WsOperation | WsAPIOperation; + params?: (TWSTopic | string | number)[] | TWSParams; + id: number; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface WSAPIResponse { + /** Auto-generated */ + id: string; - SUBSCRIBE: never; - UNSUBSCRIBE: never; - LIST_SUBSCRIPTIONS: never; - SET_PROPERTY: never; - GET_PROPERTY: never; + status: number; + result: TResponseData; + rateLimits: { + rateLimitType: 'REQUEST_WEIGHT'; + interval: 'MINUTE'; + intervalNum: number; + limit: number; + count: number; + }[]; - /** - * Session authentication responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests - */ - 'session.login': WSAPIResponse; - 'session.status': WSAPIResponse; - 'session.logout': WSAPIResponse; + wsKey: WsKey; + isWSAPIResponse: boolean; - /** - * General responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests - */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + request?: any; +} +⋮---- +/** Auto-generated */ +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export type Exact = { + // This part says: if there's any key that's not in T, it's an error + // This conflicts sometimes for some reason... + // [K: string]: never; +} & { + [K in keyof T]: T[K]; +}; +⋮---- +// This part says: if there's any key that's not in T, it's an error +// This conflicts sometimes for some reason... +// [K: string]: never; +⋮---- +/** + * List of operations supported for this WsKey (connection) + */ +export interface WsAPIWsKeyTopicMap { + [WS_KEY_MAP.main]: WsOperation; + [WS_KEY_MAP.main2]: WsOperation; + [WS_KEY_MAP.main3]: WsOperation; - ping: unknown; - time: WSAPIResponse; - exchangeInfo: WSAPIResponse; + [WS_KEY_MAP.mainTestnetPublic]: WsOperation; + [WS_KEY_MAP.mainTestnetUserData]: WsOperation; - /** - * Market data responses - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api - */ - depth: WSAPIResponse; - 'trades.recent': WSAPIResponse; - 'trades.historical': WSAPIResponse; - 'blockTrades.historical': WSAPIResponse; - 'trades.aggregate': WSAPIResponse; - klines: WSAPIResponse; - uiKlines: WSAPIResponse; - avgPrice: WSAPIResponse; - executionRules: WSAPIResponse; - referencePrice: WSAPIResponse; - 'referencePrice.calculation': WSAPIResponse; - 'ticker.24hr': WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - >; - 'ticker.tradingDay': WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - >; - ticker: WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - >; - 'ticker.price': WSAPIResponse< - | WSAPIPriceTicker - | WSAPIPriceTicker[] - | WSAPIFuturesPriceTicker - | WSAPIFuturesPriceTicker[] - >; - 'ticker.book': WSAPIResponse< - | WSAPIBookTicker - | WSAPIBookTicker[] - | WSAPIFuturesBookTicker - | WSAPIFuturesBookTicker[] - >; - - /** - * Account responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests - */ + [WS_KEY_MAP.marginRiskUserData]: WsOperation; + [WS_KEY_MAP.marginUserData]: WsAPIOperation; + [WS_KEY_MAP.usdm]: WsOperation; + [WS_KEY_MAP.usdmTestnet]: WsOperation; - 'account.status': WSAPIResponse< - WSAPIAccountInformation | WSAPIFuturesAccountStatus - >; - 'account.commission': WSAPIResponse; - 'account.rateLimits.orders': WSAPIResponse; - allOrders: WSAPIResponse; - allOrderLists: WSAPIResponse; - myTrades: WSAPIResponse; - myPreventedMatches: WSAPIResponse; - myAllocations: WSAPIResponse; + [WS_KEY_MAP.coinm]: WsOperation; + [WS_KEY_MAP.coinm2]: WsOperation; + [WS_KEY_MAP.coinmTestnet]: WsOperation; + [WS_KEY_MAP.eoptions]: WsOperation; + [WS_KEY_MAP.portfolioMarginUserData]: WsOperation; + [WS_KEY_MAP.portfolioMarginProUserData]: WsOperation; - /** - * Futures account responses: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api - */ - 'account.position': WSAPIResponse; - 'v2/account.position': WSAPIResponse; - 'account.balance': WSAPIResponse; - 'v2/account.balance': WSAPIResponse; - 'v2/account.status': WSAPIResponse; + [WS_KEY_MAP.alpha]: WsOperation; - /** - * Trading responses - * - Spot: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests - * - Futures: - * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api - */ - 'order.place': WSAPIResponse; - 'order.test': WSAPIResponse< - WSAPIOrderTestResponse | WSAPIOrderTestWithCommission - >; - 'order.status': WSAPIResponse; - 'order.cancel': WSAPIResponse; - 'order.modify': WSAPIResponse; - 'order.cancelReplace': WSAPIResponse; - 'openOrders.status': WSAPIResponse; - 'openOrders.cancelAll': WSAPIResponse< - (WSAPIOrderCancel | WSAPIOrderListCancelResponse)[] - >; - 'algoOrder.place': WSAPIResponse; - 'algoOrder.cancel': WSAPIResponse; - /** - * Order list responses - */ - 'orderList.place': WSAPIResponse; - 'orderList.place.oco': WSAPIResponse; - 'orderList.place.oto': WSAPIResponse; - 'orderList.place.otoco': WSAPIResponse; - 'orderList.place.opo': WSAPIResponse; - 'orderList.place.opoco': WSAPIResponse; - 'orderList.status': WSAPIResponse; - 'orderList.cancel': WSAPIResponse; - 'openOrderLists.status': WSAPIResponse; + [WS_KEY_MAP.mainWSAPI]: WsAPIOperation; + [WS_KEY_MAP.mainWSAPI2]: WsAPIOperation; + [WS_KEY_MAP.mainWSAPITestnet]: WsAPIOperation; - /** - * SOR responses - */ - 'sor.order.place': WSAPIResponse; - 'sor.order.test': WSAPIResponse< - WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission - >; + [WS_KEY_MAP.usdmWSAPI]: WsAPIOperation; + [WS_KEY_MAP.usdmWSAPITestnet]: WsAPIOperation; - 'userDataStream.start': WSAPIResponse<{ listenKey: string }>; - 'userDataStream.ping': WSAPIResponse; - 'userDataStream.stop': WSAPIResponse; - 'userDataStream.subscribe': WSAPIResponse; - 'userDataStream.subscribe.signature': WSAPIResponse; - 'userDataStream.unsubscribe': WSAPIResponse; + [WS_KEY_MAP.coinmWSAPI]: WsAPIOperation; + [WS_KEY_MAP.coinmWSAPITestnet]: WsAPIOperation; } ⋮---- +export type WsAPIFuturesWsKey = + | typeof WS_KEY_MAP.usdmWSAPI + | typeof WS_KEY_MAP.usdmWSAPITestnet; +⋮---- /** - * Session authentication responses: - * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication + * Request parameters expected per operation. + * + * - Each "key" here is the name of the command/operation. + * - Each "value" here has the parameters required for the command. + * + * Make sure to add new topics to WS_API_Operations and the response param map too. + */ +export interface WsAPITopicRequestParamMap { + SUBSCRIBE: never; + UNSUBSCRIBE: never; + LIST_SUBSCRIPTIONS: never; + SET_PROPERTY: never; + GET_PROPERTY: never; + + /** + * Authentication commands & parameters: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests */ -⋮---- -/** - * General responses: + 'session.logon': WSAPISessionLogonRequest; + 'session.status': void; + 'session.logout': void; + + /** + * General requests & parameters: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests */ -⋮---- -/** - * Market data responses + ping: void; + time: void; + + exchangeInfo: void | WSAPIExchangeInfoRequest; + + /** + * Market data requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api */ -⋮---- -/** - * Account responses: + depth: TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesOrderBookRequest + : WSAPIOrderBookRequest; + 'trades.recent': WSAPITradesRecentRequest; + 'trades.historical': WSAPITradesHistoricalRequest; + 'blockTrades.historical': WSAPIBlockTradesHistoricalRequest; + 'trades.aggregate': WSAPITradesAggregateRequest; + klines: WSAPIKlinesRequest; + uiKlines: WSAPIKlinesRequest; + avgPrice: WSAPIAvgPriceRequest; + executionRules: void | WSAPIExecutionRulesRequest; + referencePrice: WSAPIReferencePriceRequest; + 'referencePrice.calculation': WSAPIReferencePriceCalculationRequest; + 'ticker.24hr': void | WSAPITicker24hrRequest; + 'ticker.tradingDay': WSAPITickerTradingDayRequest; + ticker: WSAPITickerRequest; + 'ticker.price': void | TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesTickerPriceRequest | undefined + : WSAPITickerPriceRequest | undefined; + 'ticker.book': void | TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesTickerBookRequest | undefined + : WSAPITickerBookRequest | undefined; + + /** + * Account requests & parameters: + * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ -⋮---- -/** - * Futures account responses: + + 'account.status': + | void + | (TWSKey extends WsAPIFuturesWsKey + ? WSAPIRecvWindowTimestamp + : WSAPIAccountInformationRequest); + + 'account.rateLimits.orders': void | WSAPIRecvWindowTimestamp; + + allOrders: WSAPIAllOrdersRequest; + + allOrderLists: void | WSAPIAllOrderListsRequest; + + myTrades: WSAPIMyTradesRequest; + + myPreventedMatches: WSAPIMyPreventedMatchesRequest; + + myAllocations: WSAPIMyAllocationsRequest; + + 'account.commission': WSAPIAccountCommissionWSAPIRequest; + + /** + * Futures account requests & parameters: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ -⋮---- -/** - * Trading responses + 'account.position': WSAPIRecvWindowTimestamp; + + 'v2/account.position': WSAPIRecvWindowTimestamp; + + 'account.balance': WSAPIRecvWindowTimestamp; + + 'v2/account.balance': WSAPIRecvWindowTimestamp; + + 'v2/account.status': WSAPIRecvWindowTimestamp; + + /** + * Trading requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api */ -⋮---- -/** - * Order list responses - */ -⋮---- -/** - * SOR responses - */ - -================ -File: src/types/websockets/ws-general.ts -================ -import { AxiosRequestConfig } from 'axios'; -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; -⋮---- -import { RestClientOptions } from '../../util/requestUtils'; -import { WsKey } from '../../util/websockets/websocket-util'; -⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; -} -⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike -⋮---- -export type WsMarket = - | 'spot' - | 'spotTestnet' - | 'crossMargin' - | 'isolatedMargin' - | 'riskDataMargin' - | 'usdm' - | 'usdmTestnet' - | 'coinm' - | 'coinmTestnet' - | 'options' - | 'optionsTestnet' - | 'portfoliom' - | 'alpha'; -⋮---- -export interface WsSharedBase { - wsMarket: WsMarket; - wsKey: WsKey; - streamName: string; -} -⋮---- -export interface WsResponse { - type: 'message'; - data: { - result: boolean | string[] | null; - id: number; - isWSAPIResponse: boolean; - wsKey: WsKey; + 'order.place': (TWSKey extends WsAPIFuturesWsKey + ? WSAPINewFuturesOrderRequest + : WSAPINewSpotOrderRequest) & { + timestamp?: number; }; -} -⋮---- -// Same as inverse futures -export type WsPublicInverseTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'klineV2'; -⋮---- -export type WsPublicUSDTPerpTopic = - | 'orderBookL2_25' - | 'orderBookL2_200' - | 'trade' - | 'insurance' - | 'instrument_info' - | 'kline'; -⋮---- -export type WsPublicSpotV1Topic = - | 'trade' - | 'realtimes' - | 'kline' - | 'mergedDepth' - | 'diffDepth'; -⋮---- -export type WsPublicSpotV2Topic = 'depth' | 'kline' | 'trade' | 'realtimes'; -⋮---- -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#public-high-frequency-public-data -export type WsPublicUSDMTopic = 'bookTicker' | 'depth'; -⋮---- -// https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Important-WebSocket-Change-Notice#market-regular-market-data -export type WsMarketUSDMTopic = - | 'aggTrade' - | 'markPrice' - | 'kline' - | 'continuousKline' - | 'miniTicker' - | 'ticker' - | 'forceOrder' - | 'compositeIndex' - | 'contractInfo' - | 'assetIndex'; -⋮---- -export type WsPublicTopics = - | WsPublicInverseTopic - | WsPublicUSDTPerpTopic - | WsPublicSpotV1Topic - | WsPublicSpotV2Topic - | WsMarketUSDMTopic - | WsPublicUSDMTopic - | string; -⋮---- -// Same as inverse futures -export type WsPrivateInverseTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order'; -⋮---- -export type WsPrivateUSDTPerpTopic = - | 'position' - | 'execution' - | 'order' - | 'stop_order' - | 'wallet'; -⋮---- -export type WsPrivateSpotTopic = - | 'outboundAccountInfo' - | 'executionReport' - | 'ticketInfo'; -⋮---- -export type WsPrivateTopic = - | WsPrivateInverseTopic - | WsPrivateUSDTPerpTopic - | WsPrivateSpotTopic - | string; -⋮---- -export type WsTopic = WsPublicTopics | WsPrivateTopic; -⋮---- -export interface WSClientConfigurableOptions { - /** Your API key */ - api_key?: string; - - /** Your API secret */ - api_secret?: string; - - beautify?: boolean; + 'order.test': WSAPIOrderTestRequest; + 'order.status': TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesOrderStatusRequest + : WSAPIOrderStatusRequest; + 'order.cancel': TWSKey extends WsAPIFuturesWsKey + ? WSAPIFuturesOrderCancelRequest + : WSAPIOrderCancelRequest; + 'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures + 'order.cancelReplace': WSAPIOrderCancelReplaceRequest; + 'order.amend.keepPriority': WSAPIOrderAmendKeepPriorityRequest; + 'openOrders.status': WSAPIOpenOrdersStatusRequest; + 'openOrders.cancelAll': WSAPIOpenOrdersCancelAllRequest; - /** - * If true, log a warning if the beautifier is missing anything for an event - */ - beautifyWarnIfMissing?: boolean; + 'algoOrder.place': WSAPINewFuturesAlgoOrderRequest; + 'algoOrder.cancel': WSAPIFuturesAlgoOrderCancelRequest; /** - * Set to `true` to connect to Binance's testnet environment. - * - * Notes: - * - Not all WebSocket categories support testnet. - * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets + * Order list requests & parameters: */ - testnet?: boolean; + 'orderList.place': WSAPIOrderListPlaceRequest; + 'orderList.place.oco': WSAPIOrderListPlaceOCORequest; + 'orderList.place.oto': WSAPIOrderListPlaceOTORequest; + 'orderList.place.otoco': WSAPIOrderListPlaceOTOCORequest; + 'orderList.place.opo': WSAPIOrderListPlaceOPORequest; + 'orderList.place.opoco': WSAPIOrderListPlaceOPOCORequest; + 'orderList.status': WSAPIOrderListStatusRequest; + 'orderList.cancel': WSAPIOrderListCancelRequest; - /** - * Set to `true` to use Binance's demo trading WebSocket endpoints. - * Demo trading uses real market data but simulated trading. - * More info: https://demo.binance.com/ - * - * Notes: - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. - */ - demoTrading?: boolean; + 'openOrderLists.status': WSAPIRecvWindowTimestamp; /** - * Default: false. If true, use market maker endpoints when available. - * Eligible for high-frequency trading users who have enrolled and qualified - * in at least one of the Futures Liquidity Provider Programs. - * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + * SOR requests & parameters: */ - useMMSubdomain?: boolean; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; - - // Disable ping/pong ws heartbeat mechanism (not recommended) - disableHeartbeat?: boolean; - - /** How often to check if the connection is alive */ - pingInterval?: number; - - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; - - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; - - restOptions?: RestClientOptions; - - requestOptions?: AxiosRequestConfig; - - wsOptions?: { - protocols?: string[]; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - agent?: any; - } & ( - | Omit, 'agent'> - | Omit, 'agent'> - ); - - wsUrl?: string; + 'sor.order.place': WSAPISOROrderPlaceRequest; + 'sor.order.test': WSAPISOROrderTestRequest; /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * User data stream: * - * Look in the examples folder for a demonstration on using node's createHmac instead. + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests + * + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + * + * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. */ - customSignMessageFn?: (message: string, secret: string) => Promise; + 'userDataStream.start': { apiKey: string }; + 'userDataStream.ping': WSAPIUserDataListenKeyRequest; + 'userDataStream.stop': WSAPIUserDataListenKeyRequest; + 'userDataStream.subscribe': void; + 'userDataStream.subscribe.signature': { timestamp: number }; + 'userDataStream.unsubscribe': void; /** - * Optional custom JSON parser used for incoming WS messages. - * Defaults to JSON.parse. + * User data streams, margin: */ - customParseJSONFn?: (raw: string) => object; + 'userDataStream.subscribe.listenToken': { listenToken: string }; } ⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- /** - * If true, log a warning if the beautifier is missing anything for an event + * Authentication commands & parameters: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests */ ⋮---- /** - * Set to `true` to connect to Binance's testnet environment. - * - * Notes: - * - Not all WebSocket categories support testnet. - * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets + * General requests & parameters: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests */ ⋮---- /** - * Set to `true` to use Binance's demo trading WebSocket endpoints. - * Demo trading uses real market data but simulated trading. - * More info: https://demo.binance.com/ - * - * Notes: - * - If demo trading, `testnet` should be set to false! - * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. + * Market data requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api */ ⋮---- /** - * Default: false. If true, use market maker endpoints when available. - * Eligible for high-frequency trading users who have enrolled and qualified - * in at least one of the Futures Liquidity Provider Programs. - * More info: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + * Account requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ -⋮---- -// Disable ping/pong ws heartbeat mechanism (not recommended) +/** + * Futures account requests & parameters: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ ⋮---- -/** How often to check if the connection is alive */ +/** + * Trading requests & parameters: + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures ⋮---- -/** Delay in milliseconds before respawning the connection */ +/** + * Order list requests & parameters: + */ ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +/** + * SOR requests & parameters: + */ ⋮---- /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * User data stream: * - * Look in the examples folder for a demonstration on using node's createHmac instead. + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests + * + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + * + * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. */ ⋮---- /** - * Optional custom JSON parser used for incoming WS messages. - * Defaults to JSON.parse. + * User data streams, margin: */ ⋮---- /** - * WS configuration that's always defined, regardless of user configuration - * (usually comes from defaults if there's no user-provided values) + * Response structure expected for each operation + * + * - Each "key" here is a command/request supported by the WS API + * - Each "value" here is the response schema for that command. */ -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - pongTimeout: number; - pingInterval: number; - reconnectTimeout: number; - recvWindow: number; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequestsIndividually: boolean; +export interface WsAPIOperationResponseMap { + [key: string]: unknown; + + SUBSCRIBE: never; + UNSUBSCRIBE: never; + LIST_SUBSCRIPTIONS: never; + SET_PROPERTY: never; + GET_PROPERTY: never; + + /** + * Session authentication responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests + */ + 'session.login': WSAPIResponse; + 'session.status': WSAPIResponse; + 'session.logout': WSAPIResponse; + + /** + * General responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests + */ + + ping: unknown; + time: WSAPIResponse; + exchangeInfo: WSAPIResponse; + + /** + * Market data responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api + */ + depth: WSAPIResponse; + 'trades.recent': WSAPIResponse; + 'trades.historical': WSAPIResponse; + 'blockTrades.historical': WSAPIResponse; + 'trades.aggregate': WSAPIResponse; + klines: WSAPIResponse; + uiKlines: WSAPIResponse; + avgPrice: WSAPIResponse; + executionRules: WSAPIResponse; + referencePrice: WSAPIResponse; + 'referencePrice.calculation': WSAPIResponse; + 'ticker.24hr': WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + >; + 'ticker.tradingDay': WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + >; + ticker: WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + >; + 'ticker.price': WSAPIResponse< + | WSAPIPriceTicker + | WSAPIPriceTicker[] + | WSAPIFuturesPriceTicker + | WSAPIFuturesPriceTicker[] + >; + 'ticker.book': WSAPIResponse< + | WSAPIBookTicker + | WSAPIBookTicker[] + | WSAPIFuturesBookTicker + | WSAPIFuturesBookTicker[] + >; + + /** + * Account responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + */ + + 'account.status': WSAPIResponse< + WSAPIAccountInformation | WSAPIFuturesAccountStatus + >; + 'account.commission': WSAPIResponse; + 'account.rateLimits.orders': WSAPIResponse; + allOrders: WSAPIResponse; + allOrderLists: WSAPIResponse; + myTrades: WSAPIResponse; + myPreventedMatches: WSAPIResponse; + myAllocations: WSAPIResponse; + + /** + * Futures account responses: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ + 'account.position': WSAPIResponse; + 'v2/account.position': WSAPIResponse; + 'account.balance': WSAPIResponse; + 'v2/account.balance': WSAPIResponse; + 'v2/account.status': WSAPIResponse; + + /** + * Trading responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ + 'order.place': WSAPIResponse; + 'order.test': WSAPIResponse< + WSAPIOrderTestResponse | WSAPIOrderTestWithCommission + >; + 'order.status': WSAPIResponse; + 'order.cancel': WSAPIResponse; + 'order.modify': WSAPIResponse; + 'order.cancelReplace': WSAPIResponse; + 'openOrders.status': WSAPIResponse; + 'openOrders.cancelAll': WSAPIResponse< + (WSAPIOrderCancel | WSAPIOrderListCancelResponse)[] + >; + 'algoOrder.place': WSAPIResponse; + 'algoOrder.cancel': WSAPIResponse; + /** + * Order list responses + */ + 'orderList.place': WSAPIResponse; + 'orderList.place.oco': WSAPIResponse; + 'orderList.place.oto': WSAPIResponse; + 'orderList.place.otoco': WSAPIResponse; + 'orderList.place.opo': WSAPIResponse; + 'orderList.place.opoco': WSAPIResponse; + 'orderList.status': WSAPIResponse; + 'orderList.cancel': WSAPIResponse; + 'openOrderLists.status': WSAPIResponse; + + /** + * SOR responses + */ + 'sor.order.place': WSAPIResponse; + 'sor.order.test': WSAPIResponse< + WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission + >; + + 'userDataStream.start': WSAPIResponse<{ listenKey: string }>; + 'userDataStream.ping': WSAPIResponse; + 'userDataStream.stop': WSAPIResponse; + 'userDataStream.subscribe': WSAPIResponse; + 'userDataStream.subscribe.signature': WSAPIResponse; + 'userDataStream.unsubscribe': WSAPIResponse; } +⋮---- +/** + * Session authentication responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests + */ +⋮---- +/** + * General responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests + */ +⋮---- +/** + * Market data responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api + */ +⋮---- +/** + * Account responses: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests + */ +⋮---- +/** + * Futures account responses: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api + */ +⋮---- +/** + * Trading responses + * - Spot: + * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests + * - Futures: + * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api + */ +⋮---- +/** + * Order list responses + */ +⋮---- +/** + * SOR responses + */ ================ File: examples/Rest/Futures/rest-future-bracket-order.ts @@ -14263,2396 +14264,1638 @@ 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'; -} +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'; -} +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 NewOrderError { - code: number; - msg: string; +export interface FuturesConvertPair { + fromAsset: string; + toAsset: string; + fromAssetMinAmount: string; + fromAssetMaxAmount: string; + toAssetMinAmount: string; + toAssetMaxAmount: string; } ⋮---- -export interface OrderResult { - avgPrice: numberInString; - clientOrderId: string; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - time: number; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - goodTillDate: number; - cumBase?: numberInString; - pair?: string; +export interface FuturesConvertQuoteRequest { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + validTime?: '10s' | '30s' | '1m' | '2m'; } ⋮---- -export interface ModifyFuturesOrderResult { - orderId: number; +export interface FuturesConvertQuote { + quoteId: string; + ratio: string; + inverseRatio: string; + validTimestamp: number; + toAmount: string; + fromAmount: string; +} +⋮---- +export interface FuturesConvertOrderStatus { + orderId: string; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; +} +⋮---- +/** + * Algo Order Types (Effective 2025-12-02) + * USDⓈ-M Futures conditional orders migrate to Algo Service + */ +⋮---- +export type FuturesAlgoOrderType = 'CONDITIONAL'; +⋮---- +export type FuturesAlgoConditionalOrderTypes = + | 'STOP_MARKET' + | 'TAKE_PROFIT_MARKET' + | 'STOP' + | 'TAKE_PROFIT' + | 'TRAILING_STOP_MARKET'; +⋮---- +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update + */ +export type FuturesAlgoOrderStatus = + | 'NEW' + | 'CANCELED' + | 'TRIGGERING' + | 'TRIGGERED' + | 'FINISHED' + | 'REJECTED' + | 'EXPIRED'; +⋮---- +export interface FuturesNewAlgoOrderParams { + algoType: FuturesAlgoOrderType; symbol: string; - 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 +// 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 } + > + > { + try { + // Note: Only Ed25519 keys are supported for this feature. + // RSA & HMAC keys will automatically sign each individual request instead. -================ -File: src/websocket-client.ts -================ -import WebSocket from 'isomorphic-ws'; + // 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. + const timestamp = Date.now() + (this.getTimeOffsetMs() || 0); ⋮---- -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'; +// Note: Only Ed25519 keys are supported for this feature. +// RSA & HMAC keys will automatically sign each individual request instead. ⋮---- -type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} +// Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. ⋮---- -/** If true, will skip auth requirement for WS API connection */ +// Note: You still have to specify the timestamp parameter for SIGNED requests. ⋮---- -/** - * 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. - */ +protected sendPingEvent(wsKey: WsKey) ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -/** - * 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 sendPongEvent(wsKey: WsKey) ⋮---- -// fn pointers: +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -private getUserDataStreamManager(): UserDataStreamManager +// 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 getRestClientOptions(): RestClientOptions +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** - * 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. + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ -public connectAll(): Promise[] +protected async getWsRequestEvents( + wsKey: WsKey, + operation: WsOperation, + requests: WsTopicRequest[], +): Promise>[]> ⋮---- -/** - * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if - * you're only working with one product group. - */ -public connectPublic(): Promise[] +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- -/** - * This function serves no purpose in the Binance SDK - */ -public async connectPrivate(): Promise +// 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 -⋮---- -/** - * 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 } - > - > { - try { - // 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. - const timestamp = Date.now() + (this.getTimeOffsetMs() || 0); -⋮---- -// 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); + event: MessageEventLike, +): EmittableEvent[] +⋮---- +// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); ⋮---- /** * @@ -17237,145 +16480,905 @@ public subscribeSymbolLiquidationOrders( wsKeyOverride?: WsKey, ): Promise ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise +⋮---- +/** + * Subscribe to partial book depths (snapshots). + * + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs + */ +public subscribePartialBookDepths( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 100 | 250 | 500 | 1000, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise +⋮---- +/** + * Subscribe to orderbook depth updates to locally manage an order book. + * + * Note that the updatems parameter depends on which market you're trading + * + * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream + * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams + */ +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | '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; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; +} +⋮---- +export interface WSAPIOrderTestRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + computeCommissionRates?: boolean; + timestamp: number; + recvWindow?: number; +} +⋮---- +export interface WSAPIOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelReplaceRequest { + symbol: string; + cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; + cancelOrderId?: number; + cancelOrigClientOrderId?: string; + cancelNewClientOrderId?: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersCancelAllRequest { + symbol: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * Order list request types + */ +export interface WSAPIOrderListPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + price: numberInString; + quantity: numberInString; + listClientOrderId?: string; + limitClientOrderId?: string; + limitIcebergQty?: numberInString; + limitStrategyId?: number; + limitStrategyType?: number; + stopPrice?: numberInString; + trailingDelta?: number; + stopClientOrderId?: string; + stopLimitPrice?: numberInString; + stopLimitTimeInForce?: string; + stopIcebergQty?: numberInString; + stopStrategyId?: number; + stopStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOCORequest { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: numberInString; + listClientOrderId?: string; + aboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + aboveClientOrderId?: string; + aboveIcebergQty?: numberInString; + abovePrice?: numberInString; + aboveStopPrice?: numberInString; + aboveTrailingDelta?: number; + aboveTimeInForce?: string; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + belowClientOrderId?: string; + belowIcebergQty?: numberInString; + belowPrice?: numberInString; + belowStopPrice?: numberInString; + belowTrailingDelta?: number; + belowTimeInForce?: string; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOTORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingQuantity: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOTOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: number | string; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: numberInString; + pendingAboveStopPrice?: numberInString; + pendingAboveTrailingDelta?: numberInString; + pendingAboveIcebergQty?: numberInString; + pendingAboveTimeInForce?: string; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingBelowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOPORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOPOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingSide: 'BUY' | 'SELL'; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: numberInString; + pendingAboveStopPrice?: numberInString; + pendingAboveTrailingDelta?: numberInString; + pendingAboveIcebergQty?: numberInString; + pendingAboveTimeInForce?: string; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingAbovePegPriceType?: string; + pendingAbovePegOffsetType?: string; + pendingAbovePegOffsetValue?: number; + pendingBelowType?: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListCancelRequest { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * SOR request types + */ +export interface WSAPISOROrderPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + price?: numberInString; + quantity: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: string; + timestamp: number; + recvWindow?: number; +} +⋮---- +export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { + computeCommissionRates?: boolean; +}; ⋮---- /** - * Subscribe to partial book depths (snapshots). - * - * Note: - * - spot only supports 1000ms or 100ms for updateMs - * - futures only support 100, 250 or 500ms for updateMs - */ -public subscribePartialBookDepths( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 100 | 250 | 500 | 1000, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise + * Futures market data request types + */ ⋮---- -/** - * Subscribe to orderbook depth updates to locally manage an order book. - * - * Note that the updatems parameter depends on which market you're trading - * - * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream - * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams - */ -public subscribeDiffBookDepth( - symbol: string, - updateMs: 100 | 250 | 500 | 1000 = 100, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface WSAPIFuturesOrderBookRequest { + symbol: string; + limit?: number; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; +} ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; +} ⋮---- /** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise + * Futures trading request types + */ ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - 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 block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - 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 mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface WSAPIFuturesOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - wsKeyOverride?: WsKey, -): Promise +export interface WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface WSAPIFuturesPositionRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise +export interface WSAPIFuturesPositionV2Request { + symbol?: string; + recvWindow?: number; + timestamp: number; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +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: src/types/spot.ts @@ -18110,7 +18113,7 @@ export interface SpotExecutionRulesResponse { export interface SpotExecutionRulesParams { symbol?: string; symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; } ⋮---- /** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ @@ -25780,7 +25783,7 @@ getReferencePrice(params: { ⋮---- getReferencePriceCalculation(params: { symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; }): Promise ⋮---- get24hrChangeStatistics(params?: { @@ -29257,7 +29260,7 @@ File: package.json ================ { "name": "binance", - "version": "3.6.10", + "version": "3.6.12", "description": "Professional Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", From 55b5d7f3bb2ca34cfef29c6431c72b3f94f41e73 Mon Sep 17 00:00:00 2001 From: JJ-Cro Date: Tue, 3 Nov 2026 11:17:26 +0100 Subject: [PATCH 3/6] chore: drop added tests --- test/spot/symbolStatus.test.ts | 68 ---------------------------------- 1 file changed, 68 deletions(-) delete mode 100644 test/spot/symbolStatus.test.ts diff --git a/test/spot/symbolStatus.test.ts b/test/spot/symbolStatus.test.ts deleted file mode 100644 index 0138871a..00000000 --- a/test/spot/symbolStatus.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { MainClient, WebsocketAPIClient } from '../../src/index'; -import { WS_KEY_MAP } from '../../src/util/websockets/websocket-util'; - -describe.each(['TRADING', 'HALT', 'BREAK', 'CANCEL_ONLY', undefined] as const)( - 'Spot symbolStatus filter: %s', - (symbolStatus) => { - afterEach(() => { - jest.restoreAllMocks(); - }); - - it('forwards the REST execution rules filter', async () => { - const client = new MainClient(); - const getSpy = jest.spyOn(client, 'get').mockResolvedValue({}); - - await client.getExecutionRules({ symbolStatus }); - - expect(getSpy).toHaveBeenCalledWith('api/v3/executionRules', { - symbolStatus, - }); - }); - - it('forwards the REST reference price calculation filter', async () => { - const client = new MainClient(); - const getSpy = jest.spyOn(client, 'get').mockResolvedValue({}); - const params = { symbol: 'BTCUSDT', symbolStatus }; - - await client.getReferencePriceCalculation(params); - - expect(getSpy).toHaveBeenCalledWith( - 'api/v3/referencePrice/calculation', - params, - ); - }); - - it('forwards the WebSocket execution rules filter without authentication', async () => { - const client = new WebsocketAPIClient(); - const sendSpy = jest - .spyOn(client.getWSClient(), 'sendWSAPIRequest') - .mockResolvedValue({}); - - await client.getSpotExecutionRules({ symbolStatus }); - - expect(sendSpy).toHaveBeenCalledWith( - WS_KEY_MAP.mainWSAPI, - 'executionRules', - { symbolStatus }, - { authIsOptional: true }, - ); - }); - - it('forwards the WebSocket reference price calculation filter without authentication', async () => { - const client = new WebsocketAPIClient(); - const sendSpy = jest - .spyOn(client.getWSClient(), 'sendWSAPIRequest') - .mockResolvedValue({}); - const params = { symbol: 'BTCUSDT', symbolStatus }; - - await client.getSpotReferencePriceCalculation(params); - - expect(sendSpy).toHaveBeenCalledWith( - WS_KEY_MAP.mainWSAPI, - 'referencePrice.calculation', - params, - { authIsOptional: true }, - ); - }); - }, -); From 2f9b3f00fba42c744d112c2c49b6f3a4af364644 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Tue, 3 Nov 2026 11:18:27 +0100 Subject: [PATCH 4/6] chore: regenerate endpoint docs and examples --- llms.txt | 224 +++++++++++++++++++++++++++---------------------------- 1 file changed, 112 insertions(+), 112 deletions(-) diff --git a/llms.txt b/llms.txt index c1b43c25..a15412ef 100644 --- a/llms.txt +++ b/llms.txt @@ -1105,6 +1105,118 @@ function onUserDataEvent(data: WsUserDataEvents) // wsClient.closeAll(); // }, 1000 * 15); +================ +File: examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts +================ +// or +// import { +// DefaultLogger, +// isWsFormattedFuturesUserDataEvent, +// isWsFormattedSpotUserDataEvent, +// isWsFormattedSpotUserDataExecutionReport, +// isWsFormattedUserDataEvent, +// WebsocketClient, +// WsUserDataEvents, +// } from 'binance'; +⋮---- +import { + DefaultLogger, + isWsFormattedFuturesUserDataEvent, + isWsFormattedSpotUserDataEvent, + isWsFormattedSpotUserDataExecutionReport, + isWsFormattedUserDataEvent, + WebsocketClient, + WsConnectionStateEnum, + WsUserDataEvents, +} from '../../../src/index'; +⋮---- +// Optional, hook and customise logging behavior +⋮---- +// testnet: true, +⋮---- +// wsClient.on('message', (data) => { +// console.log('raw message received ', JSON.stringify(data, null, 2)); +// }); +⋮---- +function onUserDataEvent(data: WsUserDataEvents) +⋮---- +// the market denotes which API category it came from +// if (data.wsMarket.includes('spot')) { +⋮---- +// or use a type guard, if one exists (PRs welcome) +⋮---- +// The wsKey can be parsed to determine the type of message (what websocket it came from) +// if (!Array.isArray(data) && data.wsKey.includes('userData')) { +// return onUserDataEvent(data); +// } +⋮---- +// or use a type guard if available +⋮---- +// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +⋮---- +// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: +// - fetch balances +// - fetch positions +// - fetch orders +⋮---- +/** + * This example demonstrates subscribing to the user data stream via the + * listen key workflow. + * + * Note: the listen key workflow is deprecated for "spot" markets. Use the + * WebSocket API `userDataStream.subscribe` workflow instead (only available + * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + * + * Each method below opens a dedicated WS connection attached to an automatically + * fetched listen key (a session for your user data stream). + * + * Once subscribed, you don't need to do anything else. Listen-key keep-alive, refresh, reconnects, etc are all automatically handled by the SDK. + */ +⋮---- +/** + * Note: for spot markets, the listen key workflow is deprecated. Use the + * WebSocket API `userDataStream.subscribe` workflow instead (only available + * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. + */ +// Deprecated, see above: wsClient.subscribeSpotUserDataStream(); +// Deprecated, see above: wsClient.subscribeSpotUserDataStream('main2'); +// Deprecated, see above: wsClient.subscribeCrossMarginUserDataStream(); +// Deprecated, see above: wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDC'); +⋮---- +/** + * Futures + */ +⋮---- +// Example 5: usdm futures +⋮---- +// Example 6: coinm futures +⋮---- +// Example 7: portfolio margin +⋮---- +// Example 8: portfolio margin pro +⋮---- +// after 15 seconds, kill user data connections one by one (or all at once) +⋮---- +// console.log('killing all connections at once'); +// wsClient.closeAll(); +⋮---- +// or: +⋮---- +// console.log('killing all connections'); +// wsClient.closeAll(); +// Example 5: usdm futures +⋮---- +// Example 6: coinm futures +⋮---- +// // Example 7: portfolio margin +// wsClient.unsubscribePortfolioMarginUserDataStream(); +// // Example 8: portfolio margin pro +// wsClient.unsubscribePortfolioMarginUserDataStream( +// 'portfolioMarginProUserData', +// ); +⋮---- +// after 20 seconds, list the remaining open connections + ================ File: examples/WebSockets/Private(userdata)/ws-userdata-README.MD ================ @@ -2842,118 +2954,6 @@ File: tsconfig.linting.json ] } -================ -File: examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts -================ -// or -// import { -// DefaultLogger, -// isWsFormattedFuturesUserDataEvent, -// isWsFormattedSpotUserDataEvent, -// isWsFormattedSpotUserDataExecutionReport, -// isWsFormattedUserDataEvent, -// WebsocketClient, -// WsUserDataEvents, -// } from 'binance'; -⋮---- -import { - DefaultLogger, - isWsFormattedFuturesUserDataEvent, - isWsFormattedSpotUserDataEvent, - isWsFormattedSpotUserDataExecutionReport, - isWsFormattedUserDataEvent, - WebsocketClient, - WsConnectionStateEnum, - WsUserDataEvents, -} from '../../../src/index'; -⋮---- -// Optional, hook and customise logging behavior -⋮---- -// testnet: true, -⋮---- -// wsClient.on('message', (data) => { -// console.log('raw message received ', JSON.stringify(data, null, 2)); -// }); -⋮---- -function onUserDataEvent(data: WsUserDataEvents) -⋮---- -// the market denotes which API category it came from -// if (data.wsMarket.includes('spot')) { -⋮---- -// or use a type guard, if one exists (PRs welcome) -⋮---- -// The wsKey can be parsed to determine the type of message (what websocket it came from) -// if (!Array.isArray(data) && data.wsKey.includes('userData')) { -// return onUserDataEvent(data); -// } -⋮---- -// or use a type guard if available -⋮---- -// response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -⋮---- -// This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: -// - fetch balances -// - fetch positions -// - fetch orders -⋮---- -/** - * This example demonstrates subscribing to the user data stream via the - * listen key workflow. - * - * Note: the listen key workflow is deprecated for "spot" markets. Use the - * WebSocket API `userDataStream.subscribe` workflow instead (only available - * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. - * - * Each method below opens a dedicated WS connection attached to an automatically - * fetched listen key (a session for your user data stream). - * - * Once subscribed, you don't need to do anything else. Listen-key keep-alive, refresh, reconnects, etc are all automatically handled by the SDK. - */ -⋮---- -/** - * Note: for spot markets, the listen key workflow is deprecated. Use the - * WebSocket API `userDataStream.subscribe` workflow instead (only available - * in spot right now). See `subscribeUserDataStream()` in the WebsocketAPIClient. - */ -// Deprecated, see above: wsClient.subscribeSpotUserDataStream(); -// Deprecated, see above: wsClient.subscribeSpotUserDataStream('main2'); -// Deprecated, see above: wsClient.subscribeCrossMarginUserDataStream(); -// Deprecated, see above: wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDC'); -⋮---- -/** - * Futures - */ -⋮---- -// Example 5: usdm futures -⋮---- -// Example 6: coinm futures -⋮---- -// Example 7: portfolio margin -⋮---- -// Example 8: portfolio margin pro -⋮---- -// after 15 seconds, kill user data connections one by one (or all at once) -⋮---- -// console.log('killing all connections at once'); -// wsClient.closeAll(); -⋮---- -// or: -⋮---- -// console.log('killing all connections'); -// wsClient.closeAll(); -// Example 5: usdm futures -⋮---- -// Example 6: coinm futures -⋮---- -// // Example 7: portfolio margin -// wsClient.unsubscribePortfolioMarginUserDataStream(); -// // Example 8: portfolio margin pro -// wsClient.unsubscribePortfolioMarginUserDataStream( -// 'portfolioMarginProUserData', -// ); -⋮---- -// after 20 seconds, list the remaining open connections - ================ File: src/types/websockets/ws-general.ts ================ From d49135c2982767dbe931f3223601552c86dcb36f Mon Sep 17 00:00:00 2001 From: JJ-Cro Date: Mon, 9 Nov 2026 09:21:01 +0100 Subject: [PATCH 5/6] feat(v3.6.12): add margin ratios and sub-account API key management - Add borrow and transfer-out collateral ratio types for cross margin. - Add sub-account API key query, creation, deletion and permission methods. - Support FIX trading and reading permissions for sub-account API keys. --- src/main-client.ts | 59 +++++++++++++++++++++++++++++++ src/types/spot.ts | 88 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+) diff --git a/src/main-client.ts b/src/main-client.ts index 68e31ff6..8361e753 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -140,6 +140,8 @@ import { CreateInvestmentPlanParams, CreateInvestmentPlanResponse, CreateSpecialLowLatencyKeyParams, + CreateSubAccountApiKeyParams, + CreateSubAccountApiKeyResponse, CreateSubAccountParams, CrossMarginFeeData, CrossMarginTransferHistory, @@ -151,6 +153,8 @@ import { DelegationHistory, DelegationHistoryParams, DeleteApiKeyBrokerSubAccountParams, + DeleteSubAccountApiKeyParams, + DeleteSubAccountApiKeyResponse, DelistScheduleResponse, DepositAddress, DepositAddressListParams, @@ -343,6 +347,7 @@ import { GetSpotRebateHistoryRecordsResponse, GetStatisticListParams, GetStatisticListResponse, + GetSubAccountApiKeysParams, GetSubAccountDepositHistoryParams, GetSubscriptionTransactionHistoryParams, GetTargetAssetListParams, @@ -416,6 +421,8 @@ import { MarginOTOCOOrder, MarginOTOOrder, MarginTransactionResponse, + ModifySubAccountApiKeyPermissionParams, + ModifySubAccountApiKeyPermissionResponse, NewFutureAccountTransferParams, NewOrderListOPOCOParams, NewOrderListOPOCOResponse, @@ -567,6 +574,7 @@ import { StakingProductPosition, StakingProductType, SubAccountAddOrDeleteIPList, + SubAccountApiKey, SubAccountAssetDetails, SubAccountAssets, SubAccountAssetsParams, @@ -1178,9 +1186,19 @@ export class MainClient extends BaseRestClient { * **/ + /** + * Get cross margin collateral ratios. + * The additional ratio sets are undocumented in the endpoint reference but confirmed by Binance staff. + * @see https://dev.binance.vision/t/39429 + */ getCrossMarginCollateralRatio(): Promise< { + /** Liquidation collateral ratios. */ collaterals: Collateral[]; + /** Transfer-out collateral ratios (undocumented, confirmed by Binance staff). */ + withdrawCollaterals?: Collateral[]; + /** Borrow collateral ratios (undocumented, confirmed by Binance staff). */ + borrowCollaterals?: Collateral[]; assetNames: string[]; }[] > { @@ -2088,6 +2106,47 @@ export class MainClient extends BaseRestClient { * **/ + /** + * Query a sub-account's API keys (for master account). + */ + getSubAccountApiKeys( + params: GetSubAccountApiKeysParams, + ): Promise> { + return this.getPrivate('sapi/v1/sub-account/subAccountApi', params); + } + + /** + * Create a sub-account API key (for master account). + * Permission flags default to false. FIX permissions require an Ed25519 key. + */ + createSubAccountApiKey( + params: CreateSubAccountApiKeyParams, + ): Promise { + return this.postPrivate('sapi/v1/sub-account/subAccountApi', params); + } + + /** + * Delete a sub-account API key (for master account). + */ + deleteSubAccountApiKey( + params: DeleteSubAccountApiKeyParams, + ): Promise { + return this.deletePrivate('sapi/v1/sub-account/subAccountApi', params); + } + + /** + * Modify a sub-account API key's permissions (for master account). + * FIX permissions require an Ed25519 key and remain unchanged when omitted. + */ + modifySubAccountApiKeyPermission( + params: ModifySubAccountApiKeyPermissionParams, + ): Promise { + return this.postPrivate( + 'sapi/v1/sub-account/subAccountApiPermission', + params, + ); + } + getSubAccountIPRestriction( params: BasicSubAccount, ): Promise { diff --git a/src/types/spot.ts b/src/types/spot.ts index 479d6970..9688678c 100644 --- a/src/types/spot.ts +++ b/src/types/spot.ts @@ -1410,6 +1410,93 @@ export interface CreateSubAccountParams { subAccountString: string; } +export interface GetSubAccountApiKeysParams { + email: string; + subAccountApiKey?: string; + /** Page number, default 1, minimum 1. */ + page?: number; + /** Page size, default 30, maximum 100. */ + size?: number; + recvWindow?: number; +} + +export interface CreateSubAccountApiKeyParams { + email: string; + apiName: string; + /** 1: unrestricted, 2: trusted IPs only, 3: third-party IP restriction. */ + status: 1 | 2 | 3; + canTrade?: boolean; + canMarginLoanRepay?: boolean; + canFuturesTrade?: boolean; + canUniversalTransfer?: boolean; + canVanillaOptions?: boolean; + /** FIX trading requires an Ed25519 key; other key types return -9000 when enabled. */ + canFixApiTrading?: boolean; + /** FIX reading requires an Ed25519 key; other key types return -9000 when enabled. */ + canFixApiReading?: boolean; + /** Required when status is 2. Maximum 500 characters. */ + ipAddress?: string; + /** Required when status is 3. */ + thirdPartyName?: string; + /** Ed25519 public key. */ + publicKey?: string; + recvWindow?: number; +} + +export interface CreateSubAccountApiKeyResponse { + apiName: string; + apiKey: string; + /** Returned only on creation. */ + secretKey: string; + canTrade: boolean; + canMarginLoanRepay: boolean; + canFuturesTrade: boolean; + canUniversalTransfer: boolean; + canVanillaOptions: boolean; + canFixApiTrading: boolean; + canFixApiReading: boolean; + status: number; + ipList: string[]; +} + +export interface DeleteSubAccountApiKeyParams extends BasicSubAccount { + recvWindow?: number; +} + +export type DeleteSubAccountApiKeyResponse = Record; + +export interface ModifySubAccountApiKeyPermissionParams + extends BasicSubAccount { + canTrade?: boolean; + canMarginLoanRepay?: boolean; + canFuturesTrade?: boolean; + canUniversalTransfer?: boolean; + canVanillaOptions?: boolean; + /** Ed25519 keys only; omitted values remain unchanged. Other key types return -9000 when enabled. */ + canFixApiTrading?: boolean; + /** Ed25519 keys only; omitted values remain unchanged. Other key types return -9000 when enabled. */ + canFixApiReading?: boolean; + recvWindow?: number; +} + +export interface ModifySubAccountApiKeyPermissionResponse { + apiName: string; + apikey: string; + canTrade: boolean; + canMarginLoanRepay: boolean; + canFuturesTrade: boolean; + canUniversalTransfer: boolean; + canVanillaOptions: boolean; + canFixApiTrading: boolean; + canFixApiReading: boolean; + timestamp: number; +} + +export interface SubAccountApiKey + extends ModifySubAccountApiKeyPermissionResponse { + email: string; +} + export interface EnableOrDisableIPRestrictionForSubAccountParams extends BasicSubAccount { ipAddress?: string; @@ -3209,6 +3296,7 @@ export interface MarginOrderCountUsageResponse { export interface Collateral { minUsdValue: string; + /** Omitted for the highest tier (no upper limit), confirmed by Binance staff on Dev Vision. */ maxUsdValue?: string; discountRate: string; } From afbd56b7415613ebeba3a5f8269db348757a02ad Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 9 Nov 2026 09:21:54 +0100 Subject: [PATCH 6/6] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 1068 +- .../MainClient/createSubAccountApiKey.js | 22 + .../MainClient/deleteSubAccountApiKey.js | 22 + .../apidoc/MainClient/getSubAccountApiKeys.js | 22 + .../modifySubAccountApiKeyPermission.js | 22 + llms.txt | 30000 ++++++++-------- 6 files changed, 15889 insertions(+), 15267 deletions(-) create mode 100644 examples/apidoc/MainClient/createSubAccountApiKey.js create mode 100644 examples/apidoc/MainClient/deleteSubAccountApiKey.js create mode 100644 examples/apidoc/MainClient/getSubAccountApiKeys.js create mode 100644 examples/apidoc/MainClient/modifySubAccountApiKeyPermission.js diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 3838288f..91d34e34 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -52,538 +52,542 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [testConnectivity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L790) | | GET | `api/v3/ping` | -| [getExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L794) | | GET | `api/v3/exchangeInfo` | -| [getOrderBook()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L814) | | GET | `api/v3/depth` | -| [getRecentTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L818) | | GET | `api/v3/trades` | -| [getHistoricalTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L822) | | GET | `api/v3/historicalTrades` | -| [getHistoricalBlockTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L826) | | GET | `api/v3/historicalBlockTrades` | -| [getAggregateTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L832) | | GET | `api/v3/aggTrades` | -| [getKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L838) | | GET | `api/v3/klines` | -| [getUIKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L842) | | GET | `api/v3/uiKlines` | -| [getAvgPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L846) | | GET | `api/v3/avgPrice` | -| [getExecutionRules()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L850) | | GET | `api/v3/executionRules?symbols=` | -| [getReferencePrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L865) | | GET | `api/v3/referencePrice` | -| [getReferencePriceCalculation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L871) | | GET | `api/v3/referencePrice/calculation` | -| [get24hrChangeStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L878) | | GET | `api/v3/ticker/24hr?symbols=` | -| [getTradingDayTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L908) | | GET | `api/v3/ticker/tradingDay?symbols=` | -| [getSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L923) | | GET | `api/v3/ticker/price?symbols=` | -| [getSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L940) | | GET | `api/v3/ticker/bookTicker?symbols=` | -| [getRollingWindowTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L957) | | GET | `api/v3/ticker?symbols=` | -| [submitNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L979) | :closed_lock_with_key: | POST | `api/v3/order` | -| [testNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L987) | :closed_lock_with_key: | POST | `api/v3/order/test` | -| [getOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L995) | :closed_lock_with_key: | GET | `api/v3/order` | -| [cancelOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L999) | :closed_lock_with_key: | DELETE | `api/v3/order` | -| [cancelAllSymbolOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1003) | :closed_lock_with_key: | DELETE | `api/v3/openOrders` | -| [replaceOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1009) | :closed_lock_with_key: | POST | `api/v3/order/cancelReplace` | -| [amendOrderKeepPriority()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1023) | :closed_lock_with_key: | PUT | `fapi/v1/order/amend/keepPriority` | -| [getOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1030) | :closed_lock_with_key: | GET | `api/v3/openOrders` | -| [getAllOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1034) | :closed_lock_with_key: | GET | `api/v3/allOrders` | -| [submitNewOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1041) | :closed_lock_with_key: | POST | `api/v3/order/oco` | -| [submitNewOrderList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1048) | :closed_lock_with_key: | POST | `api/v3/orderList/oco` | -| [submitNewOrderListOTO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1057) | :closed_lock_with_key: | POST | `api/v3/orderList/oto` | -| [submitNewOrderListOTOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1066) | :closed_lock_with_key: | POST | `api/v3/orderList/otoco` | -| [submitNewOrderListOPO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1076) | :closed_lock_with_key: | POST | `api/v3/orderList/opo` | -| [submitNewOrderListOPOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1085) | :closed_lock_with_key: | POST | `api/v3/orderList/opoco` | -| [cancelOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1095) | :closed_lock_with_key: | DELETE | `api/v3/orderList` | -| [getOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1100) | :closed_lock_with_key: | GET | `api/v3/orderList` | -| [getAllOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1104) | :closed_lock_with_key: | GET | `api/v3/allOrderList` | -| [getAllOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1111) | :closed_lock_with_key: | GET | `api/v3/openOrderList` | -| [submitNewSOROrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1118) | :closed_lock_with_key: | POST | `api/v3/sor/order` | -| [testNewSOROrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1129) | :closed_lock_with_key: | POST | `api/v3/sor/order/test` | -| [getAccountInformation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1145) | :closed_lock_with_key: | GET | `api/v3/account` | -| [getAccountTradeList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1151) | :closed_lock_with_key: | GET | `api/v3/myTrades` | -| [getOrderRateLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1157) | :closed_lock_with_key: | GET | `api/v3/rateLimit/order` | -| [getPreventedMatches()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1161) | :closed_lock_with_key: | GET | `api/v3/myPreventedMatches` | -| [getAllocations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1167) | :closed_lock_with_key: | GET | `api/v3/myAllocations` | -| [getCommissionRates()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1171) | :closed_lock_with_key: | GET | `api/v3/account/commission` | -| [getCrossMarginCollateralRatio()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1181) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginCollateralRatio` | -| [getAllCrossMarginPairs()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1190) | | GET | `sapi/v1/margin/allPairs` | -| [getIsolatedMarginAllSymbols()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1194) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/allPairs` | -| [getAllMarginAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1200) | | GET | `sapi/v1/margin/allAssets` | -| [getMarginDelistSchedule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1204) | :closed_lock_with_key: | GET | `sapi/v1/margin/delist-schedule` | -| [getIsolatedMarginTierData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1208) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginTier` | -| [queryMarginPriceIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1214) | | GET | `sapi/v1/margin/priceIndex` | -| [getMarginAvailableInventory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1220) | :closed_lock_with_key: | GET | `sapi/v1/margin/available-inventory` | -| [getLeverageBracket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1226) | :closed_lock_with_key: | GET | `sapi/v1/margin/leverageBracket` | -| [getNextHourlyInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1236) | :closed_lock_with_key: | GET | `sapi/v1/margin/next-hourly-interest-rate` | -| [getMarginInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1242) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestHistory` | -| [submitMarginAccountBorrowRepay()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1249) | :closed_lock_with_key: | POST | `sapi/v1/margin/borrow-repay` | -| [getMarginAccountBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1255) | :closed_lock_with_key: | GET | `sapi/v1/margin/borrow-repay` | -| [getMarginInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1261) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestRateHistory` | -| [queryMaxBorrow()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1267) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxBorrowable` | -| [getMarginForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1279) | :closed_lock_with_key: | GET | `sapi/v1/margin/forceLiquidationRec` | -| [getSmallLiabilityExchangeCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1288) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability` | -| [getSmallLiabilityExchangeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1292) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability-history` | -| [marginAccountCancelOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1304) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/openOrders` | -| [marginAccountCancelOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1310) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/orderList` | -| [marginAccountCancelOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1315) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/order` | -| [marginAccountNewOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1321) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oco` | -| [marginAccountNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1328) | :closed_lock_with_key: | POST | `sapi/v1/margin/order` | -| [getMarginOrderCountUsage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1336) | :closed_lock_with_key: | GET | `sapi/v1/margin/rateLimit/order` | -| [queryMarginAccountAllOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1342) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrderList` | -| [queryMarginAccountAllOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1348) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrders` | -| [queryMarginAccountOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1354) | :closed_lock_with_key: | GET | `sapi/v1/margin/orderList` | -| [queryMarginAccountOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1358) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrderList` | -| [queryMarginAccountOpenOTOOrderLists()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1365) | :closed_lock_with_key: | GET | `sapi/v1/margin/oto/openOrderList` | -| [queryMarginAccountOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1371) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrders` | -| [queryMarginAccountOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1375) | :closed_lock_with_key: | GET | `sapi/v1/margin/order` | -| [queryMarginAccountTradeList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1379) | :closed_lock_with_key: | GET | `sapi/v1/margin/myTrades` | -| [submitSmallLiabilityExchange()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1385) | :closed_lock_with_key: | POST | `sapi/v1/margin/exchange-small-liability` | -| [submitManualLiquidation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1392) | :closed_lock_with_key: | POST | `sapi/v1/margin/manual-liquidation` | -| [submitMarginOTOOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1401) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oto` | -| [submitMarginOTOCOOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1413) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/otoco` | -| [createMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1426) | :closed_lock_with_key: | POST | `sapi/v1/margin/apiKey` | -| [deleteMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1432) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/apiKey` | -| [updateMarginIPForSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1440) | :closed_lock_with_key: | PUT | `sapi/v1/margin/apiKey/ip` | -| [getMarginSpecialLowLatencyKeys()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1451) | :closed_lock_with_key: | GET | `sapi/v1/margin/api-key-list` | -| [getMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1460) | :closed_lock_with_key: | GET | `sapi/v1/margin/apiKey` | -| [getMarginLiquidationLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1470) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan` | -| [repayMarginLiquidationLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1477) | :closed_lock_with_key: | POST | `sapi/v1/margin/liquidation-loan/repay` | -| [getMarginLiquidationLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1486) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan/repay-history` | -| [exitMarginSpecialKeyMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1498) | :closed_lock_with_key: | POST | `sapi/v1/margin/exit-special-key-mode` | -| [getCrossMarginTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1508) | :closed_lock_with_key: | GET | `sapi/v1/margin/transfer` | -| [queryMaxTransferOutAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1514) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxTransferable` | -| [updateCrossMarginMaxLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1526) | :closed_lock_with_key: | POST | `sapi/v1/margin/max-leverage` | -| [disableIsolatedMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1532) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/isolated/account` | -| [enableIsolatedMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1539) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/account` | -| [getBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1546) | :closed_lock_with_key: | GET | `sapi/v1/bnbBurn` | -| [getMarginSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1550) | :closed_lock_with_key: | GET | `sapi/v1/margin/tradeCoeff` | -| [queryCrossMarginAccountDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1554) | :closed_lock_with_key: | GET | `sapi/v1/margin/account` | -| [getCrossMarginFeeData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1558) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginData` | -| [getIsolatedMarginAccountLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1564) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/accountLimit` | -| [getIsolatedMarginAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1571) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/account` | -| [getIsolatedMarginFeeData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1577) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginData` | -| [toggleBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1583) | :closed_lock_with_key: | POST | `sapi/v1/bnbBurn` | -| [getMarginCapitalFlow()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1591) | :closed_lock_with_key: | GET | `sapi/v1/margin/capital-flow` | -| [queryLoanRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1600) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan` | -| [queryRepayRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1609) | :closed_lock_with_key: | GET | `sapi/v1/margin/repay` | -| [isolatedMarginAccountTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1618) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/transfer` | -| [getBalances()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1630) | :closed_lock_with_key: | GET | `sapi/v1/capital/config/getall` | -| [withdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1634) | :closed_lock_with_key: | POST | `sapi/v1/capital/withdraw/apply` | -| [getWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1638) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/history` | -| [getWithdrawAddresses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1644) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/address/list` | -| [getWithdrawQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1648) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/quota` | -| [getDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1655) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/hisrec` | -| [getDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1659) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address` | -| [getDepositAddresses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1665) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address/list` | -| [submitDepositCredit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1671) | :closed_lock_with_key: | POST | `sapi/v1/capital/deposit/credit-apply` | -| [getAutoConvertStablecoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1680) | :closed_lock_with_key: | GET | `sapi/v1/capital/contract/convertible-coins` | -| [setConvertibleCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1687) | :closed_lock_with_key: | POST | `sapi/v1/capital/contract/convertible-coins` | -| [getAssetDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1700) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDetail` | -| [getWalletBalances()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1706) | :closed_lock_with_key: | GET | `sapi/v1/asset/wallet/balance` | -| [getUserAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1712) | :closed_lock_with_key: | POST | `sapi/v3/asset/getUserAsset` | -| [getSpotAssetTags()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1716) | | GET | `sapi/v1/spot/asset/tags` | -| [submitUniversalTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1720) | :closed_lock_with_key: | POST | `sapi/v1/asset/transfer` | -| [getUniversalTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1726) | :closed_lock_with_key: | GET | `sapi/v1/asset/transfer` | -| [getDust()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1732) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-btc` | -| [convertDustToBnb()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1736) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust` | -| [convertDustAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1743) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/convert` | -| [queryDustConvertibleAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1750) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/query-convertible-assets` | -| [getDustLog()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1759) | :closed_lock_with_key: | GET | `sapi/v1/asset/dribblet` | -| [getAssetDividendRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1763) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDividend` | -| [getTradeFee()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1767) | :closed_lock_with_key: | GET | `sapi/v1/asset/tradeFee` | -| [getFundingAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1771) | :closed_lock_with_key: | POST | `sapi/v1/asset/get-funding-asset` | -| [getCloudMiningHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1775) | :closed_lock_with_key: | GET | `sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage` | -| [getDelegationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1785) | :closed_lock_with_key: | GET | `sapi/v1/asset/custody/transfer-history` | -| [submitNewFutureAccountTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1815) | :closed_lock_with_key: | POST | `sapi/v1/futures/transfer` | -| [getFutureAccountTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1825) | :closed_lock_with_key: | GET | `sapi/v1/futures/transfer` | -| [getCrossCollateralBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1834) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/borrow/history` | -| [getCrossCollateralRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1841) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/repay/history` | -| [getCrossCollateralWalletV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1848) | :closed_lock_with_key: | GET | `sapi/v2/futures/loan/wallet` | -| [getAdjustCrossCollateralLTVHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1855) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/adjustCollateral/history` | -| [getCrossCollateralLiquidationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1867) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/liquidationHistory` | -| [getCrossCollateralInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1876) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/interestHistory` | -| [getAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1888) | :closed_lock_with_key: | GET | `sapi/v1/account/info` | -| [getDailyAccountSnapshot()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1892) | :closed_lock_with_key: | GET | `sapi/v1/accountSnapshot` | -| [disableFastWithdrawSwitch()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1898) | :closed_lock_with_key: | POST | `sapi/v1/account/disableFastWithdrawSwitch` | -| [enableFastWithdrawSwitch()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1902) | :closed_lock_with_key: | POST | `sapi/v1/account/enableFastWithdrawSwitch` | -| [getAccountStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1906) | :closed_lock_with_key: | GET | `sapi/v1/account/status` | -| [getApiTradingStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1910) | :closed_lock_with_key: | GET | `sapi/v1/account/apiTradingStatus` | -| [getApiKeyPermissions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1914) | :closed_lock_with_key: | GET | `sapi/v1/account/apiRestrictions` | -| [withdrawTravelRule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1930) | :closed_lock_with_key: | POST | `sapi/v1/localentity/withdraw/apply` | -| [getTravelRuleWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1941) | :closed_lock_with_key: | GET | `sapi/v1/localentity/withdraw/history` | -| [getTravelRuleWithdrawHistoryV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1950) | :closed_lock_with_key: | GET | `sapi/v2/localentity/withdraw/history` | -| [submitTravelRuleDepositQuestionnaire()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1962) | :closed_lock_with_key: | PUT | `sapi/v1/localentity/deposit/provide-info` | -| [getTravelRuleDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1971) | :closed_lock_with_key: | GET | `sapi/v1/localentity/deposit/history` | -| [getOnboardedVASPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1982) | :closed_lock_with_key: | GET | `sapi/v1/localentity/vasp` | -| [getTravelRuleCountryList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1986) | :closed_lock_with_key: | GET | `sapi/v1/localentity/country/list` | -| [getTravelRuleRegionList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1990) | :closed_lock_with_key: | GET | `sapi/v1/localentity/region/list` | -| [getSystemStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2002) | | GET | `sapi/v1/system/status` | -| [getDelistSchedule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2006) | :closed_lock_with_key: | GET | `sapi/v1/spot/delist-schedule` | -| [createVirtualSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2016) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/virtualSubAccount` | -| [getSubAccountList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2022) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/list` | -| [subAccountEnableFutures()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2028) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/enable` | -| [subAccountEnableMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2036) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/enable` | -| [enableOptionsForSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2040) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/eoptions/enable` | -| [subAccountEnableLeverageToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2050) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/blvt/enable` | -| [getSubAccountStatusOnMarginOrFutures()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2056) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/status` | -| [getSubAccountFuturesPositionRisk()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2062) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/positionRisk` | -| [getSubAccountFuturesPositionRiskV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2070) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/positionRisk` | -| [getSubAccountTransactionStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2076) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transaction-statistics` | -| [getSubAccountIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2091) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/subAccountApi/ipRestriction` | -| [subAccountDeleteIPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2100) | :closed_lock_with_key: | DELETE | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | -| [subAccountAddIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2109) | :closed_lock_with_key: | POST | `sapi/v2/sub-account/subAccountApi/ipRestriction` | -| [subAccountAddIPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2122) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | -| [subAccountEnableOrDisableIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2135) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction` | -| [subAccountFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2150) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/transfer` | -| [getSubAccountFuturesAccountDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2156) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/account` | -| [getSubAccountDetailOnFuturesAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2162) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/account` | -| [getSubAccountDetailOnMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2168) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/account` | -| [getSubAccountDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2174) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subAddress` | -| [getSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2180) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subHisrec` | -| [getSubAccountFuturesAccountSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2186) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/accountSummary` | -| [getSubAccountSummaryOnFuturesAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2190) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/accountSummary` | -| [getSubAccountsSummaryOfMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2199) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/accountSummary` | -| [subAccountMarginTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2203) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/transfer` | -| [getSubAccountAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2209) | :closed_lock_with_key: | GET | `sapi/v3/sub-account/assets` | -| [getSubAccountAssetsMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2215) | :closed_lock_with_key: | GET | `sapi/v4/sub-account/assets` | -| [getSubAccountFuturesAssetTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2221) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/internalTransfer` | -| [getSubAccountSpotAssetTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2230) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/sub/transfer/history` | -| [getSubAccountSpotAssetsSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2236) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/spotSummary` | -| [getSubAccountUniversalTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2242) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/universalTransfer` | -| [subAccountFuturesAssetTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2248) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/internalTransfer` | -| [subAccountTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2257) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transfer/subUserHistory` | -| [subAccountTransferToMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2266) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToMaster` | -| [subAccountTransferToSameMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2272) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToSub` | -| [subAccountUniversalTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2278) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/universalTransfer` | -| [subAccountMovePosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2284) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/move-position` | -| [getSubAccountFuturesPositionMoveHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2293) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/move-position` | -| [depositAssetsIntoManagedSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2308) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/deposit` | -| [getManagedSubAccountDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2314) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/deposit/address` | -| [withdrawAssetsFromManagedSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2323) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/withdraw` | -| [getManagedSubAccountTransfersParent()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2329) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForTradeParent` | -| [getManagedSubAccountTransferLog()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2341) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/query-trans-log` | -| [getManagedSubAccountTransfersInvestor()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2353) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForInvestor` | -| [getManagedSubAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2365) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/info` | -| [getManagedSubAccountSnapshot()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2372) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/accountSnapshot` | -| [getManagedSubAccountAssetDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2381) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/asset` | -| [getManagedSubAccountMarginAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2387) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/marginAsset` | -| [getManagedSubAccountFuturesAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2394) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/fetch-future-asset` | -| [getAutoInvestAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2410) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/all/asset` | -| [getAutoInvestSourceAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2417) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/source-asset/list` | -| [getAutoInvestTargetAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2426) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/list` | -| [getAutoInvestTargetAssetsROI()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2435) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/roi/list` | -| [getAutoInvestIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2444) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/info` | -| [getAutoInvestPlans()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2450) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/list` | -| [submitAutoInvestOneTimeTransaction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2468) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/one-off` | -| [updateAutoInvestPlanStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2484) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit-status` | -| [updateAutoInvestmentPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2493) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit` | -| [submitAutoInvestRedemption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2510) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/redeem` | -| [getAutoInvestSubscriptionTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2518) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/history/list` | -| [getOneTimeTransactionStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2524) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/one-off/status` | -| [submitAutoInvestmentPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2533) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/add` | -| [getAutoInvestRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2548) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/redeem/history` | -| [getAutoInvestPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2557) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/id` | -| [getAutoInvestUserIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2561) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/user-summary` | -| [getAutoInvestRebalanceHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2570) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/rebalance/history` | -| [getConvertPairs()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2585) | :closed_lock_with_key: | GET | `sapi/v1/convert/exchangeInfo` | -| [getConvertAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2589) | :closed_lock_with_key: | GET | `sapi/v1/convert/assetInfo` | -| [convertQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2599) | :closed_lock_with_key: | POST | `sapi/v1/convert/getQuote` | -| [acceptQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2603) | :closed_lock_with_key: | POST | `sapi/v1/convert/acceptQuote` | -| [getConvertTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2607) | :closed_lock_with_key: | GET | `sapi/v1/convert/tradeFlow` | -| [getOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2611) | :closed_lock_with_key: | GET | `sapi/v1/convert/orderStatus` | -| [submitConvertLimitOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2615) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/placeOrder` | -| [cancelConvertLimitOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2619) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/cancelOrder` | -| [getConvertLimitOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2623) | :closed_lock_with_key: | GET | `sapi/v1/convert/limit/queryOpenOrders` | -| [getEthStakingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2638) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/account` | -| [getEthStakingAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2642) | :closed_lock_with_key: | GET | `sapi/v2/eth-staking/account` | -| [getEthStakingQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2646) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/quota` | -| [subscribeEthStakingV1()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2659) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/stake` | -| [subscribeEthStakingV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2665) | :closed_lock_with_key: | POST | `sapi/v2/eth-staking/eth/stake` | -| [redeemEth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2671) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/redeem` | -| [wrapBeth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2675) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/wbeth/wrap` | -| [getEthStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2685) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/stakingHistory` | -| [getEthRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2695) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/redemptionHistory` | -| [getBethRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2705) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rewardsHistory` | -| [getWbethRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2715) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/wbethRewardsHistory` | -| [getEthRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2724) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rateHistory` | -| [getBethWrapHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2734) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/wrapHistory` | -| [getBethUnwrapHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2744) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/unwrapHistory` | -| [getBfusdAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2760) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/account` | -| [getBfusdQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2764) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/quota` | -| [subscribeBfusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2768) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/subscribe` | -| [redeemBfusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2774) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/redeem` | -| [getBfusdSubscriptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2778) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/subscriptionHistory` | -| [getBfusdRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2784) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/redemptionHistory` | -| [getBfusdRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2790) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rewardsHistory` | -| [getBfusdRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2796) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rateHistory` | -| [getRwusdAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2808) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/account` | -| [getRwusdQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2812) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/quota` | -| [subscribeRwusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2816) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/subscribe` | -| [redeemRwusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2822) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/redeem` | -| [getRwusdSubscriptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2826) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/subscriptionHistory` | -| [getRwusdRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2832) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/redemptionHistory` | -| [getRwusdRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2838) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rewardsHistory` | -| [getRwusdRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2844) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rateHistory` | -| [getStakingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2853) | :closed_lock_with_key: | GET | `sapi/v1/staking/productList` | -| [getStakingProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2864) | :closed_lock_with_key: | GET | `sapi/v1/staking/position` | -| [getStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2876) | :closed_lock_with_key: | GET | `sapi/v1/staking/stakingRecord` | -| [getPersonalLeftQuotaOfStakingProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2883) | :closed_lock_with_key: | GET | `sapi/v1/staking/personalLeftQuota` | -| [getSolStakingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2896) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/account` | -| [getSolStakingQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2900) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/quota` | -| [subscribeSolStaking()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2910) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/stake` | -| [redeemSol()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2916) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/redeem` | -| [claimSolBoostRewards()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2920) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/claim` | -| [getSolStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2932) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/stakingHistory` | -| [getSolRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2942) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/redemptionHistory` | -| [getBnsolRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2952) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/bnsolRewardsHistory` | -| [getBnsolRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2963) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/rateHistory` | -| [getSolBoostRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2973) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/boostRewardsHistory` | -| [getSolUnclaimedRewards()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2983) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/unclaimedRewards` | -| [getOnchainYieldsLockedProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2998) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/list` | -| [getOnchainYieldsLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3004) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/personalLeftQuota` | -| [getOnchainYieldsLockedPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3013) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/position` | -| [getOnchainYieldsAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3019) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/account` | -| [getOnchainYieldsLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3029) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/subscriptionPreview` | -| [subscribeOnchainYieldsLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3038) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/subscribe` | -| [setOnchainYieldsLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3044) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setAutoSubscribe` | -| [setOnchainYieldsLockedRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3053) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setRedeemOption` | -| [redeemOnchainYieldsLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3062) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/redeem` | -| [getOnchainYieldsLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3074) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/subscriptionRecord` | -| [getOnchainYieldsLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3083) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/rewardsRecord` | -| [getOnchainYieldsLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3092) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/redemptionRecord` | -| [getSoftStakingProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3107) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/list` | -| [setSoftStaking()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3113) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/set` | -| [getSoftStakingRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3119) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/history/rewardsRecord` | -| [getFuturesLeadTraderStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3134) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/userStatus` | -| [getFuturesLeadTradingSymbolWhitelist()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3138) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/leadSymbol` | -| [getMiningAlgos()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3150) | | GET | `sapi/v1/mining/pub/algoList` | -| [getMiningCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3154) | | GET | `sapi/v1/mining/pub/coinList` | -| [getHashrateResales()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3158) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/config/details/list` | -| [getMiners()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3167) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/list` | -| [getMinerDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3171) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/detail` | -| [getExtraBonuses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3177) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/other` | -| [getMiningEarnings()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3183) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/list` | -| [cancelHashrateResaleConfig()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3189) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config/cancel` | -| [getHashrateResale()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3198) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/profit/details` | -| [getMiningAccountEarnings()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3207) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/uid` | -| [getMiningStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3213) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/status` | -| [submitHashrateResale()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3219) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config` | -| [getMiningAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3223) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/list` | -| [submitVpNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3235) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderVp` | -| [submitTwapNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3242) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderTwap` | -| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3249) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/futures/order` | -| [getAlgoSubOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3257) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/subOrders` | -| [getAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3263) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/openOrders` | -| [getAlgoHistoricalOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3270) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/historicalOrders` | -| [submitSpotAlgoTwapOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3283) | :closed_lock_with_key: | POST | `sapi/v1/algo/spot/newOrderTwap` | -| [cancelSpotAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3290) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/spot/order` | -| [getSpotAlgoSubOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3298) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/subOrders` | -| [getSpotAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3304) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/openOrders` | -| [getSpotAlgoHistoricalOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3311) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/historicalOrders` | -| [getCryptoLoanFlexibleCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3326) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/collateral/data` | -| [getCryptoLoanFlexibleAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3335) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/loanable/data` | -| [borrowCryptoLoanFlexible()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3348) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/borrow` | -| [repayCryptoLoanFlexible()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3354) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay` | -| [repayCryptoLoanFlexibleWithCollateral()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3360) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay/collateral` | -| [adjustCryptoLoanFlexibleLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3366) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/adjust/ltv` | -| [getCryptoLoanFlexibleLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3378) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ltv/adjustment/history` | -| [getFlexibleLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3390) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/rate` | -| [getLoanFlexibleBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3401) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/borrow/history` | -| [getCryptoLoanFlexibleOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3410) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ongoing/orders` | -| [getFlexibleLoanLiquidationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3419) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/liquidation/history` | -| [getLoanFlexibleRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3428) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/history` | -| [getCryptoLoanLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3446) | :closed_lock_with_key: | GET | `sapi/v1/loan/loanable/data` | -| [getCryptoLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3453) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/collateral/rate` | -| [getCryptoLoanCollateralAssetsData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3462) | :closed_lock_with_key: | GET | `sapi/v1/loan/collateral/data` | -| [getCryptoLoansIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3475) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | -| [borrowCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3490) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | -| [repayCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3499) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | -| [adjustCryptoLoanLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3508) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | -| [customizeCryptoLoanMarginCall()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3517) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | -| [getCryptoLoanOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3533) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | -| [getCryptoLoanBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3544) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | -| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3555) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | -| [getCryptoLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3568) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | -| [getSimpleEarnAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3580) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | -| [getFlexibleSavingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3584) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | -| [getSimpleEarnLockedProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3591) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | -| [getFlexibleProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3600) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | -| [getLockedProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3609) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | -| [getFlexiblePersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3618) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | -| [getLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3627) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | -| [purchaseFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3642) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | -| [subscribeSimpleEarnLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3648) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | -| [redeemFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3654) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | -| [redeemLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3660) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | -| [setFlexibleAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3666) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | -| [setLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3675) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | -| [getFlexibleSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3684) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | -| [getLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3693) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | -| [setLockedProductRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3702) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | -| [getFlexibleSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3720) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | -| [getLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3732) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | -| [getFlexibleRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3744) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | -| [getLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3756) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | -| [getFlexibleRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3766) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | -| [getLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3776) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | -| [getCollateralRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3786) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | -| [getRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3796) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | -| [getVipBorrowInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3812) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | -| [getVipLoanInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3818) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | -| [getVipLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3827) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | -| [getVipCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3834) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | -| [getVipLoanOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3847) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | -| [getVipLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3854) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | -| [checkVipCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3863) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | -| [getVipApplicationStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3870) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | -| [renewVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3883) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | -| [repayVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3887) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | -| [borrowVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3891) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | -| [getVipLoanFixedRateMarket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3895) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/fixed/market` | -| [borrowVipLoanFixedRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3902) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/fixed/borrow` | -| [getDualInvestmentProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3914) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | -| [subscribeDualInvestmentProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3929) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | -| [getDualInvestmentPositions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3935) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | -| [getDualInvestmentAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3944) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | -| [getVipLoanAccruedInterest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3948) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | -| [updateAutoCompoundStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3962) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | -| [createGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3977) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | -| [createDualTokenGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3981) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | -| [redeemGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3985) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | -| [verifyGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3989) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | -| [getTokenLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3993) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | -| [getRsaPublicKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3997) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | -| [getNftTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4007) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | -| [getNftDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4014) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | -| [getNftWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4021) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | -| [getNftAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4028) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | -| [getC2CTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4041) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | -| [getFiatOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4056) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | -| [getFiatPaymentsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4062) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | -| [fiatWithdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4068) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | -| [fiatDeposit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4072) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | -| [getFiatOrderDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4076) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | -| [getSpotRebateHistoryRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4088) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | -| [getPortfolioMarginIndexPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4101) | | GET | `sapi/v1/portfolio/asset-index-price` | -| [getPortfolioMarginAssetLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4107) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | -| [getPortfolioMarginProCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4113) | | GET | `sapi/v1/portfolio/collateralRate` | -| [getPortfolioMarginProTieredCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4119) | | GET | `sapi/v2/portfolio/collateralRate` | -| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4130) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | -| [getPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4134) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/delta-mode` | -| [switchPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4138) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/delta-mode` | -| [setPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4144) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | -| [getPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4150) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | -| [deletePortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4154) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | -| [bnbTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4158) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | -| [submitPortfolioMarginProFullTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4164) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | -| [submitPortfolioMarginProSpecificTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4177) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | -| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4187) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | -| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4195) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | -| [repayFuturesNegativeBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4199) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | -| [updateAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4205) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | -| [getAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4211) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | -| [getPortfolioMarginProInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4217) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | -| [getPortfolioMarginProSpanAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4223) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | -| [getPortfolioMarginProAccountBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4227) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | -| [mintPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4237) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | -| [redeemPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4247) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | -| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4255) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | -| [transferLDUSDTPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4270) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | -| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4283) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | -| [getFuturesTickLevelOrderbookDataLink()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4300) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | -| [getBlvtInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4314) | | GET | `sapi/v1/blvt/tokenInfo` | -| [subscribeBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4318) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | -| [getBlvtSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4322) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | -| [redeemBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4328) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | -| [getBlvtRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4332) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | -| [getBlvtUserLimitInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4338) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | -| [getPayTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4349) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | -| [getInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4359) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | -| [closeInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4365) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | -| [addInstLoanCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4369) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | -| [getActiveInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4375) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | -| [getClosedInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4379) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | -| [getInstLoanForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4391) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | -| [transferInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4405) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | -| [getInstitutionalLoanMaxBorrowable()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4417) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/max-borrowable` | -| [borrowInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4423) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | -| [getInstLoanInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4429) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | -| [repayInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4438) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | -| [getInstLoanBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4444) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | -| [getMarginInterestRebateBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4450) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | -| [getMarginInterestRebateBalanceRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4454) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | -| [getAlphaTokenList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4469) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | -| [getAlphaExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4476) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | -| [getAlphaAggTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4483) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | -| [getAlphaKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4491) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | -| [getAlphaTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4499) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | -| [getAlphaFullDepth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4507) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | -| [createBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4523) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [getBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4529) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | -| [enableMarginBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4535) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | -| [createApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4541) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | -| [changePermissionApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4547) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | -| [changeComissionBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4553) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | -| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4559) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | -| [updateIpRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4568) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | -| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4582) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | -| [deleteApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4598) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | -| [getSubAccountBrokerIpRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4604) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | -| [getApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4620) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | -| [getBrokerInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4626) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | -| [updateSubAccountBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4630) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | -| [updateSubAccountMarginInterestBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4640) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | -| [getSubAccountBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4653) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | -| [deleteBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4669) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | -| [transferBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4679) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | -| [getBrokerSubAccountHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4685) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | -| [submitBrokerSubFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4691) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | -| [getSubAccountFuturesTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4706) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | -| [getBrokerSubDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4718) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | -| [getBrokerSubAccountSpotAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4724) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | -| [getSubAccountMarginAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4733) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | -| [querySubAccountFuturesAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4742) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | -| [universalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4751) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | -| [getUniversalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4758) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | -| [updateBrokerSubAccountCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4770) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | -| [updateBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4776) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | -| [getBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4785) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | -| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4794) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | -| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4803) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | -| [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4812) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | -| [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4818) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | -| [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4855) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | -| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4866) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | -| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4885) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4895) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | -| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4936) | | POST | `api/v3/userDataStream` | -| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4940) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | -| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4944) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | -| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4951) | | POST | `sapi/v1/userDataStream` | -| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4955) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4959) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4964) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4972) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4981) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4993) | | POST | `sapi/v1/margin/listen-key` | -| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4997) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5001) | | DELETE | `sapi/v1/margin/listen-key` | -| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5013) | | POST | `sapi/v2/margin/listen-key` | -| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5021) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5029) | | DELETE | `sapi/v2/margin/listen-key` | -| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5033) | | POST | `sapi/v2/margin/uta/listen-key` | -| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5037) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | -| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5041) | | DELETE | `sapi/v2/margin/uta/listen-key` | -| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5049) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | -| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5071) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | -| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5078) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | -| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5087) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | -| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5096) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | -| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5111) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | -| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5120) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | -| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5134) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | -| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5144) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | -| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5153) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | -| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5162) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | -| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5169) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | -| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5176) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | -| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5183) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | -| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5190) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | -| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5207) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | -| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5215) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | -| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5222) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | +| [testConnectivity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L798) | | GET | `api/v3/ping` | +| [getExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L802) | | GET | `api/v3/exchangeInfo` | +| [getOrderBook()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L822) | | GET | `api/v3/depth` | +| [getRecentTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L826) | | GET | `api/v3/trades` | +| [getHistoricalTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L830) | | GET | `api/v3/historicalTrades` | +| [getHistoricalBlockTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L834) | | GET | `api/v3/historicalBlockTrades` | +| [getAggregateTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L840) | | GET | `api/v3/aggTrades` | +| [getKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L846) | | GET | `api/v3/klines` | +| [getUIKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L850) | | GET | `api/v3/uiKlines` | +| [getAvgPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L854) | | GET | `api/v3/avgPrice` | +| [getExecutionRules()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L858) | | GET | `api/v3/executionRules?symbols=` | +| [getReferencePrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L873) | | GET | `api/v3/referencePrice` | +| [getReferencePriceCalculation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L879) | | GET | `api/v3/referencePrice/calculation` | +| [get24hrChangeStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L886) | | GET | `api/v3/ticker/24hr?symbols=` | +| [getTradingDayTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L916) | | GET | `api/v3/ticker/tradingDay?symbols=` | +| [getSymbolPriceTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L931) | | GET | `api/v3/ticker/price?symbols=` | +| [getSymbolOrderBookTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L948) | | GET | `api/v3/ticker/bookTicker?symbols=` | +| [getRollingWindowTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L965) | | GET | `api/v3/ticker?symbols=` | +| [submitNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L987) | :closed_lock_with_key: | POST | `api/v3/order` | +| [testNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L995) | :closed_lock_with_key: | POST | `api/v3/order/test` | +| [getOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1003) | :closed_lock_with_key: | GET | `api/v3/order` | +| [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` | +| [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` | +| [submitNewOrderList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1056) | :closed_lock_with_key: | POST | `api/v3/orderList/oco` | +| [submitNewOrderListOTO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1065) | :closed_lock_with_key: | POST | `api/v3/orderList/oto` | +| [submitNewOrderListOTOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1074) | :closed_lock_with_key: | POST | `api/v3/orderList/otoco` | +| [submitNewOrderListOPO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1084) | :closed_lock_with_key: | POST | `api/v3/orderList/opo` | +| [submitNewOrderListOPOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1093) | :closed_lock_with_key: | POST | `api/v3/orderList/opoco` | +| [cancelOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1103) | :closed_lock_with_key: | DELETE | `api/v3/orderList` | +| [getOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1108) | :closed_lock_with_key: | GET | `api/v3/orderList` | +| [getAllOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1112) | :closed_lock_with_key: | GET | `api/v3/allOrderList` | +| [getAllOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1119) | :closed_lock_with_key: | GET | `api/v3/openOrderList` | +| [submitNewSOROrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1126) | :closed_lock_with_key: | POST | `api/v3/sor/order` | +| [testNewSOROrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1137) | :closed_lock_with_key: | POST | `api/v3/sor/order/test` | +| [getAccountInformation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1153) | :closed_lock_with_key: | GET | `api/v3/account` | +| [getAccountTradeList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1159) | :closed_lock_with_key: | GET | `api/v3/myTrades` | +| [getOrderRateLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1165) | :closed_lock_with_key: | GET | `api/v3/rateLimit/order` | +| [getPreventedMatches()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1169) | :closed_lock_with_key: | GET | `api/v3/myPreventedMatches` | +| [getAllocations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1175) | :closed_lock_with_key: | GET | `api/v3/myAllocations` | +| [getCommissionRates()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1179) | :closed_lock_with_key: | GET | `api/v3/account/commission` | +| [getCrossMarginCollateralRatio()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1194) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginCollateralRatio` | +| [getAllCrossMarginPairs()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1208) | | GET | `sapi/v1/margin/allPairs` | +| [getIsolatedMarginAllSymbols()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1212) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/allPairs` | +| [getAllMarginAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1218) | | GET | `sapi/v1/margin/allAssets` | +| [getMarginDelistSchedule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1222) | :closed_lock_with_key: | GET | `sapi/v1/margin/delist-schedule` | +| [getIsolatedMarginTierData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1226) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginTier` | +| [queryMarginPriceIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1232) | | GET | `sapi/v1/margin/priceIndex` | +| [getMarginAvailableInventory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1238) | :closed_lock_with_key: | GET | `sapi/v1/margin/available-inventory` | +| [getLeverageBracket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1244) | :closed_lock_with_key: | GET | `sapi/v1/margin/leverageBracket` | +| [getNextHourlyInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1254) | :closed_lock_with_key: | GET | `sapi/v1/margin/next-hourly-interest-rate` | +| [getMarginInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1260) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestHistory` | +| [submitMarginAccountBorrowRepay()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1267) | :closed_lock_with_key: | POST | `sapi/v1/margin/borrow-repay` | +| [getMarginAccountBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1273) | :closed_lock_with_key: | GET | `sapi/v1/margin/borrow-repay` | +| [getMarginInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1279) | :closed_lock_with_key: | GET | `sapi/v1/margin/interestRateHistory` | +| [queryMaxBorrow()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1285) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxBorrowable` | +| [getMarginForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1297) | :closed_lock_with_key: | GET | `sapi/v1/margin/forceLiquidationRec` | +| [getSmallLiabilityExchangeCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1306) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability` | +| [getSmallLiabilityExchangeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1310) | :closed_lock_with_key: | GET | `sapi/v1/margin/exchange-small-liability-history` | +| [marginAccountCancelOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1322) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/openOrders` | +| [marginAccountCancelOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1328) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/orderList` | +| [marginAccountCancelOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1333) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/order` | +| [marginAccountNewOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1339) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oco` | +| [marginAccountNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1346) | :closed_lock_with_key: | POST | `sapi/v1/margin/order` | +| [getMarginOrderCountUsage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1354) | :closed_lock_with_key: | GET | `sapi/v1/margin/rateLimit/order` | +| [queryMarginAccountAllOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1360) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrderList` | +| [queryMarginAccountAllOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1366) | :closed_lock_with_key: | GET | `sapi/v1/margin/allOrders` | +| [queryMarginAccountOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1372) | :closed_lock_with_key: | GET | `sapi/v1/margin/orderList` | +| [queryMarginAccountOpenOCO()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1376) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrderList` | +| [queryMarginAccountOpenOTOOrderLists()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1383) | :closed_lock_with_key: | GET | `sapi/v1/margin/oto/openOrderList` | +| [queryMarginAccountOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1389) | :closed_lock_with_key: | GET | `sapi/v1/margin/openOrders` | +| [queryMarginAccountOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1393) | :closed_lock_with_key: | GET | `sapi/v1/margin/order` | +| [queryMarginAccountTradeList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1397) | :closed_lock_with_key: | GET | `sapi/v1/margin/myTrades` | +| [submitSmallLiabilityExchange()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1403) | :closed_lock_with_key: | POST | `sapi/v1/margin/exchange-small-liability` | +| [submitManualLiquidation()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1410) | :closed_lock_with_key: | POST | `sapi/v1/margin/manual-liquidation` | +| [submitMarginOTOOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1419) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/oto` | +| [submitMarginOTOCOOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1431) | :closed_lock_with_key: | POST | `sapi/v1/margin/order/otoco` | +| [createMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1444) | :closed_lock_with_key: | POST | `sapi/v1/margin/apiKey` | +| [deleteMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1450) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/apiKey` | +| [updateMarginIPForSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1458) | :closed_lock_with_key: | PUT | `sapi/v1/margin/apiKey/ip` | +| [getMarginSpecialLowLatencyKeys()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1469) | :closed_lock_with_key: | GET | `sapi/v1/margin/api-key-list` | +| [getMarginSpecialLowLatencyKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1478) | :closed_lock_with_key: | GET | `sapi/v1/margin/apiKey` | +| [getMarginLiquidationLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1488) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan` | +| [repayMarginLiquidationLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1495) | :closed_lock_with_key: | POST | `sapi/v1/margin/liquidation-loan/repay` | +| [getMarginLiquidationLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1504) | :closed_lock_with_key: | GET | `sapi/v1/margin/liquidation-loan/repay-history` | +| [exitMarginSpecialKeyMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1516) | :closed_lock_with_key: | POST | `sapi/v1/margin/exit-special-key-mode` | +| [getCrossMarginTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1526) | :closed_lock_with_key: | GET | `sapi/v1/margin/transfer` | +| [queryMaxTransferOutAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1532) | :closed_lock_with_key: | GET | `sapi/v1/margin/maxTransferable` | +| [updateCrossMarginMaxLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1544) | :closed_lock_with_key: | POST | `sapi/v1/margin/max-leverage` | +| [disableIsolatedMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1550) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/isolated/account` | +| [enableIsolatedMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1557) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/account` | +| [getBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1564) | :closed_lock_with_key: | GET | `sapi/v1/bnbBurn` | +| [getMarginSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1568) | :closed_lock_with_key: | GET | `sapi/v1/margin/tradeCoeff` | +| [queryCrossMarginAccountDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1572) | :closed_lock_with_key: | GET | `sapi/v1/margin/account` | +| [getCrossMarginFeeData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1576) | :closed_lock_with_key: | GET | `sapi/v1/margin/crossMarginData` | +| [getIsolatedMarginAccountLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1582) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/accountLimit` | +| [getIsolatedMarginAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1589) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolated/account` | +| [getIsolatedMarginFeeData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1595) | :closed_lock_with_key: | GET | `sapi/v1/margin/isolatedMarginData` | +| [toggleBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1601) | :closed_lock_with_key: | POST | `sapi/v1/bnbBurn` | +| [getMarginCapitalFlow()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1609) | :closed_lock_with_key: | GET | `sapi/v1/margin/capital-flow` | +| [queryLoanRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1618) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan` | +| [queryRepayRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1627) | :closed_lock_with_key: | GET | `sapi/v1/margin/repay` | +| [isolatedMarginAccountTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1636) | :closed_lock_with_key: | POST | `sapi/v1/margin/isolated/transfer` | +| [getBalances()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1648) | :closed_lock_with_key: | GET | `sapi/v1/capital/config/getall` | +| [withdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1652) | :closed_lock_with_key: | POST | `sapi/v1/capital/withdraw/apply` | +| [getWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1656) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/history` | +| [getWithdrawAddresses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1662) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/address/list` | +| [getWithdrawQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1666) | :closed_lock_with_key: | GET | `sapi/v1/capital/withdraw/quota` | +| [getDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1673) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/hisrec` | +| [getDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1677) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address` | +| [getDepositAddresses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1683) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/address/list` | +| [submitDepositCredit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1689) | :closed_lock_with_key: | POST | `sapi/v1/capital/deposit/credit-apply` | +| [getAutoConvertStablecoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1698) | :closed_lock_with_key: | GET | `sapi/v1/capital/contract/convertible-coins` | +| [setConvertibleCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1705) | :closed_lock_with_key: | POST | `sapi/v1/capital/contract/convertible-coins` | +| [getAssetDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1718) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDetail` | +| [getWalletBalances()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1724) | :closed_lock_with_key: | GET | `sapi/v1/asset/wallet/balance` | +| [getUserAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1730) | :closed_lock_with_key: | POST | `sapi/v3/asset/getUserAsset` | +| [getSpotAssetTags()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1734) | | GET | `sapi/v1/spot/asset/tags` | +| [submitUniversalTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1738) | :closed_lock_with_key: | POST | `sapi/v1/asset/transfer` | +| [getUniversalTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1744) | :closed_lock_with_key: | GET | `sapi/v1/asset/transfer` | +| [getDust()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1750) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-btc` | +| [convertDustToBnb()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1754) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust` | +| [convertDustAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1761) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/convert` | +| [queryDustConvertibleAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1768) | :closed_lock_with_key: | POST | `sapi/v1/asset/dust-convert/query-convertible-assets` | +| [getDustLog()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1777) | :closed_lock_with_key: | GET | `sapi/v1/asset/dribblet` | +| [getAssetDividendRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1781) | :closed_lock_with_key: | GET | `sapi/v1/asset/assetDividend` | +| [getTradeFee()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1785) | :closed_lock_with_key: | GET | `sapi/v1/asset/tradeFee` | +| [getFundingAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1789) | :closed_lock_with_key: | POST | `sapi/v1/asset/get-funding-asset` | +| [getCloudMiningHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1793) | :closed_lock_with_key: | GET | `sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage` | +| [getDelegationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1803) | :closed_lock_with_key: | GET | `sapi/v1/asset/custody/transfer-history` | +| [submitNewFutureAccountTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1833) | :closed_lock_with_key: | POST | `sapi/v1/futures/transfer` | +| [getFutureAccountTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1843) | :closed_lock_with_key: | GET | `sapi/v1/futures/transfer` | +| [getCrossCollateralBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1852) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/borrow/history` | +| [getCrossCollateralRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1859) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/repay/history` | +| [getCrossCollateralWalletV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1866) | :closed_lock_with_key: | GET | `sapi/v2/futures/loan/wallet` | +| [getAdjustCrossCollateralLTVHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1873) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/adjustCollateral/history` | +| [getCrossCollateralLiquidationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1885) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/liquidationHistory` | +| [getCrossCollateralInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1894) | :closed_lock_with_key: | GET | `sapi/v1/futures/loan/interestHistory` | +| [getAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1906) | :closed_lock_with_key: | GET | `sapi/v1/account/info` | +| [getDailyAccountSnapshot()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1910) | :closed_lock_with_key: | GET | `sapi/v1/accountSnapshot` | +| [disableFastWithdrawSwitch()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1916) | :closed_lock_with_key: | POST | `sapi/v1/account/disableFastWithdrawSwitch` | +| [enableFastWithdrawSwitch()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1920) | :closed_lock_with_key: | POST | `sapi/v1/account/enableFastWithdrawSwitch` | +| [getAccountStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1924) | :closed_lock_with_key: | GET | `sapi/v1/account/status` | +| [getApiTradingStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1928) | :closed_lock_with_key: | GET | `sapi/v1/account/apiTradingStatus` | +| [getApiKeyPermissions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1932) | :closed_lock_with_key: | GET | `sapi/v1/account/apiRestrictions` | +| [withdrawTravelRule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1948) | :closed_lock_with_key: | POST | `sapi/v1/localentity/withdraw/apply` | +| [getTravelRuleWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1959) | :closed_lock_with_key: | GET | `sapi/v1/localentity/withdraw/history` | +| [getTravelRuleWithdrawHistoryV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1968) | :closed_lock_with_key: | GET | `sapi/v2/localentity/withdraw/history` | +| [submitTravelRuleDepositQuestionnaire()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1980) | :closed_lock_with_key: | PUT | `sapi/v1/localentity/deposit/provide-info` | +| [getTravelRuleDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L1989) | :closed_lock_with_key: | GET | `sapi/v1/localentity/deposit/history` | +| [getOnboardedVASPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2000) | :closed_lock_with_key: | GET | `sapi/v1/localentity/vasp` | +| [getTravelRuleCountryList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2004) | :closed_lock_with_key: | GET | `sapi/v1/localentity/country/list` | +| [getTravelRuleRegionList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2008) | :closed_lock_with_key: | GET | `sapi/v1/localentity/region/list` | +| [getSystemStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2020) | | GET | `sapi/v1/system/status` | +| [getDelistSchedule()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2024) | :closed_lock_with_key: | GET | `sapi/v1/spot/delist-schedule` | +| [createVirtualSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2034) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/virtualSubAccount` | +| [getSubAccountList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2040) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/list` | +| [subAccountEnableFutures()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2046) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/enable` | +| [subAccountEnableMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2054) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/enable` | +| [enableOptionsForSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2058) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/eoptions/enable` | +| [subAccountEnableLeverageToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2068) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/blvt/enable` | +| [getSubAccountStatusOnMarginOrFutures()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2074) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/status` | +| [getSubAccountFuturesPositionRisk()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2080) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/positionRisk` | +| [getSubAccountFuturesPositionRiskV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2088) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/positionRisk` | +| [getSubAccountTransactionStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2094) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transaction-statistics` | +| [getSubAccountApiKeys()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2112) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/subAccountApi` | +| [createSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2122) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi` | +| [deleteSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2131) | :closed_lock_with_key: | DELETE | `sapi/v1/sub-account/subAccountApi` | +| [modifySubAccountApiKeyPermission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2141) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApiPermission` | +| [getSubAccountIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2150) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/subAccountApi/ipRestriction` | +| [subAccountDeleteIPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2159) | :closed_lock_with_key: | DELETE | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | +| [subAccountAddIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2168) | :closed_lock_with_key: | POST | `sapi/v2/sub-account/subAccountApi/ipRestriction` | +| [subAccountAddIPList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2181) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction/ipList` | +| [subAccountEnableOrDisableIPRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2194) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/subAccountApi/ipRestriction` | +| [subAccountFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2209) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/transfer` | +| [getSubAccountFuturesAccountDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2215) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/account` | +| [getSubAccountDetailOnFuturesAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2221) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/account` | +| [getSubAccountDetailOnMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2227) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/account` | +| [getSubAccountDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2233) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subAddress` | +| [getSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2239) | :closed_lock_with_key: | GET | `sapi/v1/capital/deposit/subHisrec` | +| [getSubAccountFuturesAccountSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2245) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/accountSummary` | +| [getSubAccountSummaryOnFuturesAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2249) | :closed_lock_with_key: | GET | `sapi/v2/sub-account/futures/accountSummary` | +| [getSubAccountsSummaryOfMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2258) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/margin/accountSummary` | +| [subAccountMarginTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2262) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/margin/transfer` | +| [getSubAccountAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2268) | :closed_lock_with_key: | GET | `sapi/v3/sub-account/assets` | +| [getSubAccountAssetsMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2274) | :closed_lock_with_key: | GET | `sapi/v4/sub-account/assets` | +| [getSubAccountFuturesAssetTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2280) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/internalTransfer` | +| [getSubAccountSpotAssetTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2289) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/sub/transfer/history` | +| [getSubAccountSpotAssetsSummary()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2295) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/spotSummary` | +| [getSubAccountUniversalTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2301) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/universalTransfer` | +| [subAccountFuturesAssetTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2307) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/internalTransfer` | +| [subAccountTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2316) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/transfer/subUserHistory` | +| [subAccountTransferToMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2325) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToMaster` | +| [subAccountTransferToSameMaster()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2331) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/transfer/subToSub` | +| [subAccountUniversalTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2337) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/universalTransfer` | +| [subAccountMovePosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2343) | :closed_lock_with_key: | POST | `sapi/v1/sub-account/futures/move-position` | +| [getSubAccountFuturesPositionMoveHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2352) | :closed_lock_with_key: | GET | `sapi/v1/sub-account/futures/move-position` | +| [depositAssetsIntoManagedSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2367) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/deposit` | +| [getManagedSubAccountDepositAddress()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2373) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/deposit/address` | +| [withdrawAssetsFromManagedSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2382) | :closed_lock_with_key: | POST | `sapi/v1/managed-subaccount/withdraw` | +| [getManagedSubAccountTransfersParent()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2388) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForTradeParent` | +| [getManagedSubAccountTransferLog()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2400) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/query-trans-log` | +| [getManagedSubAccountTransfersInvestor()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2412) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/queryTransLogForInvestor` | +| [getManagedSubAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2424) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/info` | +| [getManagedSubAccountSnapshot()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2431) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/accountSnapshot` | +| [getManagedSubAccountAssetDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2440) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/asset` | +| [getManagedSubAccountMarginAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2446) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/marginAsset` | +| [getManagedSubAccountFuturesAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2453) | :closed_lock_with_key: | GET | `sapi/v1/managed-subaccount/fetch-future-asset` | +| [getAutoInvestAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2469) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/all/asset` | +| [getAutoInvestSourceAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2476) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/source-asset/list` | +| [getAutoInvestTargetAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2485) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/list` | +| [getAutoInvestTargetAssetsROI()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2494) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/target-asset/roi/list` | +| [getAutoInvestIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2503) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/info` | +| [getAutoInvestPlans()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2509) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/list` | +| [submitAutoInvestOneTimeTransaction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2527) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/one-off` | +| [updateAutoInvestPlanStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2543) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit-status` | +| [updateAutoInvestmentPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2552) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/edit` | +| [submitAutoInvestRedemption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2569) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/redeem` | +| [getAutoInvestSubscriptionTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2577) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/history/list` | +| [getOneTimeTransactionStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2583) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/one-off/status` | +| [submitAutoInvestmentPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2592) | :closed_lock_with_key: | POST | `sapi/v1/lending/auto-invest/plan/add` | +| [getAutoInvestRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2607) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/redeem/history` | +| [getAutoInvestPlan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2616) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/plan/id` | +| [getAutoInvestUserIndex()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2620) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/index/user-summary` | +| [getAutoInvestRebalanceHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2629) | :closed_lock_with_key: | GET | `sapi/v1/lending/auto-invest/rebalance/history` | +| [getConvertPairs()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2644) | :closed_lock_with_key: | GET | `sapi/v1/convert/exchangeInfo` | +| [getConvertAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2648) | :closed_lock_with_key: | GET | `sapi/v1/convert/assetInfo` | +| [convertQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2658) | :closed_lock_with_key: | POST | `sapi/v1/convert/getQuote` | +| [acceptQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2662) | :closed_lock_with_key: | POST | `sapi/v1/convert/acceptQuote` | +| [getConvertTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2666) | :closed_lock_with_key: | GET | `sapi/v1/convert/tradeFlow` | +| [getOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2670) | :closed_lock_with_key: | GET | `sapi/v1/convert/orderStatus` | +| [submitConvertLimitOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2674) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/placeOrder` | +| [cancelConvertLimitOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2678) | :closed_lock_with_key: | POST | `sapi/v1/convert/limit/cancelOrder` | +| [getConvertLimitOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2682) | :closed_lock_with_key: | GET | `sapi/v1/convert/limit/queryOpenOrders` | +| [getEthStakingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2697) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/account` | +| [getEthStakingAccountV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2701) | :closed_lock_with_key: | GET | `sapi/v2/eth-staking/account` | +| [getEthStakingQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2705) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/quota` | +| [subscribeEthStakingV1()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2718) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/stake` | +| [subscribeEthStakingV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2724) | :closed_lock_with_key: | POST | `sapi/v2/eth-staking/eth/stake` | +| [redeemEth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2730) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/eth/redeem` | +| [wrapBeth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2734) | :closed_lock_with_key: | POST | `sapi/v1/eth-staking/wbeth/wrap` | +| [getEthStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2744) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/stakingHistory` | +| [getEthRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2754) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/redemptionHistory` | +| [getBethRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2764) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rewardsHistory` | +| [getWbethRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2774) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/wbethRewardsHistory` | +| [getEthRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2783) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/eth/history/rateHistory` | +| [getBethWrapHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2793) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/wrapHistory` | +| [getBethUnwrapHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2803) | :closed_lock_with_key: | GET | `sapi/v1/eth-staking/wbeth/history/unwrapHistory` | +| [getBfusdAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2819) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/account` | +| [getBfusdQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2823) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/quota` | +| [subscribeBfusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2827) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/subscribe` | +| [redeemBfusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2833) | :closed_lock_with_key: | POST | `sapi/v1/bfusd/redeem` | +| [getBfusdSubscriptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2837) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/subscriptionHistory` | +| [getBfusdRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2843) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/redemptionHistory` | +| [getBfusdRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2849) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rewardsHistory` | +| [getBfusdRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2855) | :closed_lock_with_key: | GET | `sapi/v1/bfusd/history/rateHistory` | +| [getRwusdAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2867) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/account` | +| [getRwusdQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2871) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/quota` | +| [subscribeRwusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2875) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/subscribe` | +| [redeemRwusd()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2881) | :closed_lock_with_key: | POST | `sapi/v1/rwusd/redeem` | +| [getRwusdSubscriptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2885) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/subscriptionHistory` | +| [getRwusdRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2891) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/redemptionHistory` | +| [getRwusdRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2897) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rewardsHistory` | +| [getRwusdRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2903) | :closed_lock_with_key: | GET | `sapi/v1/rwusd/history/rateHistory` | +| [getStakingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2912) | :closed_lock_with_key: | GET | `sapi/v1/staking/productList` | +| [getStakingProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2923) | :closed_lock_with_key: | GET | `sapi/v1/staking/position` | +| [getStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2935) | :closed_lock_with_key: | GET | `sapi/v1/staking/stakingRecord` | +| [getPersonalLeftQuotaOfStakingProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2942) | :closed_lock_with_key: | GET | `sapi/v1/staking/personalLeftQuota` | +| [getSolStakingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2955) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/account` | +| [getSolStakingQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2959) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/quota` | +| [subscribeSolStaking()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2969) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/stake` | +| [redeemSol()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2975) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/redeem` | +| [claimSolBoostRewards()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2979) | :closed_lock_with_key: | POST | `sapi/v1/sol-staking/sol/claim` | +| [getSolStakingHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L2991) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/stakingHistory` | +| [getSolRedemptionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3001) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/redemptionHistory` | +| [getBnsolRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3011) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/bnsolRewardsHistory` | +| [getBnsolRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3022) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/rateHistory` | +| [getSolBoostRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3032) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/boostRewardsHistory` | +| [getSolUnclaimedRewards()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3042) | :closed_lock_with_key: | GET | `sapi/v1/sol-staking/sol/history/unclaimedRewards` | +| [getOnchainYieldsLockedProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3057) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/list` | +| [getOnchainYieldsLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3063) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/personalLeftQuota` | +| [getOnchainYieldsLockedPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3072) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/position` | +| [getOnchainYieldsAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3078) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/account` | +| [getOnchainYieldsLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3088) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/subscriptionPreview` | +| [subscribeOnchainYieldsLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3097) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/subscribe` | +| [setOnchainYieldsLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3103) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setAutoSubscribe` | +| [setOnchainYieldsLockedRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3112) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/setRedeemOption` | +| [redeemOnchainYieldsLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3121) | :closed_lock_with_key: | POST | `sapi/v1/onchain-yields/locked/redeem` | +| [getOnchainYieldsLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3133) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/subscriptionRecord` | +| [getOnchainYieldsLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3142) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/rewardsRecord` | +| [getOnchainYieldsLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3151) | :closed_lock_with_key: | GET | `sapi/v1/onchain-yields/locked/history/redemptionRecord` | +| [getSoftStakingProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3166) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/list` | +| [setSoftStaking()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3172) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/set` | +| [getSoftStakingRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3178) | :closed_lock_with_key: | GET | `sapi/v1/soft-staking/history/rewardsRecord` | +| [getFuturesLeadTraderStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3193) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/userStatus` | +| [getFuturesLeadTradingSymbolWhitelist()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3197) | :closed_lock_with_key: | GET | `sapi/v1/copyTrading/futures/leadSymbol` | +| [getMiningAlgos()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3209) | | GET | `sapi/v1/mining/pub/algoList` | +| [getMiningCoins()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3213) | | GET | `sapi/v1/mining/pub/coinList` | +| [getHashrateResales()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3217) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/config/details/list` | +| [getMiners()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3226) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/list` | +| [getMinerDetails()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3230) | :closed_lock_with_key: | GET | `sapi/v1/mining/worker/detail` | +| [getExtraBonuses()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3236) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/other` | +| [getMiningEarnings()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3242) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/list` | +| [cancelHashrateResaleConfig()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3248) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config/cancel` | +| [getHashrateResale()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3257) | :closed_lock_with_key: | GET | `sapi/v1/mining/hash-transfer/profit/details` | +| [getMiningAccountEarnings()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3266) | :closed_lock_with_key: | GET | `sapi/v1/mining/payment/uid` | +| [getMiningStatistics()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3272) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/status` | +| [submitHashrateResale()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3278) | :closed_lock_with_key: | POST | `sapi/v1/mining/hash-transfer/config` | +| [getMiningAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3282) | :closed_lock_with_key: | GET | `sapi/v1/mining/statistics/user/list` | +| [submitVpNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3294) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderVp` | +| [submitTwapNewOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3301) | :closed_lock_with_key: | POST | `sapi/v1/algo/futures/newOrderTwap` | +| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3308) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/futures/order` | +| [getAlgoSubOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3316) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/subOrders` | +| [getAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3322) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/openOrders` | +| [getAlgoHistoricalOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3329) | :closed_lock_with_key: | GET | `sapi/v1/algo/futures/historicalOrders` | +| [submitSpotAlgoTwapOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3342) | :closed_lock_with_key: | POST | `sapi/v1/algo/spot/newOrderTwap` | +| [cancelSpotAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3349) | :closed_lock_with_key: | DELETE | `sapi/v1/algo/spot/order` | +| [getSpotAlgoSubOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3357) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/subOrders` | +| [getSpotAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3363) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/openOrders` | +| [getSpotAlgoHistoricalOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3370) | :closed_lock_with_key: | GET | `sapi/v1/algo/spot/historicalOrders` | +| [getCryptoLoanFlexibleCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3385) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/collateral/data` | +| [getCryptoLoanFlexibleAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3394) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/loanable/data` | +| [borrowCryptoLoanFlexible()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3407) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/borrow` | +| [repayCryptoLoanFlexible()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3413) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay` | +| [repayCryptoLoanFlexibleWithCollateral()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3419) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/repay/collateral` | +| [adjustCryptoLoanFlexibleLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3425) | :closed_lock_with_key: | POST | `sapi/v2/loan/flexible/adjust/ltv` | +| [getCryptoLoanFlexibleLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3437) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ltv/adjustment/history` | +| [getFlexibleLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3449) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/rate` | +| [getLoanFlexibleBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3460) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/borrow/history` | +| [getCryptoLoanFlexibleOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3469) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/ongoing/orders` | +| [getFlexibleLoanLiquidationHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3478) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/liquidation/history` | +| [getLoanFlexibleRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3487) | :closed_lock_with_key: | GET | `sapi/v2/loan/flexible/repay/history` | +| [getCryptoLoanLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3505) | :closed_lock_with_key: | GET | `sapi/v1/loan/loanable/data` | +| [getCryptoLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3512) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/collateral/rate` | +| [getCryptoLoanCollateralAssetsData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3521) | :closed_lock_with_key: | GET | `sapi/v1/loan/collateral/data` | +| [getCryptoLoansIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3534) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | +| [borrowCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3549) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | +| [repayCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3558) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | +| [adjustCryptoLoanLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3567) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | +| [customizeCryptoLoanMarginCall()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3576) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | +| [getCryptoLoanOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3592) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | +| [getCryptoLoanBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3603) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | +| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3614) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | +| [getCryptoLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3627) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | +| [getSimpleEarnAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3639) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | +| [getFlexibleSavingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3643) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | +| [getSimpleEarnLockedProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3650) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | +| [getFlexibleProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3659) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | +| [getLockedProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3668) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | +| [getFlexiblePersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3677) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | +| [getLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3686) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | +| [purchaseFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3701) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | +| [subscribeSimpleEarnLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3707) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | +| [redeemFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3713) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | +| [redeemLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3719) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | +| [setFlexibleAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3725) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | +| [setLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3734) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | +| [getFlexibleSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3743) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | +| [getLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3752) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | +| [setLockedProductRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3761) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | +| [getFlexibleSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3779) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | +| [getLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3791) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | +| [getFlexibleRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3803) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | +| [getLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3815) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | +| [getFlexibleRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3825) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | +| [getLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3835) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | +| [getCollateralRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3845) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | +| [getRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3855) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | +| [getVipBorrowInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3871) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | +| [getVipLoanInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3877) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | +| [getVipLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3886) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | +| [getVipCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3893) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | +| [getVipLoanOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3906) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | +| [getVipLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3913) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | +| [checkVipCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3922) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | +| [getVipApplicationStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3929) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | +| [renewVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3942) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | +| [repayVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3946) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | +| [borrowVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3950) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | +| [getVipLoanFixedRateMarket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3954) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/fixed/market` | +| [borrowVipLoanFixedRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3961) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/fixed/borrow` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3973) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | +| [subscribeDualInvestmentProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3988) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | +| [getDualInvestmentPositions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3994) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | +| [getDualInvestmentAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4003) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | +| [getVipLoanAccruedInterest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4007) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | +| [updateAutoCompoundStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4021) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | +| [createGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4036) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | +| [createDualTokenGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4040) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | +| [redeemGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4044) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | +| [verifyGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4048) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | +| [getTokenLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4052) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | +| [getRsaPublicKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4056) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | +| [getNftTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4066) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | +| [getNftDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4073) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | +| [getNftWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4080) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | +| [getNftAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4087) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | +| [getC2CTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4100) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | +| [getFiatOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4115) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | +| [getFiatPaymentsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4121) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | +| [fiatWithdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4127) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | +| [fiatDeposit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4131) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | +| [getFiatOrderDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4135) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | +| [getSpotRebateHistoryRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4147) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | +| [getPortfolioMarginIndexPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4160) | | GET | `sapi/v1/portfolio/asset-index-price` | +| [getPortfolioMarginAssetLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4166) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | +| [getPortfolioMarginProCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4172) | | GET | `sapi/v1/portfolio/collateralRate` | +| [getPortfolioMarginProTieredCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4178) | | GET | `sapi/v2/portfolio/collateralRate` | +| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4189) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | +| [getPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4193) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/delta-mode` | +| [switchPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4197) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/delta-mode` | +| [setPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4203) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | +| [getPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4209) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | +| [deletePortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4213) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | +| [bnbTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4217) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | +| [submitPortfolioMarginProFullTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4223) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | +| [submitPortfolioMarginProSpecificTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4236) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | +| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4246) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | +| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4254) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | +| [repayFuturesNegativeBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4258) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | +| [updateAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4264) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | +| [getAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4270) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | +| [getPortfolioMarginProInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4276) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | +| [getPortfolioMarginProSpanAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4282) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | +| [getPortfolioMarginProAccountBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4286) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | +| [mintPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4296) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | +| [redeemPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4306) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | +| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4314) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | +| [transferLDUSDTPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4329) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | +| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4342) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | +| [getFuturesTickLevelOrderbookDataLink()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4359) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | +| [getBlvtInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4373) | | GET | `sapi/v1/blvt/tokenInfo` | +| [subscribeBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4377) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | +| [getBlvtSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4381) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | +| [redeemBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4387) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | +| [getBlvtRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4391) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | +| [getBlvtUserLimitInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4397) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | +| [getPayTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4408) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | +| [getInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4418) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | +| [closeInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4424) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | +| [addInstLoanCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4428) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | +| [getActiveInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4434) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | +| [getClosedInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4438) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | +| [getInstLoanForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4450) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | +| [transferInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4464) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | +| [getInstitutionalLoanMaxBorrowable()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4476) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/max-borrowable` | +| [borrowInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4482) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | +| [getInstLoanInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4488) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | +| [repayInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4497) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | +| [getInstLoanBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4503) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | +| [getMarginInterestRebateBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4509) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | +| [getMarginInterestRebateBalanceRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4513) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | +| [getAlphaTokenList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4528) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | +| [getAlphaExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4535) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | +| [getAlphaAggTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4542) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | +| [getAlphaKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4550) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | +| [getAlphaTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4558) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | +| [getAlphaFullDepth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4566) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | +| [createBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4582) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [getBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4588) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | +| [enableMarginBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4594) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | +| [createApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4600) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | +| [changePermissionApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4606) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [changeComissionBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4612) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4618) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | +| [updateIpRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4627) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | +| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4641) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | +| [deleteApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4657) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | +| [getSubAccountBrokerIpRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4663) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | +| [getApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4679) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | +| [getBrokerInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4685) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | +| [updateSubAccountBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4689) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | +| [updateSubAccountMarginInterestBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4699) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | +| [getSubAccountBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4712) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | +| [deleteBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4728) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | +| [transferBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4738) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | +| [getBrokerSubAccountHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4744) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | +| [submitBrokerSubFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4750) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | +| [getSubAccountFuturesTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4765) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | +| [getBrokerSubDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4777) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | +| [getBrokerSubAccountSpotAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4783) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | +| [getSubAccountMarginAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4792) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | +| [querySubAccountFuturesAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4801) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | +| [universalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4810) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | +| [getUniversalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4817) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | +| [updateBrokerSubAccountCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4829) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | +| [updateBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4835) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | +| [getBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4844) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | +| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4853) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4862) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4871) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | +| [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4877) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | +| [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4914) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | +| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4925) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | +| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4944) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4954) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | +| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4995) | | POST | `api/v3/userDataStream` | +| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4999) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | +| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5003) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | +| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5010) | | POST | `sapi/v1/userDataStream` | +| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5014) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5018) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5023) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5031) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5040) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5052) | | POST | `sapi/v1/margin/listen-key` | +| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5056) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5060) | | DELETE | `sapi/v1/margin/listen-key` | +| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5072) | | POST | `sapi/v2/margin/listen-key` | +| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5080) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5088) | | DELETE | `sapi/v2/margin/listen-key` | +| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5092) | | POST | `sapi/v2/margin/uta/listen-key` | +| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5096) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | +| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5100) | | DELETE | `sapi/v2/margin/uta/listen-key` | +| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5108) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | +| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5130) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | +| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5137) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | +| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5146) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | +| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5155) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | +| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5170) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | +| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5179) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | +| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5193) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | +| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5203) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | +| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5212) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | +| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5221) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | +| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5228) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | +| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5235) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | +| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5242) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | +| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5249) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | +| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5266) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | +| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5274) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | +| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5281) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | # usdm-client.ts diff --git a/examples/apidoc/MainClient/createSubAccountApiKey.js b/examples/apidoc/MainClient/createSubAccountApiKey.js new file mode 100644 index 00000000..4a0a3573 --- /dev/null +++ b/examples/apidoc/MainClient/createSubAccountApiKey.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/sub-account/subAccountApi +// METHOD: POST +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.createSubAccountApiKey(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/deleteSubAccountApiKey.js b/examples/apidoc/MainClient/deleteSubAccountApiKey.js new file mode 100644 index 00000000..3cb2dafb --- /dev/null +++ b/examples/apidoc/MainClient/deleteSubAccountApiKey.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/sub-account/subAccountApi +// METHOD: DELETE +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.deleteSubAccountApiKey(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getSubAccountApiKeys.js b/examples/apidoc/MainClient/getSubAccountApiKeys.js new file mode 100644 index 00000000..85e1282c --- /dev/null +++ b/examples/apidoc/MainClient/getSubAccountApiKeys.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/sub-account/subAccountApi +// METHOD: GET +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getSubAccountApiKeys(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/modifySubAccountApiKeyPermission.js b/examples/apidoc/MainClient/modifySubAccountApiKeyPermission.js new file mode 100644 index 00000000..e6ee5a40 --- /dev/null +++ b/examples/apidoc/MainClient/modifySubAccountApiKeyPermission.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v1/sub-account/subAccountApiPermission +// METHOD: POST +// PUBLIC: NO + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.modifySubAccountApiKeyPermission(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index a15412ef..c324c03c 100644 --- a/llms.txt +++ b/llms.txt @@ -535,7 +535,7 @@ public processCandleEvent( candle: EngineCandle, interval: string, isCandleClosed: boolean, -): void + ): void ⋮---- // console.log(this.symbol, `Open candle update`); ⋮---- @@ -558,7 +558,7 @@ public trimExcessCandles(interval: string): void public getCandles( interval: string, includeOpenCandle?: boolean, -): EngineCandle[] + ): EngineCandle[] ⋮---- // check last candle has same open time as open candle, just in case ⋮---- @@ -739,7 +739,7 @@ function formatOrderParams( price: number, quantity: number, symbolInfo: any, -): +): { symbol: string; price: number; quantity: number } ⋮---- // Check if price is within allowed range ⋮---- @@ -4463,7 +4463,7 @@ constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, -) + ) ⋮---- public getWSClient(): WebsocketClient ⋮---- @@ -4487,7 +4487,7 @@ testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> */ getSpotServerTime( wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query current exchange trading rules, rate limits, and symbol information @@ -4495,7 +4495,7 @@ getSpotServerTime( getSpotExchangeInfo( params?: WSAPIExchangeInfoRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /* * @@ -4510,7 +4510,7 @@ getSpotExchangeInfo( getSpotOrderBook( params: WSAPIOrderBookRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get recent trades @@ -4519,7 +4519,7 @@ getSpotOrderBook( getSpotRecentTrades( params: WSAPITradesRecentRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get historical trades @@ -4528,7 +4528,7 @@ getSpotRecentTrades( getSpotHistoricalTrades( params: WSAPITradesHistoricalRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get historical block trades @@ -4536,7 +4536,7 @@ getSpotHistoricalTrades( getSpotHistoricalBlockTrades( params: WSAPIBlockTradesHistoricalRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get aggregate trades @@ -4545,7 +4545,7 @@ getSpotHistoricalBlockTrades( getSpotAggregateTrades( params: WSAPITradesAggregateRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get klines (candlestick bars) @@ -4554,7 +4554,7 @@ getSpotAggregateTrades( getSpotKlines( params: WSAPIKlinesRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get klines (candlestick bars) optimized for presentation @@ -4563,7 +4563,7 @@ getSpotKlines( getSpotUIKlines( params: WSAPIKlinesRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get current average price for a symbol @@ -4571,7 +4571,7 @@ getSpotUIKlines( getSpotAveragePrice( params: WSAPIAvgPriceRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. @@ -4579,7 +4579,7 @@ getSpotAveragePrice( getSpotExecutionRules( params?: WSAPIExecutionRulesRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query reference price for a symbol. @@ -4587,7 +4587,7 @@ getSpotExecutionRules( getSpotReferencePrice( params: WSAPIReferencePriceRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query how reference price is calculated for a symbol. @@ -4595,7 +4595,7 @@ getSpotReferencePrice( getSpotReferencePriceCalculation( params: WSAPIReferencePriceCalculationRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get 24-hour rolling window price change statistics @@ -4608,13 +4608,7 @@ getSpot24hrTicker( WSAPIResponse< WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker.24hr', - params, - { authIsOptional: true }, - ); + > ⋮---- /** * Get price change statistics for a trading day @@ -4626,13 +4620,7 @@ getSpotTradingDayTicker( WSAPIResponse< WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker.tradingDay', - params, - { authIsOptional: true }, - ); + > ⋮---- /** * Get rolling window price change statistics with a custom window @@ -4645,13 +4633,7 @@ getSpotTicker( WSAPIResponse< WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker', - params, - { authIsOptional: true }, - ); + > ⋮---- /** * Get the latest market price for a symbol @@ -4660,7 +4642,7 @@ getSpotTicker( getSpotSymbolPriceTicker( params?: WSAPITickerPriceRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get the current best price and quantity on the order book @@ -4669,7 +4651,7 @@ getSpotSymbolPriceTicker( getSpotSymbolOrderBookTicker( params?: WSAPITickerBookRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /* * @@ -4681,7 +4663,7 @@ getSpotSymbolOrderBookTicker( ⋮---- getSpotSessionStatus( wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /* * @@ -4695,7 +4677,7 @@ getSpotSessionStatus( submitNewSpotOrder( params: WSAPINewSpotOrderRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Test order placement @@ -4706,12 +4688,7 @@ testSpotOrder( wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'order.test', - params, - ); + > ⋮---- /** * Check execution status of an order @@ -4720,7 +4697,7 @@ testSpotOrder( getSpotOrderStatus( params: WSAPIOrderStatusRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Cancel an active order @@ -4729,7 +4706,7 @@ getSpotOrderStatus( cancelSpotOrder( params: WSAPIOrderCancelRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Cancel an existing order and immediately place a new order @@ -4738,7 +4715,7 @@ cancelSpotOrder( cancelReplaceSpotOrder( params: WSAPIOrderCancelReplaceRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Reduce the quantity of an existing open order. @@ -4748,7 +4725,7 @@ cancelReplaceSpotOrder( amendSpotOrderKeepPriority( params: WSAPIOrderAmendKeepPriorityRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query execution status of all open orders @@ -4757,7 +4734,7 @@ amendSpotOrderKeepPriority( getSpotOpenOrders( params: WSAPIOpenOrdersStatusRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Cancel all open orders on a symbol @@ -4768,12 +4745,7 @@ cancelAllSpotOpenOrders( wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]> - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'openOrders.cancelAll', - params, - ); + > ⋮---- /** * Place a new order list @@ -4782,7 +4754,7 @@ cancelAllSpotOpenOrders( placeSpotOrderList( params: WSAPIOrderListPlaceRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Place a new OCO (One-Cancels-the-Other) order list @@ -4791,7 +4763,7 @@ placeSpotOrderList( placeSpotOCOOrderList( params: WSAPIOrderListPlaceOCORequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Place a new OTO (One-Triggers-the-Other) order list @@ -4800,7 +4772,7 @@ placeSpotOCOOrderList( placeSpotOTOOrderList( params: WSAPIOrderListPlaceOTORequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list @@ -4809,7 +4781,7 @@ placeSpotOTOOrderList( placeSpotOTOCOOrderList( params: WSAPIOrderListPlaceOTOCORequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Place a new OPO (One-Pays-the-Other) order list @@ -4818,7 +4790,7 @@ placeSpotOTOCOOrderList( placeSpotOPOOrderList( params: WSAPIOrderListPlaceOPORequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Place a new OPOCO (One-Pays-One-Cancels-the-Other) order list @@ -4827,7 +4799,7 @@ placeSpotOPOOrderList( placeSpotOPOCOOrderList( params: WSAPIOrderListPlaceOPOCORequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Check execution status of an order list @@ -4836,7 +4808,7 @@ placeSpotOPOCOOrderList( getSpotOrderListStatus( params: WSAPIOrderListStatusRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Cancel an active order list @@ -4845,7 +4817,7 @@ getSpotOrderListStatus( cancelSpotOrderList( params: WSAPIOrderListCancelRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query execution status of all open order lists @@ -4854,7 +4826,7 @@ cancelSpotOrderList( getSpotOpenOrderLists( params: WSAPIRecvWindowTimestamp, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Place a new order using Smart Order Routing (SOR) @@ -4863,7 +4835,7 @@ getSpotOpenOrderLists( placeSpotSOROrder( params: WSAPISOROrderPlaceRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) @@ -4876,12 +4848,7 @@ testSpotSOROrder( WSAPIResponse< WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'sor.order.test', - params, - ); + > ⋮---- /* * @@ -4896,7 +4863,7 @@ testSpotSOROrder( getSpotAccountInformation( params: WSAPIAccountInformationRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query your current unfilled order count for all intervals @@ -4905,7 +4872,7 @@ getSpotAccountInformation( getSpotOrderRateLimits( params: WSAPIRecvWindowTimestamp, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query information about all your orders – active, canceled, filled – filtered by time range @@ -4914,7 +4881,7 @@ getSpotOrderRateLimits( getSpotAllOrders( params: WSAPIAllOrdersRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query information about all your order lists, filtered by time range @@ -4923,7 +4890,7 @@ getSpotAllOrders( getSpotAllOrderLists( params: WSAPIAllOrderListsRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Query information about all your trades, filtered by time range @@ -4932,7 +4899,7 @@ getSpotAllOrderLists( getSpotMyTrades( params: WSAPIMyTradesRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Displays the list of orders that were expired due to STP @@ -4941,7 +4908,7 @@ getSpotMyTrades( getSpotPreventedMatches( params: WSAPIMyPreventedMatchesRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Retrieves allocations resulting from SOR order placement @@ -4950,7 +4917,7 @@ getSpotPreventedMatches( getSpotAllocations( params: WSAPIMyAllocationsRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /** * Get current account commission rates @@ -4959,7 +4926,7 @@ getSpotAllocations( getSpotAccountCommission( params: WSAPIAccountCommissionWSAPIRequest, wsKey?: WSAPIWsKeyMain, -): Promise> + ): Promise> ⋮---- /* * @@ -4973,7 +4940,7 @@ getSpotAccountCommission( */ getFuturesOrderBook( params: WSAPIFuturesOrderBookRequest, -): Promise> + ): Promise> ⋮---- /** * Get latest price for a futures symbol or symbols @@ -4983,13 +4950,7 @@ getFuturesSymbolPriceTicker( params?: WSAPIFuturesTickerPriceRequest, ): Promise< WSAPIResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.usdmWSAPI, - 'ticker.price', - params, - { authIsOptional: true }, - ); + > ⋮---- /** * Get best price/qty on the order book for a futures symbol or symbols @@ -4997,7 +4958,7 @@ getFuturesSymbolPriceTicker( */ getFuturesSymbolOrderBookTicker( params?: WSAPIFuturesTickerBookRequest, -): Promise> + ): Promise> ⋮---- /* * @@ -5013,7 +4974,7 @@ getFuturesSymbolOrderBookTicker( submitNewFuturesOrder( market: 'usdm' | 'coinm', params: WSAPINewFuturesOrderRequest, -): Promise> + ): Promise> ⋮---- /** * Modify an existing futures order @@ -5023,7 +4984,7 @@ submitNewFuturesOrder( modifyFuturesOrder( market: 'usdm' | 'coinm', params: WSAPIFuturesOrderModifyRequest, -): Promise> + ): Promise> ⋮---- /** * Cancel a futures order @@ -5033,7 +4994,7 @@ modifyFuturesOrder( cancelFuturesOrder( market: 'usdm' | 'coinm', params: WSAPIFuturesOrderCancelRequest, -): Promise> + ): Promise> ⋮---- /** * Query futures order status @@ -5043,7 +5004,7 @@ cancelFuturesOrder( getFuturesOrderStatus( market: 'usdm' | 'coinm', params: WSAPIFuturesOrderStatusRequest, -): Promise> + ): Promise> ⋮---- /** * Get current position information (V2) @@ -5051,7 +5012,7 @@ getFuturesOrderStatus( */ getFuturesPositionV2( params: WSAPIFuturesPositionV2Request, -): Promise> + ): Promise> ⋮---- /** * Get current position information @@ -5062,7 +5023,7 @@ getFuturesPositionV2( getFuturesPosition( market: 'usdm' | 'coinm', params: WSAPIFuturesPositionRequest, -): Promise> + ): Promise> ⋮---- /** * Send in a new algo order @@ -5071,7 +5032,7 @@ getFuturesPosition( */ submitNewFuturesAlgoOrder( params: WSAPINewFuturesAlgoOrderRequest, -): Promise> + ): Promise> ⋮---- /** * Cancel an active algo order. @@ -5081,7 +5042,7 @@ submitNewFuturesAlgoOrder( */ cancelFuturesAlgoOrder( params: WSAPIFuturesAlgoOrderCancelRequest, -): Promise> + ): Promise> ⋮---- /* * @@ -5095,7 +5056,7 @@ cancelFuturesAlgoOrder( */ getFuturesAccountBalanceV2( params: WSAPIRecvWindowTimestamp, -): Promise> + ): Promise> ⋮---- /** * Get account balance information @@ -5106,7 +5067,7 @@ getFuturesAccountBalanceV2( getFuturesAccountBalance( market: 'usdm' | 'coinm', params: WSAPIRecvWindowTimestamp, -): Promise> + ): Promise> ⋮---- /** * Get account information (V2) @@ -5114,7 +5075,7 @@ getFuturesAccountBalance( */ getFuturesAccountStatusV2( params: WSAPIRecvWindowTimestamp, -): Promise> + ): Promise> ⋮---- /** * Get account information @@ -5125,7 +5086,7 @@ getFuturesAccountStatusV2( getFuturesAccountStatus( market: 'usdm' | 'coinm', params: WSAPIRecvWindowTimestamp, -): Promise> + ): Promise> ⋮---- /* * @@ -5145,7 +5106,7 @@ getFuturesAccountStatus( startUserDataStreamForKey( params: { apiKey: string }, wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> ⋮---- /** * Attempt to "ping" a listen key. @@ -5159,7 +5120,7 @@ startUserDataStreamForKey( pingUserDataStreamForKey( params: WSAPIUserDataListenKeyRequest, wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> + ): Promise> ⋮---- /** * Stop the user data stream listen key. @@ -5171,7 +5132,7 @@ pingUserDataStreamForKey( stopUserDataStreamForKey( params: WSAPIUserDataListenKeyRequest, wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> + ): Promise> ⋮---- /** * Consolidated method to clear any timers related to user data stream subscriptions for a given wsKey, if found. @@ -5191,7 +5152,7 @@ clearUserDataStreamTimers(wsKey: WSAPIWsKey) async subscribeUserDataStream( wsKey: WSAPIWsKey, isRefreshingToken: boolean = false, -): Promise | WSConnectedResult | undefined> + ): Promise | WSConnectedResult | undefined> ⋮---- // User data stream works differently for margin, since Feb 2026, via a listen token mechanic ⋮---- @@ -5216,7 +5177,7 @@ async subscribeUserDataStream( */ unsubscribeUserDataStream( wsKey: WSAPIWsKey, -): Promise> ⋮---- /** * @@ -5262,19 +5223,19 @@ private setupSignMechanic() private async tryResubscribeUserDataStream( wsKey: WSAPIWsKey, isRefreshingToken: boolean, -) + ) ⋮---- // Just in case the refresh timer is still running ⋮---- private getSubscribedUserDataStreamState(wsKey: WSAPIWsKey) ⋮---- -private handleWSCloseEvent(params: +private handleWSCloseEvent(params: { wsKey: WsKey }) ⋮---- // Not a WS API connection ⋮---- // If connection closes and we have a record of subscribing to user data stream on this connection, then we can assume it was likely an unintentional disconnect and we should attempt to resubscribe when it reconnects ⋮---- -private handleWSReconnectedEvent(params: +private handleWSReconnectedEvent(params: { wsKey: WsKey }) ⋮---- // Not a WS API connection ⋮---- @@ -5417,7 +5378,7 @@ export class WebsocketClientV1 extends EventEmitter constructor( options: WSClientConfigurableOptions, logger?: typeof DefaultLogger, -) + ) ⋮---- // Some defaults: ⋮---- @@ -5433,7 +5394,7 @@ public connectToWsUrl( url: string, wsKey?: WsKey | string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- // Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node ⋮---- @@ -5454,7 +5415,7 @@ private onWsClose( wsKey: WsKey | string, ws: WebSocket, wsUrl: string, -) + ) ⋮---- // Clear any timers before we initiate revival ⋮---- @@ -5464,7 +5425,7 @@ private onWsMessage( event: WebSocket.MessageEvent, wsKey: WsKey | string, source: WsEventInternalSrc, -) + ) ⋮---- // Edge case where raw event does not include event type, detect using wsKey and mutate msg.e ⋮---- @@ -5479,13 +5440,13 @@ private onWsPing( wsKey: WsKey | string, ws: WebSocket, source: WsEventInternalSrc, -) + ) ⋮---- private onWsPong( event: any, wsKey: WsKey | string, source: WsEventInternalSrc, -) + ) ⋮---- /** * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. @@ -5495,7 +5456,7 @@ private executeReconnectableClose( wsKey: WsKey | string, reason: string, wsUrl: string, -) + ) ⋮---- public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) ⋮---- @@ -5508,13 +5469,13 @@ private parseWsError( error: any, wsKey: WsKey | string, wsUrl: string, -) + ) ⋮---- private reconnectWithDelay( wsKey: WsKey | string, connectionDelayMs: number, wsUrl: string, -) + ) ⋮---- // We'll set a new one once the new stream respawns, with a diff listenKey in the key ⋮---- @@ -5559,7 +5520,7 @@ public requestSetProperty( property: 'combined' | string, value: any, requestId: number, -) + ) ⋮---- /** * Send WS message to get property state @@ -5568,7 +5529,7 @@ public requestGetProperty( wsKey: WsKey, property: 'combined' | string, requestId: number, -) + ) ⋮---- /** * -------------------------- @@ -5583,7 +5544,7 @@ private setKeepAliveListenKeyTimer( wsKey: WsKey, symbol?: string, isTestnet?: boolean, -) + ) ⋮---- // Set timer to keep WS alive every 50 minutes ⋮---- @@ -5596,7 +5557,7 @@ private sendKeepAliveForMarket( wsKey: WsKey, symbol?: string, isTestnet?: boolean, -) + ) ⋮---- private async checkKeepAliveListenKey( listenKey: string, @@ -5605,7 +5566,7 @@ private async checkKeepAliveListenKey( wsKey: WsKey, symbol?: string, isTestnet?: boolean, -) + ) ⋮---- // Simple way to test keep alive failure handling: // throw new Error(`Fake keep alive failure`); @@ -5627,7 +5588,7 @@ private async respawnUserDataStream( symbol?: string, isTestnet?: boolean, respawnAttempt?: number, -): Promise + ): Promise ⋮---- // If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key ⋮---- @@ -5647,7 +5608,7 @@ public subscribeEndpoint( endpoint: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to aggregate trades for a symbol in a market category @@ -5656,7 +5617,7 @@ public subscribeAggregateTrades( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to trades for a symbol in a market category @@ -5666,7 +5627,7 @@ public subscribeTrades( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to block trades for a symbol in spot markets. @@ -5674,7 +5635,7 @@ public subscribeTrades( public subscribeBlockTrades( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to coin index for a symbol in COINM Futures markets @@ -5685,7 +5646,7 @@ public subscribeCoinIndexPrice( // eslint-disable-next-line @typescript-eslint/no-unused-vars _updateSpeedMs: 1000 | 3000 = 3000, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- @@ -5697,7 +5658,7 @@ public subscribeMarkPrice( market: 'usdm' | 'coinm', updateSpeedMs: 1000 | 3000 = 3000, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to mark price for all symbols in a market category @@ -5706,7 +5667,7 @@ public subscribeAllMarketMarkPrice( market: 'usdm' | 'coinm', updateSpeedMs: 1000 | 3000 = 3000, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to klines(candles) for a symbol in a market category @@ -5716,7 +5677,7 @@ public subscribeKlines( interval: KlineInterval, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to continuous contract klines(candles) for a symbol futures @@ -5727,7 +5688,7 @@ public subscribeContinuousContractKlines( interval: KlineInterval, market: 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to index klines(candles) for a symbol in a coinm futures @@ -5736,7 +5697,7 @@ public subscribeIndexKlines( symbol: string, interval: KlineInterval, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to index klines(candles) for a symbol in a coinm futures @@ -5745,7 +5706,7 @@ public subscribeMarkPriceKlines( symbol: string, interval: KlineInterval, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to mini 24hr ticker for a symbol in market category. @@ -5754,7 +5715,7 @@ public subscribeSymbolMini24hrTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to mini 24hr mini ticker in market category. @@ -5762,7 +5723,7 @@ public subscribeSymbolMini24hrTicker( public subscribeAllMini24hrTickers( market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to 24hr ticker for a symbol in any market. @@ -5771,7 +5732,7 @@ public subscribeSymbol24hrTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to 24hr ticker in any market. @@ -5779,7 +5740,7 @@ public subscribeSymbol24hrTicker( public subscribeAll24hrTickers( market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to rolling window ticker statistics for all market symbols, @@ -5794,7 +5755,7 @@ public subscribeAllRollingWindowTickers( market: 'spot', windowSize: '1h' | '4h' | '1d', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. @@ -5803,7 +5764,7 @@ public subscribeSymbolBookTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. @@ -5811,7 +5772,7 @@ public subscribeSymbolBookTicker( public subscribeAllBookTickers( market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. @@ -5820,7 +5781,7 @@ public subscribeSymbolLiquidationOrders( symbol: string, market: 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. @@ -5828,7 +5789,7 @@ public subscribeSymbolLiquidationOrders( public subscribeAllLiquidationOrders( market: 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to partial book depths (snapshots). @@ -5845,7 +5806,7 @@ public subscribePartialBookDepths( updateMs: 100 | 250 | 500 | 1000, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to orderbook depth updates to locally manage an order book. @@ -5862,7 +5823,7 @@ public subscribeDiffBookDepth( updateMs: 100 | 250 | 500 | 1000 = 100, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. @@ -5870,7 +5831,7 @@ public subscribeDiffBookDepth( public subscribeContractInfoStream( market: 'usdm' | 'coinm', forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * -------------------------- @@ -5884,7 +5845,7 @@ public subscribeContractInfoStream( public subscribeSpotAggregateTrades( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to trades for a symbol in spot markets. @@ -5892,7 +5853,7 @@ public subscribeSpotAggregateTrades( public subscribeSpotTrades( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to block trades for a symbol in spot markets. @@ -5900,7 +5861,7 @@ public subscribeSpotTrades( public subscribeSpotBlockTrades( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to candles for a symbol in spot markets. @@ -5909,7 +5870,7 @@ public subscribeSpotKline( symbol: string, interval: KlineInterval, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to mini 24hr ticker for a symbol in spot markets. @@ -5917,14 +5878,14 @@ public subscribeSpotKline( public subscribeSpotSymbolMini24hrTicker( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to mini 24hr mini ticker in spot markets. */ public subscribeSpotAllMini24hrTickers( forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to 24hr ticker for a symbol in spot markets. @@ -5932,7 +5893,7 @@ public subscribeSpotAllMini24hrTickers( public subscribeSpotSymbol24hrTicker( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to 24hr ticker in spot markets. @@ -5945,7 +5906,7 @@ public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket public subscribeSpotSymbolBookTicker( symbol: string, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. @@ -5960,7 +5921,7 @@ public subscribeSpotPartialBookDepth( levels: 5 | 10 | 20, updateMs: 1000 | 100 = 1000, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to spot orderbook depth updates to locally manage an order book. @@ -5969,7 +5930,7 @@ public subscribeSpotDiffBookDepth( symbol: string, updateMs: 1000 | 100 = 1000, forceNewConnection?: boolean, -): WebSocket + ): WebSocket ⋮---- /** * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. @@ -5979,7 +5940,7 @@ public subscribeSpotUserDataStreamWithListenKey( listenKey: string, forceNewConnection?: boolean, isReconnecting?: boolean, -): WebSocket | undefined + ): WebSocket | undefined ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- @@ -5989,7 +5950,7 @@ public subscribeSpotUserDataStreamWithListenKey( public async subscribeSpotUserDataStream( forceNewConnection?: boolean, isReconnecting?: boolean, -): Promise + ): Promise ⋮---- /** * Subscribe to margin user data stream - listen key is automatically generated. @@ -5997,7 +5958,7 @@ public async subscribeSpotUserDataStream( public async subscribeMarginUserDataStream( forceNewConnection?: boolean, isReconnecting?: boolean, -): Promise + ): Promise ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- @@ -6008,7 +5969,7 @@ public async subscribeIsolatedMarginUserDataStream( symbol: string, forceNewConnection?: boolean, isReconnecting?: boolean, -): Promise + ): Promise ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- @@ -6025,7 +5986,7 @@ public async subscribeUsdFuturesUserDataStream( isTestnet?: boolean, forceNewConnection?: boolean, isReconnecting?: boolean, -): Promise + ): Promise ⋮---- // Necessary so client knows this is a reconnect ⋮---- @@ -6038,7 +5999,7 @@ public async subscribeCoinFuturesUserDataStream( isTestnet?: boolean, forceNewConnection?: boolean, isReconnecting?: boolean, -): Promise + ): Promise ⋮---- // Necessary so client knows this is a reconnect ⋮---- @@ -8386,7 +8347,7 @@ export class CoinMClient extends BaseRestClient constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, -) + ) ⋮---- /** * Abstraction required by each client to aid with time sync / drift handling @@ -8409,28 +8370,28 @@ getRecentTrades(params: RecentTradesParams): Promise ⋮---- getHistoricalTrades( params: HistoricalTradesParams, -): Promise + ): Promise ⋮---- getAggregateTrades( params: SymbolFromPaginatedRequestFromId, -): Promise + ): Promise ⋮---- /** * Index Price and Mark Price */ -getMarkPrice(params?: +getMarkPrice(params?: { symbol?: string }): Promise ⋮---- getFundingRateHistory( params?: Partial, -): Promise + ): Promise ⋮---- -getFundingRate(params?: +getFundingRate(params?: { symbol?: string }): Promise ⋮---- getKlines(params: KlinesParams): Promise ⋮---- getContinuousContractKlines( params: ContinuousContractKlinesParams, -): Promise + ): Promise ⋮---- getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- @@ -8441,37 +8402,37 @@ getPremiumIndexKlines(params: KlinesParams): Promise get24hrChangeStatistics(params?: { symbol?: string; pair?: string; -}): Promise + }): Promise ⋮---- getSymbolPriceTicker(params?: { symbol?: string; pair?: string; -}): Promise + }): Promise ⋮---- getSymbolOrderBookTicker(params?: { symbol?: string; pair?: string; -}): Promise + }): Promise ⋮---- -getOpenInterest(params: +getOpenInterest(params: { symbol: string }): Promise ⋮---- getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise ⋮---- getTopTradersLongShortAccountRatio( params: FuturesCoinMLongShortAccountRatioParams, -): Promise + ): Promise ⋮---- getTopTradersLongShortPositionRatio( params: FuturesDataPaginatedParams & { pair?: string }, -): Promise + ): Promise ⋮---- getGlobalLongShortAccountRatio( params: FuturesDataPaginatedParams, -): Promise + ): Promise ⋮---- getTakerBuySellVolume( params: FuturesCoinMTakerBuySellVolumeParams, -): Promise + ): Promise ⋮---- getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise ⋮---- @@ -8481,7 +8442,7 @@ getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise **/ getIndexPriceConstituents(params: { symbol: string; -}): Promise + }): Promise ⋮---- /** * possibly @deprecated @@ -8489,7 +8450,7 @@ getIndexPriceConstituents(params: { **/ getQuarterlyContractSettlementPrices(params: { pair: string; -}): Promise + }): Promise ⋮---- /** * @@ -8506,46 +8467,46 @@ submitNewOrder(params: NewFuturesOrderParams): Promise */ submitMultipleOrders( orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> + ): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- /** * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue */ modifyOrder( params: ModifyFuturesOrderParams, -): Promise + ): 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)[]> + ): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> ⋮---- getOrderModifyHistory( params: GetOrderModifyHistoryParams, -): Promise + ): Promise ⋮---- cancelOrder(params: CancelOrderParams): Promise ⋮---- cancelMultipleOrders( params: CancelMultipleOrdersParams, -): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> + ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- cancelAllOpenOrders(params: { symbol?: string; -}): Promise + }): Promise ⋮---- // Auto-cancel all open orders setCancelOrdersOnTimeout( params: CancelOrdersTimeoutParams, -): Promise + ): Promise ⋮---- getOrder(params: GetOrderParams): Promise ⋮---- getAllOrders(params: GetAllOrdersParams): Promise ⋮---- -getAllOpenOrders(params?: +getAllOpenOrders(params?: { symbol?: string }): Promise ⋮---- getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- @@ -8558,26 +8519,26 @@ getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- submitNewAlgoOrder( params: FuturesNewAlgoOrderParams, -): Promise + ): Promise ⋮---- cancelAlgoOrder( params: FuturesCancelAlgoOrderParams, -): Promise + ): Promise ⋮---- getOpenAlgoOrders( params?: FuturesQueryOpenAlgoOrdersParams, -): Promise + ): Promise ⋮---- getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- getAccountTrades( params: CoinMAccountTradeParams & { orderId?: number }, -): Promise + ): Promise ⋮---- getPositions(params?: { marginAsset?: string; pair?: string; -}): Promise + }): Promise ⋮---- setPositionMode(params: PositionModeParams): Promise ⋮---- @@ -8585,15 +8546,15 @@ setMarginType(params: SetMarginTypeParams): Promise ⋮---- setLeverage(params: SetLeverageParams): Promise ⋮---- -getADLQuantileEstimation(params?: +getADLQuantileEstimation(params?: { symbol?: string }): Promise ⋮---- setIsolatedPositionMargin( params: SetIsolatedMarginParams, -): Promise + ): Promise ⋮---- getPositionMarginChangeHistory( params: GetPositionMarginChangeHistoryParams, -): Promise + ): Promise /** * * Account Endpoints @@ -8604,7 +8565,7 @@ getBalance(): Promise ⋮---- getAccountCommissionRate(params: { symbol?: string; -}): Promise + }): Promise ⋮---- getAccountInformation(): Promise ⋮---- @@ -8613,7 +8574,7 @@ getAccountInformation(): Promise */ getNotionalAndLeverageBrackets(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- // TO ADD: dapi/v1/leverageBracket // can use dapi/v2/leverageBracket @@ -8634,29 +8595,38 @@ getIncomeHistory(params?: GetIncomeHistoryParams): Promise getDownloadIdForFuturesTransactionHistory(params: { startTime: number; endTime: number; -}): Promise< + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- getFuturesTransactionHistoryDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- getDownloadIdForFuturesOrderHistory(params: { startTime: number; endTime: number; -}): Promise< + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- getFuturesOrderHistoryDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- getDownloadIdForFuturesTradeHistory(params: { startTime: number; endTime: number; -}): Promise< + }): Promise<{ + avgCostTimestampOfLast30d: number; + downloadId: string; + }> ⋮---- getFuturesTradeHistoryDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- /** * @@ -8666,14 +8636,16 @@ getFuturesTradeHistoryDownloadLink(params: { ⋮---- getClassicPortfolioMarginAccount(params: { asset: string; -}): Promise + }): Promise ⋮---- /** * @deprecated at 6th August, 2024 **/ getClassicPortfolioMarginNotionalLimits( params?: GetClassicPortfolioMarginNotionalLimitParams, -): Promise< + ): Promise<{ + notionalLimits: ClassicPortfolioMarginNotionalLimit[]; + }> ⋮---- /** * @@ -8689,7 +8661,7 @@ getClassicPortfolioMarginNotionalLimits( getBrokerIfNewFuturesUser( brokerId: string, type: 1 | 2 = 1, -): Promise< + ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> ⋮---- /** * @deprecated @@ -8697,7 +8669,7 @@ getBrokerIfNewFuturesUser( setBrokerCustomIdForClient( customerId: string, email: string, -): Promise< + ): Promise<{ customerId: string; email: string }> ⋮---- /** * @deprecated @@ -8707,7 +8679,7 @@ getBrokerClientCustomIds( email: string, page?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -8727,7 +8699,7 @@ getBrokerUserTradeVolume( startTime?: number, endTime?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -8737,7 +8709,7 @@ getBrokerRebateVolume( startTime?: number, endTime?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -8747,7 +8719,7 @@ getBrokerTradeDetail( startTime?: number, endTime?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @@ -8755,7 +8727,7 @@ getBrokerTradeDetail( * **/ ⋮---- -getFuturesUserDataListenKey(): Promise< +getFuturesUserDataListenKey(): Promise<{ listenKey: string }> ⋮---- keepAliveFuturesUserDataListenKey(): Promise ⋮---- @@ -8772,7 +8744,7 @@ private validateOrderId( | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, -): void + ): void ================ File: src/portfolio-client.ts @@ -8913,7 +8885,7 @@ export class PortfolioClient extends BaseRestClient constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, -) + ) ⋮---- getClientId(): BinanceBaseUrlKey ⋮---- @@ -8940,199 +8912,218 @@ signTradFiPerpsContract(): Promise ⋮---- submitNewUMOrder( params: NewPortfolioUMOrderReq, -): Promise + ): Promise ⋮---- /** * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). */ submitNewUMConditionalOrder( params: NewPortfolioUMConditionalOrderReq, -): Promise + ): Promise ⋮---- submitNewUMAlgoOrder( params: NewPortfolioUMAlgoOrderReq, -): Promise + ): Promise ⋮---- submitNewCMOrder( params: NewPortfolioCMOrderReq, -): Promise + ): Promise ⋮---- submitNewCMConditionalOrder( params: NewPortfolioCMConditionalOrderReq, -): Promise + ): Promise ⋮---- submitNewMarginOrder( params: NewPortfolioMarginOrderReq, -): Promise + ): Promise ⋮---- -submitMarginLoan(params: +submitMarginLoan(params: { asset: string; amount: string }): Promise<{ + tranId: number; + }> ⋮---- -submitMarginRepay(params: +submitMarginRepay(params: { asset: string; amount: string }): Promise<{ + tranId: number; + }> ⋮---- submitNewMarginOCO( params: NewPortfolioMarginOCOReq, -): Promise + ): Promise ⋮---- cancelUMOrder( params: CancelPortfolioUMOrderReq, -): Promise + ): Promise ⋮---- -cancelAllUMOrders(params: +cancelAllUMOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- /** * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). */ cancelUMConditionalOrder( params: CancelPortfolioUMConditionalOrderReq, -): Promise + ): Promise ⋮---- cancelUMAlgoOrder( params: CancelPortfolioUMAlgoOrderReq, -): Promise + ): Promise ⋮---- /** * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). */ -cancelAllUMConditionalOrders(params: +cancelAllUMConditionalOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- cancelAllUMAlgoOpenOrders(params: { symbol: string; -}): Promise + }): Promise ⋮---- cancelCMOrder( params: CancelPortfolioCMOrderReq, -): Promise + ): Promise ⋮---- -cancelAllCMOrders(params: +cancelAllCMOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- cancelCMConditionalOrder( params: CancelPortfolioCMConditionalOrderReq, -): Promise + ): Promise ⋮---- -cancelAllCMConditionalOrders(params: +cancelAllCMConditionalOrders(params: { symbol: string }): Promise<{ + code: number; + msg: string; + }> ⋮---- cancelMarginOrder( params: CancelPortfolioMarginOrderReq, -): Promise + ): Promise ⋮---- cancelMarginOCO( params: CancelPortfolioMarginOCOReq, -): Promise + ): Promise ⋮---- cancelAllMarginOrders(params: { symbol: string; -}): Promise + }): Promise ⋮---- modifyUMOrder( params: ModifyPortfolioUMOrderReq, -): Promise + ): Promise ⋮---- modifyCMOrder( params: ModifyPortfolioCMOrderReq, -): Promise + ): Promise ⋮---- getUMOrder(params: QueryPortfolioUMOrderReq): Promise ⋮---- getAllUMOrders( params: QueryPortfolioAllUMOrdersReq, -): Promise + ): Promise ⋮---- getUMOpenOrder( params: QueryPortfolioUMOpenOrderReq, -): Promise + ): Promise ⋮---- -getAllUMOpenOrders(params: +getAllUMOpenOrders(params: { symbol?: string }): Promise ⋮---- /** * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). */ getAllUMConditionalOrders( params: QueryPortfolioAllUMConditionalOrdersReq, -): Promise + ): Promise ⋮---- getAllUMAlgoOrders( params: QueryPortfolioAllUMAlgoOrdersReq, -): Promise + ): Promise ⋮---- /** * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). */ getUMOpenConditionalOrders(params: { symbol?: string; -}): Promise + }): Promise ⋮---- getUMAlgoOpenOrders(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- /** * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). */ getUMOpenConditionalOrder( params: QueryPortfolioUMOpenConditionalOrderReq, -): Promise + ): Promise ⋮---- getUMAlgoOrder( params: QueryPortfolioUMAlgoOrderReq, -): Promise + ): Promise ⋮---- /** * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. */ getUMConditionalOrderHistory( params: QueryPortfolioUMConditionalOrderHistoryReq, -): Promise + ): Promise ⋮---- getCMOrder(params: QueryPortfolioCMOrderReq): Promise ⋮---- getAllCMOrders( params: QueryPortfolioAllCMOrdersReq, -): Promise + ): Promise ⋮---- getCMOpenOrder( params: QueryPortfolioCMOpenOrderReq, -): Promise + ): Promise ⋮---- getAllCMOpenOrders(params: { symbol?: string; pair?: string; -}): Promise + }): Promise ⋮---- getCMOpenConditionalOrders(params: { symbol?: string; -}): Promise + }): Promise ⋮---- getCMOpenConditionalOrder(params: { symbol: string; strategyId?: number; newClientStrategyId?: string; -}): Promise + }): Promise ⋮---- getAllCMConditionalOrders( params: QueryPortfolioAllCMConditionalOrdersReq, -): Promise + ): Promise ⋮---- getCMConditionalOrderHistory( params: QueryPortfolioCMConditionalOrderHistoryReq, -): Promise + ): Promise ⋮---- getUMForceOrders( params: QueryPortfolioUMForceOrdersReq, -): Promise + ): Promise ⋮---- getCMForceOrders( params: QueryPortfolioCMForceOrdersReq, -): Promise + ): Promise ⋮---- getUMOrderModificationHistory( params: QueryPortfolioUMOrderAmendmentReq, -): Promise + ): Promise ⋮---- getCMOrderModificationHistory( params: QueryPortfolioCMOrderAmendmentReq, -): Promise + ): Promise ⋮---- -getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< +getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise<{ + rows: PortfolioMarginForceOrder[]; + total: number; + }> ⋮---- getUMTrades(params: QueryPortfolioUMTradesReq): Promise ⋮---- @@ -9143,54 +9134,52 @@ getUMADLQuantile(params: { symbol?: string }): Promise< symbol: string; adlQuantile: PortfolioADLQuantile; }[] - > { - return this.getPrivate('papi/v1/um/adlQuantile', params); + > ⋮---- getCMADLQuantile(params: { symbol?: string }): Promise< { symbol: string; adlQuantile: PortfolioADLQuantile; }[] - > { - return this.getPrivate('papi/v1/cm/adlQuantile', params); + > ⋮---- toggleUMFeeBurn(params: { feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off -}): Promise< + }): Promise<{ code: number; msg: string }> ⋮---- feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off ⋮---- -getUMFeeBurnStatus(): Promise< +getUMFeeBurnStatus(): Promise<{ feeBurn: boolean }> ⋮---- getMarginOrder( params: QueryPortfolioMarginOrderReq, -): Promise + ): Promise ⋮---- getMarginOpenOrders(params: { symbol: string; -}): Promise + }): Promise ⋮---- getAllMarginOrders( params: QueryPortfolioMarginAllOrdersReq, -): Promise + ): Promise ⋮---- getMarginOCO( params: QueryPortfolioMarginOCOReq, -): Promise + ): Promise ⋮---- getAllMarginOCO( params: QueryPortfolioMarginAllOCOReq, -): Promise + ): Promise ⋮---- getMarginOpenOCO(): Promise ⋮---- getMarginTrades( params: QueryPortfolioMarginTradesReq, -): Promise + ): Promise ⋮---- repayMarginDebt( params: PortfolioMarginRepayDebtReq, -): Promise + ): Promise ⋮---- /** * @@ -9198,25 +9187,30 @@ repayMarginDebt( * **/ ⋮---- -getBalance(params?: +getBalance(params?: { asset?: string }): Promise ⋮---- getAccountInfo(): Promise ⋮---- -getMarginMaxBorrow(params: +getMarginMaxBorrow(params: { asset: string }): Promise<{ + amount: string; // account's currently max borrowable amount with sufficient system availability + borrowLimit: string; // max borrowable amount limited by the account level + }> ⋮---- amount: string; // account's currently max borrowable amount with sufficient system availability borrowLimit: string; // max borrowable amount limited by the account level ⋮---- -getMarginMaxWithdraw(params: +getMarginMaxWithdraw(params: { asset: string }): Promise<{ + amount: string; // max withdrawable amount + }> ⋮---- amount: string; // max withdrawable amount ⋮---- -getUMPosition(params?: +getUMPosition(params?: { symbol?: string }): Promise ⋮---- getCMPosition(params?: { marginAsset?: string; pair?: string; -}): Promise + }): Promise ⋮---- /** * Change UM initial leverage (`POST /papi/v1/um/leverage`). @@ -9224,23 +9218,41 @@ getCMPosition(params?: { * bracket 1 `initialLeverage` from `GET /papi/v1/um/leverageBracket` * (Binance derivatives changelog 2026-10-09). */ -updateUMLeverage(params: +updateUMLeverage(params: { symbol: string; leverage: number }): Promise<{ + leverage: number; + maxNotionalValue: string; + symbol: string; + }> ⋮---- -updateCMLeverage(params: +updateCMLeverage(params: { symbol: string; leverage: number }): Promise<{ + leverage: number; + maxQty: string; + symbol: string; + }> ⋮---- updateUMPositionMode(params: { dualSidePosition: 'true' | 'false'; -}): Promise< + }): Promise<{ + code: number; + msg: string; + }> ⋮---- updateCMPositionMode(params: { dualSidePosition: 'true' | 'false'; -}): Promise< + }): Promise<{ + code: number; + msg: string; + }> ⋮---- -getUMPositionMode(): Promise< +getUMPositionMode(): Promise<{ + dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode + }> ⋮---- dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -getCMPositionMode(): Promise< +getCMPositionMode(): Promise<{ + dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode + }> ⋮---- dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- @@ -9250,52 +9262,75 @@ getUMLeverageBrackets(params?: { symbol?: string }): Promise< notionalCoef: string; brackets: PortfolioUMLeverageBracket[]; }[] - > { - return this.getPrivate('papi/v1/um/leverageBracket', params); + > ⋮---- getCMLeverageBrackets(params?: { symbol?: string }): Promise< { symbol: string; brackets: PortfolioCMLeverageBracket[]; }[] - > { - return this.getPrivate('papi/v1/cm/leverageBracket', params); + > ⋮---- getUMTradingStatus(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- -getUMCommissionRate(params: +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% + }> ⋮---- makerCommissionRate: string; // e.g., "0.0002" for 0.02% takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -getCMCommissionRate(params: +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% + }> ⋮---- makerCommissionRate: string; // e.g., "0.0002" for 0.02% takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise< +getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise<{ + rows: PortfolioMarginLoanRecord[]; + total: number; + }> ⋮---- -getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< +getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise<{ + rows: PortfolioMarginRepayRecord[]; + total: number; + }> ⋮---- -getAutoRepayFuturesStatus(): Promise< +getAutoRepayFuturesStatus(): Promise<{ + autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off + }> ⋮---- autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off ⋮---- updateAutoRepayFuturesStatus(params: { autoRepay: 'true' | 'false'; -}): Promise< + }): Promise<{ + msg: string; + }> ⋮---- -getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< +getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise<{ + rows: PortfolioMarginInterestRecord[]; + total: number; + }> ⋮---- -repayFuturesNegativeBalance(): Promise< +repayFuturesNegativeBalance(): Promise<{ + msg: string; + }> ⋮---- getPortfolioNegativeBalanceInterestHistory( params?: GetPortfolioInterestHistoryReq, -): Promise + ): Promise ⋮---- -autoCollectFunds(): Promise< +autoCollectFunds(): Promise<{ + msg: string; + }> ⋮---- /** * Fund collection by asset (`POST /papi/v1/asset-collection`). @@ -9308,12 +9343,16 @@ transferAssetFuturesMargin(params: { asset: string; amount?: number; futureType?: 'UM' | 'CM' | 'OPTION'; -}): Promise< + }): Promise<{ + msg: string; + }> ⋮---- transferBNB(params: { amount: string; transferSide: 'TO_UM' | 'FROM_UM'; -}): Promise< + }): Promise<{ + tranId: number; // transaction id + }> ⋮---- tranId: number; // transaction id ⋮---- @@ -9323,7 +9362,7 @@ tranId: number; // transaction id */ getUMIncomeHistory( params?: QueryPortfolioUMIncomeReq, -): Promise + ): Promise ⋮---- /** * Query CM income history (`GET /papi/v1/cm/income`). @@ -9331,28 +9370,40 @@ getUMIncomeHistory( */ getCMIncomeHistory( params?: QueryPortfolioCMIncomeReq, -): Promise + ): Promise ⋮---- -getUMAccount(): 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< +getCMAccount(): Promise<{ + assets: PortfolioCMAccountAsset[]; + positions: PortfolioCMAccountPosition[]; + }> ⋮---- getUMAccountConfig(): Promise ⋮---- getUMSymbolConfig(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- -getUMAccountV2(): 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< + }): 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 @@ -9361,12 +9412,15 @@ avgCostTimestampOfLast30d: number; // Average time taken for data download in th ⋮---- getUMTradeDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- getUMOrderHistoryDownloadId(params: { startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms -}): Promise< + }): 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 @@ -9375,12 +9429,15 @@ avgCostTimestampOfLast30d: number; // Average time taken for data download in th ⋮---- getUMOrderDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- getUMTransactionHistoryDownloadId(params: { startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms -}): Promise< + }): 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 @@ -9389,7 +9446,7 @@ avgCostTimestampOfLast30d: number; // Average time taken for data download in th ⋮---- getUMTransactionDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. @@ -9401,14 +9458,14 @@ private validateOrderId( | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, -): void + ): void ⋮---- /** * * User Data Stream Endpoints * **/ -getPMUserDataListenKey(): Promise< +getPMUserDataListenKey(): Promise<{ listenKey: string }> ⋮---- keepAlivePMUserDataListenKey(): Promise ⋮---- @@ -9534,7 +9591,7 @@ export class USDMClient extends BaseRestClient constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, -) + ) ⋮---- /** * Abstraction required by each client to aid with time sync / drift handling @@ -9556,23 +9613,23 @@ getOrderBook(params: OrderBookParams): Promise getRpiOrderBook(params: { symbol: string; limit?: number; -}): Promise + }): Promise ⋮---- getRecentTrades(params: RecentTradesParams): Promise ⋮---- getHistoricalTrades( params: HistoricalTradesParams, -): Promise + ): Promise ⋮---- getAggregateTrades( params: SymbolFromPaginatedRequestFromId, -): Promise + ): Promise ⋮---- getKlines(params: KlinesParams): Promise ⋮---- getContinuousContractKlines( params: ContinuousContractKlinesParams, -): Promise + ): Promise ⋮---- getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- @@ -9584,11 +9641,11 @@ getMarkPrice(params: ⋮---- getMarkPrice(): Promise; ⋮---- -getMarkPrice(params?: +getMarkPrice(params?: { symbol?: string }): Promise ⋮---- getFundingRateHistory( params?: Partial, -): Promise + ): Promise ⋮---- getFundingRates(): Promise ⋮---- @@ -9598,7 +9655,7 @@ get24hrChangeStatistics(): Promise; ⋮---- get24hrChangeStatistics(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getSymbolPriceTicker(params: ⋮---- @@ -9606,7 +9663,7 @@ getSymbolPriceTicker(): Promise; ⋮---- getSymbolPriceTicker(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getSymbolPriceTickerV2(params: ⋮---- @@ -9614,7 +9671,7 @@ getSymbolPriceTickerV2(): Promise; ⋮---- getSymbolPriceTickerV2(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getSymbolOrderBookTicker(params: { symbol: string; @@ -9624,37 +9681,37 @@ getSymbolOrderBookTicker(): Promise; ⋮---- getSymbolOrderBookTicker(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getQuarterlyContractSettlementPrices(params: { pair: string; -}): Promise + }): Promise ⋮---- -getOpenInterest(params: +getOpenInterest(params: { symbol: string }): Promise ⋮---- getOpenInterestStatistics( params: FuturesDataPaginatedParams, -): Promise + ): Promise ⋮---- getTopTradersLongShortPositionRatio( params: FuturesDataPaginatedParams, -): Promise + ): Promise ⋮---- getTopTradersLongShortAccountRatio( params: FuturesDataPaginatedParams, -): Promise + ): Promise ⋮---- getGlobalLongShortAccountRatio( params: FuturesDataPaginatedParams, -): Promise + ): Promise ⋮---- getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise ⋮---- getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -getCompositeSymbolIndex(params?: +getCompositeSymbolIndex(params?: { symbol?: string }): Promise ⋮---- -getMultiAssetsModeAssetIndex(params?: +getMultiAssetsModeAssetIndex(params?: { symbol?: string }): Promise ⋮---- /** * Possibly @deprecated, found only in old docs @@ -9663,11 +9720,11 @@ getBasis(params: BasisParams): Promise ⋮---- getIndexPriceConstituents(params: { symbol: string; -}): Promise + }): Promise ⋮---- getInsuranceFundBalance(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getTradingSchedule(): Promise ⋮---- @@ -9688,7 +9745,7 @@ submitNewOrder(params: NewFuturesOrderParams): Promise */ submitMultipleOrders( orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> + ): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- // Known issue: `quantity` and `price` should be sent as strings, see #523, #526 ⋮---- @@ -9697,34 +9754,34 @@ submitMultipleOrders( */ modifyOrder( params: ModifyFuturesOrderParams, -): Promise + ): Promise ⋮---- modifyMultipleOrders(orders: ModifyOrderParams[]): Promise ⋮---- getOrderModifyHistory( params: GetFuturesOrderModifyHistoryParams, -): Promise + ): Promise ⋮---- cancelOrder(params: CancelOrderParams): Promise ⋮---- cancelMultipleOrders( params: CancelMultipleOrdersParams, -): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> + ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- cancelAllOpenOrders(params: { symbol: string; -}): Promise + }): Promise ⋮---- // Auto-cancel all open orders setCancelOrdersOnTimeout( params: CancelOrdersTimeoutParams, -): Promise + ): Promise ⋮---- getOrder(params: GetOrderParams): Promise ⋮---- getAllOrders(params?: GetFuturesAllOrdersParams): Promise ⋮---- -getAllOpenOrders(params?: +getAllOpenOrders(params?: { symbol?: string }): Promise ⋮---- getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- @@ -9732,7 +9789,7 @@ getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- getAccountTrades( params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise + ): Promise ⋮---- setMarginType(params: SetMarginTypeParams): Promise ⋮---- @@ -9748,11 +9805,11 @@ setLeverage(params: SetLeverageParams): Promise ⋮---- setMultiAssetsMode(params: { multiAssetsMargin: MultiAssetsMode; -}): Promise + }): Promise ⋮---- setIsolatedPositionMargin( params: SetIsolatedMarginParams, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -9760,9 +9817,9 @@ setIsolatedPositionMargin( **/ getPositions(params?: Partial): Promise ⋮---- -getPositionsV3(params?: +getPositionsV3(params?: { symbol?: string }): Promise ⋮---- -getADLQuantileEstimation(params?: +getADLQuantileEstimation(params?: { symbol?: string }): Promise ⋮---- getSymbolAdlRisk(params: ⋮---- @@ -9770,11 +9827,11 @@ getSymbolAdlRisk(): Promise; ⋮---- getSymbolAdlRisk(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getPositionMarginChangeHistory( params: GetPositionMarginChangeHistoryParams, -): Promise + ): Promise ⋮---- /** * @@ -9800,11 +9857,11 @@ getAccountInformation(): Promise ⋮---- getAccountCommissionRate(params: { symbol: string; -}): Promise + }): Promise ⋮---- getFuturesAccountConfig(): Promise ⋮---- -getFuturesSymbolConfig(params: +getFuturesSymbolConfig(params: { symbol?: string }): Promise ⋮---- getUserForceOrders(): Promise ⋮---- @@ -9813,7 +9870,7 @@ getUserForceOrders(): Promise */ getNotionalAndLeverageBrackets(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- getMultiAssetsMode(): Promise ⋮---- @@ -9827,7 +9884,7 @@ getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- getApiQuantitativeRulesIndicators(params?: { symbol?: string; -}): Promise + }): Promise ⋮---- /** * Get a download id for futures transaction history (`GET /fapi/v1/income/asyn`). @@ -9837,37 +9894,39 @@ getApiQuantitativeRulesIndicators(params?: { getFuturesTransactionHistoryDownloadId(params: { startTime: number; endTime: number; -}): Promise + }): Promise ⋮---- getFuturesTransactionHistoryDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- getFuturesOrderHistoryDownloadId(params: { startTime: number; endTime: number; -}): Promise + }): Promise ⋮---- getFuturesOrderHistoryDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- getFuturesTradeHistoryDownloadId(params: { startTime: number; endTime: number; -}): Promise + }): Promise ⋮---- getFuturesTradeDownloadLink(params: { downloadId: string; -}): Promise + }): Promise ⋮---- setBNBBurnEnabled(params: { feeBurn: 'true' | 'false'; -}): Promise< + }): Promise<{ code: number; msg: string }> ⋮---- -getBNBBurnStatus(): Promise< +getBNBBurnStatus(): Promise<{ + feeBurn: boolean; + }> ⋮---- -signTradFiPerpsAgreement(): Promise< +signTradFiPerpsAgreement(): Promise<{ code: number; msg: string }> ⋮---- testOrder(params: NewFuturesOrderParams): Promise ⋮---- @@ -9880,27 +9939,27 @@ testOrder(params: NewFuturesOrderParams): Promise ⋮---- submitNewAlgoOrder( params: FuturesNewAlgoOrderParams, -): Promise + ): Promise ⋮---- cancelAlgoOrder( params: FuturesCancelAlgoOrderParams, -): Promise + ): Promise ⋮---- cancelAllAlgoOpenOrders(params: { symbol: string; -}): Promise + }): Promise ⋮---- getAlgoOrder( params: FuturesQueryAlgoOrderParams, -): Promise + ): Promise ⋮---- getOpenAlgoOrders( params?: FuturesQueryOpenAlgoOrdersParams, -): Promise + ): Promise ⋮---- getAllAlgoOrders( params: FuturesQueryAllAlgoOrdersParams, -): Promise + ): Promise ⋮---- /** * @@ -9911,18 +9970,22 @@ getAllAlgoOrders( getAllConvertPairs(params?: { fromAsset?: string; toAsset?: string; -}): Promise + }): Promise ⋮---- submitConvertQuoteRequest( params: FuturesConvertQuoteRequest, -): Promise + ): Promise ⋮---- -acceptConvertQuote(params: +acceptConvertQuote(params: { quoteId: string }): Promise<{ + orderId: string; + createTime: number; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; + }> ⋮---- getConvertOrderStatus(params: { orderId?: string; quoteId?: string; -}): Promise + }): Promise ⋮---- /** * @@ -9932,7 +9995,7 @@ getConvertOrderStatus(params: { ⋮---- getPortfolioMarginProAccountInfo(params: { asset: string; -}): Promise + }): Promise ⋮---- /** * @@ -9948,7 +10011,7 @@ getPortfolioMarginProAccountInfo(params: { getBrokerIfNewFuturesUser( brokerId: string, type: 1 | 2 = 1, -): Promise< + ): Promise<{ brokerId: string; rebateWorking: boolean; ifNewUser: boolean }> ⋮---- /** * @deprecated @@ -9956,7 +10019,7 @@ getBrokerIfNewFuturesUser( setBrokerCustomIdForClient( customerId: string, email: string, -): Promise< + ): Promise<{ customerId: string; email: string }> ⋮---- /** * @deprecated @@ -9966,7 +10029,7 @@ getBrokerClientCustomIds( email: string, page?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -9986,7 +10049,7 @@ getBrokerUserTradeVolume( startTime?: number, endTime?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -9996,7 +10059,7 @@ getBrokerRebateVolume( startTime?: number, endTime?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @deprecated @@ -10006,7 +10069,7 @@ getBrokerTradeDetail( startTime?: number, endTime?: number, limit?: number, -): Promise + ): Promise ⋮---- /** * @@ -10016,7 +10079,7 @@ getBrokerTradeDetail( ⋮---- // USD-M Futures ⋮---- -getFuturesUserDataListenKey(): Promise< +getFuturesUserDataListenKey(): Promise<{ listenKey: string }> ⋮---- keepAliveFuturesUserDataListenKey(): Promise ⋮---- @@ -10033,7 +10096,7 @@ private validateOrderId( | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, -): void + ): void ================ File: src/types/websockets/ws-api-responses.ts @@ -14264,14996 +14327,15463 @@ 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/futures.ts +File: src/types/websockets/ws-api-requests.ts ================ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderType, + FuturesOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; import { BooleanString, - ExchangeFilter, KlineInterval, numberInString, - OrderBookRow, + OrderResponseType, OrderSide, - OrderStatus, OrderTimeInForce, OrderType, - RateLimiter, SelfTradePreventionMode, - SymbolIcebergPartsFilter, - SymbolLotSizeFilter, - SymbolMarketLotSizeFilter, - SymbolMaxIcebergOrdersFilter, - SymbolMaxPositionFilter, - SymbolPriceFilter, -} from './shared'; +} from '../shared'; ⋮---- -export type FuturesContractType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; +/** + * Simple request params with timestamp (required) & recv window (optional) + */ +export type WSAPIRecvWindowTimestamp = { + recvWindow?: number; + timestamp: number; +}; ⋮---- -export interface ContinuousContractKlinesParams { - pair: string; - contractType: FuturesContractType; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; +/** + * + * Authentication request types + * + */ +export interface WSAPISessionLogonRequest { + timestamp: number; } ⋮---- -export interface IndexPriceKlinesParams { - pair: string; - 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 SymbolKlinePaginatedParams { +/** + * + * Market data request types + * + */ +⋮---- +export interface WSAPIOrderBookRequest { symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; limit?: number; + symbolStatus?: string; } ⋮---- -export interface FuturesDataPaginatedParams { +export interface WSAPITradesRecentRequest { 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'; +export interface WSAPITradesHistoricalRequest { + symbol: string; + fromId?: number; 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'; +export interface WSAPIBlockTradesHistoricalRequest { + symbol: string; + fromId: number; 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; +export interface WSAPITradesAggregateRequest { + symbol: string; + fromId?: number; startTime?: number; endTime?: number; + limit?: number; } ⋮---- -export interface GetFuturesAllOrdersParams { - symbol?: string; - orderId?: number; +export interface WSAPIKlinesRequest { + symbol: string; + interval: KlineInterval; startTime?: number; endTime?: number; + timeZone?: string; limit?: number; } ⋮---- -export enum EnumDualSideMode { - HedgeMode = 'true', - OneWayMode = 'false', +export interface WSAPIAvgPriceRequest { + symbol: string; } ⋮---- -export type DualSideMode = `${EnumDualSideMode}`; -⋮---- -export enum EnumMultiAssetMode { - MultiAssetsMode = 'true', - SingleAssetsMode = '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 MultiAssetsMode = `${EnumMultiAssetMode}`; -⋮---- -export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; -⋮---- -export type MarginType = 'ISOLATED' | 'CROSSED'; -⋮---- -export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; -⋮---- -export type FuturesOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; -⋮---- -export type PriceMatchMode = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; -⋮---- -// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. -export interface NewFuturesOrderParams { +export interface WSAPIReferencePriceRequest { symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesOrderType; - timeInForce?: OrderTimeInForce; - quantity?: numberType; - reduceOnly?: BooleanString; - price?: numberType; - newClientOrderId?: string; - stopPrice?: numberType; - closePosition?: BooleanString; - activationPrice?: numberType; - callbackRate?: numberType; - workingType?: WorkingType; - priceProtect?: BooleanString; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: SelfTradePreventionMode; - priceMatch?: PriceMatchMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface ModifyFuturesOrderParams { - orderId?: number; - origClientOrderId?: string; +export interface WSAPIReferencePriceCalculationRequest { symbol: string; - side: OrderSide; - quantity?: numberType; - price?: numberType; - priceMatch?: PriceMatchMode; - modifyId?: number; - reduceOnly?: BooleanString; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; } ⋮---- -export enum EnumPositionMarginChangeType { - AddPositionMargin = 1, - ReducePositionMargin = 0, +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITicker24hrRequest { + symbol?: string; + symbols?: string[]; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; } ⋮---- -export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; -⋮---- -export type IncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'SPECIAL_FUNDING_FEE' - | 'COMMISSION' - | 'INSURANCE_CLEAR'; -⋮---- -export interface CancelMultipleOrdersParams { - symbol: string; - orderIdList?: number[]; - origClientOrderIdList?: string[]; -} -⋮---- -export interface CancelOrdersTimeoutParams { - symbol: string; - countdownTime?: 0 | number; +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerTradingDayRequest { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; } ⋮---- -export interface SetLeverageParams { - symbol: string; - leverage: number; +/** + * 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 interface SetLeverageResult { - leverage: number; - maxNotionalValue: numberInString; - symbol: string; -} +windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' ⋮---- -export interface SetMarginTypeParams { - symbol: string; - marginType: MarginType; +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerPriceRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; } ⋮---- -export interface SetIsolatedMarginParams { - symbol: string; - positionSide?: PositionSide; - amount: number; - type: PositionMarginChangeType; +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerBookRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; } ⋮---- -export interface SetIsolatedMarginResult { - amount: numberInString; - code: 200 | number; - msg: string; - type: 1 | 2; -} +/** + * + * Account request types - Spot + * + */ ⋮---- -export interface GetPositionMarginChangeHistoryParams { +export interface WSAPIAllOrdersRequest { symbol: string; - type?: PositionMarginChangeType; + orderId?: number; startTime?: number; endTime?: number; limit?: 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; +export interface WSAPIAllOrderListsRequest { + fromId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- -export interface IncomeHistory { - symbol?: string; - incomeType: IncomeType; - income: string; - asset: string; - time: number; - info: string; - tranId: number; - tradeId: string; +export interface WSAPIMyTradesRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; } ⋮---- -export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; +export interface WSAPIMyPreventedMatchesRequest { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} ⋮---- -export interface GetForceOrdersParams { - symbol?: string; - autoCloseType?: ForceOrderCloseType; +export interface WSAPIMyAllocationsRequest { + symbol: string; startTime?: number; endTime?: number; + fromAllocationId?: number; limit?: number; + orderId?: number; } ⋮---- -export type ContactType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; +/** + * Trading request types + */ +type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; +type SpotPegOffsetType = 'PRICE_LEVEL'; ⋮---- -export type ContractStatus = - | 'PENDING_TRADING' - | 'TRADING' - | 'PRE_DELIVERING' - | 'DELIVERING' - | 'DELIVERED' - | 'CANCELLED' - | 'PRE_SETTLE' - | 'SETTLING' - | 'CLOSE'; +export interface WSAPINewSpotOrderRequest { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; +} ⋮---- -export interface FuturesSymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - multiplierDecimal: numberInString; +export interface WSAPIOrderTestRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + computeCommissionRates?: boolean; + timestamp: number; + recvWindow?: number; } ⋮---- -export interface FuturesSymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - limit: number; +export interface WSAPIOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FuturesSymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - limit: number; +export interface WSAPIOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FuturesSymbolMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - notional: numberInString; +export interface WSAPIOrderCancelReplaceRequest { + symbol: string; + cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; + cancelOrderId?: number; + cancelOrigClientOrderId?: string; + cancelNewClientOrderId?: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; + recvWindow?: number; + timestamp: 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 WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -/** - * Undocumented. Observed value: `NONE`. - */ -⋮---- -export type FuturesSymbolFilter = - | SymbolPriceFilter - | FuturesSymbolPercentPriceFilter - | SymbolLotSizeFilter - | FuturesSymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | FuturesSymbolMaxOrdersFilter - | FuturesSymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter - | FuturesSymbolPositionRiskControlFilter; -⋮---- -export interface FuturesSymbolExchangeInfo { - symbol: string; - pair: string; - contractType: ContactType; - deliveryDate: number; - onboardDate: number; - status: ContractStatus; - maintMarginPercent: numberInString; - requiredMarginPercent: numberInString; - baseAsset: string; - quoteAsset: string; - marginAsset: string; - pricePrecision: number; - quantityPrecision: number; - baseAssetPrecision: number; - quotePrecision: number; - underlyingType: 'COIN' | 'INDEX'; // No other known values - underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc - settlePlan: number; - triggerProtect: numberInString; - filters: FuturesSymbolFilter[]; - OrderType: OrderType[]; - timeInForce: OrderTimeInForce[]; - liquidationFee: numberInString; - marketTakeBound: numberInString; - contractSize?: number; -} -⋮---- -underlyingType: 'COIN' | 'INDEX'; // No other known values -underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc -⋮---- -export interface FuturesExchangeInfo { - exchangeFilters: ExchangeFilter[]; - rateLimits: RateLimiter[]; - serverTime: number; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any[]; - symbols: FuturesSymbolExchangeInfo[]; - timezone: string; -} -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface FuturesOrderBook { - lastUpdateId: number; - E: number; - T: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; -} -⋮---- -export interface RawFuturesTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface AggregateFuturesTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface MarkPrice { +export interface WSAPIOpenOrdersCancelAllRequest { symbol: string; - markPrice: numberInString; - indexPrice: numberInString; - estimatedSettlePrice: numberInString; - lastFundingRate: numberInString; - interestRate: numberInString; - nextFundingTime: number; - time: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FundingRateHistory { +/** + * Order list request types + */ +export interface WSAPIOrderListPlaceRequest { symbol: string; - fundingRate: numberInString; - fundingTime: number; - markPrice: numberInString; - rateType?: 'Regular' | 'Special'; + 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 FuturesSymbolOrderBookTicker { +export interface WSAPIOrderListPlaceOCORequest { symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; + side: 'BUY' | 'SELL'; + quantity: numberInString; + listClientOrderId?: string; + aboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + aboveClientOrderId?: string; + aboveIcebergQty?: numberInString; + abovePrice?: numberInString; + aboveStopPrice?: numberInString; + aboveTrailingDelta?: number; + aboveTimeInForce?: string; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + belowClientOrderId?: string; + belowIcebergQty?: numberInString; + belowPrice?: numberInString; + belowStopPrice?: numberInString; + belowTrailingDelta?: number; + belowTimeInForce?: string; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface OpenInterest { - openInterest: numberInString; +export interface WSAPIOrderListPlaceOTORequest { symbol: string; - time: number; + 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 HistoricOpenInterest { +export interface WSAPIOrderListPlaceOTOCORequest { symbol: string; - sumOpenInterest: string; - sumOpenInterestValue: string; - CMCCirculatingSupply: 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 PositionModeParams { - dualSidePosition: DualSideMode; -} -⋮---- -export interface ModeChangeResult { - code: 200 | number; - msg: 'success' | string; -} -⋮---- -export interface PositionModeResponse { - dualSidePosition: boolean; -} -⋮---- -export interface MultiAssetModeResponse { - multiAssetsMargin: boolean; +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 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; +export interface WSAPIOrderListPlaceOPOCORequest { symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - origType: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - goodTillDate?: number; + 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 NewOrderError { - code: number; - msg: string; +export interface WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface OrderResult { - avgPrice: numberInString; - clientOrderId: string; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; +export interface WSAPIOrderListCancelRequest { 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; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface ModifyFuturesOrderResult { - orderId: number; +/** + * SOR request types + */ +export interface WSAPISOROrderPlaceRequest { 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; + 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 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; +export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { + computeCommissionRates?: boolean; +}; +⋮---- +/** + * Futures market data request types + */ +⋮---- +export interface WSAPIFuturesOrderBookRequest { symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; + limit?: number; } ⋮---- -export interface CancelAllOpenOrdersResult { - code: 200 | numberInString; - msg: string; +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; } ⋮---- -export interface FuturesAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - marginAvailable: boolean; - updateTime: numberInString; +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; } ⋮---- -export interface FuturesCoinMAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - withdrawAvailable: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - updateTime: number; -} +/** + * Futures trading request types + */ ⋮---- -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 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 FuturesAccountPosition { +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +export interface WSAPIFuturesOrderModifyRequest { 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; + 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; } ⋮---- -export interface FuturesCoinMAccountPosition { +export interface WSAPIFuturesOrderCancelRequest { 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; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: 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 WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FuturesCoinMAccountInformation { - assets: Omit[]; - positions: FuturesCoinMAccountPosition[]; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; +export interface WSAPIFuturesPositionRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FuturesPosition { - entryPrice: numberInString; - marginType: 'isolated' | 'cross'; - isAutoAddMargin: 'false' | 'true'; - isolatedMargin: numberInString; - leverage: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - maxNotionalValue: numberInString; - positionAmt: numberInString; - notional: numberInString; - isolatedWallet: numberInString; - symbol: string; - unRealizedProfit: numberInString; - positionSide: PositionSide; - updateTime: number; +export interface WSAPIFuturesPositionV2Request { + symbol?: string; + recvWindow?: number; + timestamp: 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 WSAPIAccountInformationRequest { + omitZeroBalances?: boolean; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FuturesPositionTrade { - buyer: boolean; - commission: numberInString; - commissionAsset: string; - id: number; - maker: boolean; - orderId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - realizedPnl: numberInString; - side: OrderSide; - positionSide: PositionSide; +export interface WSAPIAccountCommissionWSAPIRequest { symbol: string; - time: number; - pair?: string; - baseQty?: numberInString; - marginAsset?: string; } ⋮---- -export interface ForceOrderResult { - orderId: number; +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api + */ +export interface WSAPINewFuturesAlgoOrderRequest { + algoType: FuturesAlgoOrderType; 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; + positionSide?: PositionSide; + type: FuturesAlgoConditionalOrderTypes; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberInString; + clientAlgoId?: string; + triggerPrice?: numberInString; + closePosition?: BooleanString; + activatePrice?: numberInString; + callbackRate?: numberInString; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: OrderResponseType; + priceMatch?: PriceMatchMode; + selfTradePreventionMode?: SelfTradePreventionMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD + recvWindow?: number; + timestamp: number; } ⋮---- -export interface SymbolLeverageBracket { - bracket: number; - initialLeverage: number; - notionalCap: number; - notionalFloor: number; - maintMarginRatio: number; - cum: number; -} -⋮---- -export interface SymbolLeverageBracketsResult { - symbol: string; - brackets: SymbolLeverageBracket[]; -} -⋮---- -export interface UserCommissionRate { - symbol: string; - makerCommissionRate: numberInString; - takerCommissionRate: numberInString; - rpiCommissionRate?: numberInString; -} +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -export interface FuturesAccountConfig { - feeTier: number; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - dualSidePosition: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId: number; +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order + */ +export interface WSAPIFuturesAlgoOrderCancelRequest { + algoid?: number; + clientalgoid?: string; + recvWindow?: number; + timestamp: number; } + +================ +File: src/types/futures.ts +================ +import { + BooleanString, + ExchangeFilter, + KlineInterval, + numberInString, + OrderBookRow, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SymbolIcebergPartsFilter, + SymbolLotSizeFilter, + SymbolMarketLotSizeFilter, + SymbolMaxIcebergOrdersFilter, + SymbolMaxPositionFilter, + SymbolPriceFilter, +} from './shared'; ⋮---- -export interface SymbolConfig { - symbol: string; - marginType: string; - isAutoAddMargin: string; - leverage: number; - maxNotionalValue: string; -} +export type FuturesContractType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; ⋮---- -export interface UserForceOrder { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; +export interface ContinuousContractKlinesParams { + pair: string; + contractType: FuturesContractType; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface RebateDataOverview { - brokerId: string; - newTraderRebateCommission: numberInString; - oldTraderRebateCommission: numberInString; - totalTradeUser: number; - unit: string; - totalTradeVol: numberInString; - totalRebateVol: numberInString; - time: number; +export interface IndexPriceKlinesParams { + pair: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface SetCancelTimeoutResult { +export interface SymbolKlinePaginatedParams { symbol: string; - countdownTime: numberInString; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface ChangeStats24hr { +export interface FuturesDataPaginatedParams { symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First tradeId - lastId: number; // Last tradeId - count: number; -} -⋮---- -firstId: number; // First tradeId -lastId: number; // Last tradeId -⋮---- -export interface OrderAmendmentDetailPrice { - before: numberInString; - after: numberInString; -} -⋮---- -export interface OrderAmendmentDetailQty { - before: numberInString; - after: numberInString; -} -⋮---- -export interface OrderAmendmentDetail { - price: OrderAmendmentDetailPrice; - origQty: OrderAmendmentDetailQty; - count: number; + contractType?: string; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface OrderAmendment { - amendmentId: number; - symbol: string; +export interface FuturesCoinMTakerBuySellVolumeParams { pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: OrderAmendmentDetail; - modifyId?: number; -} -⋮---- -export interface QuarterlyContractSettlementPrice { - deliveryTime: number; - deliveryPrice: number; + 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 BasisParams { +export interface FuturesCoinMBasisParams { pair: string; contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit: number; + limit?: number; startTime?: number; endTime?: number; } ⋮---- -export interface Basis { - indexPrice: string; - contractType: string; - basisRate: string; - futuresPrice: string; - annualizedBasisRate: string; - basis: string; +export interface FuturesCoinMLongShortAccountRatioParams { pair: string; - timestamp: number; -} -⋮---- -export interface IndexPriceConstituent { - exchange: string; - symbol: string; - price: numberInString; - weight: numberInString; -} -⋮---- -export interface IndexPriceConstituents { - symbol: string; - time: number; - constituents: IndexPriceConstituent[]; -} -⋮---- -export interface InsuranceFundBalance { - symbols: string[]; - assets: { - asset: string; - marginBalance: string; - updateTime: number; - }[]; -} -⋮---- -export interface ModifyOrderParams { - orderId?: number; - origClientOrderId?: string; - symbol: string; - side: 'SELL' | 'BUY'; - quantity: string; - price: string; - priceMatch?: - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; - modifyId?: number; - reduceOnly?: BooleanString; - recvWindow?: number; - timestamp: number; + contractType?: 'PERPETUAL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface GetFuturesOrderModifyHistoryParams { - symbol: string; +export interface GetFuturesAllOrdersParams { + symbol?: string; orderId?: number; - origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- -export interface FuturesTradeHistoryDownloadId { - avgCostTimestampOfLast30d: number; - downloadId: string; +export enum EnumDualSideMode { + HedgeMode = 'true', + OneWayMode = 'false', } ⋮---- -export interface FuturesTransactionDownloadLink { - downloadId: string; - status: 'completed' | 'processing'; - url: string; - expirationTimestamp: number; - isExpired: boolean | null; -} +export type DualSideMode = `${EnumDualSideMode}`; ⋮---- -export interface PortfolioMarginProAccountInfo { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; // This field will be ignored in the response +export enum EnumMultiAssetMode { + MultiAssetsMode = 'true', + SingleAssetsMode = 'false', } ⋮---- -maxWithdrawAmount: string; // This field will be ignored in the response +export type MultiAssetsMode = `${EnumMultiAssetMode}`; ⋮---- -export interface FuturesConvertPair { - fromAsset: string; - toAsset: string; - fromAssetMinAmount: string; - fromAssetMaxAmount: string; - toAssetMinAmount: string; - toAssetMaxAmount: string; -} -⋮---- -export interface FuturesConvertQuoteRequest { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - validTime?: '10s' | '30s' | '1m' | '2m'; -} -⋮---- -export interface FuturesConvertQuote { - quoteId: string; - ratio: string; - inverseRatio: string; - validTimestamp: number; - toAmount: string; - fromAmount: string; -} -⋮---- -export interface FuturesConvertOrderStatus { - orderId: string; - orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - ratio: string; - inverseRatio: string; - createTime: number; -} +export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; ⋮---- -/** - * Algo Order Types (Effective 2025-12-02) - * USDⓈ-M Futures conditional orders migrate to Algo Service - */ +export type MarginType = 'ISOLATED' | 'CROSSED'; ⋮---- -export type FuturesAlgoOrderType = 'CONDITIONAL'; +export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- -export type FuturesAlgoConditionalOrderTypes = - | 'STOP_MARKET' - | 'TAKE_PROFIT_MARKET' +export type FuturesOrderType = + | 'LIMIT' + | 'MARKET' | 'STOP' + | 'STOP_MARKET' | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' | '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 type PriceMatchMode = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; ⋮---- -export interface FuturesNewAlgoOrderParams { - algoType: FuturesAlgoOrderType; +// 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: FuturesAlgoConditionalOrderTypes; + type: FuturesOrderType; timeInForce?: OrderTimeInForce; - quantity?: numberInString; - price?: numberInString; - triggerPrice?: numberInString; - workingType?: WorkingType; - priceMatch?: PriceMatchMode; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberType; + newClientOrderId?: string; + stopPrice?: numberType; closePosition?: BooleanString; + activationPrice?: numberType; + callbackRate?: numberType; + workingType?: WorkingType; priceProtect?: BooleanString; - reduceOnly?: BooleanString; - activatePrice?: numberInString; - callbackRate?: numberInString; - clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ + newOrderRespType?: 'ACK' | 'RESULT'; selfTradePreventionMode?: SelfTradePreventionMode; - goodTillDate?: number; + priceMatch?: PriceMatchMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- -clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -export interface FuturesAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - algoType: FuturesAlgoOrderType; - orderType: FuturesAlgoConditionalOrderTypes; +export interface ModifyFuturesOrderParams { + orderId?: number; + origClientOrderId?: string; 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; + quantity?: numberType; + price?: numberType; + priceMatch?: PriceMatchMode; + modifyId?: number; + reduceOnly?: BooleanString; } ⋮---- -export interface FuturesCancelAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; +export enum EnumPositionMarginChangeType { + AddPositionMargin = 1, + ReducePositionMargin = 0, } ⋮---- -export interface FuturesCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} +export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; ⋮---- -export interface FuturesCancelAllAlgoOpenOrdersResponse { - code: number; - msg: string; -} +export type IncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'SPECIAL_FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR'; ⋮---- -export interface FuturesQueryAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; +export interface CancelMultipleOrdersParams { + symbol: string; + orderIdList?: number[]; + origClientOrderIdList?: string[]; } ⋮---- -export interface FuturesQueryAlgoOrderResponse - extends FuturesAlgoOrderResponse { - actualOrderId: numberInString; - actualPrice: numberInString; - tpTriggerPrice?: numberInString; - tpPrice?: numberInString; - slTriggerPrice?: numberInString; - slPrice?: numberInString; - tpOrderType?: string; +export interface CancelOrdersTimeoutParams { + symbol: string; + countdownTime?: 0 | number; } ⋮---- -export interface FuturesQueryOpenAlgoOrdersParams { - algoType?: FuturesAlgoOrderType; - symbol?: string; - algoId?: number; +export interface SetLeverageParams { + symbol: string; + leverage: number; } ⋮---- -export interface FuturesQueryAllAlgoOrdersParams { +export interface SetLeverageResult { + leverage: number; + maxNotionalValue: numberInString; symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 500; max 1000 } ⋮---- -limit?: number; // Default 500; max 1000 +export interface SetMarginTypeParams { + symbol: string; + marginType: MarginType; +} ⋮---- -export interface SymbolAdlRisk { +export interface SetIsolatedMarginParams { symbol: string; - adlRisk: 'low' | 'medium' | 'high'; - updateTime: number; + positionSide?: PositionSide; + amount: number; + type: PositionMarginChangeType; } ⋮---- -export interface TradingSession { - startTime: number; - endTime: number; - type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; +export interface SetIsolatedMarginResult { + amount: numberInString; + code: 200 | number; + msg: string; + type: 1 | 2; } ⋮---- -export interface MarketSchedule { - sessions: TradingSession[]; +export interface GetPositionMarginChangeHistoryParams { + symbol: string; + type?: PositionMarginChangeType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -export interface TradingSchedule { - updateTime: number; - marketSchedules: { - EQUITY?: MarketSchedule; - COMMODITY?: MarketSchedule; - KR_EQUITY?: MarketSchedule; - HK_EQUITY?: MarketSchedule; - CN_EQUITY?: MarketSchedule; - FX?: MarketSchedule; - }; +/** + * 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 RpiOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; +export interface IncomeHistory { + symbol?: string; + incomeType: IncomeType; + income: string; + asset: string; + time: number; + info: string; + tranId: number; + tradeId: string; } ⋮---- -E: number; // Message output time -T: number; // Transaction time - -================ -File: src/websocket-client.ts -================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { KlineInterval } from './types/shared'; -import { - Exact, - WsAPIOperationResponseMap, - WsAPITopicRequestParamMap, - WsAPIWsKeyTopicMap, - WsOperation, - WsRequestOperationBinance, -} from './types/websockets/ws-api'; -import { - MessageEventLike, - WSClientConfigurableOptions, - WsMarket, - WsTopic, -} from './types/websockets/ws-general'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient'; -import Beautifier from './util/beautifier'; -import { DefaultLogger } from './util/logger'; -import { signMessage } from './util/node-support'; -import { - appendEventIfMissing, - requiresWSAPINewClientOID, - RestClientOptions, - serialiseParams, - validateWSAPINewClientOID, -} from './util/requestUtils'; -import { neverGuard } from './util/typeGuards'; -import { SignAlgorithm, SignEncodeMethod } from './util/webCryptoAPI'; -import { RestClientCache } from './util/websockets/rest-client-cache'; -import { UserDataStreamManager } from './util/websockets/user-data-stream-manager'; -import { - EVENT_TYPES_USER_DATA, - getLegacyWsKeyContext, - getLegacyWsStoreKeyWithContext, - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getPromiseRefForWSAPIRequest, - getRealWsKeyFromDerivedWsKey, - getTestnetWsKey, - getTopicsPerWSKey, - getWsKeyForProductGroup, - getWsUrl, - getWsURLSuffix, - isPrivateWsTopic, - isWSPingFrameAvailable, - isWSPongFrameAvailable, - MiscUserDataConnectionState, - parseEventTypeFromMessage, - parseRawWsMessage, - resolveUserDataMarketForWsKey, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WSAPIWsKey, - WSConnectionCategory, - WsKey, - WsTopicRequest, -} from './util/websockets/websocket-util'; -import { WSConnectedResult } from './util/websockets/WsStore.types'; -⋮---- -type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; +export interface GetForceOrdersParams { + symbol?: string; + autoCloseType?: ForceOrderCloseType; + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -/** If true, will skip auth requirement for WS API connection */ -⋮---- -/** - * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. - * - * When possible, it will subscribe to all requested topics on a single websocket connection. A list of - * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. - * - * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically - * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. - * - * If any connection is reconnected, the WS client will: - * - Emit the "reconnecting" event when the process begins. - * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a - * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed - * while disconnected. - * - * User data streams will use a dedicated connection per stream for increased resilience. - */ -⋮---- -export class WebsocketClient extends BaseWebsocketClient< -⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +export type ContactType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; ⋮---- -/** - * 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 type ContractStatus = + | 'PENDING_TRADING' + | 'TRADING' + | 'PRE_DELIVERING' + | 'DELIVERING' + | 'DELIVERED' + | 'CANCELLED' + | 'PRE_SETTLE' + | 'SETTLING' + | 'CLOSE'; ⋮---- -// fn pointers: +export interface FuturesSymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + multiplierDecimal: numberInString; +} ⋮---- -protected onWsCloseCleanup(wsKey: WsKey): void +export interface FuturesSymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + limit: number; +} ⋮---- -private getUserDataStreamManager(): UserDataStreamManager +export interface FuturesSymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + limit: number; +} ⋮---- -private getRestClientOptions(): RestClientOptions +export interface FuturesSymbolMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + notional: 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. + * 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`. */ -public connectAll(): Promise[] + positionControlSide: string; +} ⋮---- /** - * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if - * you're only working with one product group. + * Undocumented. Observed value: `NONE`. */ -public connectPublic(): Promise[] ⋮---- -/** - * This function serves no purpose in the Binance SDK - */ -public async connectPrivate(): Promise +export type FuturesSymbolFilter = + | SymbolPriceFilter + | FuturesSymbolPercentPriceFilter + | SymbolLotSizeFilter + | FuturesSymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | FuturesSymbolMaxOrdersFilter + | FuturesSymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter + | FuturesSymbolPositionRiskControlFilter; ⋮---- -/** - * 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 FuturesSymbolExchangeInfo { + symbol: string; + pair: string; + contractType: ContactType; + deliveryDate: number; + onboardDate: number; + status: ContractStatus; + maintMarginPercent: numberInString; + requiredMarginPercent: numberInString; + baseAsset: string; + quoteAsset: string; + marginAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + underlyingType: 'COIN' | 'INDEX'; // No other known values + underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc + settlePlan: number; + triggerProtect: numberInString; + filters: FuturesSymbolFilter[]; + OrderType: OrderType[]; + timeInForce: OrderTimeInForce[]; + liquidationFee: numberInString; + marketTakeBound: numberInString; + contractSize?: number; +} ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +underlyingType: 'COIN' | 'INDEX'; // No other known values +underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc ⋮---- -/** - * 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 FuturesExchangeInfo { + exchangeFilters: ExchangeFilter[]; + rateLimits: RateLimiter[]; + serverTime: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any[]; + symbols: FuturesSymbolExchangeInfo[]; + timezone: string; +} ⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) -⋮---- -/** - * - * - * - * 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 +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); +export interface FuturesOrderBook { + lastUpdateId: number; + E: number; + T: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); +export interface RawFuturesTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} ⋮---- -// Some commands don't require authentication. +export interface AggregateFuturesTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; +} ⋮---- -// Only if authOnConnect is enabled (aka using Ed25519 keys) +export interface MarkPrice { + symbol: string; + markPrice: numberInString; + indexPrice: numberInString; + estimatedSettlePrice: numberInString; + lastFundingRate: numberInString; + interestRate: numberInString; + nextFundingTime: number; + time: number; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +export interface FundingRateHistory { + symbol: string; + fundingRate: numberInString; + fundingTime: number; + markPrice: numberInString; + rateType?: 'Regular' | 'Special'; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +export interface FuturesSymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; +} ⋮---- -/** - * 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 OpenInterest { + openInterest: numberInString; + symbol: string; + time: number; +} ⋮---- -// Sign, if needed +export interface HistoricOpenInterest { + symbol: string; + sumOpenInterest: string; + sumOpenInterestValue: string; + CMCCirculatingSupply: string; + timestamp: number; +} ⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +export interface PositionModeParams { + dualSidePosition: DualSideMode; +} ⋮---- -// Enrich returned promise with request context for easier debugging +export interface ModeChangeResult { + code: 200 | number; + msg: 'success' | string; +} ⋮---- -// throw e; +export interface PositionModeResponse { + dualSidePosition: boolean; +} ⋮---- -// this.logger.trace( -// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, -// ); +export interface MultiAssetModeResponse { + multiAssetsMargin: boolean; +} ⋮---- -// Send event. +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; +} ⋮---- -// Return deferred promise, so caller can await this call +export interface NewOrderError { + code: number; + msg: string; +} ⋮---- -/** - * - * - * Internal methods - not intended for public use - * - * - */ +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; +} ⋮---- -/** - * @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 } - > - > { - try { - // 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. - const timestamp = Date.now() + (this.getTimeOffsetMs() || 0); -⋮---- -// Note: Only Ed25519 keys are supported for this feature. -// RSA & HMAC keys will automatically sign each individual request instead. +export interface ModifyFuturesOrderResult { + orderId: number; + symbol: string; + pair: string; + status: OrderStatus; + clientOrderId: string; + price: numberInString; + avgPrice: numberInString; + origQty: numberInString; + executedQty: numberInString; + cumQty: numberInString; + cumBase: numberInString; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + reduceOnly: boolean; + closePosition: boolean; + side: OrderSide; + positionSide: PositionSide; + stopPrice: numberInString; + workingType: WorkingType; + priceProtect: boolean; + origType: FuturesOrderType; + updateTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + modifyId?: number; +} ⋮---- -// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. +export interface CancelFuturesOrderResult { + clientOrderId: string; + cumQty: numberInString; + cumQuote: numberInString; + executedQty: numberInString; + orderId: number; + origQty: numberInString; + origType: FuturesOrderType; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; +} ⋮---- -// 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. +export interface CancelAllOpenOrdersResult { + code: 200 | numberInString; + msg: string; +} ⋮---- -// Note: You still have to specify the timestamp parameter for SIGNED requests. +export interface FuturesAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + marginAvailable: boolean; + updateTime: numberInString; +} ⋮---- -protected sendPingEvent(wsKey: WsKey) +export interface FuturesCoinMAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + withdrawAvailable: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + updateTime: number; +} ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +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; +} ⋮---- -// 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 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; +} ⋮---- -protected sendPongEvent(wsKey: WsKey) +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; +} ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +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[]; +} ⋮---- -// 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 FuturesCoinMAccountInformation { + assets: Omit[]; + positions: FuturesCoinMAccountPosition[]; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; +} ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface FuturesPosition { + entryPrice: numberInString; + marginType: 'isolated' | 'cross'; + isAutoAddMargin: 'false' | 'true'; + isolatedMargin: numberInString; + leverage: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + maxNotionalValue: numberInString; + positionAmt: numberInString; + notional: numberInString; + isolatedWallet: numberInString; + symbol: string; + unRealizedProfit: numberInString; + positionSide: PositionSide; + updateTime: number; +} ⋮---- -/** - * @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>[]> +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; +} ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +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; +} ⋮---- -// Cache midflight subs on the req ID -// Enrich response with subs for that req ID +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; +} ⋮---- -protected getPrivateWSKeys(): WsKey[] +export interface SymbolLeverageBracket { + bracket: number; + initialLeverage: number; + notionalCap: number; + notionalFloor: number; + maintMarginRatio: number; + cum: number; +} ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +export interface SymbolLeverageBracketsResult { + symbol: string; + brackets: SymbolLeverageBracket[]; +} ⋮---- -/** - * Determines if a topic is for a private channel, using a hardcoded list of strings - */ -protected isPrivateTopicRequest(request: WsTopicRequest): boolean +export interface UserCommissionRate { + symbol: string; + makerCommissionRate: numberInString; + takerCommissionRate: numberInString; + rpiCommissionRate?: numberInString; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPing(msg: any): boolean +export interface FuturesAccountConfig { + feeTier: number; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + dualSidePosition: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId: number; +} ⋮---- -// For binance, all ping/pong events are frame events +export interface SymbolConfig { + symbol: string; + marginType: string; + isAutoAddMargin: string; + leverage: number; + maxNotionalValue: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPong(msg: any): boolean +export interface UserForceOrder { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; +} ⋮---- -// For binance, all ping/pong events are frame events +export interface RebateDataOverview { + brokerId: string; + newTraderRebateCommission: numberInString; + oldTraderRebateCommission: numberInString; + totalTradeUser: number; + unit: string; + totalTradeVol: numberInString; + totalRebateVol: numberInString; + time: number; +} ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] +export interface SetCancelTimeoutResult { + symbol: string; + countdownTime: numberInString; +} ⋮---- -// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); +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; +} ⋮---- -/** - * - * Extract event from JSON - * - */ +firstId: number; // First tradeId +lastId: number; // Last tradeId ⋮---- -/** - * - * Minor data normalisation & preparation - * - */ +export interface OrderAmendmentDetailPrice { + before: numberInString; + after: numberInString; +} ⋮---- -// ws consumers: { data: ... } -// ws api consumers (user data): { event: ... } -// other responses: { ... } +export interface OrderAmendmentDetailQty { + before: numberInString; + after: numberInString; +} ⋮---- -// First try, the child node +export interface OrderAmendmentDetail { + price: OrderAmendmentDetailPrice; + origQty: OrderAmendmentDetailQty; + count: number; +} ⋮---- -// Second try, the parent +export interface OrderAmendment { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: OrderAmendmentDetail; + modifyId?: number; +} ⋮---- -// Some events don't include the topic (event name) -// This tries to extract and append it, using available context +export interface QuarterlyContractSettlementPrice { + deliveryTime: number; + deliveryPrice: number; +} ⋮---- -// This attaches `wsMarket` and `streamName` to incoming events -// If the event is an array, it's attached to each element in the array +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; +} ⋮---- -/** - * - * - * Main parsing logic below: - * - * - */ +export interface Basis { + indexPrice: string; + contractType: string; + basisRate: string; + futuresPrice: string; + annualizedBasisRate: string; + basis: string; + pair: string; + timestamp: number; +} ⋮---- -// parsed: JSON.stringify(parsed, null, 2), +export interface IndexPriceConstituent { + exchange: string; + symbol: string; + price: numberInString; + weight: numberInString; +} ⋮---- -// WS API response +export interface IndexPriceConstituents { + symbol: string; + time: number; + constituents: IndexPriceConstituent[]; +} ⋮---- -/** - * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): - * - * { - * result: null, - * id: 1, - * }; - * - * Currently there's no simple way to tell this apart from an actual WS API response with - * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, - * but that will not affect usage. - * - * Unrelated, example wsapi error for reference: - * - { - id: 1, - status: 400, - error: { - code: -1021, - msg: "Timestamp for this request was 1000ms ahead of the server's time." - }, - rateLimits: [ - { - rateLimitType: 'REQUEST_WEIGHT', - interval: 'MINUTE', - intervalNum: 1, - limit: 6000, - count: 4 - } - ], - wsKey: 'mainWSAPI', - isWSAPIResponse: true - } - */ -⋮---- -// This is the counterpart to getPromiseRefForWSAPIRequest -⋮---- -// WS API Exception -⋮---- -// authenticated +export interface InsuranceFundBalance { + symbols: string[]; + assets: { + asset: string; + marginBalance: string; + updateTime: number; + }[]; +} ⋮---- -// Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests +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; +} ⋮---- -// WS API Success +export interface GetFuturesOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -// Handle incoming event that listen key expired +export interface FuturesTradeHistoryDownloadId { + avgCostTimestampOfLast30d: number; + downloadId: string; +} ⋮---- -// handle this how? +export interface FuturesTransactionDownloadLink { + downloadId: string; + status: 'completed' | 'processing'; + url: string; + expirationTimestamp: number; + isExpired: boolean | null; +} ⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn -// Automatically leads to triggerCustomReconnectionWorkflow() to handle fresh user data respawn +export interface PortfolioMarginProAccountInfo { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; // This field will be ignored in the response +} ⋮---- -// Suffix all events for the beautifier, if market is options -// Options has some conflicting keys with different intentions, so will be suffixed +maxWithdrawAmount: string; // This field will be ignored in the response ⋮---- -// emit an additional event for user data messages +export interface FuturesConvertPair { + fromAsset: string; + toAsset: string; + fromAssetMinAmount: string; + fromAssetMaxAmount: string; + toAssetMinAmount: string; + toAssetMaxAmount: string; +} ⋮---- -// Messages for a subscribed topic all include the "topic" property +export interface FuturesConvertQuoteRequest { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + validTime?: '10s' | '30s' | '1m' | '2m'; +} ⋮---- -// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property +export interface FuturesConvertQuote { + quoteId: string; + ratio: string; + inverseRatio: string; + validTimestamp: number; + toAmount: string; + fromAmount: string; +} ⋮---- -// Failed request +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; +} ⋮---- -// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) +/** + * Algo Order Types (Effective 2025-12-02) + * USDⓈ-M Futures conditional orders migrate to Algo Service + */ ⋮---- -// Request/reply pattern for authentication success +export type FuturesAlgoOrderType = 'CONDITIONAL'; ⋮---- -// In case of catastrophic failure, fallback to noisy emit update +export type FuturesAlgoConditionalOrderTypes = + | 'STOP_MARKET' + | 'TAKE_PROFIT_MARKET' + | 'STOP' + | 'TAKE_PROFIT' + | 'TRAILING_STOP_MARKET'; ⋮---- /** - * - * - * - * - * - * User Data Streams - * - * - * - * - * - */ + * 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'; ⋮---- -/** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ +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; +} ⋮---- -/** - * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. - * Supports spot, margin & isolated margin listen keys. - */ -public async subscribeSpotUserDataStreamWithListenKey( - wsKey: WsKey, - listenKey: string, - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ ⋮---- -/** - * Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeSpotUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +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; +} ⋮---- -public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise +export interface FuturesCancelAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -public async fetchMarginListenToken(params?: { - symbol?: string; - isIsolated?: boolean; - validity?: number; -}): Promise< +export interface FuturesCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} ⋮---- -/** - * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeCrossMarginUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface FuturesCancelAllAlgoOpenOrdersResponse { + code: number; + msg: string; +} ⋮---- -public unsubscribeCrossMarginUserDataStream( - wsKey: WsKey = 'main', -): Promise +export interface FuturesQueryAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface FuturesQueryAlgoOrderResponse + extends FuturesAlgoOrderResponse { + actualOrderId: numberInString; + actualPrice: numberInString; + tpTriggerPrice?: numberInString; + tpPrice?: numberInString; + slTriggerPrice?: numberInString; + slPrice?: numberInString; + tpOrderType?: string; +} ⋮---- -public unsubscribeIsolatedMarginUserDataStream( - symbol: string, - wsKey: WsKey = 'main', -): Promise +export interface FuturesQueryOpenAlgoOrdersParams { + algoType?: FuturesAlgoOrderType; + symbol?: string; + algoId?: number; +} ⋮---- -/** - * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeMarginRiskUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface FuturesQueryAllAlgoOrdersParams { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 500; max 1000 +} ⋮---- -public unsubscribeMarginRiskUserDataStream( - wsKey: WsKey = 'main', -): Promise +limit?: number; // Default 500; max 1000 +⋮---- +export interface SymbolAdlRisk { + symbol: string; + adlRisk: 'low' | 'medium' | 'high'; + updateTime: number; +} +⋮---- +export interface TradingSession { + startTime: number; + endTime: number; + type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; +} +⋮---- +export interface MarketSchedule { + sessions: TradingSession[]; +} +⋮---- +export interface TradingSchedule { + updateTime: number; + marketSchedules: { + EQUITY?: MarketSchedule; + COMMODITY?: MarketSchedule; + KR_EQUITY?: MarketSchedule; + HK_EQUITY?: MarketSchedule; + CN_EQUITY?: MarketSchedule; + FX?: MarketSchedule; + }; +} +⋮---- +export interface RpiOrderBook { + lastUpdateId: number; + E: number; // Message output time + T: number; // Transaction time + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} +⋮---- +E: number; // Message output time +T: number; // Transaction time + +================ +File: src/websocket-client.ts +================ +import WebSocket from 'isomorphic-ws'; +⋮---- +import { KlineInterval } from './types/shared'; +import { + Exact, + WsAPIOperationResponseMap, + WsAPITopicRequestParamMap, + WsAPIWsKeyTopicMap, + WsOperation, + WsRequestOperationBinance, +} from './types/websockets/ws-api'; +import { + MessageEventLike, + WSClientConfigurableOptions, + WsMarket, + WsTopic, +} from './types/websockets/ws-general'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient'; +import Beautifier from './util/beautifier'; +import { DefaultLogger } from './util/logger'; +import { signMessage } from './util/node-support'; +import { + appendEventIfMissing, + requiresWSAPINewClientOID, + RestClientOptions, + serialiseParams, + validateWSAPINewClientOID, +} from './util/requestUtils'; +import { neverGuard } from './util/typeGuards'; +import { SignAlgorithm, SignEncodeMethod } from './util/webCryptoAPI'; +import { RestClientCache } from './util/websockets/rest-client-cache'; +import { UserDataStreamManager } from './util/websockets/user-data-stream-manager'; +import { + EVENT_TYPES_USER_DATA, + getLegacyWsKeyContext, + getLegacyWsStoreKeyWithContext, + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getPromiseRefForWSAPIRequest, + getRealWsKeyFromDerivedWsKey, + getTestnetWsKey, + getTopicsPerWSKey, + getWsKeyForProductGroup, + getWsUrl, + getWsURLSuffix, + isPrivateWsTopic, + isWSPingFrameAvailable, + isWSPongFrameAvailable, + MiscUserDataConnectionState, + parseEventTypeFromMessage, + parseRawWsMessage, + resolveUserDataMarketForWsKey, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WSAPIWsKey, + WSConnectionCategory, + WsKey, + WsTopicRequest, +} from './util/websockets/websocket-util'; +import { WSConnectedResult } from './util/websockets/WsStore.types'; +⋮---- +type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +⋮---- +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; +} +⋮---- +/** If true, will skip auth requirement for WS API connection */ ⋮---- /** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ + * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. + * + * When possible, it will subscribe to all requested topics on a single websocket connection. A list of + * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. + * + * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically + * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. + * + * If any connection is reconnected, the WS client will: + * - Emit the "reconnecting" event when the process begins. + * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a + * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed + * while disconnected. + * + * User data streams will use a dedicated connection per stream for increased resilience. + */ +⋮---- +export class WebsocketClient extends BaseWebsocketClient< +⋮---- +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- /** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribeUsdFuturesUserDataStream( - userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise + * 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 + */ ⋮---- -userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate +// fn pointers: ⋮---- -// Prevent 'usdm' from being used unintentionally, since this has to be routed via the private endpoints. +protected onWsCloseCleanup(wsKey: WsKey): void ⋮---- -public unsubscribeUsdFuturesUserDataStream( - wsKey: WsKey = WS_KEY_MAP.usdmPrivate, -): Promise +private getUserDataStreamManager(): UserDataStreamManager +⋮---- +private getRestClientOptions(): RestClientOptions ⋮---- /** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * Request connection of all dependent (public & WS API) websockets in prod, instead of waiting + * for automatic connection by SDK. * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + * 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 async subscribeCoinFuturesUserDataStream( - wsKey: WsKey = 'coinm', // coinm | coinmTestnet - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +public connectAll(): Promise[] ⋮---- -wsKey: WsKey = 'coinm', // coinm | coinmTestnet +/** + * 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[] ⋮---- -public unsubscribeCoinFuturesUserDataStream( - wsKey: WsKey = 'coinm', -): Promise +/** + * This function serves no purpose in the Binance SDK + */ +public async connectPrivate(): Promise ⋮---- /** - * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * Ensures the WS API connection is active and ready. * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + * 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 async subscribePortfolioMarginUserDataStream( - wsKey: WsKey = 'portfolioMarginUserData', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise ⋮---- -public unsubscribePortfolioMarginUserDataStream( - wsKey: WsKey = 'portfolioMarginUserData', -): Promise +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- /** - * Close an active, dedicated, user data stream connection. + * Request subscription to one or more topics. Pass topics as either an array of strings, + * or array of objects (if the topic has parameters). * - * @param wsKey - the connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures. - * @param wsMarket - the product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)). - */ -public async closeUserDataStream( - wsKey: WsKey, - wsMarket: WsMarket, - symbol?: string, -): Promise -⋮---- -// built around the assumption in how per-connection listen key wskeys are created -// isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main -// coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm -⋮---- -protected isCustomReconnectionNeeded(wsKey: string): boolean -⋮---- -protected async triggerCustomReconnectionWorkflow( - legacyWsKey: string, -): Promise -⋮---- -private async respawnUserDataStream( + * 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, - market: WsMarket, - context: { - symbol?: string; - isTestnet?: boolean; - respawnAttempt?: number; - } = {}, -): Promise -⋮---- -// Handle corner case where wsKey is still the derived key for some reason... -⋮---- -// 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 -⋮---- -// Prevent simultaneous timers in same scope -⋮---- -// Execute reconnection workflow after short delay + ): Promise ⋮---- /** - * Subscribe to the European Options user data stream - listen key is automatically generated. + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. * - * Not supported at this time. Please get in touch if you need this. + * - 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 async subscribeEuropeanOptionsUserData( -// wsKey: WsKey = 'eoptions', -// forceNewConnection?: boolean, -// isReconnecting?: boolean, -// ): Promise { -// try { -// const { listenKey } = await this.restClientCache -// .getEuropeanOptionsClient( -// this.getRestClientOptions(), -// this.options.requestOptions, -// ) -// .getUserDataListenKey(); -⋮---- -// const market: WsMarket = 'options'; -⋮---- -// return this.subscribeGeneralUserDataStreamWithListenKey( -// wsKey, -// market, -// listenKey, -// forceNewConnection, -// isReconnecting, -// ); -// } catch (e) { -// this.logger.error('Failed to connect to Options user data', { -// ...WS_LOGGER_CATEGORY, -// error: e, -// }); -// this.emit('exception', { -// functionRef: 'subscribePortfolioMarginUserDataStream()', -// wsKey, -// forceNewConnection, -// isReconnecting, -// error: e?.stack || e, -// }); -// } -// } +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 * - * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. - * + * https://github.com/tiagosiebler/awesome-crypto-examples/wiki/REST-API-vs-WebSockets-vs-WebSocket-API * * * */ ⋮---- /** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ -⋮---- -/** - * Advanced: Subscribe to a universal market websocket stream + * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. * - * This is NOT recommended unless you're very confident with what you're doing. + * 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 */ -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', -): Promise +⋮---- +// 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 ⋮---- /** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): 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'); ⋮---- /** - * Subscribe to trades for a symbol in a market category - * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning - */ -public subscribeTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise + * 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 ⋮---- /** - * Subscribe to block trades for a symbol in spot markets. + * + * + * Internal methods - not intended for public use + * + * */ -public subscribeBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, -): 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. + * @returns The WS URL to connect to for this WS key */ -public subscribeCoinIndexPrice( - symbol: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, -): Promise +async getWsUrl( + wsKey: WsKey, + connectionType: 'public' | 'market' | 'private' = 'market', + ): Promise ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, + ): Promise +⋮---- +// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); ⋮---- /** - * Subscribe to mark price for a symbol in a market category + * 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. */ -public subscribeMarkPrice( - symbol: string, - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, -): Promise +private async signWSAPIRequest( + requestEvent: WsRequestOperationBinance, + requestFlags?: WSAPIRequestFlags, + ): Promise> ⋮---- /** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, -): 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. + */ ⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise< + WsRequestOperationBinance< + string, + { apiKey: string; signature: string; timestamp: 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', - wsKeyOverride?: WsKey, -): Promise +// Note: Only Ed25519 keys are supported for this feature. +// RSA & HMAC keys will automatically sign each individual request instead. ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, -): Promise +// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, -): Promise +// 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. ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +// Note: You still have to specify the timestamp parameter for SIGNED requests. ⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +protected sendPingEvent(wsKey: WsKey) ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -/** - * Subscribe to Alpha Trading WebSocket Market Data streams. - * Base URL: wss://nbstream.binance.com/w3w/wsa/stream - */ -public subscribeAlpha(topics: string | string[]): 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) ⋮---- -/** - * Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24) - */ -public subscribeAlphaAllTokensTicker24(): Promise +protected sendPongEvent(wsKey: WsKey) ⋮---- -/** - * Subscribe to Alpha aggregate trades for a symbol - * @param symbol e.g. ALPHA_474USDT - */ -public subscribeAlphaAggTrade(symbol: string): Promise +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -/** - * Subscribe to Alpha full depth for a symbol - * @param symbol e.g. ALPHA_474USDT - * @param intervalMs 0, 100, or 500 - */ -public subscribeAlphaFulldepth( - symbol: string, - intervalMs: 0 | 100 | 500 = 500, -): Promise +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -/** - * Subscribe to Alpha klines for a contract - * @param contractAddress Contract address - * @param chainId Chain ID (e.g. CT_501, 56) - * @param interval 1s, 1m, 5m, 15m, 1h, 4h, 1d - */ -public subscribeAlphaKline( - contractAddress: string, - chainId: string, - interval: '1s' | '1m' | '5m' | '15m' | '1h' | '4h' | '1d', -): Promise +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** - * Subscribe to 24hr ticker in any market. + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +protected async getWsRequestEvents( + wsKey: WsKey, + operation: WsOperation, + requests: WsTopicRequest[], + ): 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', - wsKeyOverride?: WsKey, -): Promise +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +// Cache midflight subs on the req ID +// Enrich response with subs for that req ID ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +protected getPrivateWSKeys(): WsKey[] ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** - * Subscribe to best bid/ask for all symbols in spot markets. + * Determines if a topic is for a private channel, using a hardcoded list of strings */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- -/** - * Subscribe to partial book depths (snapshots). - * - * Note: - * - spot only supports 1000ms or 100ms for updateMs - * - futures only support 100, 250 or 500ms for updateMs - */ -public subscribePartialBookDepths( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 100 | 250 | 500 | 1000, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPing(msg: any): boolean ⋮---- -/** - * Subscribe to orderbook depth updates to locally manage an order book. - * - * Note that the updatems parameter depends on which market you're trading - * - * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream - * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams - */ -public subscribeDiffBookDepth( - symbol: string, - updateMs: 100 | 250 | 500 | 1000 = 100, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +// For binance, all ping/pong events are frame events ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPong(msg: any): boolean ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +// For binance, all ping/pong events are frame events ⋮---- /** - * Subscribe to aggregate trades for a symbol in spot markets. + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ -public subscribeSpotAggregateTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, + ): EmittableEvent[] ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); ⋮---- /** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise + * + * Extract event from JSON + * + */ ⋮---- /** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, -): Promise + * + * Minor data normalisation & preparation + * + */ ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +// ws consumers: { data: ... } +// ws api consumers (user data): { event: ... } +// other responses: { ... } ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - wsKeyOverride?: WsKey, -): Promise +// First try, the child node ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +// Second try, the parent ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise +// Some events don't include the topic (event name) +// This tries to extract and append it, using available context ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +// This attaches `wsMarket` and `streamName` to incoming events +// If the event is an array, it's attached to each element in the array ⋮---- /** - * Subscribe to top bid/ask levels for symbol in spot markets. - */ -public subscribeSpotPartialBookDepth( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 1000 | 100 = 1000, - wsKeyOverride?: WsKey, -): Promise + * + * + * Main parsing logic below: + * + * + */ ⋮---- -/** - * 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'; +// parsed: JSON.stringify(parsed, null, 2), ⋮---- -/** - * Simple request params with timestamp (required) & recv window (optional) - */ -export type WSAPIRecvWindowTimestamp = { - recvWindow?: number; - timestamp: number; -}; +// WS API response ⋮---- /** - * - * Authentication request types - * - */ -export interface WSAPISessionLogonRequest { - timestamp: number; -} + * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): + * + * { + * result: null, + * id: 1, + * }; + * + * Currently there's no simple way to tell this apart from an actual WS API response with + * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, + * but that will not affect usage. + * + * Unrelated, example wsapi error for reference: + * + { + id: 1, + status: 400, + error: { + code: -1021, + msg: "Timestamp for this request was 1000ms ahead of the server's time." + }, + rateLimits: [ + { + rateLimitType: 'REQUEST_WEIGHT', + interval: 'MINUTE', + intervalNum: 1, + limit: 6000, + count: 4 + } + ], + wsKey: 'mainWSAPI', + isWSAPIResponse: true + } + */ ⋮---- -/** - * - * General request types - * - */ -export interface WSAPIExchangeInfoRequest { - symbol?: string; - symbols?: string[]; - permissions?: string[]; - showPermissionSets?: boolean; - symbolStatus?: string; -} +// This is the counterpart to getPromiseRefForWSAPIRequest ⋮---- -/** - * - * Market data request types - * - */ +// WS API Exception ⋮---- -export interface WSAPIOrderBookRequest { - symbol: string; - limit?: number; - symbolStatus?: string; -} +// authenticated ⋮---- -export interface WSAPITradesRecentRequest { - symbol: string; - limit?: number; -} +// Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests ⋮---- -export interface WSAPITradesHistoricalRequest { - symbol: string; - fromId?: number; - limit?: number; -} +// WS API Success ⋮---- -export interface WSAPIBlockTradesHistoricalRequest { - symbol: string; - fromId: number; - limit?: number; -} +// Handle incoming event that listen key expired ⋮---- -export interface WSAPITradesAggregateRequest { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +// handle this how? ⋮---- -export interface WSAPIKlinesRequest { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn +// Automatically leads to triggerCustomReconnectionWorkflow() to handle fresh user data respawn ⋮---- -export interface WSAPIAvgPriceRequest { - symbol: string; -} +// Suffix all events for the beautifier, if market is options +// Options has some conflicting keys with different intentions, so will be suffixed ⋮---- -/** - * 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'; -} +// emit an additional event for user data messages ⋮---- -export interface WSAPIReferencePriceRequest { - symbol: string; -} +// Messages for a subscribed topic all include the "topic" property ⋮---- -export interface WSAPIReferencePriceCalculationRequest { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; -} +// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITicker24hrRequest { - symbol?: string; - symbols?: string[]; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} +// Failed request ⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerTradingDayRequest { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} +// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- -/** - * 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; -} +// Request/reply pattern for authentication success ⋮---- -windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' +// In case of catastrophic failure, fallback to noisy emit update ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerPriceRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} + * + * + * + * + * + * User Data Streams + * + * + * + * + * + */ ⋮---- /** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerBookRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- + **/ ⋮---- /** - * - * Account request types - Spot - * - */ + * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. + * Supports spot, margin & isolated margin listen keys. + */ +public async subscribeSpotUserDataStreamWithListenKey( + wsKey: WsKey, + listenKey: string, + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -export interface WSAPIAllOrdersRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeSpotUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -export interface WSAPIAllOrderListsRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise ⋮---- -export interface WSAPIMyTradesRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} +public async fetchMarginListenToken(params?: { + symbol?: string; + isIsolated?: boolean; + validity?: number; + }): Promise<{ + token: string; + expirationTime: number; + }> ⋮---- -export interface WSAPIMyPreventedMatchesRequest { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} +/** + * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeCrossMarginUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -export interface WSAPIMyAllocationsRequest { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} +public unsubscribeCrossMarginUserDataStream( + wsKey: WsKey = 'main', + ): Promise ⋮---- /** - * Trading request types - */ -type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; -type SpotPegOffsetType = 'PRICE_LEVEL'; + * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -export interface WSAPINewSpotOrderRequest { - symbol: string; - side: OrderSide; - type: OrderType; - timeInForce?: OrderTimeInForce; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; -} +public unsubscribeIsolatedMarginUserDataStream( + symbol: string, + wsKey: WsKey = 'main', + ): Promise ⋮---- -export interface WSAPIOrderTestRequest { - symbol: string; - side: 'BUY' | 'SELL'; - type: string; - timeInForce?: string; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - computeCommissionRates?: boolean; - timestamp: number; - recvWindow?: number; -} +/** + * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) + */ +public async subscribeMarginRiskUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -export interface WSAPIOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +public unsubscribeMarginRiskUserDataStream( + wsKey: WsKey = 'main', + ): Promise ⋮---- -export interface WSAPIOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - recvWindow?: number; - timestamp: number; -} +/** + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- -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; -} +/** + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribeUsdFuturesUserDataStream( + userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -export interface WSAPIOrderAmendKeepPriorityRequest { - symbol: string; - orderId?: number | string; - origClientOrderId?: string; - newClientOrderId?: string; - newQty?: string; - recvWindow?: number; - timestamp: number; -} +userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate ⋮---- -export interface WSAPIOpenOrdersStatusRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} +// Prevent 'usdm' from being used unintentionally, since this has to be routed via the private endpoints. ⋮---- -export interface WSAPIOpenOrdersCancelAllRequest { - symbol: string; - recvWindow?: number; - timestamp: number; -} +public unsubscribeUsdFuturesUserDataStream( + wsKey: WsKey = WS_KEY_MAP.usdmPrivate, + ): Promise ⋮---- /** - * Order list request types - */ -export interface WSAPIOrderListPlaceRequest { - symbol: string; - side: 'BUY' | 'SELL'; - price: numberInString; - quantity: numberInString; - listClientOrderId?: string; - limitClientOrderId?: string; - limitIcebergQty?: numberInString; - limitStrategyId?: number; - limitStrategyType?: number; - stopPrice?: numberInString; - trailingDelta?: number; - stopClientOrderId?: string; - stopLimitPrice?: numberInString; - stopLimitTimeInForce?: string; - stopIcebergQty?: numberInString; - stopStrategyId?: number; - stopStrategyType?: number; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -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; -} + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribeCoinFuturesUserDataStream( + wsKey: WsKey = 'coinm', // coinm | coinmTestnet + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -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; -} +wsKey: WsKey = 'coinm', // coinm | coinmTestnet ⋮---- -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; -} +public unsubscribeCoinFuturesUserDataStream( + wsKey: WsKey = 'coinm', + ): Promise ⋮---- -export interface WSAPIOrderListPlaceOPORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - 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; -} +/** + * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribePortfolioMarginUserDataStream( + wsKey: WsKey = 'portfolioMarginUserData', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, + ): Promise ⋮---- -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; -} +public unsubscribePortfolioMarginUserDataStream( + wsKey: WsKey = 'portfolioMarginUserData', + ): Promise ⋮---- -export interface WSAPIOrderListStatusRequest { - origClientOrderId?: string; - orderListId?: number; - recvWindow?: number; - timestamp: number; -} +/** + * Close an active, dedicated, user data stream connection. + * + * @param wsKey - the connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures. + * @param wsMarket - the product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)). + */ +public async closeUserDataStream( + wsKey: WsKey, + wsMarket: WsMarket, + symbol?: string, + ): Promise ⋮---- -export interface WSAPIOrderListCancelRequest { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +// built around the assumption in how per-connection listen key wskeys are created +// isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main +// coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm ⋮---- -/** - * 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; -} +protected isCustomReconnectionNeeded(wsKey: string): boolean ⋮---- -export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { - computeCommissionRates?: boolean; -}; +protected async triggerCustomReconnectionWorkflow( + legacyWsKey: string, + ): Promise ⋮---- -/** - * Futures market data request types - */ +private async respawnUserDataStream( + wsKey: WsKey, + market: WsMarket, + context: { + symbol?: string; + isTestnet?: boolean; + respawnAttempt?: number; + } = {}, + ): Promise ⋮---- -export interface WSAPIFuturesOrderBookRequest { - symbol: string; - limit?: number; -} +// Handle corner case where wsKey is still the derived key for some reason... ⋮---- -export interface WSAPIFuturesTickerPriceRequest { - symbol?: string; -} +// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key ⋮---- -export interface WSAPIFuturesTickerBookRequest { - symbol?: string; -} +// Prevent simultaneous timers in same scope ⋮---- -/** - * Futures trading request types - */ +// Execute reconnection workflow after short delay ⋮---- -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 the European Options user data stream - listen key is automatically generated. + * + * Not supported at this time. Please get in touch if you need this. + */ +// public async subscribeEuropeanOptionsUserData( +// wsKey: WsKey = 'eoptions', +// forceNewConnection?: boolean, +// isReconnecting?: boolean, +// ): Promise { +// try { +// const { listenKey } = await this.restClientCache +// .getEuropeanOptionsClient( +// this.getRestClientOptions(), +// this.options.requestOptions, +// ) +// .getUserDataListenKey(); ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +// const market: WsMarket = 'options'; ⋮---- -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; -} +// return this.subscribeGeneralUserDataStreamWithListenKey( +// wsKey, +// market, +// listenKey, +// forceNewConnection, +// isReconnecting, +// ); +// } catch (e) { +// this.logger.error('Failed to connect to Options user data', { +// ...WS_LOGGER_CATEGORY, +// error: e, +// }); +// this.emit('exception', { +// functionRef: 'subscribePortfolioMarginUserDataStream()', +// wsKey, +// forceNewConnection, +// isReconnecting, +// error: e?.stack || e, +// }); +// } +// } ⋮---- -export interface WSAPIFuturesOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +/** + * + * + * + * + * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. + * + * + * + * + */ ⋮---- -export interface WSAPIFuturesOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} +/** + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- + **/ ⋮---- -export interface WSAPIFuturesPositionRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} +/** + * Advanced: Subscribe to a universal market websocket stream + * + * This is NOT recommended unless you're very confident with what you're doing. + */ +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', + ): Promise ⋮---- -export interface WSAPIFuturesPositionV2Request { - symbol?: string; - recvWindow?: number; - timestamp: number; -} +/** + * Subscribe to aggregate trades for a symbol in a market category + */ +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface WSAPIAccountInformationRequest { - omitZeroBalances?: boolean; - recvWindow?: number; - timestamp: number; -} +/** + * Subscribe to trades for a symbol in a market category + * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning + */ +public subscribeTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface WSAPIAccountCommissionWSAPIRequest { - symbol: string; -} +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeBlockTrades( + symbol: string, + 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; -} + * Subscribe to coin index for a symbol in COINM Futures markets + * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. + */ +public subscribeCoinIndexPrice( + symbol: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- /** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order - */ -export interface WSAPIFuturesAlgoOrderCancelRequest { - algoid?: number; - clientalgoid?: string; - recvWindow?: number; - timestamp: number; -} - -================ -File: src/types/spot.ts -================ -import { - ExchangeFilter, - ExchangeSymbol, - GenericCodeMsgError, - numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRow, - OrderResponseType, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - RateLimiter, - SelfTradePreventionMode, - SideEffects, - StringBoolean, - SymbolFilter, -} from './shared'; + * Subscribe to mark price for a symbol in a market category + */ +public subscribeMarkPrice( + symbol: string, + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface BasicTimeRangeParam { - startTime?: number; - endTime?: number; -} +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface BasicFromPaginatedParams { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Subscribe to klines(candles) for a symbol in a market category + */ +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export type SymbolStatus = - | 'PRE_TRADING' - | 'TRADING' - | 'POST_TRADING' - | 'END_OF_DAY' - | 'HALT' - | 'AUCTION_MATCH' - | 'BREAK' - | 'CANCEL_ONLY'; +/** + * Subscribe to continuous contract klines(candles) for a symbol futures + */ +public subscribeContinuousContractKlines( + symbol: string, + contractType: 'perpetual' | 'current_quarter' | 'next_quarter', + interval: KlineInterval, + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface SystemStatusResponse { - status: 0 | 1; - msg: 'normal' | 'system maintenance'; -} +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface DailyAccountSnapshotParams { - type: 'SPOT' | 'MARGIN' | 'FUTURES'; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeMarkPriceKlines( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface SpotBalance { - asset: string; - free: numberInString; - locked: numberInString; -} +/** + * Subscribe to mini 24hr ticker for a symbol in market category. + */ +public subscribeSymbolMini24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface MarginBalance { - asset: string; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; -} +/** + * Subscribe to mini 24hr mini ticker in market category. + */ +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface DailyFuturesBalance { - asset: string; - marginBalance: numberInString; - walletBalance: numberInString; -} +/** + * Subscribe to 24hr ticker for a symbol in any market. + */ +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface DailyFuturesPositionState { - entryPrice: numberInString; - markPrice: numberInString; - positionAmt: numberInString; - symbol: string; - unRealizedProfit: numberInString; -} +/** + * Subscribe to Alpha Trading WebSocket Market Data streams. + * Base URL: wss://nbstream.binance.com/w3w/wsa/stream + */ +public subscribeAlpha(topics: string | string[]): Promise ⋮---- -export interface DailySpotAccountSnapshot { - data: { - balances: SpotBalance[]; - totalAssetOfBtc: numberInString; - }; - type: 'spot'; - updateTime: number; -} +/** + * Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24) + */ +public subscribeAlphaAllTokensTicker24(): Promise ⋮---- -export interface DailyMarginAccountSnapshot { - data: { - marginLevel: numberInString; - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; - userAssets: MarginBalance[]; - }; - type: 'margin'; - updateTime: number; -} +/** + * Subscribe to Alpha aggregate trades for a symbol + * @param symbol e.g. ALPHA_474USDT + */ +public subscribeAlphaAggTrade(symbol: string): Promise ⋮---- -export interface DailyFuturesAccountSnapshot { - data: { - assets: DailyFuturesBalance[]; - position: DailyFuturesPositionState[]; - }; - type: 'futures'; - updateTime: number; -} +/** + * Subscribe to Alpha full depth for a symbol + * @param symbol e.g. ALPHA_474USDT + * @param intervalMs 0, 100, or 500 + */ +public subscribeAlphaFulldepth( + symbol: string, + intervalMs: 0 | 100 | 500 = 500, + ): Promise ⋮---- -export type DailyAccountSnapshotElement = - | DailySpotAccountSnapshot - | DailyMarginAccountSnapshot - | DailyFuturesAccountSnapshot; +/** + * Subscribe to Alpha klines for a contract + * @param contractAddress Contract address + * @param chainId Chain ID (e.g. CT_501, 56) + * @param interval 1s, 1m, 5m, 15m, 1h, 4h, 1d + */ +public subscribeAlphaKline( + contractAddress: string, + chainId: string, + interval: '1s' | '1m' | '5m' | '15m' | '1h' | '4h' | '1d', + ): Promise ⋮---- -export interface DailyAccountSnapshot { - code: number; - msg: string; - snapshotVos: DailyAccountSnapshotElement[]; -} +/** + * Subscribe to 24hr ticker in any market. + */ +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface CoinNetwork { - addressRegex: string; - coin: string; - depositDesc: string; - depositEnable: boolean; - isDefault: boolean; - memoRegex: string; - minConfirm: number; - name: string; - network: string; - resetAddressStatus: boolean; - specialTips?: string; - specialWithdrawTips?: string; - unlockConfirm: number; - withdrawDesc: string; - withdrawEnable: boolean; - withdrawFee: numberInString; - withdrawMin: numberInString; - withdrawMax: numberInString; - withdrawInternalMin: numberInString; - withdrawIntegerMultiple: numberInString; - depositDust?: numberInString; - sameAddress: boolean; - estimatedArrivalTime: number; - busy: boolean; - contractAddressUrl?: string; - contractAddress?: string; -} +/** + * Subscribe to rolling window ticker statistics for all market symbols, + * computed over multiple windows. Note that only tickers that have + * changed will be present in the array. + * + * Notes: + * - Supported window sizes: 1h,4h,1d. + * - Supported markets: spot + */ +public subscribeAllRollingWindowTickers( + market: 'spot', + windowSize: '1h' | '4h' | '1d', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface AllCoinsInformationResponse { - coin: string; - depositAllEnable: boolean; - free: numberInString; - freeze: numberInString; - ipoable: numberInString; - ipoing: numberInString; - isLegalMoney: boolean; - locked: numberInString; - name: string; - networkList: CoinNetwork[]; - storage: numberInString; - trading: boolean; - withdrawAllEnable: boolean; - withdrawing: numberInString; -} -⋮---- -export interface WithdrawParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; -} -⋮---- -export interface TransferBrokerSubAccountParams { - fromId?: string; - toId?: string; - clientTranId?: string; - asset: string; - amount: number; -} +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface ConvertQuoteRequestParams { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - walletType?: string; - validTime?: string; -} +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllBookTickers( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface EnableConvertSubAccountParams { - subAccountId: string; - convert: boolean; -} +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface AcceptQuoteRequestParams { - quoteId: string; -} +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface GetOrderStatusParams { - orderId?: string; - quoteId?: string; -} +/** + * Subscribe to partial book depths (snapshots). + * + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs + */ +public subscribePartialBookDepths( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 100 | 250 | 500 | 1000, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface GetConvertTradeHistoryParams { - startTime: number; - endTime?: number; - limit?: string; -} +/** + * Subscribe to orderbook depth updates to locally manage an order book. + * + * Note that the updatems parameter depends on which market you're trading + * + * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream + * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams + */ +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface TransferBrokerSubAccount { - txnId: numberInString; -} +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export enum EnumDepositStatus { - Pending = 0, - CreditedButCannotWithdraw = 6, - WrongDeposit = 7, - WaitingUserConfirm = 8, - Success = 1, - Rejected = 2, -} +/** + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- -export type DepositStatusCode = `${EnumDepositStatus}`; +/** + * Subscribe to aggregate trades for a symbol in spot markets. + */ +public subscribeSpotAggregateTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface DepositHistoryParams { - coin?: string; // Optional: Filter by coin - status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) - startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) - endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) - offset?: number; // Optional: Pagination offset (Default: 0) - limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) - txId?: string; // Optional: Filter by transaction ID - includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) -} +/** + * Subscribe to trades for a symbol in spot markets. + */ +public subscribeSpotTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -coin?: string; // Optional: Filter by coin -status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) -startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) -endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) -offset?: number; // Optional: Pagination offset (Default: 0) -limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) -txId?: string; // Optional: Filter by transaction ID -includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +/** + * Subscribe to block trades for a symbol in spot markets. + */ +public subscribeSpotBlockTrades( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface DepositHistory { - amount: numberInString; - coin: string; - network: string; - status: number; - address: string; - addressTag: string; - txId: string; - insertTime: number; - transferType: number; - confirmTimes: string; -} +/** + * Subscribe to candles for a symbol in spot markets. + */ +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export enum EnumWithdrawStatus { - EmailSent = 0, - Cancelled = 1, - AwaitingApproval = 2, - Rejected = 3, - Processing = 4, - Failure = 5, - Completed = 6, -} +/** + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export type WithdrawStatusCode = `${EnumWithdrawStatus}`; +/** + * Subscribe to mini 24hr mini ticker in spot markets. + */ +public subscribeSpotAllMini24hrTickers( + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export interface WithdrawHistoryParams { - coin?: string; // Optional: Filter by coin - withdrawOrderId?: string; // Optional: Filter by withdraw order ID - status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) - offset?: number; // Optional: Pagination offset - limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) - idList?: string; // Optional: Comma-separated list of withdrawal IDs - startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) - endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) -} +/** + * Subscribe to 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbol24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -coin?: string; // Optional: Filter by coin -withdrawOrderId?: string; // Optional: Filter by withdraw order ID -status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) -offset?: number; // Optional: Pagination offset -limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) -idList?: string; // Optional: Comma-separated list of withdrawal IDs -startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) -endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +/** + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise ⋮---- -export enum EnumWithdrawTransferType { - External = 0, - Interal = 1, -} +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + wsKeyOverride?: WsKey, + ): Promise ⋮---- -export type WithdrawTransferType = `${EnumWithdrawTransferType}`; -⋮---- -export interface WithdrawHistory { - address: string; - amount: numberInString; - applyTime: string; - coin: string; - id: string; - withdrawOrderId: string; - network: string; - transferType: WithdrawTransferType; - status: number; - transactionFee: numberInString; - txId: string; -} -⋮---- -export interface DepositAddressParams { - coin: string; - network?: string; - amount?: number; -} -⋮---- -export interface DepositAddressResponse { - address: string; - coin: string; - tag: string; - url: string; -} -⋮---- -export interface ConvertDustParams { - asset: string[]; - accountType?: 'SPOT' | 'MARGIN'; -} -⋮---- -export type DustConvertAccountType = 'SPOT' | 'MARGIN'; -⋮---- -export interface DustConvertParams { - asset: string[]; - accountType?: DustConvertAccountType; - clientId?: string; - targetAsset?: string; - thirdPartyClientId?: string; - dustQuotaAssetToTargetAssetPrice?: numberInString; -} -⋮---- -export interface DustConvertibleAssetsParams { - targetAsset: string; - accountType?: DustConvertAccountType; - dustQuotaAssetToTargetAssetPrice?: numberInString; -} -⋮---- -export interface DustConvertibleAssetDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - exchange: numberInString; - toQuotaAssetAmount: numberInString; - toTargetAssetAmount: numberInString; - toTargetAssetOffExchange: numberInString; -} -⋮---- -export interface DustConvertibleAssetsResponse { - dribbletPercentage: numberInString; - totalTransferQuotaAssetAmount: numberInString; - totalTransferTargetAssetAmount: numberInString; - dribbletBase: numberInString; - details: DustConvertibleAssetDetail[]; -} -⋮---- -export interface DustInfoDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - toBTC: numberInString; - toBNB: numberInString; - toBNBOffExchange: numberInString; - exchange: numberInString; -} -⋮---- -export interface DustInfo { - details: DustInfoDetail[]; - totalTransferBtc: numberInString; - totalTransferBNB: numberInString; - dribbletPercentage: numberInString; -} -⋮---- -export interface DustConversionResult { - amount: numberInString; - fromAsset: string; - operateTime: number; - serviceChargeAmount: numberInString; - tranId: number; - transferedAmount: numberInString; -} -⋮---- -export interface DustConversion { - totalServiceCharge: numberInString; - totalTransfered: numberInString; - transferResult: DustConversionResult[]; -} -⋮---- -export interface UserAssetDribbletDetail { - transId: number; - serviceChargeAmount: numberInString; - amount: numberInString; - operateTime: number; - transferedAmount: numberInString; - fromAsset: string; -} -⋮---- -export interface UserAssetDribblet { - operateTime: number; - totalTransferedAmount: numberInString; - totalServiceChargeAmount: numberInString; - transId: number; - userAssetDribbletDetails: UserAssetDribbletDetail[]; -} -⋮---- -export interface DustLog { - total: number; - userAssetDribblets: UserAssetDribblet[]; -} -⋮---- -export enum EnumUniversalTransferType { - SpotToUSDM = 'MAIN_UMFUTURE', - SpotToCOINM = 'MAIN_CMFUTURE', - SpotToMargin = 'MAIN_MARGIN', - SpotToFunding = 'MAIN_FUNDING', - SpotToOptions = 'MAIN_OPTION', - FundingToSpot = 'FUNDING_MAIN', - FundingToUSDM = 'FUNDING_UMFUTURE', - FundingToCOINM = 'FUNDING_CMFUTURE', - FundingToMargin = 'FUNDING_MARGIN', - FundingToOptions = 'FUNDING_OPTION', - USDMToSpot = 'UMFUTURE_MAIN', - USDMToFunding = 'UMFUTURE_FUNDING', - USDMToMargin = 'UMFUTURE_MARGIN', - USDMToOptions = 'UMFUTURE_OPTION', - COINMToSpot = 'CMFUTURE_MAIN', - COINMToFunding = 'CMFUTURE_FUNDING', - COINMToMargin = 'CMFUTURE_MARGIN', - MarginToSpot = 'MARGIN_MAIN', - MarginToUSDM = 'MARGIN_UMFUTURE', - MarginToCOINM = 'MARGIN_CMFUTURE', - MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', - MarginToFunding = 'MARGIN_FUNDING', - MarginToOptions = 'MARGIN_OPTION', - IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', - IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', - OptionsToSpot = 'OPTION_MAIN', - OptionsToUSDM = 'OPTION_UMFUTURE', - OptionsToFunding = 'OPTION_FUNDING', - OptionsToMargin = 'OPTION_MARGIN', -} -⋮---- -export type UniversalTransferType = `${EnumUniversalTransferType}`; -⋮---- -export interface UniversalTransferParams { - type: UniversalTransferType; - asset: string; - amount: number; - fromSymbol: string; - toSymbol: string; -} -⋮---- -export interface UniversalTransferHistoryParams { - type: UniversalTransferType; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface ExchangeInfoParams { - symbol?: string; - symbols?: string[]; - permissions?: string | string[]; - showPermissionSets?: boolean; - symbolStatus?: string; -} -⋮---- -type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; -type SpotPegOffsetType = 'PRICE_LEVEL'; -⋮---- -export interface NewSpotOrderParams< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> { - symbol: string; - side: OrderSide; - type: T; - timeInForce?: OrderTimeInForce; - quantity?: number; - quoteOrderQty?: number; - price?: number; - newClientOrderId?: string; - strategyId?: number; - strategyType?: number; - stopPrice?: number; - trailingDelta?: number; - icebergQty?: number; - newOrderRespType?: RT; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - isIsolated?: StringBoolean; - sideEffectType?: SideEffects; - autoRepayAtCancel?: StringBoolean; -} -⋮---- -export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; -export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; -⋮---- -export interface ReplaceSpotOrderParams< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends NewSpotOrderParams { - cancelReplaceMode: CancelReplaceMode; - cancelNewClientOrderId?: string; - cancelOrigClientOrderId?: string; - cancelOrderId?: number; - cancelRestrictions?: CancelRestrictions; -} -⋮---- -export interface GetOCOParams { - symbol?: string; - orderListId?: number; - origClientOrderId?: string; -} -⋮---- -export interface NewSpotSOROrderParams { - symbol: string; - side: OrderSide; - type: OrderType; - timeInForce?: OrderTimeInForce; - quantity: number; - price?: number; - newClientOrderId?: string; - strategyId?: number; - strategyType?: number; - icebergQty?: number; - newOrderRespType?: OrderResponseType; - selfTradePreventionMode?: SelfTradePreventionMode; -} -⋮---- -export type APILockTriggerCondition = 'GCR' | 'IFER' | 'UFR'; -⋮---- -export interface APITriggerConditionSymbolStatus { - i: APILockTriggerCondition; - c: number; - v: number; - t: number; -} -⋮---- -export interface APITradingStatus { - data: { - isLocked: boolean; - plannedRecoverTime: number; - triggerCondition: Record; - indicators: Record; - updateTime: number; - }; -} -⋮---- -export interface APIPermissions { - ipRestrict: boolean; - createTime: number; - enableReading: boolean; - enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals - enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly - enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed - enableFutures: boolean; // API Key created before your futures account opened does not support futures API service - permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization - enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading - enableSpotAndMarginTrading: boolean; // Spot and margin trading - tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission - enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading - enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading - enablePortfolioMarginTrading: true; -} -⋮---- -enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals -enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly -enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed -enableFutures: boolean; // API Key created before your futures account opened does not support futures API service -permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization -enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading -enableSpotAndMarginTrading: boolean; // Spot and margin trading -tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission -enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading -enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading -⋮---- -export interface AssetDetail { - minWithdrawAmount: numberInString; - depositStatus: boolean; - withdrawFee: number; - withdrawStatus: boolean; - depositTip?: string; -} -⋮---- -export interface SymbolTradeFee { - symbol: string; - makerCommission: numberInString; - takerCommission: numberInString; -} -⋮---- -export interface SymbolExchangeInfo { - symbol: string; - status: string; - baseAsset: string; - baseAssetPrecision: number; - quoteAsset: string; - quotePrecision: number; - quoteAssetPrecision: number; - baseCommissionPrecision: number; - quoteCommissionPrecision: number; - orderTypes: OrderType[]; - icebergAllowed: boolean; - ocoAllowed: boolean; - opoAllowed: boolean; - quoteOrderQtyMarketAllowed: boolean; - allowTrailingStop: boolean; - cancelReplaceAllowed: boolean; - isSpotTradingAllowed: boolean; - isMarginTradingAllowed: boolean; - filters: SymbolFilter[]; - permissions: ('SPOT' | 'MARGIN')[]; - defaultSelfTradePreventionMode: SelfTradePreventionMode; - allowedSelfTradePreventionModes: SelfTradePreventionMode[]; -} -⋮---- -export interface ExchangeInfo { - timezone: string; - serverTime: number; - rateLimits: RateLimiter[]; - exchangeFilters: ExchangeFilter[]; - symbols: SymbolExchangeInfo[]; -} -⋮---- -export interface OrderBookResponse { - lastUpdateId: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; -} -⋮---- -export interface RawTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; -} -⋮---- -export interface BlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface HistoricalBlockTradesParams { - symbol: string; - fromId: number; - limit?: number; -} -⋮---- -export interface RawAccountTrade { - symbol: string; - id: number; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isBestMatch: boolean; -} -⋮---- -export interface AggregateTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; - M: boolean; -} -⋮---- -export interface CurrentAvgPrice { - mins: number; - price: numberInString; - closeTime: number; -} -⋮---- -/** Spot PRICE_RANGE execution rule (GET /api/v3/executionRules). */ -export interface SpotPriceRangeExecutionRule { - ruleType: 'PRICE_RANGE'; - bidLimitMultUp: numberInString; - bidLimitMultDown: numberInString; - askLimitMultUp: numberInString; - askLimitMultDown: numberInString; -} -⋮---- -export interface SpotSymbolExecutionRules { - symbol: string; - rules: SpotPriceRangeExecutionRule[]; -} -⋮---- -export interface SpotExecutionRulesResponse { - symbolRules: SpotSymbolExecutionRules[]; -} -⋮---- -/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ -export interface SpotExecutionRulesParams { - symbol?: string; - symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; -} -⋮---- -/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ -export interface SpotReferencePriceResponse { - symbol: string; - referencePrice: numberInString | null; - timestamp: number; -} -⋮---- -/** GET /api/v3/referencePrice or /referencePrice/calculation when no reference price has ever been set (code -2043). */ -export interface SpotReferencePriceNeverSetError { - code: -2043; - msg: string; -} -⋮---- -export type SpotReferencePriceResult = - | SpotReferencePriceResponse - | SpotReferencePriceNeverSetError; -⋮---- -/** Reference price is computed as an arithmetic mean in the matching engine. */ -export interface SpotReferencePriceCalculationArithmeticMean { - symbol: string; - calculationType: 'ARITHMETIC_MEAN'; - bucketCount: number; - bucketWidthMs: number; -} -⋮---- -/** Reference price is computed outside the matching engine. */ -export interface SpotReferencePriceCalculationExternal { - symbol: string; - calculationType: 'EXTERNAL'; - externalCalculationId: number; -} -⋮---- -export type SpotReferencePriceCalculationResponse = - | SpotReferencePriceCalculationArithmeticMean - | SpotReferencePriceCalculationExternal - | SpotReferencePriceNeverSetError; -⋮---- -export interface DailyChangeStatistic { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - prevClosePrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- -export interface SymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; -} -⋮---- -export interface OrderResponseACK { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; -} -⋮---- -/** Conditional fields on POST /api/v3/order RESULT/FULL. Only present when the matching condition is met. */ -export interface SpotNewOrderConditionalFields { - icebergQty?: numberInString; - preventedMatchId?: number; - preventedQuantity?: numberInString; - stopPrice?: numberInString; - strategyId?: number; - strategyType?: number; - trailingDelta?: number; - trailingTime?: number; - pegPriceType?: SpotPegPriceType; - pegOffsetType?: SpotPegOffsetType; - pegOffsetValue?: number; - peggedPrice?: numberInString; -} -⋮---- -export interface OrderResponseResult extends SpotNewOrderConditionalFields { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; -} -⋮---- -/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ -⋮---- -export interface OrderFill { - price: numberInString; - qty: numberInString; - commission: numberInString | null; - commissionAsset: string | null; - tradeId: number; -} -⋮---- -export interface OrderResponseFull extends SpotNewOrderConditionalFields { - symbol: string; - orderId: number; - orderListId?: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - marginBuyBorrowAmount?: number; - marginBuyBorrowAsset?: string; - isIsolated?: boolean; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; - fills: OrderFill[]; -} -⋮---- -/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ -⋮---- -export type OrderResponse = - | OrderResponseACK - | OrderResponseResult - | OrderResponseFull; -⋮---- -export type OrderResponseTypeFor< - RT extends OrderResponseType | undefined = undefined, - T extends OrderType | undefined = undefined, -> = RT extends 'ACK' - ? OrderResponseACK - : RT extends 'RESULT' - ? OrderResponseResult - : RT extends 'FULL' - ? OrderResponseFull - : T extends 'MARKET' | 'LIMIT' - ? OrderResponseFull - : OrderResponseACK; -⋮---- -export interface OrderListOrder { - symbol: string; - orderId: number; - clientOrderId: string; - /** Present only for expired orders. */ - expiryReason?: string; -} -⋮---- -/** Present only for expired orders. */ -⋮---- -export interface OrderListResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: [OrderListOrder, OrderListOrder]; - orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; -} -⋮---- -export interface OrderList { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: [OrderListOrder, OrderListOrder]; -} -export interface SOROrderFill { - matchType: string; - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; - tradeId: number; - allocId: number; -} -⋮---- -export type SOROrderResponseFull = OrderResponseFull & { - workingTime: number; - fills: SOROrderFill[]; - workingFloor: string; - selfTradePreventionMode: string; - usedSor: true; -}; -⋮---- -export interface SORTestOrderResponse { - standardCommissionForOrder: { - //Standard commission rates on trades from the order. - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - //Tax commission rates for trades from the order. - maker: numberInString; - taker: numberInString; - }; - discount: { - //Discount on standard commissions when paying in BNB. - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ - 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. - }; -} -⋮---- -//Standard commission rates on trades from the order. -⋮---- -//Tax commission rates for trades from the order. -⋮---- -//Discount on standard commissions when paying in BNB. -⋮---- -/** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ -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 { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - selfTradePreventionMode: SelfTradePreventionMode; -} -⋮---- -export interface CancelOrderListResult extends OrderList { - orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; -} -⋮---- -export interface GenericReplaceSpotOrderResult { - cancelResult: 'SUCCESS' | 'FAILURE'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: C; - newOrderResponse: N; -} -⋮---- -export interface ReplaceSpotOrderCancelStopFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'NOT_ATTEMPTED'; -} -⋮---- -export interface ReplaceSpotOrderNewFailure - extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - GenericCodeMsgError - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'FAILURE'; -} -⋮---- -export interface ReplaceSpotOrderCancelAllowFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'SUCCESS'; -} -⋮---- -export interface ReplaceSpotOrderCancelAllFailure - extends GenericReplaceSpotOrderResult< - GenericCodeMsgError, - GenericCodeMsgError - > { - cancelResult: 'FAILURE'; - newOrderResult: 'FAILURE'; -} -⋮---- -export interface ReplaceSpotOrderResultError { - data: - | ReplaceSpotOrderCancelStopFailure - | ReplaceSpotOrderNewFailure - | ReplaceSpotOrderCancelAllowFailure - | ReplaceSpotOrderCancelAllFailure; -} -⋮---- -export interface ReplaceSpotOrderResultSuccess< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - OrderResponseTypeFor - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'SUCCESS'; -} -⋮---- -export interface SpotOrder { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - stopPrice: numberInString; - icebergQty: numberInString; - time: number; - updateTime: number; - isWorking: boolean; - origQuoteOrderQty: numberInString; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present only for expired orders. */ - expiryReason?: string; -} -⋮---- -/** Present only for expired orders. */ -⋮---- -export interface SpotAmendKeepPriorityResult { - transactTime: number; - executionId: number; - amendedOrder: { - symbol: string; - orderId: number; - orderListId: number; - origClientOrderId: string; - clientOrderId: string; - price: string; - qty: string; - executedQty: string; - preventedQty: string; - quoteOrderQty: string; - cumulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }; - listStatus?: { - orderListId: number; - contingencyType: string; - listOrderStatus: string; - listClientOrderId: string; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - }; -} -⋮---- -export interface SpotAssetBalance { - asset: string; - free: numberInString; - locked: numberInString; -} -⋮---- -export interface AccountInformation { - makerCommission: number; - takerCommission: number; - buyerCommission: number; - sellerCommission: number; - commissionRates: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - canTrade: boolean; - canWithdraw: boolean; - canDeposit: boolean; - brokered: boolean; - requireSelfTradePrevention: boolean; - preventSor: boolean; - updateTime: number; - accoountType: string; - balances: SpotAssetBalance[]; - permissions: string[]; - uid: number; -} -⋮---- -export interface CrossMarginAccountTransferParams { - asset: string; - amount: number; - type: 1 | 2; -} -⋮---- -export interface MarginTransactionResponse { - tranId: number; -} -⋮---- -export interface MarginAccountLoanParams { - asset: string; - isIsolated: StringBoolean; - symbol: string; - amount: number; - type: 'BORROW' | 'REPAY'; -} -⋮---- -export interface QueryMarginAssetParams { - asset: string; -} -⋮---- -export interface QueryMarginAssetResponse { - assetFullName: string; - assetName: string; - isBorrowable: boolean; - isMortgageable: boolean; - userMinBorrow: numberInString; - userMinRepay: numberInString; - /** - * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. - * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. - */ - delistTime?: number; -} -⋮---- -/** - * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. - * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. - */ -⋮---- -export interface QueryCrossMarginPairParams { - symbol: string; -} -⋮---- -/** - * Row from `GET /sapi/v1/margin/allPairs`. - * Dev-confirmed: this response has no `delistTime`. Documentation examples that include it are wrong. - */ -export interface QueryCrossMarginPairResponse { - id: number; - symbol: string; - base: string; - quote: string; - isMarginTrade: boolean; - isBuyAllowed: boolean; - isSellAllowed: boolean; -} -⋮---- -export interface QueryMarginPriceIndexResponse { - calcTime: number; - price: numberInString; - symbol: string; -} -⋮---- -export interface QueryMarginRecordParams { - asset: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - archived?: boolean; -} -⋮---- -export interface GetMarginAccountBorrowRepayRecordsParams { - asset?: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - type: 'BORROW' | 'REPAY'; -} -⋮---- -export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; -⋮---- -export interface MarginAccountRecord { - isolatedSymbol?: string; - asset: string; - principal: numberInString; - status: LoanStatus; - timestamp: number; - txId: number; -} -⋮---- -export interface QueryCrossMarginAccountDetailsParams { - created: boolean; - borrowEnabled: boolean; - marginLevel: numberInString; - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; - totalCollateralValueInUSDT: numberInString; - totalOpenOrderLossInUSDT: numberInString; - tradeEnabled: boolean; - transferInEnabled: boolean; - transferOutEnabled: boolean; - accountType: string; - userAssets: MarginBalance[]; -} -⋮---- -export interface BasicMarginAssetParams { - asset: string; - isolatedSymbol?: string; -} -⋮---- -export interface QueryMaxBorrowResponse { - amount: numberInString; - borrowLimit: numberInString; -} -⋮---- -export interface QueryMaxTransferOutAmountResponse { - amount: numberInString; -} -⋮---- -export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; -⋮---- -export interface IsolatedMarginAccountTransferParams { - asset: string; - symbol: string; - transFrom: IsolatedMarginTransfer; - transTo: IsolatedMarginTransfer; - amount: number; -} -⋮---- -export interface IsolatedMarginAccountAsset { - asset: string; - borrowEnabled: boolean; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; - netAssetOfBtc: numberInString; - repayEnabled: boolean; - totalAsset: numberInString; -} -⋮---- -export type IsolatedMarginLevelStatus = - | 'EXCESSIVE' - | 'NORMAL' - | 'MARGIN_CALL' - | 'PRE_LIQUIDATION' - | 'FORCE_LIQUIDATION'; -⋮---- -export interface IsolatedMarginAccountAssets { - baseAsset: IsolatedMarginAccountAsset; - quoteAsset: IsolatedMarginAccountAsset; - symbol: string; - isolatedCreated: boolean; - enabled: boolean; - marginLevel: numberInString; - marginLevelStatus: IsolatedMarginLevelStatus; - marginRatio: numberInString; - indexPrice: numberInString; - liquidatePrice: numberInString; - liquidateRate: numberInString; - tradeEnabled: boolean; -} -⋮---- -export interface IsolatedMarginAccountInfo { - assets: IsolatedMarginAccountAssets[]; - totalAssetOfBtc?: numberInString; - totalLiabilityOfBtc?: numberInString; - totalNetAssetOfBtc?: numberInString; -} -⋮---- -export interface SpotSubUserAssetBtcList { - email: string; - totalAsset: numberInString; -} -⋮---- -export interface SubAccountList { - email: string; - isFreeze: boolean; - createTime: number; - isManagedSubAccount: boolean; - isAssetManagementSubAccount: boolean; -} -⋮---- -export interface SubAccountDepositHistoryList { - depositId: number; - subAccountId: string; - amount: string; - coin: string; - network: string; - status: number; - address: string; - addressTag: string; - txId: string; - insertTime: number; - sourceAddress: string; - confirmTimes: string; -} -⋮---- -export interface SubAccountTransferHistoryList { - fromId?: string; - toId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountBasicTransfer { - from: string; - to: string; - asset: string; - qty: numberInString; - tranId: number; - time: number; -} -⋮---- -export interface MarginTradeCoeffVo { - forceLiquidationBar: numberInString; - marginCallBar: numberInString; - normalBar: numberInString; -} -⋮---- -export interface SubAccountStatus { - email: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - insertTime: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - mobile: number; -} -⋮---- -export interface BasicBtcTotals { - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; -} -⋮---- -export interface FuturesSubAccountAssets { - asset: string; - initialMargin: numberInString; - maintenanceMargin: numberInString; - marginBalance: numberInString; - maxWithdrawAmount: numberInString; - openOrderInitialMargin: numberInString; - positionInitialMargin: numberInString; - unrealizedProfit: numberInString; - walletBalance: numberInString; -} -⋮---- -export interface FuturesSubAccountList { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - email: string; -} -⋮---- -export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; -⋮---- -export interface SubAccountTransferHistory { - counterParty: string; - email: string; - type: number; - asset: string; - qty: numberInString; - fromAccountType: AccountType; - toAccountType: AccountType; - status: string; - tranId: number; - time: number; -} -⋮---- -export interface SubAccountUniversalTransferHistory { - tranId: number; - fromEmail: string; - toEmail: string; - asset: string; - amount: numberInString; - createTimeStamp: number; - fromAccountType: AccountType; - toAccountType: AccountType; - status: string; - clientTranId?: string; -} -⋮---- -export interface BasicSubAccount { - email: string; - subAccountApiKey: string; -} -⋮---- -export interface CreateSubAccountParams { - subAccountString: string; -} -⋮---- -export interface EnableOrDisableIPRestrictionForSubAccountParams - extends BasicSubAccount { - ipAddress?: string; -} -⋮---- -export interface GetBrokerSubAccountHistoryParams { - fromId?: string; - toId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; -} -⋮---- -export interface CreateBrokerSubAccountParams { - tag?: string; -} -⋮---- -export interface GetBrokerSubAccountParams { - subAccountId?: string; - page?: number; - size?: number; -} -⋮---- -export interface GetApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey?: string; - page?: number; - size?: number; -} -⋮---- -export interface CreateApiKeyBrokerSubAccountParams { - subAccountId: string; - canTrade: boolean; - marginTrade?: boolean; - futuresTrade?: boolean; -} -export interface ApiKeyBrokerSubAccount { - subAccountId: string; - apiKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} -⋮---- -export interface UpdateIpRestrictionForSubApiKey { - subAccountId: string; - ipAddress?: string; - subAccountApiKey: string; - status: string; -} -⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canUniversalTransfer: boolean; -} -⋮---- -export interface EnableMarginBrokerSubAccountParams { - subAccountId: string; - margin: boolean; -} -⋮---- -export interface EnableMarginBrokerSubAccountResponse { - subAccountId: string; - enableMargin: boolean; - updateTime: number; -} -⋮---- -export interface EnableFuturesBrokerSubAccountParams { - subAccountId: string; - futures: boolean; -} -⋮---- -export interface EnableFuturesBrokerSubAccountResponse { - subAccountId: string; - enableFutures: boolean; - updateTime: number; -} -⋮---- -export interface EnableMarginApiKeyBrokerSubAccountParams { - subAccountId: string; - margin: boolean; -} -export interface UniversalTransferBrokerParams { - fromId?: string; - toId?: string; - fromAccountType: string; - toAccountType: string; - asset: string; - amount: number; -} -⋮---- -export interface GetUniversalTransferBrokerParams { - fromId?: string; - toId?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; -} -⋮---- -export interface GetBrokerSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface DeleteApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; -} -⋮---- -export interface ChangePermissionApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} -⋮---- -export interface ChangePermissionApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} -⋮---- -export interface VirtualSubAccount { - email: string; -} -⋮---- -export interface BrokerSubAccountHistory { - subAccountsHistory: SubAccountTransferHistoryList[]; -} -⋮---- -export interface BrokerSubAccount { - subaccountId: string; - email: string; - makerCommission?: string; - takerCommission?: string; - marginMakerCommission?: string; - marginTakerCommission?: string; - createTime?: number; - tag: string; -} -⋮---- -export interface CreateApiKeyBrokerSubAccountResponse { - subaccountId: string; - apiKey: string; - secretKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; -} -⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canUniversalTransfer: boolean; -} -⋮---- -export interface GetBrokerInfoResponse { - maxMakerCommission: string; - minMakerCommission: string; - maxTakerCommission: string; - minTakerCommission: string; - subAccountQty: number; - maxSubAccountQty: number; -} -export interface SubAccountListParams { - email?: string; - isFreeze?: StringBoolean; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountListResponse { - subAccounts: SubAccountList[]; -} -⋮---- -export interface SubAccountSpotAssetTransferHistoryParams { - fromEmail?: string; - toEmail?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountSpotAssetTransferHistory - extends SubAccountBasicTransfer { - status: string; -} -⋮---- -export interface SubAccountFuturesAssetTransferHistoryParams { - email: string; - futuresType: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountFuturesAssetTransferHistory { - success: boolean; - futuresType: number; - transfers: SubAccountBasicTransfer[]; -} -⋮---- -export interface SubAccountFuturesAssetTransferParams { - fromEmail: string; - toEmail: string; - futuresType: number; - asset: string; - amount: number; -} -⋮---- -export interface SubAccountFuturesAssetTransfer { - success: boolean; - txnId: numberInString; -} -⋮---- -export interface SubAccountAssetsParams { - email: string; -} -⋮---- -export interface SubAccountAssets { - balances: SpotBalance[]; -} -⋮---- -export interface SubAccountSpotAssetsSummaryParams { - email?: string; - page?: number; - size?: number; -} -⋮---- -export interface SubAccountSpotAssetsSummary { - totalCount: number; - masterAccountTotalAsset: numberInString; - spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; -} -⋮---- -export interface SubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; -} -⋮---- -export interface SubAccountDepositAddress { - address: string; - coin: string; - tag: string; - url: string; -} -⋮---- -export interface SubAccountDepositHistoryParams extends DepositHistoryParams { - email: string; -} -⋮---- -export interface SubAccountEnableMargin { - email: string; - isMarginEnabled: boolean; -} -⋮---- -export interface SubAccountMarginAccountDetail extends BasicBtcTotals { - email: string; - marginLevel: numberInString; - marginTradeCoeffVo: MarginTradeCoeffVo; - marginUserAssetVoList: MarginBalance[]; -} -⋮---- -export interface SubAccountListBtc extends BasicBtcTotals { - email: string; -} -⋮---- -export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { - subAccountList: SubAccountListBtc; -} -⋮---- -export interface SubAccountEnableFutures { - email: string; - isFuturesEnabled: boolean; -} -⋮---- -export interface SubAccountFuturesAccountDetail { - email: string; - asset: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - maxWithdrawAmount: numberInString; - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - updateTime: number; -} -⋮---- -export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { - subAccountList: FuturesSubAccountList[]; -} -⋮---- -export interface FuturesPositionRisk { - entryPrice: numberInString; - leverage: numberInString; - maxNotional: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - positionAmount: numberInString; - symbol: string; - unrealizedProfit: numberInString; -} -⋮---- -export interface SubAccountTransferParams { - email: string; - asset: string; - amount: number; - type: number; -} -⋮---- -export interface SubAccountTransfer { - txnId: numberInString; -} -⋮---- -export interface SubAccountTransferToSameMasterParams { - toEmail: string; - asset: string; - amount: number; -} -⋮---- -export interface SubAccountTransferToMasterParams { - asset: string; - amount: number; -} -⋮---- -export interface SubAccountTransferHistoryParams { - asset?: string; - type?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface SubAccountUniversalTransferParams { - fromEmail?: string; - toEmail?: string; - fromAccountType: AccountType; - toAccountType: AccountType; - clientTranId?: string; - asset: string; - amount: number; -} -⋮---- -export interface SubAccountMovePositionParams { - fromUserEmail: string; - toUserEmail: string; - productType: 'UM' | 'OPTION'; - orderArgs: { - symbol: string; - quantity: number; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - }[]; -} -export interface SubAccountUniversalTransfer extends SubAccountTransfer { - clientTranId?: string; -} -⋮---- -export interface SubAccountMovePosition { - fromUserEmail: string; - toUserEmail: string; - productType: 'UM' | 'OPTION'; - symbol: string; - priceType: string; - price: string; - quantity: string; - positionSide: string | null; - side: string; - success: boolean; -} -⋮---- -export interface SubAccountMovePositionHistoryParams { - symbol: string; - productType?: 'UM' | 'OPTION'; - startTime?: number; - endTime?: number; - page: number; - row: number; -} -⋮---- -export interface SubAccountMovePositionHistory { - fromUserEmail: string; - toUserEmail: string; - productType: 'UM' | 'OPTION'; - symbol: string; - price: string; - quantity: string; - positionSide: string | null; - side: string; - timeStamp: number; -} -⋮---- -export interface SubAccountUniversalTransferHistoryParams { - fromEmail?: string; - toEmail?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountUniversalTransferHistoryResponse { - result: SubAccountUniversalTransferHistory[]; - totalCount: number; -} -⋮---- -export interface SubAccountEnableLeverageToken { - email: string; - enableBlvt: boolean; -} -⋮---- -export interface AddIpRestriction extends BasicSubAccount { - status: string; - ipAddress: string; -} -⋮---- -export interface SubAccountEnableOrDisableIPRestriction { - ipRestrict: boolean; - ipList: string[]; - updateTime: number; - apiKey: string; -} -⋮---- -export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { - ipAddress: string; -} -⋮---- -export interface AddIPListForSubAccountResponseParams { - ip: string; - updateTime: number; - apiKey: string; -} -⋮---- -export interface SubAccountAssetDetails { - coin: string; - name: string; - totalBalance: numberInString; - availableBalance: numberInString; - inOrder: numberInString; - btcValue: numberInString; -} -⋮---- -export interface WithdrawAssetsFromManagedSubAccountParams { - fromEmail: string; - asset: string; - amount: number; - transferDate?: number; -} -⋮---- -export interface BasicFuturesSubAccountParams { - email: string; - futuresType: 1 | 2; -} -⋮---- -export interface SubAccountSummaryOnFuturesAccountV2Params { - futuresType: 1 | 2; - page?: number; - limit?: number; -} -⋮---- -export interface SubAccountUSDMDetail { - futureAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - maxWithdrawAmount: numberInString; - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - updateTime: number; - }; -} -⋮---- -export interface COINMSubAccount { - email: string; - totalMarginBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; -} -⋮---- -export interface SubAccountCOINMDetail { - deliveryAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; - }; -} -⋮---- -export interface SubAccountUSDMSummary { - futureAccountSummaryResp: { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - subAccountList: FuturesSubAccountList[]; - }; -} -⋮---- -export interface SubAccountCOINMSummary { - deliveryAccountSummaryResp: { - totalMarginBalanceOfBTC: numberInString; - totalUnrealizedProfitOfBTC: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; - subAccountList: COINMSubAccount[]; - }; -} -⋮---- -export interface COINMPositionRisk { - entryPrice: numberInString; - markPrice: numberInString; - leverage: numberInString; - isolated: numberInString; - isolatedWallet: numberInString; - isolatedMargin: numberInString; - isAutoAddMargin: numberInString; - positionSide: string; - positionAmount: numberInString; - symbol: string; - unrealizedProfit: numberInString; -} -⋮---- -export interface SubAccountUSDMPositionRisk { - futurePositionRiskVos: FuturesPositionRisk[]; -} -⋮---- -export interface SubAccountCOINMPositionRisk { - deliveryPositionRiskVos: COINMPositionRisk[]; -} -⋮---- -export interface StakingProductDetail { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - apy: numberInString; -} -⋮---- -export interface StakingProductQuota { - totalPersonalQuota: numberInString; - minimum: numberInString; -} -⋮---- -export interface StakingProduct { - projectId: string; - detail: StakingProductDetail; - quota: StakingProductQuota; -} -⋮---- -export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; -export type StakingStatus = 'HOLDING' | 'REDEEMED'; -export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; -export type BSwapType = 'SINGLE' | 'COMBINATION'; -export type BSwapOperationType = 'ADD' | 'REMOVE'; -⋮---- -export interface StakingProductPosition { - positionId: numberInString; - projectId: string; - asset: string; - amount: numberInString; - purchaseTime: numberInString; - duration: numberInString; - accrualDays: numberInString; - rewardAsset: string; - APY: numberInString; - rewardAmt: numberInString; - extraRewardAsset: string; - extraRewardAPY: numberInString; - estExtraRewardAmt: numberInString; - nextInterestPay: numberInString; - nextInterestPayDate: numberInString; - payInterestPeriod: numberInString; - redeemAmountEarly: numberInString; - interestEndDate: numberInString; - deliverDate: numberInString; - redeemPeriod: numberInString; - redeemingAmt: numberInString; - partialAmtDeliverDate: numberInString; - canRedeemEarly: boolean; - renewable: boolean; - type: string; - status: StakingStatus; -} -export interface StakingBasicParams { - product: StakingProductType; - current?: number; - size?: number; -} -⋮---- -export interface FlexibleSavingBasicParams { - status?: string; - featured?: number; - current?: number; - size?: number; - asset?: string; -} -⋮---- -export interface FlexibleProductPositionParams { - status?: string; - featured?: number; - current?: number; - size?: number; -} -⋮---- -export interface PurchaseFlexibleProductParams { - productId: string; - amount: number; - autoSubscribe: boolean; -} -⋮---- -export interface PurchaseFlexibleProductResponse { - purchaseId: number; -} -⋮---- -export interface RedeemFlexibleProductParams { - productId: string; - amount: number; - type: 'FAST' | 'NORMAL'; -} -⋮---- -export interface LeftDailyPurchaseQuotaFlexibleProductResponse { - asset: string; - leftQuota: string; -} -⋮---- -export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; -export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; -export type ProjectSortBy = - | 'START_TIME' - | 'LOT_SIZE' - | 'INTEREST_RATE' - | 'DURATION'; -⋮---- -export interface FixedAndActivityProjectParams { - asset?: string; - type: ProjectType; - status?: ProjectStatus; - isSortAsc?: boolean; - sortBy?: ProjectSortBy; - current?: number; - size?: number; -} -export interface FixedAndActivityProjectPositionParams { - asset?: string; - projectId?: string; - status?: StakingStatus; -} -⋮---- -export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; -⋮---- -export interface PurchaseRecordParams { - lendingType: LendingType; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface NewFutureAccountTransferParams { - asset: string; - amount: number; - type: 1 | 2 | 3 | 4; -} -⋮---- -export interface GetFutureAccountTransferHistoryParams { - asset: string; - startTime: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface FutureAccountTransfer { - asset: string; - tranId: number; - amount: string; - type: string; - timestamp: number; - status: 'PENDING' | 'CONFIRMED' | 'FAILED'; -} -⋮---- -export interface GetLoanCoinPaginatedHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -/** - * - * STAKING - * - */ -⋮---- -export interface StakingHistory { - positionId: numberInString; - time: number; - asset: string; - project?: string; - amount: numberInString; - lockPeriod?: numberInString; - deliverDate?: numberInString; - type?: string; - status: string; -} -⋮---- -export interface StakingPersonalLeftQuota { - leftPersonalQuota: numberInString; -} -⋮---- -export interface StakingHistoryParams extends StakingBasicParams { - txnType: StakingTxnType; - asset?: string; - startTime?: number; - endTime?: number; -} -export interface BSwapOperationsParams { - operationId?: number; - poolId?: number; - operation: BSwapOperationType; - startTime?: number; - endTime?: number; - limit: number; -} -⋮---- -export interface BSwapOperations { - operationId: number; - poolId: number; - poolName: string; - operation: BSwapOperationType; - status: number; - updateTime: number; - shareAmount: numberInString; -} -export interface RemoveBSwapLiquidityParams { - poolId: number; - type: BSwapType; - asset?: string; - shareAmount: number; -} -⋮---- -export interface AddBSwapLiquidityParams { - poolId: number; - type?: BSwapType; - asset: string; - quantity: number; -} -⋮---- -export interface BSwapShare { - shareAmount: number; - sharePercentage: number; - asset: { [k: string]: number }; -} -⋮---- -export interface BSwapLiquidity { - poolId: number; - poolNmae: string; - updateTime: number; - liquidity: { [k: string]: number }; - share: BSwapShare; -} -⋮---- -export interface FundingAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - btcValuation: string; -} -⋮---- -export interface GetAssetParams { - asset?: string; - needBtcValuation?: boolean; -} -⋮---- -export interface UserAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - ipoable: string; - btcValuation: string; -} -⋮---- -export interface SpotAssetTagsParams { - tag?: string; -} -⋮---- -export interface SpotAssetTag { - assetCode: string; - assetName: string; - trading: boolean; - tags: string[]; -} -⋮---- -export interface ConvertTransfer { - clientTranId: string; - asset: string; - amount: number; - targetAsset: string; - accountType?: string; -} -⋮---- -export interface ConvertTransferResponse { - tranId: number; - status: string; -} -⋮---- -export interface GetConvertBUSDHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - accountType?: string; - current?: number; - size?: number; -} -⋮---- -export interface BUSDConversionRecord { - tranId: number; - type: number; - time: number; - deductedAsset: string; - deductedAmount: string; - targetAsset: string; - targetAmount: string; - status: string; - accountType: string; -} -⋮---- -export interface CloudMiningHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - current?: number; - size?: number; -} -⋮---- -export interface CloudMining { - createTime: number; - tranId: number; - type: number; - asset: string; - amount: string; - status: string; -} -⋮---- -export interface ConvertibleCoinsResponse { - convertEnabled: boolean; - coins: string[]; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - exchangeRates: any; -} -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface ConvertibleCoinsParams { - coin: string; - enable: boolean; -} -⋮---- -export interface SubmitDepositCreditParams { - depositId?: number; - txId?: string; - subAccountId?: number; - subUserId?: number; -} -⋮---- -export interface SubmitDepositCreditResponse { - code: string; - message: string; - data: boolean; - success: boolean; -} -⋮---- -export interface DepositAddressListParams { - coin: string; - network?: string; -} -⋮---- -export interface DepositAddress { - coin: string; - address: string; - tag: string; - isDefault: number; -} -⋮---- -export interface WalletBalance { - activate: boolean; - balance: string; - walletName: string; -} -⋮---- -export interface DelegationHistoryParams { - email: string; - startTime: number; - endTime: number; - type?: 'Delegate' | 'Undelegate'; - asset?: string; - current?: number; - size?: number; -} -⋮---- -export interface DelegationHistory { - clientTranId: string; - transferType: 'Delegate' | 'Undelegate'; - asset: string; - amount: string; - time: number; -} -⋮---- -export interface DelistScheduleResponse { - delistTime: number; - symbols: string[]; -} -⋮---- -export interface WithdrawAddress { - address: string; - addressTag: string; - coin: string; - name: string; - network: string; - origin: string; - originType: string; - whiteStatus: boolean; -} -⋮---- -export interface AccountInfo { - vipLevel: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - isOptionsEnabled: boolean; - isPortfolioMarginRetailEnabled: boolean; -} -⋮---- -export interface ManagedSubAccountSnapshotParams { - email: string; - type: 'SPOT' | 'MARGIN' | 'FUTURES'; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface SubaccountBalances { - asset: string; - free: string; - locked: string; -} -⋮---- -export interface SubaccountUserAssets { - asset: string; - borrowed: string; - free: string; - interest: string; - locked: string; - netAsset: string; -} -⋮---- -export interface SubaccountAssets { - asset: string; - marginBalance: string; - walletBalance: string; -} -⋮---- -export interface SubaccountPosition { - entryPrice: string; - markPrice: string; - positionAmt: string; - symbol: string; - unRealizedProfit: string; -} -⋮---- -export interface ManagedSubAccountSnapshot { - code: number; - msg: string; - snapshotVos: { - data: { - balances?: SubaccountBalances[]; - totalAssetOfBtc?: string; - marginLevel?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - userAssets?: SubaccountUserAssets[]; - assets?: SubaccountAssets[]; - position?: SubaccountPosition[]; - }; - type: string; - updateTime: number; - }[]; -} -⋮---- -export interface ManagedSubAccountTransferLogParams { - email: string; - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: 'from' | 'to'; - transferFunctionAccountType?: - | 'SPOT' - | 'MARGIN' - | 'ISOLATED_MARGIN' - | 'USDT_FUTURE' - | 'COIN_FUTURE'; -} -⋮---- -export interface ManagerSubTransferHistoryVos { - fromEmail: string; - fromAccountType: string; - toEmail: string; - toAccountType: string; - asset: string; - amount: string; - scheduledData: number; - createTime: number; - status: string; - tranId: number; -} -⋮---- -export interface ManagedSubAccountFuturesAssetsResponse { - code: string; - message: string; - snapshotVos: { - type: string; - updateTime: number; - data: { - assets: SubaccountAssets[]; - position: SubaccountPosition[]; - }; - }[]; -} -⋮---- -export interface ManagedSubAccountMarginAssetsResponse { - marginLevel: string; - totalAssetOfBtc: string; - totalLiabilityOfBtc: string; - totalNetAssetOfBtc: string; - userAssets: SubaccountUserAssets[]; -} -⋮---- -export interface ManagedSubAccountListParams { - email?: string; - page?: number; - limit?: number; -} -⋮---- -export interface ManagerSubUserInfoVo { - rootUserId: number; - managersubUserId: number; - bindParentUserId: number; - email: string; - insertTimeStamp: number; - bindParentEmail: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - isSignedLVTRiskAgreement: boolean; -} -⋮---- -export interface SubaccountTradeInfoVos { - userId: number; - btc: number; - btcFutures: number; - btcMargin: number; - busd: number; - busdFutures: number; - busdMargin: number; - date: number; -} -export interface SubAccountTransactionStatistics { - recent30BtcTotal: string; - recent30BtcFuturesTotal: string; - recent30BtcMarginTotal: string; - recent30BusdTotal: string; - recent30BusdFuturesTotal: string; - recent30BusdMarginTotal: string; - tradeInfoVos: SubaccountTradeInfoVos[]; -} -⋮---- -export interface ManagedSubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; -} -⋮---- -export interface ManagedSubAccountDepositAddress { - coin: string; - address: string; - tag: string; - url: string; -} -⋮---- -export interface EnableOptionsForSubAccountResponse { - email: string; - isEOptionsEnabled: boolean; -} -⋮---- -export interface ManagedSubAccountTransferTTLogParams { - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: string; - transferFunctionAccountType?: string; -} -⋮---- -export interface UIKlinesParams { - symbol: string; - interval: string; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} -⋮---- -export interface Ticker24hrFull { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - prevClosePrice: string; - lastPrice: string; - lastQty: string; - bidPrice: string; - bidQty: string; - askPrice: string; - askQty: string; - openPrice: string; - highPrice: string; - lowPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- -export interface Ticker24hrMini { - symbol: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- -export type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; -⋮---- -export interface TradingDayTickerParams { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -export interface TradingDayTickerFull { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- -export interface TradingDayTickerMini { - symbol: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- -export type TradingDayTickerSingle = - | TradingDayTickerFull - | TradingDayTickerMini; -⋮---- -export type TradingDayTickerArray = - | TradingDayTickerFull[] - | TradingDayTickerMini[]; -⋮---- -export interface RollingWindowTickerParams { - symbol?: string; - symbols?: string[]; - windowSize?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -export interface NewOrderListOTOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; - workingStrategyId?: number; - workingStrategyType?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: string; - pendingStopPrice?: string; - pendingTrailingDelta?: string; - pendingQuantity: string; - pendingIcebergQty?: string; - pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingStrategyId?: number; - pendingStrategyType?: number; -} -⋮---- -export interface NewOrderListOTOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} -⋮---- -export interface NewOrderListOTOCOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESPONSE'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - workingStrategyId?: number; - workingStrategyType?: number; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: string; - pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; -} -⋮---- -export interface NewOrderListOTOCOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} -⋮---- -export interface NewOrderListOPOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: string; - pendingStopPrice?: string; - pendingTrailingDelta?: string; - pendingIcebergQty?: string; - pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingStrategyId?: number; - pendingStrategyType?: number; - pendingPegPriceType?: string; - pendingPegOffsetType?: string; - pendingPegOffsetValue?: number; -} -⋮---- -export interface NewOrderListOPOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty?: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} -⋮---- -export interface NewOrderListOPOCOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingSide: 'BUY' | 'SELL'; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingAbovePegPriceType?: string; - pendingAbovePegOffsetType?: string; - pendingAbovePegOffsetValue?: number; - pendingBelowType?: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - pendingBelowPegPriceType?: string; - pendingBelowPegOffsetType?: string; - pendingBelowPegOffsetValue?: number; -} -⋮---- -export interface NewOrderListOPOCOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty?: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} -⋮---- -export interface OrderRateLimitUsage { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} -⋮---- -export interface PreventedMatchesParams { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} -⋮---- -export interface PreventedMatch { - symbol: string; - preventedMatchId: number; - takerOrderId: number; - makerSymbol: string; - makerOrderId: number; - tradeGroupId: number; - selfTradePreventionMode: SelfTradePreventionMode; - price: string; - makerPreventedQuantity: string; - transactTime: number; -} -⋮---- -export interface AllocationsParams { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} -⋮---- -export interface Allocation { - symbol: string; - allocationId: number; - allocationType: string; - orderId: number; - orderListId: number; - price: string; - qty: string; - quoteQty: string; - commission: string; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isAllocator: boolean; -} -⋮---- -export interface CommissionRates { - symbol: string; - standardCommission: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - taxCommission: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). - * `0.75` means pay 75% of the standard commission. It is not a reduction rate. - * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. - * Does not apply to tax or special commission. - */ - discount: string; - }; -} -⋮---- -/** - * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). - * `0.75` means pay 75% of the standard commission. It is not a reduction rate. - * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. - * Does not apply to tax or special commission. - */ -⋮---- -export interface GetCrossMarginTransferHistoryParams { - asset?: string; - type?: 'ROLL_IN' | 'ROLL_OUT'; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - isolatedSymbol?: string; -} -⋮---- -export interface CrossMarginTransferHistory { - amount: string; - asset: string; - status: string; - timestamp: number; - txId: number; - type: 'ROLL_IN' | 'ROLL_OUT'; - transFrom?: string; - transTo?: string; - fromSymbol?: string; - toSymbol?: string; -} -⋮---- -export interface GetMarginInterestHistoryParams { - asset?: string; - isolatedSymbol?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface MarginInterestHistory { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset?: string; - principal: string; - interest: string; - interestRate: string; - type: - | 'PERIODIC' - | 'ON_BORROW' - | 'PERIODIC_CONVERTED' - | 'ON_BORROW_CONVERTED' - | 'PORTFOLIO'; - isolatedSymbol?: string; -} -⋮---- -export interface GetForceLiquidationRecordParams { - startTime?: number; - endTime?: number; - isolatedSymbol?: string; - current?: number; - size?: number; -} -⋮---- -export interface ForceLiquidationRecord { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - isIsolated: boolean; - updatedTime: number; -} -⋮---- -export interface QueryMarginAccountAllOCOParams { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface QueryMarginAccountTradeListParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} -⋮---- -export interface IsolatedMarginSymbol { - base: string; - isBuyAllowed: boolean; - isMarginTrade: boolean; - isSellAllowed: boolean; - quote: string; - symbol: string; - delistTime?: number; -} -⋮---- -export interface ToggleBNBBurnParams { - spotBNBBurn?: 'true' | 'false'; - interestBNBBurn?: 'true' | 'false'; -} -⋮---- -export interface BNBBurnResponse { - spotBNBBurn: boolean; - interestBNBBurn: boolean; -} -⋮---- -export interface QueryMarginInterestRateHistoryParams { - asset: string; - vipLevel?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface MarginInterestRateHistory { - asset: string; - dailyInterestRate: string; - timestamp: number; - vipLevel: number; -} -⋮---- -export interface QueryCrossMarginFeeDataParams { - vipLevel?: number; - coin?: string; -} -⋮---- -export interface CrossMarginFeeData { - vipLevel: number; - coin: string; - transferIn: boolean; - borrowable: boolean; - dailyInterest: string; - yearlyInterest: string; - borrowLimit: string; - marginablePairs: string[]; -} -⋮---- -export interface IsolatedMarginFeeData { - vipLevel: number; - symbol: string; - leverage: string; - data: { - coin: string; - dailyInterest: string; - borrowLimit: string; - }[]; -} -⋮---- -export interface QueryIsolatedMarginTierDataParams { - symbol: string; - tier?: number; -} -⋮---- -export interface IsolatedMarginTierData { - symbol: string; - tier: number; - effectiveMultiple: string; - initialRiskRatio: string; - liquidationRiskRatio: string; - baseAssetMaxBorrowable: string; - quoteAssetMaxBorrowable: string; -} -⋮---- -export interface GetMarginOrderCountUsageParams { - isIsolated?: string; - symbol?: string; -} -⋮---- -export interface MarginOrderCountUsageResponse { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} -⋮---- -export interface Collateral { - minUsdValue: string; - maxUsdValue?: string; - discountRate: string; -} -⋮---- -export interface SmallLiabilityExchangeCoin { - asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; -} -export interface GetSmallLiabilityExchangeHistoryParams { - current: number; - size: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface SmallLiabilityExchangeHistory { - asset: string; - amount: string; - targetAsset: string; - targetAmount: string; - bizType: string; - timestamp: number; -} -⋮---- -export interface GetNextHourlyInterestRateParams { - assets: string; - isIsolated: boolean; -} -⋮---- -export interface NextHourlyInterestRate { - asset: string; - nextHourlyInterestRate: string; -} -⋮---- -export interface GetMarginCapitalFlowParams { - asset?: string; - symbol?: string; - type?: string; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} -⋮---- -export interface MarginCapitalFlow { - id: number; - tranId: number; - timestamp: number; - asset: string; - symbol: string; - type: string; - amount: string; -} -⋮---- -export interface MarginDelistSchedule { - delistTime: number; - crossMarginAssets: string[]; - isolatedMarginSymbols: string[]; - updateTime: number; -} -⋮---- -export interface MarginAvailableInventoryResponse { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any; - updateTime: number; -} -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface ManualLiquidationParams { - type: string; - symbol?: string; -} -⋮---- -export interface ManualLiquidationResponse { - asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; -} -⋮---- -export interface LeverageBracket { - leverage: number; - maxDebt: number; - maintenanceMarginRate: number; - initialMarginRate: number; - fastNum: number; -} -⋮---- -export interface LiabilityCoinLeverageBracket { - assetNames: string[]; - rank: number; - brackets: LeverageBracket[]; -} -export interface GetFlexibleSubscriptionRecordParams { - productId?: string; - purchaseId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface GetFlexibleSubscriptionRecordResponse { - amount: string; - asset: string; - time: number; - purchaseId: number; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; - status: string; -} -⋮---- -export interface GetLockedSubscriptionRecordParams { - purchaseId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface LockedSubscriptionRecord { - positionId: string; - purchaseId: number; - time: number; - asset: string; - amount: string; - lockPeriod: string; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; - status: string; -} -⋮---- -export interface GetFlexibleRedemptionRecordParams { - productId?: string; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface FlexibleRedemptionRecord { - amount: string; - asset: string; - time: number; - productId: string; - redeemId: number; - destAccount: string; - status: string; -} -⋮---- -export interface GetLockedRedemptionRecordParams { - positionId?: string; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface LockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; - asset: string; - lockPeriod: string; - amount: string; - type: string; - deliverDate: string; - status: string; -} -⋮---- -export interface GetFlexibleRewardsHistoryParams { - productId?: string; - asset?: string; - startTime?: number; - endTime?: number; - type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; - current?: number; - size?: number; -} -⋮---- -export interface FlexibleRewardsHistory { - asset: string; - rewards: string; - projectId: string; - type: string; - time: number; -} -⋮---- -export interface GetLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface GetLockedRewardsHistory { - positionId: string; - time: number; - asset: string; - lockPeriod: string; - amount: string; - type: string; -} -⋮---- -export interface SetAutoSubscribeParams { - productId: string; - autoSubscribe: boolean; -} -⋮---- -export interface GetFlexibleSubscriptionPreviewParams { - productId: string; - amount: number; -} -⋮---- -export interface FlexibleSubscriptionPreview { - totalAmount: string; - rewardAsset: string; - airDropAsset: string; - estDailyBonusRewards: string; - estDailyRealTimeRewards: string; - estDailyAirdropRewards: string; -} -⋮---- -export interface GetLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; -} -⋮---- -export interface LockedSubscriptionPreview { - rewardAsset: string; - totalRewardAmt: string; - extraRewardAsset: string; - estTotalExtraRewardAmt: string; - nextPay: string; - nextPayDate: string; - valueDate: string; - rewardsEndDate: string; - deliverDate: string; - nextSubscriptionDate: string; - boostRewardAsset: string; - estDailyRewardAmt: string; -} -⋮---- -export interface GetRateHistoryParams { - productId: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface GetRateHistory { - productId: string; - asset: string; - annualPercentageRate: string; - time: number; -} -⋮---- -export interface GetCollateralRecordParams { - productId?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface CollateralRecord { - amount: string; - productId: string; - asset: string; - createTime: number; - type: string; - productName: string; - orderId: number; -} -⋮---- -export interface GetDualInvestmentProductListParams { - optionType: string; - exercisedCoin: string; - investCoin: string; - pageSize?: number; - pageIndex?: number; -} -⋮---- -export interface DualInvestmentProduct { - id: string; - investCoin: string; - exercisedCoin: string; - strikePrice: string; - duration: number; - settleDate: number; - purchaseDecimal: number; - purchaseEndTime: number; - canPurchase: boolean; - apr: string; - orderId: number; - minAmount: string; - maxAmount: string; - createTimestamp: number; - optionType: string; - isAutoCompoundEnable: boolean; - autoCompoundPlanList: string[]; -} -⋮---- -export interface SubscribeDualInvestmentProductParams { - id: string; - orderId: string; - depositAmount: number; - /** - * @deprecated Binance removed the `autoCompoundPlan` request parameter from - * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. - * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says - * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec - * still lists the parameter, so this field stays deprecated. - */ - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} -⋮---- -/** - * @deprecated Binance removed the `autoCompoundPlan` request parameter from - * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. - * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says - * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec - * still lists the parameter, so this field stays deprecated. - */ -⋮---- -export interface SubscribeDualInvestmentProductResponse { - positionId: number; - investCoin: string; - exercisedCoin: string; - subscriptionAmount: string; - duration: number; - autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; - strikePrice: string; - settleDate: number; - purchaseStatus: string; - apr: string; - orderId: number; - purchaseTime: number; - optionType: string; -} -⋮---- -export interface GetDualInvestmentPositionsParams { - status?: - | 'PENDING' - | 'PURCHASE_SUCCESS' - | 'SETTLED' - | 'PURCHASE_FAIL' - | 'REFUNDING' - | 'REFUND_SUCCESS' - | 'SETTLING'; - pageSize?: number; - pageIndex?: number; -} -⋮---- -export interface DualInvestmentPosition { - id: string; - investCoin: string; - exercisedCoin: string; - subscriptionAmount: string; - strikePrice: string; - duration: number; - settleDate: number; - purchaseStatus: string; - apr: string; - orderId: number; - purchaseEndTime: number; - optionType: string; - autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; - settlePrice?: string; - isExercised?: boolean; - settleAsset?: string; - settleAmount?: string; - subscriptionTime?: number; -} -⋮---- -export interface CheckDualInvestmentAccountsResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; -} -⋮---- -/** - * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. - * Configure auto-compound for Dual Investment positions in the Binance web UI. - * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published - * binance-api-swagger spec still lists the endpoint, so this type stays deprecated. - */ -export interface ChangeAutoCompoundStatusParams { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} -⋮---- -export interface ChangeAutoCompoundStatusResponse { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} -⋮---- -export interface GetTargetAssetListParams { - targetAsset?: string; - size?: number; - current?: number; -} -⋮---- -export interface RoiAndDimensionType { - simulateRoi: string; - dimensionValue: string; - dimensionUnit: string; -} -⋮---- -export interface AutoInvestAsset { - targetAsset: string; - roiAndDimensionTypeList: RoiAndDimensionType[]; -} -⋮---- -export interface GetTargetAssetListResponse { - targetAssets: string[]; - autoInvestAssetList: AutoInvestAsset[]; -} -⋮---- -export interface GetTargetAssetROIParams { - targetAsset: string; - hisRoiType: - | 'FIVE_YEAR' - | 'THREE_YEAR' - | 'ONE_YEAR' - | 'SIX_MONTH' - | 'THREE_MONTH' - | 'SEVEN_DAY'; -} -⋮---- -export interface TargetAssetROI { - date: string; - simulateRoi: string; -} -⋮---- -export interface GetSourceAssetListParams { - targetAsset?: string[]; - indexId?: number; - usageType: 'RECURRING' | 'ONE_TIME'; - flexibleAllowedToUse?: boolean; - sourceType?: 'MAIN_SITE' | 'TR'; -} -⋮---- -export interface SourceAsset { - sourceAsset: string; - assetMinAmount: string; - assetMaxAmount: string; - scale: string; - flexibleAmount: string; -} -⋮---- -export interface GetSourceAssetListResponse { - feeRate: string; - taxRate: string; - sourceAssets: SourceAsset[]; -} -⋮---- -export interface AutoInvestPortfolioDetail { - targetAsset: string; - percentage: number; -} -⋮---- -export interface CreateInvestmentPlanParams { - UID: string; - sourceType: 'MAIN_SITE' | 'TR'; - requestId?: string; - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; - indexId?: number; - subscriptionAmount: number; - subscriptionCycle: - | 'H1' - | 'H4' - | 'H8' - | 'H12' - | 'WEEKLY' - | 'DAILY' - | 'MONTHLY' - | 'BI_WEEKLY'; - subscriptionStartDay?: number; - subscriptionStartWeekday?: - | 'MON' - | 'TUE' - | 'WED' - | 'THU' - | 'FRI' - | 'SAT' - | 'SUN'; - subscriptionStartTime: number; - sourceAsset: string; - flexibleAllowedToUse: boolean; - details: AutoInvestPortfolioDetail[]; -} -⋮---- -export interface CreateInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; -} -⋮---- -export interface EditInvestmentPlanParams { - planId: number; - subscriptionAmount: number; - subscriptionCycle: - | 'H1' - | 'H4' - | 'H8' - | 'H12' - | 'WEEKLY' - | 'DAILY' - | 'MONTHLY' - | 'BI_WEEKLY'; - subscriptionStartDay?: number; - subscriptionStartWeekday?: - | 'MON' - | 'TUE' - | 'WED' - | 'THU' - | 'FRI' - | 'SAT' - | 'SUN'; - subscriptionStartTime: number; - sourceAsset: string; - flexibleAllowedToUse?: boolean; - details: AutoInvestPortfolioDetail[]; -} -⋮---- -export interface EditInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; -} -⋮---- -export interface ChangePlanStatusParams { - planId: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; -} -⋮---- -export interface ChangePlanStatusResponse { - planId: number; - nextExecutionDateTime: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; -} -⋮---- -export interface GetPlanDetailsParams { - planId?: number; - requestId?: string; -} -⋮---- -export interface GetSubscriptionTransactionHistoryParams { - planId?: number; - startTime?: number; - endTime?: number; - targetAsset?: string; - planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; - size?: number; - current?: number; -} -⋮---- -export interface AssetAllocation { - targetAsset: string; - allocation: string; -} -⋮---- -export interface GetIndexDetailsResponse { - indexId: number; - indexName: string; - status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; - assetAllocation: AssetAllocation[]; -} -⋮---- -export interface IndexLinkedPlanDetail { - targetAsset: string; - averagePriceInUSD: string; - totalInvestedInUSD: string; - currentInvestedInUSD: string; - purchasedAmount: string; - pnlInUSD: string; - roi: string; - percentage: string; - availableAmount: string; - redeemedAmount: string; - assetValueInUSD: string; -} -⋮---- -export interface GetIndexLinkedPlanPositionDetailsResponse { - indexId: number; - totalInvestedInUSD: string; - currentInvestedInUSD: string; - pnlInUSD: string; - roi: string; - assetAllocation: { targetAsset: string; allocation: string }[]; - details: IndexLinkedPlanDetail[]; -} -⋮---- -export interface SubmitOneTimeTransactionParams { - sourceType: 'MAIN_SITE' | 'TR'; - requestId?: string; - subscriptionAmount: number; - sourceAsset: string; - flexibleAllowedToUse?: boolean; - planId?: number; - indexId?: number; - details: AutoInvestPortfolioDetail[]; -} -⋮---- -export interface SubmitOneTimeTransactionResponse { - transactionId: number; - waitSecond: number; -} -⋮---- -export interface GetOneTimeTransactionStatusParams { - transactionId: number; - requestId?: string; -} -⋮---- -export interface GetOneTimeTransactionStatusResponse { - transactionId: number; - status: 'SUCCESS' | 'CONVERTING'; -} -⋮---- -export interface SubmitIndexLinkedPlanRedemptionParams { - indexId: number; - requestId?: string; - redemptionPercentage: number; -} -⋮---- -export interface GetIndexLinkedPlanRedemptionHistoryParams { - requestId: number; - startTime?: number; - endTime?: number; - current?: number; - asset?: string; - size?: number; -} -⋮---- -export interface IndexLinkedPlanRedemptionRecord { - indexId: number; - indexName: string; - redemptionId: number; - status: 'SUCCESS' | 'FAILED'; - asset: string; - amount: string; - redemptionDateTime: number; - transactionFee: string; - transactionFeeUnit: string; -} -⋮---- -export interface GetIndexLinkedPlanRebalanceHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RebalanceTransactionDetail { - asset: string; - transactionDateTime: number; - rebalanceDirection: 'BUY' | 'SELL'; - rebalanceAmount: string; -} -⋮---- -export interface IndexLinkedPlanRebalanceRecord { - indexId: number; - indexName: string; - rebalanceId: number; - status: 'SUCCESS' | 'INIT'; - rebalanceFee: string; - rebalanceFeeUnit: string; - transactionDetails: RebalanceTransactionDetail[]; -} -⋮---- -export interface SubscribeEthStakingV2Response { - success: boolean; - wbethAmount: string; - conversionRatio: string; -} -⋮---- -export interface RedeemEthParams { - asset?: string; - amount: number; -} -⋮---- -export interface RedeemEthResponse { - success: boolean; - arrivalTime: number; - ethAmount: string; - conversionRatio: string; -} -⋮---- -export interface GetEthStakingHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface EthStakingHistory { - time: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAmount: string; - conversionRatio: string; -} -⋮---- -export interface GetEthRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface EthRedemptionHistory { - time: number; - arrivalTime: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAsset: string; - distributeAmount: string; - conversionRatio: string; -} -⋮---- -export interface GetBethRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BethRewardsHistory { - time: number; - asset: string; - holding: string; - amount: string; - annualPercentageRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; -} -⋮---- -export interface GetEthStakingQuotaResponse { - leftStakingPersonalQuota: string; - leftRedemptionPersonalQuota: string; -} -⋮---- -export interface GetETHRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface ETHRateHistory { - annualPercentageRate: string; - exchangeRate: string; - time: number; -} -⋮---- -export interface GetEthStakingAccountResponse { - cumulativeProfitInBETH: string; - lastDayProfitInBETH: string; -} -⋮---- -export interface GetEthStakingAccountV2Response { - holdingInETH: string; - holdings: { - wbethAmount: string; - bethAmount: string; - }; - thirtyDaysProfitInETH: string; - profit: { - amountFromWBETH: string; - amountFromBETH: string; - }; -} -⋮---- -export interface WrapBethResponse { - success: boolean; - wbethAmount: string; - exchangeRate: string; -} -⋮---- -export interface GetWrapHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface WrapHistory { - time: number; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - exchangeRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; -} -⋮---- -export interface WbethRewardsHistory { - time: number; - amountInETH: string; - holding: string; - holdingInETH: string; - annualPercentageRate: string; -} -⋮---- -export interface GetWbethRewardsHistoryResponse { - estRewardsInETH: string; - rows: WbethRewardsHistory[]; - total: number; -} -⋮---- -/** - * BFUSD (sapi/v1/bfusd/*) - */ -⋮---- -export interface BfusdAccountResponse { - bfusdAmount: string; - usdtProfit: string; - bfusdProfit: string; -} -⋮---- -export interface BfusdSubscriptionQuota { - leftQuota: string; -} -⋮---- -export interface BfusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; -} -⋮---- -export interface BfusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; -} -⋮---- -export interface BfusdQuotaResponse { - subscriptionQuota: BfusdSubscriptionQuota; - fastRedemptionQuota: BfusdFastRedemptionQuota; - standardRedemptionQuota: BfusdStandardRedemptionQuota; -} -⋮---- -export interface BfusdSubscribeParams { - asset: string; - amount: number; -} -⋮---- -export interface BfusdSubscribeResponse { - success: boolean; - bfusdAmount: string; -} -⋮---- -export interface BfusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; -} -⋮---- -export interface BfusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; -} -⋮---- -export interface GetBfusdSubscriptionHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BfusdSubscriptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetBfusdRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BfusdRedemptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetBfusdRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BfusdRewardsHistoryRow { - time: number; - rewardsAmount: string; - annualPercentageRate: string; - rewardAsset?: string; - /** API may return this casing per Binance docs. */ - BFUSDPosition?: string; -} -⋮---- -/** API may return this casing per Binance docs. */ -⋮---- -export interface GetBfusdRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface BfusdRateHistoryRow { - annualPercentageRate: string; - time: number; -} -⋮---- -/** - * RWUSD (sapi/v1/rwusd/*) - */ -⋮---- -export interface RwusdAccountResponse { - rwusdAmount: string; - totalProfit: string; -} -⋮---- -export interface RwusdSubscriptionQuota { - assets: string[]; - leftQuota: string; - minimum: string; -} -⋮---- -export interface RwusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; -} -⋮---- -export interface RwusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; -} -⋮---- -export interface RwusdQuotaResponse { - subscriptionQuota: RwusdSubscriptionQuota; - fastRedemptionQuota: RwusdFastRedemptionQuota; - standardRedemptionQuota: RwusdStandardRedemptionQuota; - subscribeEnable: boolean; - redeemEnable: boolean; -} -⋮---- -export interface RwusdSubscribeParams { - asset: string; - amount: number; -} -⋮---- -export interface RwusdSubscribeResponse { - success: boolean; - rwusdAmount: string; -} -⋮---- -export interface RwusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; -} -⋮---- -export interface RwusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; -} -⋮---- -export interface GetRwusdSubscriptionHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdSubscriptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetRwusdRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdRedemptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; -} -⋮---- -export interface GetRwusdRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdRewardsHistoryRow { - time: number; - rewardsAmount: string; - rwusdPosition: string; - annualPercentageRate: string; -} -⋮---- -export interface GetRwusdRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface RwusdRateHistoryRow { - annualPercentageRate: string; - time: number; -} -⋮---- -export interface GetMiningAlgoListResponse { - algoName: string; // Algorithm name - algoId: number; // Algorithm ID - poolIndex: number; // Sequence - unit: string; // Unit -} -⋮---- -algoName: string; // Algorithm name -algoId: number; // Algorithm ID -poolIndex: number; // Sequence -unit: string; // Unit -⋮---- -export interface GetMiningCoinListResponse { - coinName: string; // Coin name - coinId: number; // Coin ID - poolIndex: number; // Sequence - unit: string; // Unit -} -⋮---- -coinName: string; // Coin name -coinId: number; // Coin ID -poolIndex: number; // Sequence -unit: string; // Unit -⋮---- -export interface GetMinerDetailsParams { - algo: string; - userName: string; - workerName: string; -} -⋮---- -export interface HashrateData { - time: number; - hashrate: string; - reject: number; -} -⋮---- -export interface MinerDetail { - workerName: string; - type: string; - hashrateDatas: HashrateData[]; -} -⋮---- -export interface GetMinerDetailsResponse { - code: number; - msg: string; - data: MinerDetail[]; -} -⋮---- -export interface GetMinerListParams { - algo: string; - userName: string; - pageIndex?: number; - sort?: number; - sortColumn?: number; - workerStatus?: number; -} -⋮---- -export interface WorkerData { - workerId: string; - workerName: string; - status: number; - hashRate: number; - dayHashRate: number; - rejectRate: number; - lastShareTime: number; -} -⋮---- -export interface GetMinerListResponse { - code: number; - msg: string; - data: { - workerDatas: WorkerData[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetEarningsListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface AccountEarningsProfit { - time: number; - type: number; - hashTransfer: number | null; - transferAmount: number | null; - dayHashRate: number; - profitAmount: number; - coinName: string; - status: number; -} -⋮---- -export interface GetEarningsListResponse { - code: number; - msg: string; - data: { - accountProfits: AccountEarningsProfit[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetExtraBonusListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface OtherProfit { - time: number; - coinName: string; - type: number; - profitAmount: number; - status: number; -} -⋮---- -export interface GetExtraBonusListResponse { - code: number; - msg: string; - data: { - otherProfits: OtherProfit[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetHashrateResaleListParams { - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface ConfigDetail { - configId: number; - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - startDay: number; - endDay: number; - status: number; -} -⋮---- -export interface GetHashrateResaleListResponse { - code: number; - msg: string; - data: { - configDetails: ConfigDetail[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetHashrateResaleDetailParams { - configId: number; - userName: string; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface ProfitTransferDetail { - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - day: number; - amount: number; - coinName: string; -} -⋮---- -export interface GetHashrateResaleDetailResponse { - code: number; - msg: string; - data: { - profitTransferDetails: ProfitTransferDetail[]; - totalNum: number; - pageSize: number; - }; -} -export interface SubmitHashrateResaleParams { - userName: string; - algo: string; - endDate: number; - startDate: number; - toPoolUser: string; - hashRate: number; -} -⋮---- -export interface CancelHashrateResaleConfigParams { - configId: number; - userName: string; -} -⋮---- -export interface GetStatisticListParams { - algo: string; - userName: string; -} -⋮---- -export interface Profit { - BTC: string; - BSV: string; - BCH: string; -} -⋮---- -export interface GetStatisticListResponse { - code: number; - msg: string; - data: { - fifteenMinHashRate: string; - dayHashRate: string; - validNum: number; - invalidNum: number; - profitToday: Profit; - profitYesterday: Profit; - userName: string; - unit: string; - algo: string; - }; -} -⋮---- -export interface getMiningAccountsListParams { - algo: string; - userName: string; -} -⋮---- -export interface MiningHashrateData { - time: number; - hashrate: string; - reject: string; -} -⋮---- -export interface MiningAccountData { - type: string; - userName: string; - list: MiningHashrateData[]; -} -⋮---- -export interface getMiningAccountsListResponse { - code: number; - msg: string; - data: MiningAccountData[]; -} -⋮---- -export interface GetMiningAccountEarningParams { - algo: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} -⋮---- -export interface AccountMiningProfit { - time: number; - coinName: string; - type: number; - puid: number; - subName: string; - amount: number; -} -⋮---- -export interface GetMiningAccountEarningResponse { - code: number; - msg: string; - data: { - accountProfits: AccountMiningProfit[]; - totalNum: number; - pageSize: number; - }; -} -⋮---- -export interface GetFutureTickLevelOrderbookDataLinkParams { - symbol: string; - dataType: 'T_DEPTH' | 'S_DEPTH'; - startTime: number; - endTime: number; -} -⋮---- -export interface HistoricalDataLink { - day: string; - url: string; -} -⋮---- -export interface SubmitVpNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - quantity: number; - urgency: 'LOW' | 'MEDIUM' | 'HIGH'; - clientAlgoId?: string; - reduceOnly?: boolean; - limitPrice?: number; -} -⋮---- -export interface SubmitVpNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface SubmitTwapNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - quantity: number; - duration: number; - clientAlgoId?: string; - reduceOnly?: boolean; - limitPrice?: number; -} -⋮---- -export interface SubmitTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface CancelAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface AlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; -} -⋮---- -export interface GetAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; - startTime?: number; - endTime?: number; - page?: number; - pageSize?: number; -} -⋮---- -export interface HistoricalAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; -} -⋮---- -export interface GetAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: number; -} -⋮---- -export interface SubOrder { - algoId: number; - orderId: number; - orderStatus: string; - executedQty: string; - executedAmt: string; - feeAmt: string; - feeAsset: string; - bookTime: number; - avgPrice: string; - side: 'BUY' | 'SELL'; - symbol: string; - subId: number; - timeInForce: string; - origQty: string; -} -⋮---- -export interface GetAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SubOrder[]; -} -⋮---- -export interface SubmitSpotTwapNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: number; - duration: number; - clientAlgoId?: string; - limitPrice?: number; - stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; -} -⋮---- -export interface SubmitSpotTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface CancelSpotAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: string; -} -⋮---- -export interface SpotAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; - /** Order duration in seconds. Only returned for TWAP orders. */ - duration?: number; -} -⋮---- -/** Order duration in seconds. Only returned for TWAP orders. */ -⋮---- -export interface GetSpotAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; - startTime?: number; - endTime?: number; - page?: number; - pageSize?: number; -} -⋮---- -export interface HistoricalSpotAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; - /** Order duration in seconds. Only returned for TWAP orders. */ - duration?: number; -} -⋮---- -/** Order duration in seconds. Only returned for TWAP orders. */ -⋮---- -export interface GetSpotAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: number; -} -⋮---- -export interface SpotSubOrder { - algoId: number; - orderId: number; - orderStatus: string; - executedQty: string; - executedAmt: string; - feeAmt: string; - feeAsset: string; - bookTime: number; - avgPrice: string; - side: 'BUY' | 'SELL'; - symbol: string; - subId: number; - timeInForce: string; - origQty: string; -} -⋮---- -export interface GetSpotAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SpotSubOrder[]; -} -⋮---- -export interface GetPortfolioMarginProAccountInfoResponse { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - accountStatus: string; - accountType: string; -} -⋮---- -export interface PortfolioDeltaModeStatus { - deltaEnabled: boolean; -} -⋮---- -export interface SwitchPortfolioDeltaModeParams { - deltaEnabled: 'true' | 'false'; -} -⋮---- -export interface GetPortfolioMarginProCollateralRateResponse { - asset: string; - collateralRate: string; -} -⋮---- -export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { - asset: string; - amount: string; -} -⋮---- -export interface GetPortfolioMarginProInterestHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; -} -⋮---- -export interface GetPortfolioMarginProInterestHistoryResponse { - asset: string; - interest: string; - interestAccruedTime: number; - interestRate: string; - principal: string; -} -⋮---- -export interface GetPortfolioMarginAssetIndexPriceResponse { - asset: string; - assetIndexPrice: string; - time: number; -} -⋮---- -export interface BnbTransferParams { - amount: number; - transferSide: 'TO_UM' | 'FROM_UM'; -} -⋮---- -export interface GetPortfolioMarginAssetLeverageResponse { - asset: string; - leverage: number; -} -⋮---- -export interface SetPortfolioMarginMarginCallLevelParams { - marginCallLevel: number; -} -⋮---- -export interface PortfolioMarginMarginCallLevelResponse { - marginCallLevel: string; -} -⋮---- -export type PortfolioMarginMarginCallLevelGetResponse = - | PortfolioMarginMarginCallLevelResponse - | Record; -⋮---- -export interface PortfolioMarginMarginCallLevelDeleteResponse { - msg: string; -} -⋮---- -export interface SubscribeBlvtParams { - tokenName: string; - cost: number; -} -⋮---- -export interface SubscribeBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - amount: string; - cost: string; - timestamp: number; -} -⋮---- -export interface GetBlvtSubscriptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface BlvtSubscriptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; - fee: string; - totalCharge: string; - timestamp: number; -} -⋮---- -export interface RedeemBlvtParams { - tokenName: string; - amount: number; -} -⋮---- -export interface RedeemBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - redeemAmount: string; - amount: string; - timestamp: number; -} -⋮---- -export interface GetBlvtRedemptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface BlvtRedemptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; - fee: string; - netProceed: string; - timestamp: number; -} -⋮---- -export interface BlvtUserLimitInfo { - tokenName: string; - userDailyTotalPurchaseLimit: string; - userDailyTotalRedeemLimit: string; -} -⋮---- -export interface GetFiatOrderHistoryParams { - transactionType: string; - beginTime?: number; - endTime?: number; - page?: number; - rows?: number; -} -⋮---- -export interface GetFiatOrderHistoryResponse { - code: string; - message: string; - data: { - orderNo: string; - fiatCurrency: string; - indicatedAmount: string; - amount: string; - totalFee: string; - method: string; - status: string; - createTime: number; - updateTime: number; - }[]; - total: number; - success: boolean; -} -⋮---- -export interface GetFiatPaymentsHistoryResponse { - code: string; - message: string; - data: { - orderNo: string; - sourceAmount: string; - fiatCurrency: string; - obtainAmount: string; - cryptoCurrency: string; - totalFee: string; - price: string; - status: string; - paymentMethod?: string; - createTime: number; - updateTime: number; - }[]; - total: number; - success: boolean; -} -⋮---- -export interface WithdrawFiatAccountInfo { - accountNumber: string; - agency: string; - bankCodeForPix: string; - accountType: string; -} -⋮---- -export interface WithdrawFiatParams { - currency: string; - apiPaymentMethod: string; - amount: number; - accountInfo?: WithdrawFiatAccountInfo; -} -⋮---- -export interface FiatDepositParams { - currency: string; - apiPaymentMethod: string; - amount: number; - ext?: object; - recvWindow?: number; - timestamp?: number; -} -⋮---- -export interface FiatDepositResponse { - code: string; - message: string; - data: { - orderId: string; - }; -} -⋮---- -export interface GetFiatOrderDetailParams { - orderNo: string; - recvWindow?: number; - timestamp?: number; -} -⋮---- -export interface GetFiatOrderDetailResponse { - code: string; - message: string; - data: { - orderId: string; - orderStatus: string; - amount: string; - fee: string; - fiatCurrency: string; - errorCode: string; - errorMessage: string; - ext: object; - }; -} -⋮---- -export interface GetC2CTradeHistoryParams { - tradeType: string; - startTimestamp?: number; - endTimestamp?: number; - page?: number; - rows?: number; -} -⋮---- -export interface c2cTradeData { - orderNumber: string; - advNo: string; - tradeType: string; - asset: string; - fiat: string; - fiatSymbol: string; - amount: string; - totalPrice: string; - unitPrice: string; - orderStatus: string; - createTime: number; - commission: string; - counterPartNickName: string; - advertisementRole: string; -} -export interface GetC2CTradeHistoryResponse { - code: string; - message: string; - data: c2cTradeData[]; - total: number; - success: boolean; -} -⋮---- -export interface GetVipLoanOngoingOrdersParams { - orderId?: number; - collateralAccountId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} -⋮---- -export interface VipOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - loanRate: string; - residualInterest: string; - collateralAccountId: string; - collateralCoin: string; - totalCollateralValueAfterHaircut: string; - lockedCollateralValue: string; - currentLTV: string; - expirationTime: number; - loanDate: string; - loanTerm: string; - initialLtv: string; - marginCallLtv: string; - liquidationLtv: string; -} -⋮---- -export interface VipLoanRepayParams { - orderId: number; - amount: number; -} -⋮---- -export interface VipLoanRepayResponse { - loanCoin: string; - repayAmount: string; - remainingPrincipal: string; - remainingInterest: string; - collateralCoin: string; - currentLTV: string; - repayStatus: string; -} -⋮---- -export interface GetVipLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface VipLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - repayInterest: string; - repayPrincipal: string; - collateralCoin: string; - repayStatus: string; - loanDate: string; - repayTime: string; - orderId: string; -} -⋮---- -export interface VipLoanRenewParams { - orderId: number; - loanTerm?: number; -} -⋮---- -export interface VipLoanRenewResponse { - loanAccountId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; -} -⋮---- -export interface CheckVipCollateralAccountParams { - orderId?: number; - collateralAccountId?: number; -} -⋮---- -export interface VipCollateralAccount { - collateralAccountId: string; - collateralCoin: string; -} -⋮---- -export interface VipLoanBorrowParams { - loanAccountId: number; - loanCoin: string; - loanAmount: number; - collateralAccountId: string; - collateralCoin: string; - isFlexibleRate: boolean; - loanTerm?: number; -} -⋮---- -export interface VipLoanBorrowResponse { - loanAccountId: string; - requestId: string; - loanCoin: string; - isFlexibleRate: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm?: string; -} -⋮---- -export interface GetLoanableAssetsDataParams { - loanCoin?: string; - vipLevel?: number; -} -⋮---- -export interface GetApplicationStatusParams { - current?: number; - limit?: number; -} -⋮---- -export interface ApplicationStatus { - loanAccountId: string; - orderId: string; - requestId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; - status: string; - loanDate: string; -} -⋮---- -export interface BorrowInterestRate { - asset: string; - flexibleDailyInterestRate: string; - flexibleYearlyInterestRate: string; - time: number; -} -⋮---- -export interface GetCryptoLoansIncomeHistoryParams { - asset?: string; - type?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetCryptoLoansIncomeHistoryResponse { - asset: string; - type: string; - amount: string; - timestamp: number; - tranId: string; -} -⋮---- -export interface BorrowCryptoLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; - loanTerm: number; -} -⋮---- -export interface BorrowCryptoLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - hourlyInterestRate: string; - orderId: string; -} -⋮---- -export interface GetLoanBorrowHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface LoanBorrowHistory { - orderId: number; - loanCoin: string; - initialLoanAmount: string; - hourlyInterestRate: string; - loanTerm: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: string; -} -⋮---- -export interface GetLoanOngoingOrdersParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} -⋮---- -export interface LoanOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - residualInterest: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; - expirationTime: number; -} -⋮---- -export interface RepayCryptoLoanParams { - orderId: number; - amount: number; - type?: number; - collateralReturn?: boolean; -} -⋮---- -export interface RepayCryptoLoanResponse { - loanCoin: string; - remainingPrincipal?: string; - remainingInterest?: string; - collateralCoin: string; - remainingCollateral?: string; - currentLTV?: string; - repayStatus: string; -} -⋮---- -export interface GetLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface LoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralUsed: string; - collateralReturn: string; - repayType: string; - repayStatus: string; - repayTime: number; - orderId: number; -} -⋮---- -export interface AdjustCryptoLoanLTVParams { - orderId: number; - amount: number; - direction: 'ADDITIONAL' | 'REDUCED'; -} -⋮---- -export interface AdjustCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - currentLTV: string; -} -⋮---- -export interface GetLoanLTVAdjustmentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface LoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; - orderId: number; -} -⋮---- -export interface LoanableAssetData { - loanCoin: string; - _7dHourlyInterestRate: string; - _7dDailyInterestRate: string; - _14dHourlyInterestRate: string; - _14dDailyInterestRate: string; - _30dHourlyInterestRate: string; - _30dDailyInterestRate: string; - _90dHourlyInterestRate: string; - _90dDailyInterestRate: string; - _180dHourlyInterestRate: string; - _180dDailyInterestRate: string; - minLimit: string; - maxLimit: string; - vipLevel: number; -} -⋮---- -export interface GetCollateralAssetDataParams { - collateralCoin?: string; - vipLevel?: number; -} -⋮---- -export interface CollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; - vipLevel: number; -} -⋮---- -export interface CheckCollateralRepayRateParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; -} -⋮---- -export interface CheckCollateralRepayRateResponse { - loanCoin: string; - collateralCoin: string; - repayAmount: string; - rate: string; -} -⋮---- -export interface CustomizeMarginCallParams { - orderId?: number; - collateralCoin?: string; - marginCall: number; -} -⋮---- -export interface CustomizeMarginCall { - orderId: string; - collateralCoin: string; - preMarginCall: string; - afterMarginCall: string; - customizeTime: number; -} -⋮---- -export interface BorrowFlexibleLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; -} -⋮---- -export interface BorrowFlexibleLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - status: 'Succeeds' | 'Failed' | 'Processing'; -} -⋮---- -export interface GetFlexibleLoanOngoingOrdersParams { - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleLoanOngoingOrder { - loanCoin: string; - totalDebt: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; -} -⋮---- -export interface GetFlexibleLoanLiquidationHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; // Default: 1, max: 1000 - limit?: number; // Default: 10, max: 100 - recvWindow?: number; -} -⋮---- -current?: number; // Default: 1, max: 1000 -limit?: number; // Default: 10, max: 100 -⋮---- -export interface FlexibleLoanLiquidationHistoryRecord { - loanCoin: string; - liquidationDebt: string; - collateralCoin: string; - liquidationCollateralAmount: string; - returnCollateralAmount: string; - liquidationFee: string; - liquidationStartingPrice: string; - liquidationStartingTime: number; - status: 'Liquidated' | 'Liquidating'; -} -⋮---- -export interface GetFlexibleCryptoLoanBorrowHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleCryptoLoanBorrowHistory { - loanCoin: string; - initialLoanAmount: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: 'Succeeds' | 'Failed' | 'Processing'; -} -⋮---- -export interface RepayCryptoFlexibleLoanParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; - collateralReturn?: boolean; - fullRepayment?: boolean; -} -⋮---- -export interface RepayCryptoFlexibleLoanResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; -} -⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; // Amount of loan to repay - fullRepayment?: boolean; // Default: FALSE -} -⋮---- -repayAmount: number; // Amount of loan to repay -fullRepayment?: boolean; // Default: FALSE -⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; -} -export interface GetFlexibleCryptoLoanRepaymentHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleCryptoLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralReturn: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; - repayTime: number; -} -⋮---- -export interface AdjustFlexibleCryptoLoanLTVParams { - loanCoin: string; - collateralCoin: string; - adjustmentAmount: number; - direction: 'ADDITIONAL' | 'REDUCED'; -} -⋮---- -export interface AdjustFlexibleCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - adjustmentAmount: string; - currentLTV: string; -} -⋮---- -export interface GetFlexibleLoanLTVAdjustmentHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface FlexibleLoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - collateralAmount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; -} -⋮---- -export interface FlexibleLoanAssetData { - loanCoin: string; - flexibleInterestRate: string; - flexibleMinLimit: string; - flexibleMaxLimit: string; -} -⋮---- -export interface FlexibleLoanCollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; -} -⋮---- -export interface GetFuturesLeadTraderStatusResponse { - code: string; - message: string; - data: { - isLeadTrader: boolean; - time: number; - }; - success: boolean; -} -⋮---- -export interface GetFuturesLeadTradingSymbolWhitelistResponse { - code: string; - message: string; - data: { - symbol: string; - baseAsset: string; - quoteAsset: string; - }[]; -} -⋮---- -export interface GetPayTradeHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface GetAllConvertPairsParams { - fromAsset?: string; - toAsset?: string; -} -⋮---- -export interface SubmitConvertLimitOrderParams { - baseAsset: string; - quoteAsset: string; - limitPrice: number; - baseAmount?: number; - quoteAmount?: number; - side: 'BUY' | 'SELL'; - walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; - expiredType: '1_D' | '3_D' | '7_D' | '30_D'; -} -⋮---- -export interface ConvertLimitOpenOrder { - quoteId: string; - orderId: number; - orderStatus: string; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - ratio: string; - inverseRatio: string; - createTime: number; - expiredTimestamp: number; -} -⋮---- -export interface GetSpotRebateHistoryRecordsParams { - startTime?: number; - endTime?: number; - page?: number; -} -⋮---- -export interface SpotRebateHistoryRecord { - asset: string; - type: number; - amount: string; - updateTime: number; -} -⋮---- -export interface GetSpotRebateHistoryRecordsResponse { - status: string; - type: string; - code: string; - data: { - page: number; - totalRecords: number; - totalPageNum: number; - data: SpotRebateHistoryRecord[]; - }; -} -⋮---- -export interface GetNftTransactionHistoryParams { - orderType: number; - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} -⋮---- -export interface NftToken { - network: string; - tokenId: string; - contractAddress: string; -} -⋮---- -export interface NftTransaction { - orderNo: string; - tokens: NftToken[]; - tradeTime: number; - tradeAmount: string; - tradeCurrency: string; -} -⋮---- -export interface GetNftDepositHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} -⋮---- -export interface NftDeposit { - network: string; - txID: string | null; - contractAdrress: string; - tokenId: string; - timestamp: number; -} -⋮---- -export interface GetNftWithdrawHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} -⋮---- -export interface NftWithdraw { - network: string; - txID: string; - contractAdrress: string; - tokenId: string; - timestamp: number; - fee: number; - feeAsset: string; -} -⋮---- -export interface GetNftAssetParams { - limit?: number; - page?: number; -} -⋮---- -export interface NftAsset { - network: string; - contractAddress: string; - tokenId: string; -} -⋮---- -export interface CreateGiftCardParams { - token: string; - amount: number; -} -⋮---- -export interface CreateDualTokenGiftCardParams { - baseToken: string; - faceToken: string; - baseTokenAmount: number; - discount?: number; -} -⋮---- -export interface RedeemGiftCardParams { - code: string; - externalUid?: string; -} -⋮---- -export interface SimpleEarnProductListParams { - asset?: string; - current?: number; - size?: number; -} -⋮---- -export interface SimpleEarnFlexibleProduct { - asset: string; - latestAnnualInterestRate: string; - tierAnnualPercentageRate: Record; - airDropPercentageRate: string; - canPurchase: boolean; - canRedeem: boolean; - isSoldOut: boolean; - hot: boolean; - minPurchaseAmount: string; - productId: string; - subscriptionStartTime: number; - status: string; -} -⋮---- -export interface SimpleEarnLockedProduct { - projectId: string; - detail: { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: string; - subscriptionStartTime: number; - extraRewardAsset: string; - extraRewardAPR: string; - boostRewardAsset: string; - boostApr: string; - boostEndTime: string; - }; - quota: { - totalPersonalQuota: string; - minimum: string; - }; -} -⋮---- -export interface SimpleEarnSubscribeProductParams { - productId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; -} -⋮---- -export interface SimpleEarnSubscribeFlexibleProductResponse { - purchaseId: string; - success: boolean; -} -⋮---- -export interface SimpleEarnSubscribeLockedProductResponse { - purchaseId: string; - positionId: string; - success: boolean; -} -⋮---- -export interface SimpleEarnRedeemFlexibleProductParams { - productId: string; - redeemAll?: boolean; - amount?: number; - destAccount?: 'SPOT' | 'FUND'; -} -⋮---- -export interface SimpleEarnRedeemResponse { - success: boolean; - redeemId: string; -} -⋮---- -export interface SimpleEarnFlexibleProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; -} -⋮---- -export interface SimpleEarnLockedProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; - positionId?: string; -} -⋮---- -export interface SimpleEarnLockedProductPosition { - positionId: string; - projectId: string; - asset: string; - amount: string; - purchaseTime: string; - duration: string; - accrualDays: string; - rewardAsset: string; - APY: string; - isRenewable: boolean; - isAutoRenew: boolean; - redeemDate: string; - boostRewardAsset: string; - boostApr: string; - totalBoostRewardAmt: string; -} -⋮---- -export interface SimpleEarnAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedinBTC: string; - totalLockedinUSDT: string; -} -⋮---- -export interface GetSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface SubAccountDeposit { - depositId: number; - subAccountId: string; - address: string; - addressTag: string; - amount: string; - coin: string; - insertTime: number; - transferType: number; - network: string; - status: number; - txId: string; - sourceAddress: string; - confirmTimes: string; - selfReturnStatus: number; -} -⋮---- -// Request interface for querying sub account spot asset info -export interface QuerySubAccountSpotMarginAssetInfoParams { - subAccountId?: string; - page?: number; - size?: number; -} -⋮---- -export interface SubaccountBrokerSpotAsset { - subAccountId: string; - totalBalanceOfBtc: string; -} -⋮---- -export interface SubAccountBrokerMarginAsset { - marginEnable: boolean; - subAccountId: string; - totalAssetOfBtc?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - marginLevel?: string; -} -⋮---- -// Request interface for querying sub account futures asset info -export interface QuerySubAccountFuturesAssetInfoParams { - subAccountId?: string; - futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures - page?: number; - size?: number; -} -⋮---- -futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures -⋮---- -// Response interface for querying sub account futures asset info (USD Margined Futures) -export interface UsdtMarginedFuturesResponse { - subAccountId: string; - totalInitialMargin: string; - totalMaintenanceMargin: string; - totalWalletBalance: string; - totalUnrealizedProfit: string; - totalMarginBalance: string; - totalPositionInitialMargin: string; - totalOpenOrderInitialMargin: string; - futuresEnable: boolean; - asset: string; -} -⋮---- -// Response interface for querying sub account futures asset info (COIN Margined Futures) -export interface CoinMarginedFuturesResponse { - subAccountId: string; - totalWalletBalanceOfUsdt: string; - totalUnrealizedProfitOfUsdt: string; - totalMarginBalanceOfUsdt: string; - futuresEnable: boolean; -} -⋮---- -// Combined response interface for querying sub account futures asset info -export interface BrokerFuturesSubAccountAssets { - data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; - timestamp: number; -} -⋮---- -export interface BrokerUniversalTransfer { - toId: string; - asset: string; - qty: string; - time: number; - status: string; - txnId: string; - clientTranId: string; - fromAccountType: string; - toAccountType: string; -} -⋮---- -// Request interface for changing sub account commission -export interface ChangeSubAccountCommissionParams { - subAccountId: string; - makerCommission: number; - takerCommission: number; - marginMakerCommission?: number; - marginTakerCommission?: number; -} -⋮---- -// Response interface for changing sub account commission -export interface ChangeSubAccountCommissionResponse { - subAccountId: string; - makerCommission: number; - takerCommission: number; - marginMakerCommission: number; - marginTakerCommission: number; -} -⋮---- -// Request interface for changing sub account USDT-Ⓜ futures commission adjustment -export interface ChangeSubAccountFuturesCommissionParams { - subAccountId: string; - symbol: string; - makerAdjustment: number; - takerAdjustment: number; -} -⋮---- -// Response interface for changing sub account USDT-Ⓜ futures commission adjustment -export interface ChangeSubAccountFuturesCommissionResponse { - subAccountId: string; - symbol: string; - makerAdjustment: number; - takerAdjustment: number; - makerCommission: number; - takerCommission: number; -} -⋮---- -// Request interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface QuerySubAccountFuturesCommissionParams { - subAccountId: string; - symbol?: string; -} -⋮---- -// Response interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface BrokerSubAccountFuturesCommission { - subAccountId: string; - symbol: string; - makerCommission: number; - takerCommission: number; -} -⋮---- -export interface ChangeSubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair: string; - makerAdjustment: number; - takerAdjustment: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface QuerySubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -// Response interface for querying sub account COIN-Ⓜ futures commission adjustment -export interface BrokerSubAccountCoinFuturesCommission { - subAccountId: string; - pair: string; - makerCommission: number; - takerCommission: number; -} -⋮---- -export interface QueryBrokerSpotCommissionRebateParams { - subAccountId?: string; - startTime?: number; - endTime?: number; - page?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -// Response interface for querying spot commission rebate recent record -export interface BrokerCommissionRebate { - subaccountId: string; - income: string; - asset: string; - symbol: string; - tradeId: number; - time: number; - status: number; -} -⋮---- -export interface QueryBrokerFuturesCommissionRebateParams { - futuresType: number; // 1: USDT Futures, 2: Coin Futures - startTime: number; - endTime: number; - page?: number; - size?: number; - filterResult?: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -futuresType: number; // 1: USDT Futures, 2: Coin Futures -⋮---- -export interface SubmitMarginOTOOrderParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - sideEffectType?: SideEffects; - selfTradePreventionMode?: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - autoRepayAtCancel?: boolean; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: number; - workingQuantity: number; - workingIcebergQty?: number; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingType: OrderType; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: number; - pendingStopPrice?: number; - pendingTrailingDelta?: number; - pendingQuantity: number; - pendingIcebergQty?: number; - pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; -} -⋮---- -export interface MarginOTOOrder { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - selfTradePreventionMode: string; - }[]; -} -⋮---- -export interface SubmitMarginOTOCOOrderParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - sideEffectType?: SideEffects; - autoRepayAtCancel?: boolean; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: string; - pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; -} -⋮---- -export interface QueryMarginOpenOTOOrderListsParams { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; -} -⋮---- -export interface MarginOpenOTOOrderList { - orderListId: number; - contingencyType: 'OTO' | 'OTOCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; -} -⋮---- -export interface MarginOTOCOOrder { - orderListId: number; - contingencyType: 'OTO' | 'OTOCO'; - listStatusType: 'EXEC_STARTED'; - listOrderStatus: 'EXECUTING'; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: - | 'NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED' - | 'PENDING_NEW'; - timeInForce: 'GTC' | 'IOC' | 'FOK'; - type: - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - side: 'BUY' | 'SELL'; - stopPrice?: string; - selfTradePreventionMode: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - }[]; -} -⋮---- -export interface CreateSpecialLowLatencyKeyParams { - apiName: string; - symbol?: string; - ip?: string; - publicKey?: string; -} -⋮---- -export interface SpecialLowLatencyKeyResponse { - apiKey: string; - secretKey: string | null; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; -} -⋮---- -export interface SpecialLowLatencyKeyInfo { - apiName: string; - apiKey: string; - ip: string; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; -} -⋮---- -export interface MarginLiquidationLoan { - asset: string; - amount: string; - repaidAmount: string; - remainingAmount: string; -} -⋮---- -export interface RepayMarginLiquidationLoanParams { - asset: string; - amount: string; -} -⋮---- -export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; -⋮---- -export interface MarginLiquidationLoanRepayResponse { - repayId: number; - asset: string; - amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; -} -⋮---- -export interface GetMarginLiquidationLoanRepayHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface MarginLiquidationLoanRepayHistoryRecord { - repayId: number; - asset: string; - amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; -} -⋮---- -export interface MarginLiquidationLoanRepayHistoryResponse { - total: number; - rows: MarginLiquidationLoanRepayHistoryRecord[]; -} -⋮---- -export interface SolStakingAccount { - bnsolAmount: string; // Amount in bNSOL - holdingInSOL: string; // Holding in SOL - thirtyDaysProfitInSOL: string; // 30 days profit in SOL -} -⋮---- -bnsolAmount: string; // Amount in bNSOL -holdingInSOL: string; // Holding in SOL -thirtyDaysProfitInSOL: string; // 30 days profit in SOL -⋮---- -export interface SolStakingQuota { - leftStakingPersonalQuota: string; // Remaining personal staking quota - leftRedemptionPersonalQuota: string; // Remaining personal redemption quota - minStakeAmount: string; // Minimum stake amount - minRedeemAmount: string; // Minimum redeem amount - redeemPeriod: number; // Redemption period in days - stakeable: boolean; // Whether staking is possible - redeemable: boolean; // Whether redemption is possible - soldOut: boolean; // Whether the staking is sold out - commissionFee: string; // Commission fee - nextEpochTime: number; // Time for the next epoch - calculating: boolean; // Whether calculations are ongoing -} -⋮---- -leftStakingPersonalQuota: string; // Remaining personal staking quota -leftRedemptionPersonalQuota: string; // Remaining personal redemption quota -minStakeAmount: string; // Minimum stake amount -minRedeemAmount: string; // Minimum redeem amount -redeemPeriod: number; // Redemption period in days -stakeable: boolean; // Whether staking is possible -redeemable: boolean; // Whether redemption is possible -soldOut: boolean; // Whether the staking is sold out -commissionFee: string; // Commission fee -nextEpochTime: number; // Time for the next epoch -calculating: boolean; // Whether calculations are ongoing -⋮---- -export interface SubscribeSolStakingResponse { - success: boolean; // Indicates if the subscription was successful - bnsolAmount: string; // Amount in bNSOL received - exchangeRate: string; // SOL amount per 1 BNSOL -} -⋮---- -success: boolean; // Indicates if the subscription was successful -bnsolAmount: string; // Amount in bNSOL received -exchangeRate: string; // SOL amount per 1 BNSOL -⋮---- -export interface RedeemSolResponse { - success: boolean; // Indicates if the redemption was successful - solAmount: string; // Amount in SOL received - exchangeRate: string; // SOL amount per 1 BNSOL - arrivalTime: number; // Time of arrival for the redeemed SOL -} -⋮---- -success: boolean; // Indicates if the redemption was successful -solAmount: string; // Amount in SOL received -exchangeRate: string; // SOL amount per 1 BNSOL -arrivalTime: number; // Time of arrival for the redeemed SOL -⋮---- -export interface GetSolStakingHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} -⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory -⋮---- -export interface SolStakingHistoryRecord { - time: number; // Time of the staking event - asset: string; // Asset involved, e.g., SOL - amount: string; // Amount staked - distributeAsset: string; // Asset distributed, e.g., BNSOL - distributeAmount: string; // Amount distributed - exchangeRate: string; // Exchange rate at the time - status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event -} -⋮---- -time: number; // Time of the staking event -asset: string; // Asset involved, e.g., SOL -amount: string; // Amount staked -distributeAsset: string; // Asset distributed, e.g., BNSOL -distributeAmount: string; // Amount distributed -exchangeRate: string; // Exchange rate at the time -status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event -⋮---- -export interface GetSolRedemptionHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} -⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory -⋮---- -export interface SolRedemptionHistoryRecord { - time: number; // Time of the redemption event - arrivalTime: number; // Time of arrival for the redeemed SOL - asset: string; // Asset redeemed, e.g., BNSOL - amount: string; // Amount redeemed - distributeAsset: string; // Asset distributed, e.g., SOL - distributeAmount: string; // Amount distributed - exchangeRate: string; // Exchange rate at the time - status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event -} -⋮---- -time: number; // Time of the redemption event -arrivalTime: number; // Time of arrival for the redeemed SOL -asset: string; // Asset redeemed, e.g., BNSOL -amount: string; // Amount redeemed -distributeAsset: string; // Asset distributed, e.g., SOL -distributeAmount: string; // Amount distributed -exchangeRate: string; // Exchange rate at the time -status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event -⋮---- -export interface GetBnsolRewardsHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} -⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory -⋮---- -export interface BnsolRewardHistoryRecord { - time: number; // Time of the reward event - amountInSOL: string; // Reward amount in SOL - holding: string; // BNSOL holding balance - holdingInSOL: string; // BNSOL holding balance in SOL - annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) -} -⋮---- -time: number; // Time of the reward event -amountInSOL: string; // Reward amount in SOL -holding: string; // BNSOL holding balance -holdingInSOL: string; // BNSOL holding balance in SOL -annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) -⋮---- -export interface GetBnsolRateHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} -⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory -⋮---- -export interface SolBoostRewardsHistoryReq { - type: 'CLAIM' | 'DISTRIBUTE'; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface SolBoostRewardsHistoryRecord { - time: number; - token: string; - amount: string; - bnsolHolding?: string; // Only present if type is "DISTRIBUTE" - status?: string; // Only present if type is "CLAIM" -} -⋮---- -bnsolHolding?: string; // Only present if type is "DISTRIBUTE" -status?: string; // Only present if type is "CLAIM" -⋮---- -export interface BnsolRateHistoryRecord { - annualPercentageRate: string; // BNSOL APR - exchangeRate: string; // SOL amount per 1 BNSOL - time: number; // Time of the rate record -} -⋮---- -annualPercentageRate: string; // BNSOL APR -exchangeRate: string; // SOL amount per 1 BNSOL -time: number; // Time of the rate record -⋮---- -export interface RiskUnitMM { - asset: string; - uniMaintainUsd: string; -} -⋮---- -export interface PortfolioMarginProSpanAccountInfo { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - riskUnitMMList: RiskUnitMM[]; - marginMM: string; - otherMM: string; - accountStatus: - | 'NORMAL' - | 'MARGIN_CALL' - | 'SUPPLY_MARGIN' - | 'REDUCE_ONLY' - | 'ACTIVE_LIQUIDATION' - | 'FORCE_LIQUIDATION' - | 'BANKRUPTED'; - accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) -} -⋮---- -accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) -⋮---- -export interface PortfolioMarginProAccountBalance { - asset: string; - totalWalletBalance: string; - crossMarginAsset: string; - crossMarginBorrowed: string; - crossMarginFree: string; - crossMarginInterest: string; - crossMarginLocked: string; - umWalletBalance: string; - umUnrealizedPNL: string; - cmWalletBalance: string; - cmUnrealizedPNL: string; - updateTime: number; - negativeBalance: string; - optionWalletBalance: string; // only for PM PRO SPAN - optionEquity: string; // only for PM PRO SPAN -} -⋮---- -optionWalletBalance: string; // only for PM PRO SPAN -optionEquity: string; // only for PM PRO SPAN -⋮---- -export interface PMProMintBFUSDParams { - fromAsset: string; // USDT only - targetAsset: string; // BFUSD only - amount: number; -} -⋮---- -fromAsset: string; // USDT only -targetAsset: string; // BFUSD only -⋮---- -export interface PMProMintBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; -} -⋮---- -export interface PMProRedeemBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; -} -⋮---- -export interface PMProBankruptcyLoanRepaymentHistory { - asset: string; - amount: string; - repayTime: number; -} -⋮---- -export interface VipLoanInterestRateHistoryParams { - coin: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface VipLoanInterestRateRecord { - coin: string; - annualizedInterestRate: string; - time: number; -} -⋮---- -export interface VipLoanAccruedInterestParams { - orderId?: number; - loanCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} -⋮---- -export interface VipLoanAccruedInterestRecord { - loanCoin: string; - principalAmount: string; - interestAmount: string; - annualInterestRate: string; - accrualTime: number; - orderId: number; -} -⋮---- -export interface WithdrawTravelRuleParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; - questionnaire: string; -} -⋮---- -export interface GetTravelRuleWithdrawHistoryParams { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface GetTravelRuleWithdrawHistoryV2Params { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface SubmitTravelRuleDepositQuestionnaireParams { - tranId: number; - questionnaire: string; -} -⋮---- -export interface GetTravelRuleDepositHistoryParams { - trId?: string; - txId?: string; - tranId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - pendingQuestionnaire?: boolean; - startTime?: number; - endTime?: number; - offset?: number; - limit?: number; -} -⋮---- -export interface TravelRuleWithdrawHistoryRecord { - id: string; - trId: number; - amount: string; - transactionFee: string; - coin: string; - withdrawalStatus: number; - travelRuleStatus: number; - address: string; - addressTag?: string; - txId: string; - applyTime: string; - network?: string; - transferType: number; - withdrawOrderId?: string; - info: string; - confirmNo: number; - walletType: number; - txKey: string; - questionnaire: string; - completeTime?: string; -} -⋮---- -export interface SubmitTravelRuleDepositQuestionnaireResponse { - trId: number; - accepted: boolean; - info: string; -} -⋮---- -export interface TravelRuleDepositHistoryRecord { - trId: number; - tranId: number; - amount: string; - coin: string; - network: string; - depositStatus: number; - travelRuleStatus: number; - address: string; - addressTag?: string; - txId: string; - insertTime: number; - transferType: number; - confirmTimes: string; - unlockConfirm: number; - walletType: number; - requireQuestionnaire: boolean; - questionnaire: string | null; -} -⋮---- -export interface VASPInfo { - vaspName: string; - vaspCode?: string; - /** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ - identifier?: string; -} -⋮---- -/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ -⋮---- -export interface TravelRuleCountryInfo { - countryCode: string; - countryName: string; - blockType: 'supported' | 'limited' | 'blocked'; - depositAllowed: boolean; - withdrawalAllowed: boolean; - hasRegionRestrictions: boolean; -} -⋮---- -export interface TravelRuleCountryListResponse { - countries: TravelRuleCountryInfo[]; - lastUpdated: number; -} -⋮---- -export interface GetTravelRuleRegionListParams { - countryCode: string; -} -⋮---- -export interface TravelRuleRegionInfo { - regionName: string; - blockType: 'supported' | 'limited' | 'blocked'; - depositAllowed: boolean; - withdrawalAllowed: boolean; -} -⋮---- -export interface TravelRuleRegionListResponse { - countryCode: string; - regions: TravelRuleRegionInfo[]; - lastUpdated: number; -} -⋮---- -export interface GetVipLoanFixedRateMarketParams { - loanCoin: string; - duration?: number; - current?: number; - size?: number; -} -⋮---- -export interface VipLoanFixedRateMarketRecord { - requestId: number; - requestNo: number; - coin: string; - interestRate: numberInString; - duration: number; - minimumAmount: numberInString; - availableAmount: numberInString; - estimatedInterest: numberInString; -} -⋮---- -export interface VipLoanFixedRateBorrowParams { - supplyRequest: string; - borrowCoin: string; - loanTerm: number; - borrowUid: number; - collateralCoin: string; - collateralAccountId: string; - autoRepay?: boolean; -} -⋮---- -export interface VipLoanFixedRateBorrowResponse { - borrowCoin: string; - borrowAmount: numberInString; - actualReceivedAmount: numberInString; - collateralCoin: string; - collateralAccountId: string; - borrowInterestRate: numberInString; - duration: string; - autoRepay: boolean; - orderId: number; - status: 'Succeeds' | 'Failed' | 'Processing'; -} -⋮---- -// Institutional Loan types -export interface InstitutionalLoanLiability { - assetName: string; - principal: string; - interest: string; -} -⋮---- -export interface InstitutionalLoanWallet { - accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; -} -⋮---- -export interface InstitutionalLoanCollateralAccount { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - wallets: InstitutionalLoanWallet[]; -} -⋮---- -export interface InstitutionalLoanRiskUnitDetails { - groupId: number; - leverageTier: string; - initialLtv: string; - marginCallLtv: string; - liquidationLtv: string; - liquidationExitLtv: string; - maxTransferOutLtv: string; - parentEmail: string; - creditEmail: string; - updateTime: number; - ltv: string; - totalNetEquity: string; - totalMaintenanceMargin: string; - totalLiability: string; - // Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. - transferOutLtv: string; - parentAccountFrozenAmount: string; - maxTransferOutAmount: string; - maxAllowedBorrowLimit: string; - liabilities: InstitutionalLoanLiability[]; - collateralAccounts: InstitutionalLoanCollateralAccount[]; -} -⋮---- -// Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. -⋮---- -export interface GetInstitutionalLoanRiskUnitDetailsParams { - groupId?: number; -} -⋮---- -export interface CloseInstitutionalLoanRiskUnitResponse { - groupId: number; - status: 'CLOSED'; -} -⋮---- -export interface AddInstitutionalLoanCollateralAccountParams { - groupId: number; - subEmail: string; - enableSpot: boolean; - enableMargin: boolean; -} -⋮---- -export interface InstitutionalLoanRiskUnitMember { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - enableMargin: boolean; - enableSpot: boolean; -} -⋮---- -export interface ActiveInstitutionalLoanRiskUnit { - groupId: number; - members: InstitutionalLoanRiskUnitMember[]; - createTime: number; -} -export interface ClosedInstitutionalLoanRiskUnit { - groupId: number; - parentEmail: string; - creditEmail: string; - enabled: boolean; - createTime: number; - closeTime: number; -} -⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsParams { - current?: number; - size?: number; -} -⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsResponse { - total: number; - rows: ClosedInstitutionalLoanRiskUnit[]; -} -⋮---- -// Institutional Loan Force Liquidation interfaces -export interface InstitutionalLoanLiquidationSnapshot { - subEmail: string; - memberType: 'CREDIT' | 'COLLATERAL'; - walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; -} -⋮---- -export interface InstitutionalLoanLiquidationSnapshotData { - snapshots: InstitutionalLoanLiquidationSnapshot[]; - liabilities: InstitutionalLoanLiability[]; -} -⋮---- -export interface InstitutionalLoanForceLiquidationRecord { - groupId: number; - startLtv: number; - endLtv: number; - liquidationStartTime: number; - liquidationEndTime: number; - totalNetEquity: string; - totalMaintenanceMargin: string; - totalLiability: string; - liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; -} -⋮---- -export interface GetInstitutionalLoanForceLiquidationParams { - groupId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface GetInstitutionalLoanForceLiquidationResponse { - total: number; - rows: InstitutionalLoanForceLiquidationRecord[]; -} -⋮---- -// Risk Unit Transfer interfaces -export interface InstitutionalLoanRiskUnitTransferParams { - subEmail?: string; // Optional: subEmail can be credit account or collateral account - asset: string; // Asset Name - amount: number; // Transfer amount of the asset -} -⋮---- -subEmail?: string; // Optional: subEmail can be credit account or collateral account -asset: string; // Asset Name -amount: number; // Transfer amount of the asset -⋮---- -// Additional institutional loan types for borrow, repay, and interest history -export interface GetInstitutionalLoanMaxBorrowableParams { - groupId?: number; - assetName: string; -} -⋮---- -export interface InstitutionalLoanMaxBorrowableResponse { - maxBorrowableAmount: numberInString | null; -} -⋮---- -export interface InstitutionalLoanBorrowParams { - groupId: number; - assetName: string; - amount: number; -} -⋮---- -export interface InstitutionalLoanBorrowResponse { - transactionId: string; - amount: number; - status: string; -} -⋮---- -export interface InstitutionalLoanRepayParams { - groupId: number; - assetName: string; - amount: number; -} -⋮---- -export interface InstitutionalLoanRepayResponse { - transactionId: string; - amount: number; -} -⋮---- -export interface GetInstitutionalLoanInterestHistoryParams { - groupId?: number; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface InstitutionalLoanInterestHistoryRecord { - groupId: number; - assetName: string; - principal: string; - interestRate: string; - interest: string; - interestTimestamp: number; -} -⋮---- -export interface InstitutionalLoanInterestHistoryResponse { - total: number; - rows: InstitutionalLoanInterestHistoryRecord[]; -} -⋮---- -export interface GetInstitutionalLoanBorrowRepayRecordsParams { - groupId?: number; // Optional: Risk unit unique identifier - type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY - asset?: string; // Optional: Asset name - startTime?: number; // Optional: Start time - endTime?: number; // Optional: End time - current?: number; // Optional: The currently querying page. Start from 1. Default:1 - size?: number; // Optional: Default:10 Max:100 - recvWindow?: number; // Optional: The value cannot be greater than 60000 - timestamp: number; // Required -} -⋮---- -groupId?: number; // Optional: Risk unit unique identifier -type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY -asset?: string; // Optional: Asset name -startTime?: number; // Optional: Start time -endTime?: number; // Optional: End time -current?: number; // Optional: The currently querying page. Start from 1. Default:1 -size?: number; // Optional: Default:10 Max:100 -recvWindow?: number; // Optional: The value cannot be greater than 60000 -timestamp: number; // Required -⋮---- -export interface InstitutionalLoanBorrowRepayRecord { - tranId: number; // Transaction ID - assetName: string; // Asset name - amount: number; // Amount - status: 'CONFIRM' | 'FAILED'; // Status - type: 'BORROW' | 'REPAY'; // Type - timestamp: number; // Create Time - principal?: number; // Only present for REPAY type - interest?: number; // Only present for REPAY type -} -⋮---- -tranId: number; // Transaction ID -assetName: string; // Asset name -amount: number; // Amount -status: 'CONFIRM' | 'FAILED'; // Status -type: 'BORROW' | 'REPAY'; // Type -timestamp: number; // Create Time -principal?: number; // Only present for REPAY type -interest?: number; // Only present for REPAY type -⋮---- -export interface GetInstitutionalLoanBorrowRepayRecordsResponse { - total: number; - rows: InstitutionalLoanBorrowRepayRecord[]; -} -⋮---- -export interface MarginInterestRebateBalanceResponse { - asset: string; - balance: string; - totalGranted: string; - totalConsumed: string; -} -⋮---- -export interface GetMarginInterestRebateBalanceRecordsParams { - type?: 0 | 1 | 2; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface MarginInterestRebateBalanceRecord { - type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; - rebateAsset: string; - delta: string; - createTime: number; - groupId?: number; - liabilityAsset?: string; - deductedInterest?: string; - exchangeRate?: string; -} -⋮---- -export interface MarginInterestRebateBalanceRecordsResponse { - total: number; - rows: MarginInterestRebateBalanceRecord[]; -} -⋮---- -// On-chain Yields types -⋮---- -export interface OnchainYieldsLockedProductListParams { - asset?: string; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedProductDetail { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: 'PREHEATING' | 'PURCHASING'; - subscriptionStartTime: string; - canRedeemToFlex: boolean; -} -⋮---- -export interface OnchainYieldsLockedProductQuota { - totalPersonalQuota: string; - minimum: string; -} -⋮---- -export interface OnchainYieldsLockedProduct { - projectId: string; - detail: OnchainYieldsLockedProductDetail; - quota: OnchainYieldsLockedProductQuota; -} -⋮---- -export interface OnchainYieldsLockedProductListResponse { - rows: OnchainYieldsLockedProduct[]; - total: number; -} -⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaParams { - projectId: string; -} -⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaResponse { - leftPersonalQuota: string; -} -⋮---- -export interface OnchainYieldsLockedPositionParams { - asset?: string; - positionId?: number; - projectId?: string; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedPosition { - positionId: string; - projectId: string; - asset: string; - amount: string; - purchaseTime: string; - duration: string; - accrualDays: string; - rewardAsset: string; - APY: string; - rewardAmt: string; - nextPay?: string; - nextPayDate?: string; - payPeriod?: string; - rewardsPayDate?: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; - redeemingAmt?: string; - redeemTo?: 'FLEXIBLE' | 'SPOT'; - canRedeemEarly: boolean; - autoSubscribe: boolean; - type: 'AUTO' | 'NORMAL'; - status: 'HOLDING' | 'REDEEMING' | 'RENEWING' | 'NEW_TRANSFERRING'; -} -⋮---- -export interface OnchainYieldsLockedPositionResponse { - rows: OnchainYieldsLockedPosition[]; - total: number; -} -⋮---- -export interface OnchainYieldsAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedInBTC: string; - totalLockedInUSDT: string; -} -⋮---- -// On-chain Yields Earn types -⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; -} -⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewResponse { - rewardAsset: string; - totalRewardAmt: string; - nextPay?: string; - nextPayDate?: string; - rewardsPayDate?: string; - valueDate: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; -} -⋮---- -export interface OnchainYieldsLockedSubscribeParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; - redeemTo?: 'SPOT' | 'FLEXIBLE'; - channelId?: string; - clientId?: string; -} -⋮---- -export interface OnchainYieldsLockedSubscribeResponse { - purchaseId: number; - positionId: string; - amount: string; - success: boolean; -} -⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeParams { - positionId: string; - autoSubscribe: boolean; -} -⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeResponse { - success: boolean; -} -⋮---- -export interface OnchainYieldsLockedSetRedeemOptionParams { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; -} -⋮---- -export interface OnchainYieldsLockedSetRedeemOptionResponse { - success: boolean; -} -⋮---- -export interface OnchainYieldsLockedRedeemParams { - positionId: number; - channelId?: string; -} -⋮---- -export interface OnchainYieldsLockedRedeemResponse { - redeemId: number; - success: boolean; -} -⋮---- -// On-chain Yields History types -⋮---- -export interface OnchainYieldsLockedSubscriptionRecordParams { - purchaseId?: string; - clientId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedSubscriptionRecord { - positionId: string; - purchaseId: string; - projectId: string; - clientId: string; - time: number; - asset: string; - amount: string; - lockPeriod: string; - type: 'NORMAL' | 'AUTO'; - sourceAccount: 'SPOT' | 'FUNDING' | 'SPOTANDFUNDING'; - amtFromSpot?: string; - amtFromFunding?: string; - status: 'PURCHASING' | 'SUCCESS' | 'FAILED'; -} -⋮---- -export interface OnchainYieldsLockedSubscriptionRecordResponse { - rows: OnchainYieldsLockedSubscriptionRecord[]; - total: number; -} -⋮---- -export interface OnchainYieldsLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedRewardsRecord { - positionId: string; - time: number; - asset: string; - lockPeriod: string; - amount: string; -} -⋮---- -export interface OnchainYieldsLockedRewardsHistoryResponse { - rows: OnchainYieldsLockedRewardsRecord[]; - total: number; -} -⋮---- -export interface OnchainYieldsLockedRedemptionRecordParams { - positionId?: number; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} -⋮---- -export interface OnchainYieldsLockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; - asset: string; - lockPeriod: string; - amount: string; - originalAmount: string; - type: 'NORMAL' | 'EARLY' | 'CONVERT'; - deliverDate: string; - lossAmount: string; - isComplete: boolean; - rewardAsset: string; - rewardAmt: string; - status: 'CREATED' | 'PAID'; -} -⋮---- -export interface OnchainYieldsLockedRedemptionRecordResponse { - rows: OnchainYieldsLockedRedemptionRecord[]; - total: number; -} -⋮---- -/** - * ALPHA TRADING INTERFACES - */ -⋮---- -export interface AlphaToken { - alphaId: number; - symbol: string; - name: string; - chainId: string; - contractAddress: string; - decimals?: number; -} -⋮---- -export interface AlphaExchangeFilter { - filterType: string; - minPrice?: string; - maxPrice?: string; - tickSize?: string; - stepSize?: string; - maxQty?: string; - minQty?: string; - limit?: number; - minNotional?: string; - maxNotional?: string; - multiplierDown?: string; - multiplierUp?: string; - bidMultiplierUp?: string; - askMultiplierUp?: string; - bidMultiplierDown?: string; - askMultiplierDown?: string; -} -⋮---- -export interface AlphaSymbol { - symbol: string; - status: string; - baseAsset: string; - quoteAsset: string; - pricePrecision: number; - quantityPrecision: number; - baseAssetPrecision: number; - quotePrecision: number; - filters: AlphaExchangeFilter[]; - orderTypes: string[]; -} -⋮---- -export interface AlphaAsset { - asset: string; -} -⋮---- -export interface AlphaExchangeInfo { - timezone: string; - assets: AlphaAsset[]; - symbols: AlphaSymbol[]; -} -⋮---- -export interface AlphaAggTradesParams { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface AlphaAggTrade { - a: number; // aggregate trade ID - p: string; // price - q: string; // quantity - f: number; // first trade ID - l: number; // last trade ID - T: number; // timestamp - m: boolean; // is buyer market maker -} -⋮---- -a: number; // aggregate trade ID -p: string; // price -q: string; // quantity -f: number; // first trade ID -l: number; // last trade ID -T: number; // timestamp -m: boolean; // is buyer market maker -⋮---- -export interface AlphaKlinesParams { - symbol: string; - interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M -⋮---- -export type AlphaKline = [ - string, // Open time - string, // Open price - string, // High price - string, // Low price - string, // Close price - string, // Volume - string, // Close time - string, // Quote asset volume - string, // Number of trades - string, // Taker buy base asset volume - string, // Taker buy quote asset volume - string, // Ignore (always "0") -]; -⋮---- -string, // Open time -string, // Open price -string, // High price -string, // Low price -string, // Close price -string, // Volume -string, // Close time -string, // Quote asset volume -string, // Number of trades -string, // Taker buy base asset volume -string, // Taker buy quote asset volume -string, // Ignore (always "0") -⋮---- -export interface AlphaTickerParams { - symbol: string; -} -⋮---- -export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; -⋮---- -export interface AlphaFullDepthParams { - symbol: string; - limit?: AlphaFullDepthLimit; -} -⋮---- -export interface AlphaFullDepthData { - lastUpdateId: number; - symbol: string; - bids: [string, string][]; - asks: [string, string][]; - E: number; - T: number; -} -⋮---- -export interface AlphaFullDepthResponse { - code: string; - message: string | null; - messageDetail: string | null; - success: boolean; - data: AlphaFullDepthData; -} -⋮---- -export interface AlphaTicker { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - lastPrice: string; - lastQty: string; - openPrice: string; - highPrice: string; - lowPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- -/** - * Soft Staking interfaces - */ -export interface GetSoftStakingProductListParams { - asset?: string; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SoftStakingProduct { - asset: string; - minAmount: string; - maxCap: string; - apr: string; - stakedAmount: string; - totalProfit: string; -} -⋮---- -export interface GetSoftStakingProductListResponse { - status: boolean; - totalRewardsUsdt: string; - rows: SoftStakingProduct[]; - total: number; -} -⋮---- -export interface SetSoftStakingParams { - softStaking: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SetSoftStakingResponse { - success: boolean; -} -⋮---- -export interface GetSoftStakingRewardsHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SoftStakingRewardsRecord { - asset: string; - rewards: string; - rewardAsset: string; - avgAmount: string; - time: number; -} -⋮---- -export interface GetSoftStakingRewardsHistoryResponse { - rows: SoftStakingRewardsRecord[]; - total: number; -} - -================ -File: src/main-client.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; -⋮---- -import { - AmendKeepPriorityParams, - BasicAssetPaginatedParams, - BasicAssetParam, - BasicSymbolParam, - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - CoinStartEndLimit, - ExchangeSymbol, - GetAllOrdersParams, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, - NewOCOParams, - NewOrderListParams, - OrderBookParams, - OrderIdProperty, - OrderResponseType, - OrderType, - RecentTradesParams, - RowsWithTotal, - SymbolFromPaginatedRequestFromId, - SymbolPrice, -} from './types/shared'; -import { - AcceptQuoteRequestParams, - AccountInfo, - AccountInformation, - ActiveInstitutionalLoanRiskUnit, - AddBSwapLiquidityParams, - AddInstitutionalLoanCollateralAccountParams, - AddIpRestriction, - AdjustCryptoLoanLTVParams, - AdjustCryptoLoanLTVResponse, - AdjustFlexibleCryptoLoanLTVParams, - AdjustFlexibleCryptoLoanLTVResponse, - AggregateTrade, - AlgoOrder, - AllCoinsInformationResponse, - Allocation, - AllocationsParams, - AlphaAggTrade, - AlphaAggTradesParams, - AlphaExchangeInfo, - AlphaFullDepthParams, - AlphaFullDepthResponse, - AlphaKline, - AlphaKlinesParams, - AlphaTicker, - AlphaToken, - ApiKeyBrokerSubAccount, - APIPermissions, - APITradingStatus, - ApplicationStatus, - AssetDetail, - BasicFromPaginatedParams, - BasicFuturesSubAccountParams, - BasicMarginAssetParams, - BasicSubAccount, - BasicTimeRangeParam, - BethRewardsHistory, - BfusdAccountResponse, - BfusdQuotaResponse, - BfusdRateHistoryRow, - BfusdRedeemParams, - BfusdRedeemResponse, - BfusdRedemptionHistoryRow, - BfusdRewardsHistoryRow, - BfusdSubscribeParams, - BfusdSubscribeResponse, - BfusdSubscriptionHistoryRow, - BlockTrade, - BlvtRedemptionRecord, - BlvtSubscriptionRecord, - BlvtUserLimitInfo, - BNBBurnResponse, - BnbTransferParams, - BnsolRateHistoryRecord, - BnsolRewardHistoryRecord, - BorrowCryptoLoanParams, - BorrowCryptoLoanResponse, - BorrowFlexibleLoanParams, - BorrowFlexibleLoanResponse, - BorrowInterestRate, - BrokerCommissionRebate, - BrokerSubAccount, - BrokerSubAccountCoinFuturesCommission, - BrokerSubAccountFuturesCommission, - BrokerSubAccountHistory, - BrokerUniversalTransfer, - BSwapLiquidity, - BSwapOperations, - BSwapOperationsParams, - BUSDConversionRecord, - CancelAlgoOrderResponse, - CancelHashrateResaleConfigParams, - CancelOrderListResult, - CancelSpotAlgoOrderResponse, - CancelSpotOrderResult, - ChangeAutoCompoundStatusParams, - ChangeAutoCompoundStatusResponse, - ChangePermissionApiKeyBrokerSubAccountParams, - ChangePermissionApiKeyBrokerSubAccountResponse, - ChangePlanStatusParams, - ChangePlanStatusResponse, - ChangeSubAccountCoinFuturesCommissionParams, - ChangeSubAccountCommissionParams, - ChangeSubAccountCommissionResponse, - ChangeSubAccountFuturesCommissionParams, - ChangeSubAccountFuturesCommissionResponse, - CheckCollateralRepayRateParams, - CheckCollateralRepayRateResponse, - CheckDualInvestmentAccountsResponse, - CheckVipCollateralAccountParams, - CloseInstitutionalLoanRiskUnitResponse, - CloudMining, - CloudMiningHistoryParams, - CoinMarginedFuturesResponse, - Collateral, - CollateralAssetData, - CollateralRecord, - CommissionRates, - ConvertDustParams, - ConvertibleCoinsParams, - ConvertibleCoinsResponse, - ConvertLimitOpenOrder, - ConvertQuoteRequestParams, - ConvertTransfer, - ConvertTransferResponse, - CreateApiKeyBrokerSubAccountParams, - CreateApiKeyBrokerSubAccountResponse, - CreateBrokerSubAccountParams, - CreateDualTokenGiftCardParams, - CreateGiftCardParams, - CreateInvestmentPlanParams, - CreateInvestmentPlanResponse, - CreateSpecialLowLatencyKeyParams, - CreateSubAccountParams, - CrossMarginFeeData, - CrossMarginTransferHistory, - CurrentAvgPrice, - CustomizeMarginCall, - CustomizeMarginCallParams, - DailyAccountSnapshot, - DailyAccountSnapshotParams, - DelegationHistory, - DelegationHistoryParams, - DeleteApiKeyBrokerSubAccountParams, - DelistScheduleResponse, - DepositAddress, - DepositAddressListParams, - DepositAddressParams, - DepositAddressResponse, - DepositHistory, - DepositHistoryParams, - DualInvestmentPosition, - DualInvestmentProduct, - DustConversion, - DustConvertibleAssetsParams, - DustConvertibleAssetsResponse, - DustConvertParams, - DustInfo, - DustLog, - EditInvestmentPlanParams, - EditInvestmentPlanResponse, - EnableConvertSubAccountParams, - EnableFuturesBrokerSubAccountParams, - EnableFuturesBrokerSubAccountResponse, - EnableMarginApiKeyBrokerSubAccountParams, - EnableMarginBrokerSubAccountParams, - EnableMarginBrokerSubAccountResponse, - EnableOptionsForSubAccountResponse, - EnableOrDisableIPRestrictionForSubAccountParams, - EnableUniversalTransferApiKeyBrokerSubAccountParams, - EnableUniversalTransferApiKeyBrokerSubAccountResponse, - ETHRateHistory, - EthRedemptionHistory, - EthStakingHistory, - ExchangeInfo, - ExchangeInfoParams, - FiatDepositParams, - FiatDepositResponse, - FixedAndActivityProjectParams, - FixedAndActivityProjectPositionParams, - FlexibleCryptoLoanBorrowHistory, - FlexibleLoanAssetData, - FlexibleLoanCollateralAssetData, - FlexibleLoanLiquidationHistoryRecord, - FlexibleLoanLTVAdjustmentHistory, - FlexibleLoanOngoingOrder, - FlexibleRedemptionRecord, - FlexibleRewardsHistory, - FlexibleSubscriptionPreview, - ForceLiquidationRecord, - FundingAsset, - FutureAccountTransfer, - FuturesPositionRisk, - GetAlgoHistoricalOrdersParams, - GetAlgoSubOrdersParams, - GetAlgoSubOrdersResponse, - GetAllConvertPairsParams, - GetApiKeyBrokerSubAccountParams, - GetApplicationStatusParams, - GetAssetParams, - GetBethRewardsHistoryParams, - GetBfusdRateHistoryParams, - GetBfusdRedemptionHistoryParams, - GetBfusdRewardsHistoryParams, - GetBfusdSubscriptionHistoryParams, - GetBlvtRedemptionRecordParams, - GetBlvtSubscriptionRecordParams, - GetBnsolRateHistoryReq, - GetBnsolRewardsHistoryReq, - GetBrokerInfoResponse, - GetBrokerSubAccountDepositHistoryParams, - GetBrokerSubAccountHistoryParams, - GetBrokerSubAccountParams, - GetC2CTradeHistoryParams, - GetC2CTradeHistoryResponse, - GetClosedInstitutionalLoanRiskUnitsParams, - GetClosedInstitutionalLoanRiskUnitsResponse, - GetCollateralAssetDataParams, - GetCollateralRecordParams, - GetConvertBUSDHistoryParams, - GetConvertTradeHistoryParams, - GetCrossMarginTransferHistoryParams, - GetCryptoLoansIncomeHistoryParams, - GetCryptoLoansIncomeHistoryResponse, - GetDualInvestmentPositionsParams, - GetDualInvestmentProductListParams, - GetEarningsListParams, - GetEarningsListResponse, - GetETHRateHistoryParams, - GetEthRedemptionHistoryParams, - GetEthStakingAccountResponse, - GetEthStakingAccountV2Response, - GetEthStakingHistoryParams, - GetEthStakingQuotaResponse, - GetExtraBonusListParams, - GetExtraBonusListResponse, - GetFiatOrderDetailParams, - GetFiatOrderDetailResponse, - GetFiatOrderHistoryParams, - GetFiatOrderHistoryResponse, - GetFiatPaymentsHistoryResponse, - GetFlexibleCryptoLoanBorrowHistoryParams, - GetFlexibleLoanLiquidationHistoryParams, - GetFlexibleLoanLTVAdjustmentHistoryParams, - GetFlexibleLoanOngoingOrdersParams, - GetFlexibleRedemptionRecordParams, - GetFlexibleRewardsHistoryParams, - GetFlexibleSubscriptionPreviewParams, - GetFlexibleSubscriptionRecordParams, - GetFlexibleSubscriptionRecordResponse, - GetForceLiquidationRecordParams, - GetFutureAccountTransferHistoryParams, - GetFuturesLeadTraderStatusResponse, - GetFuturesLeadTradingSymbolWhitelistResponse, - GetFutureTickLevelOrderbookDataLinkParams, - GetHashrateResaleDetailParams, - GetHashrateResaleDetailResponse, - GetHashrateResaleListParams, - GetHashrateResaleListResponse, - GetIndexDetailsResponse, - GetIndexLinkedPlanPositionDetailsResponse, - GetIndexLinkedPlanRebalanceHistoryParams, - GetIndexLinkedPlanRedemptionHistoryParams, - GetInstitutionalLoanBorrowRepayRecordsParams, - GetInstitutionalLoanBorrowRepayRecordsResponse, - GetInstitutionalLoanForceLiquidationParams, - GetInstitutionalLoanForceLiquidationResponse, - GetInstitutionalLoanInterestHistoryParams, - GetInstitutionalLoanMaxBorrowableParams, - GetInstitutionalLoanRiskUnitDetailsParams, - GetLoanableAssetsDataParams, - GetLoanBorrowHistoryParams, - GetLoanCoinPaginatedHistoryParams, - GetLoanLTVAdjustmentHistoryParams, - GetLoanOngoingOrdersParams, - GetLoanRepaymentHistoryParams, - GetLockedRedemptionRecordParams, - GetLockedRewardsHistory, - GetLockedRewardsHistoryParams, - GetLockedSubscriptionPreviewParams, - GetLockedSubscriptionRecordParams, - GetMarginAccountBorrowRepayRecordsParams, - GetMarginCapitalFlowParams, - GetMarginInterestHistoryParams, - GetMarginInterestRebateBalanceRecordsParams, - GetMarginLiquidationLoanRepayHistoryParams, - GetMarginOrderCountUsageParams, - GetMinerDetailsParams, - GetMinerDetailsResponse, - GetMinerListParams, - GetMinerListResponse, - GetMiningAccountEarningParams, - GetMiningAccountEarningResponse, - getMiningAccountsListParams, - getMiningAccountsListResponse, - GetMiningAlgoListResponse, - GetMiningCoinListResponse, - GetNextHourlyInterestRateParams, - GetNftAssetParams, - GetNftDepositHistoryParams, - GetNftTransactionHistoryParams, - GetNftWithdrawHistoryParams, - GetOCOParams, - GetOneTimeTransactionStatusParams, - GetOneTimeTransactionStatusResponse, - GetOrderStatusParams, - GetPayTradeHistoryParams, - GetPlanDetailsParams, - GetPortfolioMarginAssetIndexPriceResponse, - GetPortfolioMarginAssetLeverageResponse, - GetPortfolioMarginProAccountInfoResponse, - GetPortfolioMarginProBankruptcyLoanAmountResponse, - GetPortfolioMarginProCollateralRateResponse, - GetPortfolioMarginProInterestHistoryParams, - GetPortfolioMarginProInterestHistoryResponse, - GetRateHistory, - GetRateHistoryParams, - GetRwusdRateHistoryParams, - GetRwusdRedemptionHistoryParams, - GetRwusdRewardsHistoryParams, - GetRwusdSubscriptionHistoryParams, - GetSmallLiabilityExchangeHistoryParams, - GetSoftStakingProductListParams, - GetSoftStakingProductListResponse, - GetSoftStakingRewardsHistoryParams, - GetSoftStakingRewardsHistoryResponse, - GetSolStakingHistoryReq, - GetSourceAssetListParams, - GetSourceAssetListResponse, - GetSpotAlgoHistoricalOrdersParams, - GetSpotAlgoSubOrdersParams, - GetSpotAlgoSubOrdersResponse, - GetSpotRebateHistoryRecordsParams, - GetSpotRebateHistoryRecordsResponse, - GetStatisticListParams, - GetStatisticListResponse, - GetSubAccountDepositHistoryParams, - GetSubscriptionTransactionHistoryParams, - GetTargetAssetListParams, - GetTargetAssetListResponse, - GetTargetAssetROIParams, - GetTravelRuleDepositHistoryParams, - GetTravelRuleRegionListParams, - GetTravelRuleWithdrawHistoryParams, - GetTravelRuleWithdrawHistoryV2Params, - GetUniversalTransferBrokerParams, - GetVipLoanFixedRateMarketParams, - GetVipLoanOngoingOrdersParams, - GetVipLoanRepaymentHistoryParams, - GetWbethRewardsHistoryResponse, - GetWrapHistoryParams, - HistoricalAlgoOrder, - HistoricalBlockTradesParams, - HistoricalDataLink, - HistoricalSpotAlgoOrder, - IndexLinkedPlanRedemptionRecord, - InstitutionalLoanBorrowParams, - InstitutionalLoanBorrowResponse, - InstitutionalLoanInterestHistoryResponse, - InstitutionalLoanMaxBorrowableResponse, - InstitutionalLoanRepayParams, - InstitutionalLoanRepayResponse, - InstitutionalLoanRiskUnitDetails, - InstitutionalLoanRiskUnitTransferParams, - IsolatedMarginAccountInfo, - IsolatedMarginAccountTransferParams, - IsolatedMarginFeeData, - IsolatedMarginSymbol, - IsolatedMarginTierData, - LeftDailyPurchaseQuotaFlexibleProductResponse, - LiabilityCoinLeverageBracket, - LoanableAssetData, - LoanBorrowHistory, - LoanLTVAdjustmentHistory, - LoanOngoingOrder, - LoanRepaymentHistory, - LockedRedemptionRecord, - LockedSubscriptionPreview, - LockedSubscriptionRecord, - ManagedSubAccountDepositAddress, - ManagedSubAccountDepositAddressParams, - ManagedSubAccountFuturesAssetsResponse, - ManagedSubAccountListParams, - ManagedSubAccountMarginAssetsResponse, - ManagedSubAccountSnapshot, - ManagedSubAccountSnapshotParams, - ManagedSubAccountTransferLogParams, - ManagedSubAccountTransferTTLogParams, - ManagerSubTransferHistoryVos, - ManagerSubUserInfoVo, - ManualLiquidationParams, - ManualLiquidationResponse, - MarginAccountLoanParams, - MarginAccountRecord, - MarginAvailableInventoryResponse, - MarginCapitalFlow, - MarginDelistSchedule, - MarginInterestHistory, - MarginInterestRateHistory, - MarginInterestRebateBalanceRecordsResponse, - MarginInterestRebateBalanceResponse, - MarginLiquidationLoan, - MarginLiquidationLoanRepayHistoryResponse, - MarginLiquidationLoanRepayResponse, - MarginOpenOTOOrderList, - MarginOrderCountUsageResponse, - MarginOTOCOOrder, - MarginOTOOrder, - MarginTransactionResponse, - NewFutureAccountTransferParams, - NewOrderListOPOCOParams, - NewOrderListOPOCOResponse, - NewOrderListOPOParams, - NewOrderListOPOResponse, - NewOrderListOTOCOParams, - NewOrderListOTOCOResponse, - NewOrderListOTOParams, - NewOrderListOTOResponse, - NewSpotOrderParams, - NewSpotSOROrderParams, - NextHourlyInterestRate, - NftAsset, - NftDeposit, - NftTransaction, - NftWithdraw, - OnchainYieldsAccountResponse, - OnchainYieldsLockedPersonalLeftQuotaParams, - OnchainYieldsLockedPersonalLeftQuotaResponse, - OnchainYieldsLockedPositionParams, - OnchainYieldsLockedPositionResponse, - OnchainYieldsLockedProductListParams, - OnchainYieldsLockedProductListResponse, - OnchainYieldsLockedRedeemParams, - OnchainYieldsLockedRedeemResponse, - OnchainYieldsLockedRedemptionRecordParams, - OnchainYieldsLockedRedemptionRecordResponse, - OnchainYieldsLockedRewardsHistoryParams, - OnchainYieldsLockedRewardsHistoryResponse, - OnchainYieldsLockedSetAutoSubscribeParams, - OnchainYieldsLockedSetAutoSubscribeResponse, - OnchainYieldsLockedSetRedeemOptionParams, - OnchainYieldsLockedSetRedeemOptionResponse, - OnchainYieldsLockedSubscribeParams, - OnchainYieldsLockedSubscribeResponse, - OnchainYieldsLockedSubscriptionPreviewParams, - OnchainYieldsLockedSubscriptionPreviewResponse, - OnchainYieldsLockedSubscriptionRecordParams, - OnchainYieldsLockedSubscriptionRecordResponse, - OrderBookResponse, - OrderList, - OrderListResponse, - OrderRateLimitUsage, - OrderResponseTypeFor, - PMProBankruptcyLoanRepaymentHistory, - PMProMintBFUSDParams, - PMProMintBFUSDResponse, - PMProRedeemBFUSDResponse, - PortfolioDeltaModeStatus, - PortfolioMarginMarginCallLevelDeleteResponse, - PortfolioMarginMarginCallLevelGetResponse, - PortfolioMarginMarginCallLevelResponse, - PortfolioMarginProAccountBalance, - PortfolioMarginProSpanAccountInfo, - PreventedMatch, - PreventedMatchesParams, - PurchaseFlexibleProductResponse, - PurchaseRecordParams, - QueryBrokerFuturesCommissionRebateParams, - QueryBrokerSpotCommissionRebateParams, - QueryCrossMarginAccountDetailsParams, - QueryCrossMarginFeeDataParams, - QueryCrossMarginPairResponse, - QueryIsolatedMarginTierDataParams, - QueryMarginAccountAllOCOParams, - QueryMarginAccountTradeListParams, - QueryMarginAssetResponse, - QueryMarginInterestRateHistoryParams, - QueryMarginOpenOTOOrderListsParams, - QueryMarginPriceIndexResponse, - QueryMarginRecordParams, - QueryMaxBorrowResponse, - QueryMaxTransferOutAmountResponse, - QuerySubAccountCoinFuturesCommissionParams, - QuerySubAccountFuturesAssetInfoParams, - QuerySubAccountFuturesCommissionParams, - QuerySubAccountSpotMarginAssetInfoParams, - RawAccountTrade, - RawTrade, - RedeemBlvtParams, - RedeemBlvtResponse, - RedeemEthParams, - RedeemEthResponse, - RedeemGiftCardParams, - RedeemSolResponse, - RemoveBSwapLiquidityParams, - RepayCryptoFlexibleLoanParams, - RepayCryptoFlexibleLoanResponse, - RepayCryptoLoanFlexibleWithCollateralParams, - RepayCryptoLoanFlexibleWithCollateralResponse, - RepayCryptoLoanParams, - RepayCryptoLoanResponse, - RepayMarginLiquidationLoanParams, - ReplaceSpotOrderParams, - ReplaceSpotOrderResultSuccess, - RollingWindowTickerParams, - RwusdAccountResponse, - RwusdQuotaResponse, - RwusdRateHistoryRow, - RwusdRedeemParams, - RwusdRedeemResponse, - RwusdRedemptionHistoryRow, - RwusdRewardsHistoryRow, - RwusdSubscribeParams, - RwusdSubscribeResponse, - RwusdSubscriptionHistoryRow, - SetAutoSubscribeParams, - SetPortfolioMarginMarginCallLevelParams, - SetSoftStakingParams, - SetSoftStakingResponse, - SimpleEarnAccountResponse, - SimpleEarnFlexibleProduct, - SimpleEarnFlexibleProductPositionParams, - SimpleEarnLockedProduct, - SimpleEarnLockedProductPosition, - SimpleEarnLockedProductPositionParams, - SimpleEarnProductListParams, - SimpleEarnRedeemFlexibleProductParams, - SimpleEarnRedeemResponse, - SimpleEarnSubscribeFlexibleProductResponse, - SimpleEarnSubscribeLockedProductResponse, - SimpleEarnSubscribeProductParams, - SmallLiabilityExchangeCoin, - SmallLiabilityExchangeHistory, - SolBoostRewardsHistoryRecord, - SolBoostRewardsHistoryReq, - SolRedemptionHistoryRecord, - SolStakingAccount, - SolStakingHistoryRecord, - SolStakingQuota, - SOROrderResponseFull, - SORTestOrderResponse, - SpecialLowLatencyKeyInfo, - SpecialLowLatencyKeyResponse, - SpotAlgoOrder, - SpotAmendKeepPriorityResult, - SpotAssetTag, - SpotAssetTagsParams, - SpotExecutionRulesParams, - SpotExecutionRulesResponse, - SpotOrder, - SpotReferencePriceCalculationResponse, - SpotReferencePriceResult, - StakingBasicParams, - StakingHistory, - StakingHistoryParams, - StakingPersonalLeftQuota, - StakingProduct, - StakingProductPosition, - StakingProductType, - SubAccountAddOrDeleteIPList, - SubAccountAssetDetails, - SubAccountAssets, - SubAccountAssetsParams, - SubaccountBalances, - SubAccountBrokerMarginAsset, - SubaccountBrokerSpotAsset, - SubAccountCOINMDetail, - SubAccountCOINMPositionRisk, - SubAccountCOINMSummary, - SubAccountDeposit, - SubAccountDepositAddress, - SubAccountDepositAddressParams, - SubAccountDepositHistoryList, - SubAccountDepositHistoryParams, - SubAccountEnableFutures, - SubAccountEnableLeverageToken, - SubAccountEnableMargin, - SubAccountEnableOrDisableIPRestriction, - SubAccountFuturesAccountDetail, - SubAccountFuturesAccountSummary, - SubAccountFuturesAssetTransfer, - SubAccountFuturesAssetTransferHistory, - SubAccountFuturesAssetTransferHistoryParams, - SubAccountFuturesAssetTransferParams, - SubAccountListParams, - SubAccountListResponse, - SubAccountMarginAccountDetail, - SubAccountMovePosition, - SubAccountMovePositionHistory, - SubAccountMovePositionHistoryParams, - SubAccountMovePositionParams, - SubAccountsMarginAccountSummary, - SubAccountSpotAssetsSummary, - SubAccountSpotAssetsSummaryParams, - SubAccountSpotAssetTransferHistory, - SubAccountSpotAssetTransferHistoryParams, - SubAccountStatus, - SubAccountSummaryOnFuturesAccountV2Params, - SubAccountTransactionStatistics, - SubAccountTransfer, - SubAccountTransferHistory, - SubAccountTransferHistoryParams, - SubAccountTransferParams, - SubAccountTransferToMasterParams, - SubAccountTransferToSameMasterParams, - SubAccountUniversalTransfer, - SubAccountUniversalTransferHistoryParams, - SubAccountUniversalTransferHistoryResponse, - SubAccountUniversalTransferParams, - SubAccountUSDMDetail, - SubAccountUSDMPositionRisk, - SubAccountUSDMSummary, - SubmitConvertLimitOrderParams, - SubmitDepositCreditParams, - SubmitDepositCreditResponse, - SubmitHashrateResaleParams, - SubmitIndexLinkedPlanRedemptionParams, - SubmitMarginOTOCOOrderParams, - SubmitMarginOTOOrderParams, - SubmitOneTimeTransactionParams, - SubmitOneTimeTransactionResponse, - SubmitSpotTwapNewOrderParams, - SubmitSpotTwapNewOrderResponse, - SubmitTravelRuleDepositQuestionnaireParams, - SubmitTravelRuleDepositQuestionnaireResponse, - SubmitTwapNewOrderParams, - SubmitTwapNewOrderResponse, - SubmitVpNewOrderParams, - SubmitVpNewOrderResponse, - SubscribeBlvtParams, - SubscribeBlvtResponse, - SubscribeDualInvestmentProductParams, - SubscribeDualInvestmentProductResponse, - SubscribeEthStakingV2Response, - SubscribeSolStakingResponse, - SwitchPortfolioDeltaModeParams, - SymbolOrderBookTicker, - SymbolTradeFee, - SystemStatusResponse, - TargetAssetROI, - Ticker24hrResponse, - ToggleBNBBurnParams, - TradingDayTickerArray, - TradingDayTickerFull, - TradingDayTickerMini, - TradingDayTickerParams, - TradingDayTickerSingle, - TransferBrokerSubAccount, - TransferBrokerSubAccountParams, - TravelRuleCountryListResponse, - TravelRuleDepositHistoryRecord, - TravelRuleRegionListResponse, - TravelRuleWithdrawHistoryRecord, - UniversalTransferBrokerParams, - UniversalTransferHistoryParams, - UniversalTransferParams, - UpdateIpRestrictionForSubApiKey, - UsdtMarginedFuturesResponse, - UserAsset, - VASPInfo, - VipCollateralAccount, - VipLoanAccruedInterestParams, - VipLoanAccruedInterestRecord, - VipLoanBorrowParams, - VipLoanBorrowResponse, - VipLoanFixedRateBorrowParams, - VipLoanFixedRateBorrowResponse, - VipLoanFixedRateMarketRecord, - VipLoanInterestRateHistoryParams, - VipLoanInterestRateRecord, - VipLoanRenewParams, - VipLoanRenewResponse, - VipLoanRepaymentHistory, - VipLoanRepayParams, - VipLoanRepayResponse, - VipOngoingOrder, - VirtualSubAccount, - WalletBalance, - WithdrawAddress, - WithdrawAssetsFromManagedSubAccountParams, - WithdrawFiatParams, - WithdrawHistory, - WithdrawHistoryParams, - WithdrawParams, - WithdrawTravelRuleParams, - WrapBethResponse, - WrapHistory, -} from './types/spot'; -import BaseRestClient from './util/BaseRestClient'; -import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, - serialiseParams, -} from './util/requestUtils'; -⋮---- -export class MainClient extends BaseRestClient -⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) -⋮---- -/** - * This method is used to get the latency and time sync between the client and the server. - * This is not official API endpoint and is only used for internal testing purposes. - * Use this method to check the latency and time sync between the client and the server. - * Final values might vary slightly, but it should be within few ms difference. - * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. - */ -async fetchLatencySummary(): Promise -⋮---- -// Adjust server time by adding estimated one-way latency -⋮---- -// Calculate time difference between adjusted server time and local time -⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise -⋮---- -/** - * - * SPOT TRADING Endpoints - General endpoints - * - **/ -⋮---- -testConnectivity(): Promise -⋮---- -getExchangeInfo(params?: ExchangeInfoParams): Promise -⋮---- -/** - * - * SPOT TRADING Endpoints - Market endpoints - * - **/ -⋮---- -getOrderBook(params: OrderBookParams): Promise -⋮---- -getRecentTrades(params: RecentTradesParams): Promise -⋮---- -getHistoricalTrades(params: HistoricalTradesParams): Promise -⋮---- -getHistoricalBlockTrades( - params: HistoricalBlockTradesParams, -): Promise -⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise -⋮---- -getKlines(params: KlinesParams): Promise -⋮---- -getUIKlines(params: KlinesParams): Promise -⋮---- -getAvgPrice(params: -⋮---- -getExecutionRules( - params?: SpotExecutionRulesParams, -): Promise -⋮---- -getReferencePrice(params: { - symbol: string; -}): Promise -⋮---- -getReferencePriceCalculation(params: { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; -}): Promise -⋮---- -get24hrChangeStatistics(params?: { - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; - }): Promise; -⋮---- -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL -⋮---- -get24hrChangeStatistics(params: { - symbol: string; // use for single symbol - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; - }): Promise; -⋮---- -symbol: string; // use for single symbol -type?: 'FULL' | 'MINI'; // default is FULL -⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; -}): Promise -⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL -⋮---- -getTradingDayTicker( - params: TradingDayTickerParams, -): Promise -⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise -⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols -⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise -⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols -⋮---- -getRollingWindowTicker( - params: RollingWindowTickerParams, -): Promise -⋮---- -/** - * - * SPOT TRADING Endpoints - Trading endpoints - * - **/ -⋮---- -submitNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> -⋮---- -testNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise -⋮---- -getOrder(params: GetOrderParams): Promise -⋮---- -cancelOrder(params: CancelOrderParams): Promise -⋮---- -cancelAllSymbolOrders(params: { - symbol: string; -}): Promise -⋮---- -replaceOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, - >( - params: ReplaceSpotOrderParams, -): Promise> -⋮---- -/** - * Reduce the quantity of an existing open order while keeping its priority in the order book. - * The new quantity must be less than the current quantity. - * https://binance-docs.github.io/apidocs/futures/en/#order-amend-keep-priority-trade - */ -amendOrderKeepPriority( - params: AmendKeepPriorityParams, -): Promise -⋮---- -getOpenOrders(params?: -⋮---- -getAllOrders(params: GetAllOrdersParams): Promise -⋮---- -/** - * @deprecated - */ -submitNewOCO(params: NewOCOParams): Promise -⋮---- -submitNewOrderList( - params: NewOrderListParams, -): Promise> -⋮---- -submitNewOrderListOTO( - params: NewOrderListOTOParams, -): Promise -⋮---- -submitNewOrderListOTOCO( - params: NewOrderListOTOCOParams, -): Promise -⋮---- -submitNewOrderListOPO( - params: NewOrderListOPOParams, -): Promise -⋮---- -submitNewOrderListOPOCO( - params: NewOrderListOPOCOParams, -): Promise -⋮---- -cancelOCO(params: CancelOCOParams): Promise -⋮---- -getOCO(params?: GetOCOParams): Promise -⋮---- -getAllOCO(params?: BasicFromPaginatedParams): Promise -⋮---- -/** - * Query open OCO - */ -getAllOpenOCO(): Promise -⋮---- -/** - * Places an order using smart order routing (SOR). - */ -submitNewSOROrder( - params: NewSpotSOROrderParams, -): Promise -⋮---- -/** - * Test new order creation and signature/recvWindow using smart order routing (SOR). - * Creates and validates a new order but does not send it into the matching engine. - */ -testNewSOROrder( - params: NewSpotSOROrderParams & { computeCommissionRates?: boolean }, -): Promise -⋮---- -/** - * - * SPOT TRADING Endpoints - Account endpoints - * - **/ -⋮---- -/** - * Get current account information - */ -getAccountInformation(params?: { - omitZeroBalances?: boolean; -}): Promise -⋮---- -getAccountTradeList( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise -⋮---- -getOrderRateLimit(): Promise -⋮---- -getPreventedMatches( - params: PreventedMatchesParams, -): Promise -⋮---- -getAllocations(params: AllocationsParams): Promise -⋮---- -getCommissionRates(params: -⋮---- -/** - * - * MARGIN TRADING Endpoints - Market Data endpoints - * - **/ -⋮---- -getCrossMarginCollateralRatio(): Promise< - { - collaterals: Collateral[]; - assetNames: string[]; - }[] - > { - return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); -⋮---- -getAllCrossMarginPairs(): Promise -⋮---- -getIsolatedMarginAllSymbols(params?: { - symbol?: string; -}): Promise -⋮---- -getAllMarginAssets(): Promise -⋮---- -getMarginDelistSchedule(): Promise -⋮---- -getIsolatedMarginTierData( - params: QueryIsolatedMarginTierDataParams, -): Promise -⋮---- -queryMarginPriceIndex( - params: BasicSymbolParam, -): Promise -⋮---- -getMarginAvailableInventory(params: { - type: string; -}): Promise -⋮---- -getLeverageBracket(): Promise -⋮---- -/** - * - * MARGIN TRADING Endpoints - Borrow and Repay endpoints - * - **/ -⋮---- -getNextHourlyInterestRate( - params: GetNextHourlyInterestRateParams, -): Promise -⋮---- -getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< -⋮---- -submitMarginAccountBorrowRepay( - params: MarginAccountLoanParams, -): Promise -⋮---- -getMarginAccountBorrowRepayRecords( - params: GetMarginAccountBorrowRepayRecordsParams, -): Promise< -⋮---- -getMarginInterestRateHistory( - params: QueryMarginInterestRateHistoryParams, -): Promise -⋮---- -queryMaxBorrow( - params: BasicMarginAssetParams, -): Promise -⋮---- -/** - * - * MARGIN TRADING Endpoints - Trade endpoints - * - **/ -⋮---- -getMarginForceLiquidationRecord( - params: GetForceLiquidationRecordParams, -): Promise< -⋮---- -getSmallLiabilityExchangeCoins(): Promise -⋮---- -getSmallLiabilityExchangeHistory( - params: GetSmallLiabilityExchangeHistoryParams, -): Promise< -⋮---- -marginAccountCancelOpenOrders( - params: BasicSymbolParam, -): Promise -⋮---- -marginAccountCancelOCO(params: CancelOCOParams): Promise -⋮---- -marginAccountCancelOrder( - params: CancelOrderParams, -): Promise -⋮---- -marginAccountNewOCO(params: NewOCOParams): Promise -⋮---- -marginAccountNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> -⋮---- -getMarginOrderCountUsage( - params: GetMarginOrderCountUsageParams, -): Promise -⋮---- -queryMarginAccountAllOCO( - params: QueryMarginAccountAllOCOParams, -): Promise -⋮---- -queryMarginAccountAllOrders( - params: GetAllOrdersParams, -): Promise -⋮---- -queryMarginAccountOCO(params: GetOCOParams): Promise -⋮---- -queryMarginAccountOpenOCO(params: { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; -}): Promise -⋮---- -queryMarginAccountOpenOTOOrderLists( - params: QueryMarginOpenOTOOrderListsParams, -): Promise -⋮---- -queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise -⋮---- -queryMarginAccountOrder(params: GetOrderParams): Promise -⋮---- -queryMarginAccountTradeList( - params: QueryMarginAccountTradeListParams, -): Promise -⋮---- -submitSmallLiabilityExchange(params: -⋮---- -submitManualLiquidation( - params: ManualLiquidationParams, -): Promise -⋮---- -/** - * Post a new OTO order for margin account - */ -submitMarginOTOOrder( - params: SubmitMarginOTOOrderParams, -): Promise -⋮---- -/** - * Submit a new OTOCO order for margin account - */ -submitMarginOTOCOOrder( - params: SubmitMarginOTOCOOrderParams, -): Promise -⋮---- -/** - * Create a special key for low-latency trading (VIP 4+ only) - */ -createMarginSpecialLowLatencyKey( - params: CreateSpecialLowLatencyKeyParams, -): Promise -⋮---- -deleteMarginSpecialLowLatencyKey(params?: { - apiKey?: string; - apiName?: string; - symbol?: string; -}): Promise -⋮---- -updateMarginIPForSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; - ip: string; -}): Promise -⋮---- -/** - * Query the list of special keys for low-latency trading - */ -getMarginSpecialLowLatencyKeys(params: { - symbol?: string; -}): Promise -⋮---- -/** - * Query information for a specific special key used in low-latency trading - */ -getMarginSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; -}): Promise -⋮---- -/** - * Query the current cross-margin liquidation loan status (bankruptcy deficit). - */ -getMarginLiquidationLoan(): Promise -⋮---- -/** - * Repay an outstanding cross-margin liquidation loan from the spot wallet. - */ -repayMarginLiquidationLoan( - params: RepayMarginLiquidationLoanParams, -): Promise -⋮---- -/** - * Query cross-margin liquidation loan repayment history. - */ -getMarginLiquidationLoanRepayHistory( - params?: GetMarginLiquidationLoanRepayHistoryParams, -): Promise -⋮---- -/** - * Exit Margin Special Key mode for Cross Margin Classic accounts. - */ -exitMarginSpecialKeyMode(): Promise -⋮---- -/** - * - * MARGIN TRADING Endpoints - Transfer endpoints - * - **/ -⋮---- -getCrossMarginTransferHistory( - params: GetCrossMarginTransferHistoryParams, -): Promise> -⋮---- -queryMaxTransferOutAmount( - params: BasicMarginAssetParams, -): Promise -⋮---- -/** - * - * MARGIN TRADING Endpoints - Account endpoints - * - **/ -⋮---- -updateCrossMarginMaxLeverage(params: -⋮---- -disableIsolatedMarginAccount(params: -⋮---- -enableIsolatedMarginAccount(params: -⋮---- -getBNBBurn(): Promise -⋮---- -getMarginSummary(): Promise -⋮---- -queryCrossMarginAccountDetails(): Promise -⋮---- -getCrossMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise -⋮---- -getIsolatedMarginAccountLimit(): Promise< -⋮---- -getIsolatedMarginAccountInfo(params?: { - symbols?: string; -}): Promise -⋮---- -getIsolatedMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise -⋮---- -toggleBNBBurn(params: ToggleBNBBurnParams): Promise -⋮---- -/** - * Possibly @deprecated - * Only existing in old documentation, not in new documentation - */ -getMarginCapitalFlow( - params: GetMarginCapitalFlowParams, -): Promise -⋮---- -/** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead - */ -queryLoanRecord( - params: QueryMarginRecordParams, -): Promise< -⋮---- -/** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead - */ -queryRepayRecord( - params: QueryMarginRecordParams, -): Promise< -⋮---- -/** - * @deprecated on 2024-01-09, use submitUniversalTransfer() instead - */ -isolatedMarginAccountTransfer( - params: IsolatedMarginAccountTransferParams, -): Promise -⋮---- -/** - * - * WALLET Endpoints - Capital endpoints - * - **/ -⋮---- -getBalances(): Promise -⋮---- -withdraw(params: WithdrawParams): Promise< -⋮---- -getWithdrawHistory( - params?: WithdrawHistoryParams, -): Promise -⋮---- -getWithdrawAddresses(): Promise -⋮---- -getWithdrawQuota(): Promise< -⋮---- -getDepositHistory(params?: DepositHistoryParams): Promise -⋮---- -getDepositAddress( - params: DepositAddressParams, -): Promise -⋮---- -getDepositAddresses( - params: DepositAddressListParams, -): Promise -⋮---- -submitDepositCredit( - params: SubmitDepositCreditParams, -): Promise -⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - */ -getAutoConvertStablecoins(): Promise -⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - */ -setConvertibleCoins(params: ConvertibleCoinsParams): Promise -⋮---- -/** - * - * WALLET Endpoints - Asset endpoints - * - **/ -⋮---- -getAssetDetail( - params?: Partial, -): Promise> -⋮---- -getWalletBalances(params?: { - quoteAsset?: string; -}): Promise -⋮---- -getUserAsset(params: GetAssetParams): Promise -⋮---- -getSpotAssetTags(params?: SpotAssetTagsParams): Promise -⋮---- -submitUniversalTransfer( - params: UniversalTransferParams, -): Promise< -⋮---- -getUniversalTransferHistory( - params: UniversalTransferHistoryParams, -): Promise -⋮---- -getDust(params: -⋮---- -convertDustToBnb(params: ConvertDustParams): Promise -⋮---- -/** - * Convert dust assets to a target asset (e.g. BNB, USDT). - */ -convertDustAssets(params: DustConvertParams): Promise -⋮---- -/** - * Query assets eligible for dust conversion. - */ -queryDustConvertibleAssets( - params: DustConvertibleAssetsParams, -): Promise -⋮---- -getDustLog(params?: BasicTimeRangeParam): Promise -⋮---- -getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise -⋮---- -getTradeFee(params?: -⋮---- -getFundingAsset(params: GetAssetParams): Promise -⋮---- -getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< -⋮---- -getDelegationHistory( - params: DelegationHistoryParams, -): Promise> -⋮---- -/** - * - * Futures Management Endpoints: - * https://binance-docs.github.io/apidocs/spot/en/#futures - * - * Note: to trade futures use the usdm-client or coinm-client. - * MainClient only has the futures endpoints listed in the "spot" docs category, primarily used for transfers. - * - **/ -⋮---- -/** - * Execute transfer between spot account and futures account. - * - * Type: - * - 1: transfer from spot account to USDT-Ⓜ futures account. - * - 2: transfer from USDT-Ⓜ futures account to spot account. - * - 3: transfer from spot account to COIN-Ⓜ futures account. - * - 4: transfer from COIN-Ⓜ futures account to spot account. - */ -⋮---- -/** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead - */ -submitNewFutureAccountTransfer( - params: NewFutureAccountTransferParams, -): Promise< -⋮---- -/** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead - */ -getFutureAccountTransferHistory( - params: GetFutureAccountTransferHistoryParams, -): Promise> -⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise -⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise -⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralWalletV2(): Promise -⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getAdjustCrossCollateralLTVHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise -⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralLiquidationHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise -⋮---- -/** - * @deprecated as of 2023-09-25 - */ -getCrossCollateralInterestHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise -⋮---- -/** - * - * WALLET Endpoints - Account endpoints - * - **/ -⋮---- -getAccountInfo(): Promise -⋮---- -getDailyAccountSnapshot( - params: DailyAccountSnapshotParams, -): Promise -⋮---- -disableFastWithdrawSwitch(): Promise -⋮---- -enableFastWithdrawSwitch(): Promise -⋮---- -getAccountStatus(): Promise< -⋮---- -getApiTradingStatus(): Promise -⋮---- -getApiKeyPermissions(): Promise -⋮---- -/** - * - * WALLET Endpoints - Travel Rule endpoints - * - **/ -⋮---- -/** - * Submit a withdrawal request for local entities that require travel rule - * - * For questionaire format, please refer to the docs: - * https://developers.binance.com/docs/wallet/travel-rule/withdraw-questionnaire - */ -withdrawTravelRule(params: WithdrawTravelRuleParams): Promise< -⋮---- -/** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistory( - params?: GetTravelRuleWithdrawHistoryParams, -): Promise -⋮---- -/** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistoryV2( - params?: GetTravelRuleWithdrawHistoryV2Params, -): Promise -⋮---- -/** - * Submit questionnaire for local entities that require travel rule - * - * for questionaire format, please refer to the docs: - * https://developers.binance.com/docs/wallet/travel-rule/deposit-questionnaire - */ -submitTravelRuleDepositQuestionnaire( - params: SubmitTravelRuleDepositQuestionnaireParams, -): Promise -⋮---- -/** - * Fetch deposit history for local entities that require travel rule - */ -getTravelRuleDepositHistory( - params?: GetTravelRuleDepositHistoryParams, -): Promise -⋮---- -/** - * Fetch the onboarded VASP list for local entities that require travel rule. - * Use the `identifier` field (not vaspCode) for the `vasp` param in deposit/withdrawal questionnaires. - * Both vaspCode and identifier accepted until 28 May 2026. - */ -getOnboardedVASPList(): Promise -⋮---- -getTravelRuleCountryList(): Promise -⋮---- -getTravelRuleRegionList( - params: GetTravelRuleRegionListParams, -): Promise -⋮---- -/** - * - * WALLET Endpoints - Other endpoints - * - **/ -⋮---- -getSystemStatus(): Promise -⋮---- -getDelistSchedule(): Promise -⋮---- -/** - * - * SUB ACCOUNT Endpoints - Account management - * - **/ -⋮---- -createVirtualSubAccount( - params: CreateSubAccountParams, -): Promise -⋮---- -getSubAccountList( - params?: SubAccountListParams, -): Promise -⋮---- -subAccountEnableFutures(email: string): Promise -⋮---- -/** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. - */ -subAccountEnableMargin(email: string): Promise -⋮---- -enableOptionsForSubAccount(params: { - email: string; -}): Promise -⋮---- -/** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. - */ -subAccountEnableLeverageToken( - params: SubAccountEnableLeverageToken, -): Promise -⋮---- -getSubAccountStatusOnMarginOrFutures(params?: { - email?: string; -}): Promise -⋮---- -getSubAccountFuturesPositionRisk( - email: string, -): Promise -⋮---- -getSubAccountFuturesPositionRiskV2( - params: BasicFuturesSubAccountParams, -): Promise -⋮---- -getSubAccountTransactionStatistics(params: { - email: string; -}): Promise -⋮---- -/** - * - * SUB ACCOUNT Endpoints - API management - * - **/ -⋮---- -getSubAccountIPRestriction( - params: BasicSubAccount, -): Promise -⋮---- -subAccountDeleteIPList( - params: SubAccountAddOrDeleteIPList, -): Promise -⋮---- -subAccountAddIPRestriction( - params: AddIpRestriction, -): Promise -⋮---- -/** - * @deprecated - * Use subAccountAddIPRestriction instead - **/ -subAccountAddIPList( - params: SubAccountEnableOrDisableIPRestriction, -): Promise -⋮---- -/** - * @deprecated - * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList - **/ -subAccountEnableOrDisableIPRestriction( - params: EnableOrDisableIPRestrictionForSubAccountParams, -): Promise -⋮---- -/** - * - * SUB ACCOUNT Endpoints - Asset management - * - **/ -⋮---- -subAccountFuturesTransfer( - params: SubAccountTransferParams, -): Promise -⋮---- -getSubAccountFuturesAccountDetail( - email: string, -): Promise -⋮---- -getSubAccountDetailOnFuturesAccountV2( - params: BasicFuturesSubAccountParams, -): Promise -⋮---- -getSubAccountDetailOnMarginAccount( - email: string, -): Promise -⋮---- -getSubAccountDepositAddress( - params: SubAccountDepositAddressParams, -): Promise -⋮---- -getSubAccountDepositHistory( - params: SubAccountDepositHistoryParams, -): Promise -⋮---- -getSubAccountFuturesAccountSummary(): Promise -⋮---- -getSubAccountSummaryOnFuturesAccountV2( - params: SubAccountSummaryOnFuturesAccountV2Params, -): Promise -⋮---- -getSubAccountsSummaryOfMarginAccount(): Promise -⋮---- -subAccountMarginTransfer( - params: SubAccountTransferParams, -): Promise -⋮---- -getSubAccountAssets( - params: SubAccountAssetsParams, -): Promise -⋮---- -getSubAccountAssetsMaster(params: -⋮---- -getSubAccountFuturesAssetTransferHistory( - params: SubAccountFuturesAssetTransferHistoryParams, -): Promise -⋮---- -getSubAccountSpotAssetTransferHistory( - params?: SubAccountSpotAssetTransferHistoryParams, -): Promise -⋮---- -getSubAccountSpotAssetsSummary( - params?: SubAccountSpotAssetsSummaryParams, -): Promise -⋮---- -getSubAccountUniversalTransferHistory( - params?: SubAccountUniversalTransferHistoryParams, -): Promise -⋮---- -subAccountFuturesAssetTransfer( - params: SubAccountFuturesAssetTransferParams, -): Promise -⋮---- -subAccountTransferHistory( - params?: SubAccountTransferHistoryParams, -): Promise -⋮---- -subAccountTransferToMaster( - params: SubAccountTransferToMasterParams, -): Promise -⋮---- -subAccountTransferToSameMaster( - params: SubAccountTransferToSameMasterParams, -): Promise -⋮---- -subAccountUniversalTransfer( - params: SubAccountUniversalTransferParams, -): Promise -⋮---- -subAccountMovePosition( - params: SubAccountMovePositionParams, -): Promise< -⋮---- -getSubAccountFuturesPositionMoveHistory( - params: SubAccountMovePositionHistoryParams, -): Promise< -⋮---- -/** - * - * SUB ACCOUNT Endpoints - Managed Sub Account - * - **/ -⋮---- -depositAssetsIntoManagedSubAccount( - params: SubAccountTransferToSameMasterParams, -): Promise -⋮---- -getManagedSubAccountDepositAddress( - params: ManagedSubAccountDepositAddressParams, -): Promise -⋮---- -withdrawAssetsFromManagedSubAccount( - params: WithdrawAssetsFromManagedSubAccountParams, -): Promise -⋮---- -getManagedSubAccountTransfersParent( - params: ManagedSubAccountTransferLogParams, -): Promise< -⋮---- -getManagedSubAccountTransferLog( - params: ManagedSubAccountTransferTTLogParams, -): Promise< -⋮---- -getManagedSubAccountTransfersInvestor( - params: ManagedSubAccountTransferLogParams, -): Promise< -⋮---- -getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< -⋮---- -getManagedSubAccountSnapshot( - params: ManagedSubAccountSnapshotParams, -): Promise -⋮---- -getManagedSubAccountAssetDetails( - email: string, -): Promise -⋮---- -getManagedSubAccountMarginAssets(params: { - email: string; - accountType?: string; -}): Promise -⋮---- -getManagedSubAccountFuturesAssets(params: { - email: string; - accountType?: string; -}): Promise -⋮---- -/** - * - * AUTO INVEST Endpoints - Market data - * - **/ -⋮---- -getAutoInvestAssets(): Promise< -⋮---- -getAutoInvestSourceAssets( - params: GetSourceAssetListParams, -): Promise -⋮---- -getAutoInvestTargetAssets( - params: GetTargetAssetListParams, -): Promise -⋮---- -getAutoInvestTargetAssetsROI( - params: GetTargetAssetROIParams, -): Promise -⋮---- -getAutoInvestIndex(params: { - indexId: number; -}): Promise -⋮---- -getAutoInvestPlans(params: { - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; -}): Promise -⋮---- -/** - * - * AUTO INVEST Endpoints - Trade - * - **/ -⋮---- -/** - * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction - * - * @param params - * @returns - */ -submitAutoInvestOneTimeTransaction( - params: SubmitOneTimeTransactionParams, -): Promise -⋮---- -updateAutoInvestPlanStatus( - params: ChangePlanStatusParams, -): Promise -⋮---- -updateAutoInvestmentPlan( - params: EditInvestmentPlanParams, -): Promise -⋮---- -submitAutoInvestRedemption( - params: SubmitIndexLinkedPlanRedemptionParams, -): Promise< -⋮---- -getAutoInvestSubscriptionTransactions( - params: GetSubscriptionTransactionHistoryParams, -): Promise -⋮---- -getOneTimeTransactionStatus( - params: GetOneTimeTransactionStatusParams, -): Promise -⋮---- -submitAutoInvestmentPlan( - params: CreateInvestmentPlanParams, -): Promise -⋮---- -getAutoInvestRedemptionHistory( - params: GetIndexLinkedPlanRedemptionHistoryParams, -): Promise -⋮---- -getAutoInvestPlan(params: GetPlanDetailsParams): Promise -⋮---- -getAutoInvestUserIndex(params: { - indexId: number; -}): Promise -⋮---- -getAutoInvestRebalanceHistory( - params: GetIndexLinkedPlanRebalanceHistoryParams, -): Promise -⋮---- -/** - * - * CONVERT Endpoints - Market Data - * - **/ -⋮---- -getConvertPairs(params: GetAllConvertPairsParams): Promise -⋮---- -getConvertAssetInfo(): Promise -⋮---- -/** - * - * CONVERT Endpoints - Trade - * - **/ -⋮---- -convertQuoteRequest(params: ConvertQuoteRequestParams): Promise -⋮---- -acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise -⋮---- -getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise -⋮---- -getOrderStatus(params: GetOrderStatusParams): Promise -⋮---- -submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise -⋮---- -cancelConvertLimitOrder(params: -⋮---- -getConvertLimitOpenOrders(): Promise< -⋮---- -/** - * - * STAKING Endpoints - ETH Staking - Account - * - **/ -⋮---- -/** - * @deprecated use getEthStakingAccountV2 instead - **/ -getEthStakingAccount(): Promise -⋮---- -getEthStakingAccountV2(): Promise -⋮---- -getEthStakingQuota(): Promise -⋮---- -/** - * - * STAKING Endpoints - ETH Staking- Staking - * - **/ -⋮---- -/** - * @deprecated use subscribeEthStakingV2 instead - **/ -subscribeEthStakingV1(params: -⋮---- -subscribeEthStakingV2(params: { - amount: number; -}): Promise -⋮---- -redeemEth(params: RedeemEthParams): Promise -⋮---- -wrapBeth(params: -⋮---- -/** - * - * STAKING Endpoints - ETH Staking - History - * - **/ -⋮---- -getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< -⋮---- -getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< -⋮---- -getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< -⋮---- -getWbethRewardsHistory( - params: GetWrapHistoryParams, -): Promise -⋮---- -getEthRateHistory(params: GetETHRateHistoryParams): Promise< -⋮---- -getBethWrapHistory(params: GetWrapHistoryParams): Promise< -⋮---- -getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< -⋮---- -/** - * - * BFUSD (sapi/v1/bfusd) - * - **/ -⋮---- -getBfusdAccount(): Promise -⋮---- -getBfusdQuota(): Promise -⋮---- -subscribeBfusd( - params: BfusdSubscribeParams, -): Promise -⋮---- -redeemBfusd(params: BfusdRedeemParams): Promise -⋮---- -getBfusdSubscriptionHistory( - params: GetBfusdSubscriptionHistoryParams, -): Promise< -⋮---- -getBfusdRedemptionHistory( - params: GetBfusdRedemptionHistoryParams, -): Promise< -⋮---- -getBfusdRewardsHistory( - params: GetBfusdRewardsHistoryParams, -): Promise< -⋮---- -getBfusdRateHistory( - params: GetBfusdRateHistoryParams, -): Promise< -⋮---- -/** - * - * RWUSD (sapi/v1/rwusd) - * - **/ -⋮---- -getRwusdAccount(): Promise -⋮---- -getRwusdQuota(): Promise -⋮---- -subscribeRwusd( - params: RwusdSubscribeParams, -): Promise -⋮---- -redeemRwusd(params: RwusdRedeemParams): Promise -⋮---- -getRwusdSubscriptionHistory( - params: GetRwusdSubscriptionHistoryParams, -): Promise< -⋮---- -getRwusdRedemptionHistory( - params: GetRwusdRedemptionHistoryParams, -): Promise< -⋮---- -getRwusdRewardsHistory( - params: GetRwusdRewardsHistoryParams, -): Promise< -⋮---- -getRwusdRateHistory( - params: GetRwusdRateHistoryParams, -): Promise< -⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingProducts( - params: StakingBasicParams & { - asset?: string; - }, -): Promise -⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingProductPosition( - params: StakingBasicParams & { - productId?: string; - asset?: string; - }, -): Promise -⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingHistory(params: StakingHistoryParams): Promise -⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getPersonalLeftQuotaOfStakingProduct(params: { - product: StakingProductType; - productId: string; -}): Promise -⋮---- -/** - * - * STAKING Endpoints - SOL Staking- Account - * - **/ -⋮---- -getSolStakingAccount(): Promise -⋮---- -getSolStakingQuota(): Promise -⋮---- -/** - * - * STAKING Endpoints - SOL Staking - Staking - * - **/ -⋮---- -subscribeSolStaking(params: { - amount: number; -}): Promise -⋮---- -redeemSol(params: -⋮---- -claimSolBoostRewards(): Promise< -⋮---- -/** - * - * STAKING Endpoints - SOL Staking- History - * - **/ -⋮---- -getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< -⋮---- -getSolRedemptionHistory(params?: { - rows: SolRedemptionHistoryRecord[]; - total: number; -}): Promise -⋮---- -getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< -⋮---- -getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< -⋮---- -getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< -⋮---- -getSolUnclaimedRewards(): Promise< - { - amount: string; - rewardsAsset: string; - }[] - > { - return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); -⋮---- -/** - * - * STAKING - Onchain Yields - Account - * - **/ -⋮---- -getOnchainYieldsLockedProducts( - params?: OnchainYieldsLockedProductListParams, -): Promise -⋮---- -getOnchainYieldsLockedPersonalLeftQuota( - params: OnchainYieldsLockedPersonalLeftQuotaParams, -): Promise -⋮---- -getOnchainYieldsLockedPosition( - params?: OnchainYieldsLockedPositionParams, -): Promise -⋮---- -getOnchainYieldsAccount(): Promise -⋮---- -/** - * - * STAKING - Onchain Yields - Earn - * - **/ -⋮---- -getOnchainYieldsLockedSubscriptionPreview( - params: OnchainYieldsLockedSubscriptionPreviewParams, -): Promise -⋮---- -subscribeOnchainYieldsLockedProduct( - params: OnchainYieldsLockedSubscribeParams, -): Promise -⋮---- -setOnchainYieldsLockedAutoSubscribe( - params: OnchainYieldsLockedSetAutoSubscribeParams, -): Promise -⋮---- -setOnchainYieldsLockedRedeemOption( - params: OnchainYieldsLockedSetRedeemOptionParams, -): Promise -⋮---- -redeemOnchainYieldsLockedProduct( - params: OnchainYieldsLockedRedeemParams, -): Promise -⋮---- -/** - * - * STAKING - Onchain Yields - History - * - **/ -⋮---- -getOnchainYieldsLockedSubscriptionRecord( - params?: OnchainYieldsLockedSubscriptionRecordParams, -): Promise -⋮---- -getOnchainYieldsLockedRewardsHistory( - params?: OnchainYieldsLockedRewardsHistoryParams, -): Promise -⋮---- -getOnchainYieldsLockedRedemptionRecord( - params?: OnchainYieldsLockedRedemptionRecordParams, -): Promise -⋮---- -/** - * - * STAKING - Soft staking - * - **/ -⋮---- -getSoftStakingProductList( - params?: GetSoftStakingProductListParams, -): Promise -⋮---- -setSoftStaking( - params: SetSoftStakingParams, -): Promise -⋮---- -getSoftStakingRewardsHistory( - params?: GetSoftStakingRewardsHistoryParams, -): Promise -⋮---- -/** - * - * COPY TRADING Endpoints - Future copy trading - * - **/ -⋮---- -getFuturesLeadTraderStatus(): Promise -⋮---- -getFuturesLeadTradingSymbolWhitelist(): Promise< - GetFuturesLeadTradingSymbolWhitelistResponse[] - > { - return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); -⋮---- -/** - * - * MINING Endpoints - rest api - * - **/ -⋮---- -getMiningAlgos(): Promise -⋮---- -getMiningCoins(): Promise -⋮---- -getHashrateResales( - params: GetHashrateResaleListParams, -): Promise -⋮---- -getMiners(params: GetMinerListParams): Promise -⋮---- -getMinerDetails( - params: GetMinerDetailsParams, -): Promise -⋮---- -getExtraBonuses( - params: GetExtraBonusListParams, -): Promise -⋮---- -getMiningEarnings( - params: GetEarningsListParams, -): Promise -⋮---- -cancelHashrateResaleConfig( - params: CancelHashrateResaleConfigParams, -): Promise -⋮---- -getHashrateResale( - params: GetHashrateResaleDetailParams, -): Promise -⋮---- -getMiningAccountEarnings( - params: GetMiningAccountEarningParams, -): Promise -⋮---- -getMiningStatistics( - params: GetStatisticListParams, -): Promise -⋮---- -submitHashrateResale(params: SubmitHashrateResaleParams): Promise -⋮---- -getMiningAccounts( - params: getMiningAccountsListParams, -): Promise -⋮---- -/** - * - * ALGO TRADING Endpoints - Future algo - * - **/ -⋮---- -submitVpNewOrder( - params: SubmitVpNewOrderParams, -): Promise -⋮---- -submitTwapNewOrder( - params: SubmitTwapNewOrderParams, -): Promise -⋮---- -cancelAlgoOrder( - params: - | { algoId: number; clientAlgoId?: string } - | { clientAlgoId: string; algoId?: number }, -): Promise -⋮---- -getAlgoSubOrders( - params: GetAlgoSubOrdersParams, -): Promise -⋮---- -getAlgoOpenOrders(): Promise< -⋮---- -getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< -⋮---- -/** - * - * ALGO TRADING Endpoints - Spot algo - * - **/ -⋮---- -submitSpotAlgoTwapOrder( - params: SubmitSpotTwapNewOrderParams, -): Promise -⋮---- -cancelSpotAlgoOrder( - params: - | { algoId: number; clientAlgoId?: string } - | { clientAlgoId: string; algoId?: number }, -): Promise -⋮---- -getSpotAlgoSubOrders( - params: GetSpotAlgoSubOrdersParams, -): Promise -⋮---- -getSpotAlgoOpenOrders(): Promise< -⋮---- -getSpotAlgoHistoricalOrders( - params: GetSpotAlgoHistoricalOrdersParams, -): Promise< -⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - Market data - * - **/ -⋮---- -getCryptoLoanFlexibleCollateralAssets(params: { - collateralCoin?: string; -}): Promise< -⋮---- -getCryptoLoanFlexibleAssets(params: -⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - Trade - * - **/ -⋮---- -borrowCryptoLoanFlexible( - params: BorrowFlexibleLoanParams, -): Promise -⋮---- -repayCryptoLoanFlexible( - params: RepayCryptoFlexibleLoanParams, -): Promise -⋮---- -repayCryptoLoanFlexibleWithCollateral( - params: RepayCryptoLoanFlexibleWithCollateralParams, -): Promise -⋮---- -adjustCryptoLoanFlexibleLTV( - params: AdjustFlexibleCryptoLoanLTVParams, -): Promise -⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - User info - * - **/ -⋮---- -getCryptoLoanFlexibleLTVAdjustmentHistory( - params: GetFlexibleLoanLTVAdjustmentHistoryParams, -): Promise< -⋮---- -getFlexibleLoanCollateralRepayRate(params: { - loanCoin: string; - collateralCoin: string; -}): Promise< -⋮---- -getLoanFlexibleBorrowHistory( - params: GetFlexibleCryptoLoanBorrowHistoryParams, -): Promise< -⋮---- -getCryptoLoanFlexibleOngoingOrders( - params: GetFlexibleLoanOngoingOrdersParams, -): Promise< -⋮---- -getFlexibleLoanLiquidationHistory( - params?: GetFlexibleLoanLiquidationHistoryParams, -): Promise< -⋮---- -getLoanFlexibleRepaymentHistory( - params: GetLoanRepaymentHistoryParams, -): Promise< -⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - Market data - * - **/ -⋮---- -/** - * @deprecated - */ -getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< -⋮---- -getCryptoLoanCollateralRepayRate( - params: CheckCollateralRepayRateParams, -): Promise -⋮---- -/** - * @deprecated - */ -getCryptoLoanCollateralAssetsData( - params: GetCollateralAssetDataParams, -): Promise< -⋮---- -/** - * @deprecated Stable Rate history was retired on 2026-10-16. - * `GET /sapi/v1/loan/income` returns HTTP 404. Flexible Rate v2 is unaffected. - */ -getCryptoLoansIncomeHistory( - params: GetCryptoLoansIncomeHistoryParams, -): Promise -⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - Trade - * - **/ -⋮---- -/** - * @deprecated - */ -borrowCryptoLoan( - params: BorrowCryptoLoanParams, -): Promise -⋮---- -/** - * @deprecated - */ -repayCryptoLoan( - params: RepayCryptoLoanParams, -): Promise -⋮---- -/** - * @deprecated - */ -adjustCryptoLoanLTV( - params: AdjustCryptoLoanLTVParams, -): Promise -⋮---- -/** - * @deprecated - */ -customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< -⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - User info - * - **/ -⋮---- -/** - * @deprecated - */ -getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< -⋮---- -/** - * @deprecated Stable Rate history was retired on 2026-10-16. - * `GET /sapi/v1/loan/borrow/history` returns HTTP 404. Flexible Rate v2 is unaffected. - */ -getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< -⋮---- -/** - * @deprecated Stable Rate history was retired on 2026-10-16. - * `GET /sapi/v1/loan/ltv/adjustment/history` returns HTTP 404. Flexible Rate v2 is unaffected. - */ -getCryptoLoanLTVAdjustmentHistory( - params: GetLoanLTVAdjustmentHistoryParams, -): Promise< -⋮---- -/** - * @deprecated Stable Rate history was retired on 2026-10-16. - * `GET /sapi/v1/loan/repay/history` returns HTTP 404. Flexible Rate v2 is unaffected. - */ -getCryptoLoanRepaymentHistory( - params: GetLoanRepaymentHistoryParams, -): Promise -⋮---- -/** - * - * SIMPLE EARN Endpoints - Account - * - **/ -⋮---- -getSimpleEarnAccount(): Promise -⋮---- -getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< -⋮---- -getSimpleEarnLockedProductList( - params?: SimpleEarnProductListParams, -): Promise< -⋮---- -getFlexibleProductPosition( - params?: SimpleEarnFlexibleProductPositionParams, -): Promise< -⋮---- -getLockedProductPosition( - params?: SimpleEarnLockedProductPositionParams, -): Promise< -⋮---- -getFlexiblePersonalLeftQuota(params: -⋮---- -getLockedPersonalLeftQuota(params: -⋮---- -/** - * - * SIMPLE EARN Endpoints - Earn - * - **/ -⋮---- -purchaseFlexibleProduct( - params: SimpleEarnSubscribeProductParams, -): Promise -⋮---- -subscribeSimpleEarnLockedProduct( - params: SimpleEarnSubscribeProductParams, -): Promise -⋮---- -redeemFlexibleProduct( - params: SimpleEarnRedeemFlexibleProductParams, -): Promise -⋮---- -redeemLockedProduct(params: { - positionId: string; -}): Promise -⋮---- -setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< -⋮---- -setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< -⋮---- -getFlexibleSubscriptionPreview( - params: GetFlexibleSubscriptionPreviewParams, -): Promise -⋮---- -getLockedSubscriptionPreview( - params: GetLockedSubscriptionPreviewParams, -): Promise -⋮---- -setLockedProductRedeemOption(params: { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; -}): Promise< -⋮---- -/** - * - * SIMPLE EARN Endpoints - History - * - **/ -⋮---- -getFlexibleSubscriptionRecord( - params: GetFlexibleSubscriptionRecordParams, -): Promise< -⋮---- -getLockedSubscriptionRecord( - params: GetLockedSubscriptionRecordParams, -): Promise< -⋮---- -getFlexibleRedemptionRecord( - params: GetFlexibleRedemptionRecordParams, -): Promise< -⋮---- -getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< -⋮---- -getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< -⋮---- -getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< -⋮---- -getCollateralRecord(params: GetCollateralRecordParams): Promise< -⋮---- -getRateHistory(params: GetRateHistoryParams): Promise< -⋮---- -/** - * - * VIP LOAN Endpoints - Market Data - * - **/ -⋮---- -getVipBorrowInterestRate(params: { - loanCoin: string; -}): Promise -⋮---- -getVipLoanInterestRateHistory( - params: VipLoanInterestRateHistoryParams, -): Promise< -⋮---- -getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< -⋮---- -getVipCollateralAssets(params: -⋮---- -/** - * - * VIP LOAN Endpoints - User Info - * - **/ -⋮---- -getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< -⋮---- -getVipLoanRepaymentHistory( - params: GetVipLoanRepaymentHistoryParams, -): Promise< -⋮---- -checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< -⋮---- -getVipApplicationStatus(params: GetApplicationStatusParams): Promise< -⋮---- -/** - * - * VIP LOAN Endpoints - Trade - * - **/ -⋮---- -renewVipLoan(params: VipLoanRenewParams): Promise -⋮---- -repayVipLoan(params: VipLoanRepayParams): Promise -⋮---- -borrowVipLoan(params: VipLoanBorrowParams): Promise -⋮---- -getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise< -⋮---- -borrowVipLoanFixedRate( - params: VipLoanFixedRateBorrowParams, -): Promise -⋮---- -/** - * - * DUAL INVESTMENT Endpoints - Market Data - * - **/ -⋮---- -getDualInvestmentProducts( - params: GetDualInvestmentProductListParams, -): Promise< -⋮---- -/** - * - * DUAL INVESTMENT Endpoints - Trade - * - **/ -⋮---- -subscribeDualInvestmentProduct( - params: SubscribeDualInvestmentProductParams, -): Promise -⋮---- -getDualInvestmentPositions( - params: GetDualInvestmentPositionsParams, -): Promise< -⋮---- -getDualInvestmentAccounts(): Promise -⋮---- -getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< -⋮---- -/** - * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. - * Calls to this method will fail. Configure auto-compound for Dual Investment positions - * in the Binance web UI. This method will be removed in a future major version. - * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published - * binance-api-swagger spec still lists the endpoint, so this method stays deprecated. - */ -updateAutoCompoundStatus( - params: ChangeAutoCompoundStatusParams, -): Promise -⋮---- -/** - * - * GIFT CARD Endpoints - Market Data - * - **/ -⋮---- -createGiftCard(params: CreateGiftCardParams): Promise -⋮---- -createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise -⋮---- -redeemGiftCard(params: RedeemGiftCardParams): Promise -⋮---- -verifyGiftCard(params: -⋮---- -getTokenLimit(params: -⋮---- -getRsaPublicKey(): Promise -⋮---- -/** - * - * NFT Endpoints - REST api - * - **/ -⋮---- -getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< -⋮---- -getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< -⋮---- -getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< -⋮---- -getNftAsset(params: GetNftAssetParams): Promise< -⋮---- -/** - * - * C2C Endpoints - * - **/ -⋮---- -getC2CTradeHistory( - params: GetC2CTradeHistoryParams, -): Promise -⋮---- -/** - * - * FIAT Endpoints - REST api - * - **/ -⋮---- -getFiatOrderHistory( - params: GetFiatOrderHistoryParams, -): Promise -⋮---- -getFiatPaymentsHistory( - params: GetFiatOrderHistoryParams, -): Promise -⋮---- -fiatWithdraw(params: WithdrawFiatParams): Promise< -⋮---- -fiatDeposit(params: FiatDepositParams): Promise -⋮---- -getFiatOrderDetail( - params: GetFiatOrderDetailParams, -): Promise -⋮---- -/** - * - * Rebate Endpoints - * - **/ -⋮---- -getSpotRebateHistoryRecords( - params: GetSpotRebateHistoryRecordsParams, -): Promise -⋮---- -/** - * - * DERIVATIVES - Portfolio Margin Pro - Market Data - * This is in mainclient because it shares the same base url - * - **/ -⋮---- -getPortfolioMarginIndexPrice(params?: { - asset?: string; -}): Promise -⋮---- -getPortfolioMarginAssetLeverage(): Promise< - GetPortfolioMarginAssetLeverageResponse[] - > { - return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); -⋮---- -getPortfolioMarginProCollateralRate(): Promise< - GetPortfolioMarginProCollateralRateResponse[] - > { - return this.get('sapi/v1/portfolio/collateralRate'); -⋮---- -getPortfolioMarginProTieredCollateralRate(): Promise -⋮---- -/** - * - * DERIVATIVES - Portfolio Margin Pro - Account - * This is in mainclient because it shares the same base url - * - **/ -⋮---- -getPortfolioMarginProAccountInfo(): Promise -⋮---- -getPortfolioDeltaMode(): Promise -⋮---- -switchPortfolioDeltaMode( - params: SwitchPortfolioDeltaModeParams, -): Promise< -⋮---- -setPortfolioMarginMarginCallLevel( - params: SetPortfolioMarginMarginCallLevelParams, -): Promise -⋮---- -getPortfolioMarginMarginCallLevel(): Promise -⋮---- -deletePortfolioMarginMarginCallLevel(): Promise -⋮---- -bnbTransfer(params: BnbTransferParams): Promise< -⋮---- -submitPortfolioMarginProFullTransfer(): Promise< -⋮---- -/** - * Fund collection by asset (`POST /sapi/v1/portfolio/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. - */ -submitPortfolioMarginProSpecificTransfer(params: { - asset: string; - amount?: number; - futureType?: 'UM' | 'CM' | 'OPTION'; -}): Promise< -⋮---- -repayPortfolioMarginProBankruptcyLoan(params: { - from?: 'SPOT' | 'MARGIN'; -}): Promise< -⋮---- -getPortfolioMarginProBankruptcyLoanAmount(): Promise -⋮---- -repayFuturesNegativeBalance(): Promise< -⋮---- -updateAutoRepayFuturesStatus(params: -⋮---- -getAutoRepayFuturesStatus(): Promise< -⋮---- -getPortfolioMarginProInterestHistory( - params: GetPortfolioMarginProInterestHistoryParams, -): Promise -⋮---- -getPortfolioMarginProSpanAccountInfo(): Promise -⋮---- -getPortfolioMarginProAccountBalance(params?: { - asset?: string; -}): Promise -⋮---- -/** - * @deprecated - * Check Simple Earn endpoints for new way of doing it - */ -mintPortfolioMarginBFUSD( - params: PMProMintBFUSDParams, -): Promise -⋮---- -/** - * @deprecated - * Check Simple Earn endpointsfor new way of doing it - */ -redeemPortfolioMarginBFUSD(params: { - fromAsset: string; // BFUSD only - targetAsset: string; // USDT only - amount: number; -}): Promise -⋮---- -fromAsset: string; // BFUSD only -targetAsset: string; // USDT only -⋮---- -getPortfolioMarginBankruptcyLoanRepayHistory(params?: { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -}): Promise< -⋮---- -/** - * Transfer LDUSDT as collateral for all types of Portfolio Margin account - */ -transferLDUSDTPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; - amount: number; -}): Promise< -⋮---- -/** - * Get transferable earn asset balance for all types of Portfolio Margin account - */ -getTransferableEarnAssetBalanceForPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; -}): Promise< -⋮---- -/** - * - * DERIVATIVES - Futures Data - Market - * This is in mainclient because it shares the same base url - * - **/ -⋮---- -getFuturesTickLevelOrderbookDataLink( - params: GetFutureTickLevelOrderbookDataLinkParams, -): Promise< -⋮---- -/** - * - * BLVT Endpoints - * BLVT category is possibly @deprecated, found only in old docs - **/ -⋮---- -getBlvtInfo(params?: -⋮---- -subscribeBlvt(params: SubscribeBlvtParams): Promise -⋮---- -getBlvtSubscriptionRecord( - params: GetBlvtSubscriptionRecordParams, -): Promise -⋮---- -redeemBlvt(params: RedeemBlvtParams): Promise -⋮---- -getBlvtRedemptionRecord( - params: GetBlvtRedemptionRecordParams, -): Promise -⋮---- -getBlvtUserLimitInfo(params: { - tokenName?: string; -}): Promise -⋮---- -/** - * - * Pay endpoints - * Found only in old docs, possibly @deprecated - **/ -getPayTransactions(params: GetPayTradeHistoryParams): Promise -⋮---- -/** - * - * INSTITUTIONAL LOAN - Account Endpoints - * - **/ -⋮---- -getInstLoanRiskUnit( - params?: GetInstitutionalLoanRiskUnitDetailsParams, -): Promise -⋮---- -closeInstLoanRiskUnit(): Promise -⋮---- -addInstLoanCollateralAccount( - params: AddInstitutionalLoanCollateralAccountParams, -): Promise -⋮---- -getActiveInstLoanRiskUnits(): Promise -⋮---- -getClosedInstLoanRiskUnits( - params?: GetClosedInstitutionalLoanRiskUnitsParams, -): Promise -⋮---- -/** - * - * INSTITUTIONAL LOAN - Trade Endpoints - * - **/ -⋮---- -getInstLoanForceLiquidationRecord( - params: GetInstitutionalLoanForceLiquidationParams, -): Promise -/** - * - * INSTITUTIONAL LOAN - TransferEndpoints - * - **/ -⋮---- -transferInstLoanRiskUnit( - params: InstitutionalLoanRiskUnitTransferParams, -): Promise -⋮---- -/** - * - * INSTITUTIONAL LOAN - Borrow/Repay Endpoints - * - **/ -⋮---- -getInstitutionalLoanMaxBorrowable( - params: GetInstitutionalLoanMaxBorrowableParams, -): Promise -⋮---- -borrowInstitutionalLoan( - params: InstitutionalLoanBorrowParams, -): Promise -⋮---- -getInstLoanInterestHistory( - params?: GetInstitutionalLoanInterestHistoryParams, -): Promise -⋮---- -repayInstitutionalLoan( - params: InstitutionalLoanRepayParams, -): Promise -⋮---- -getInstLoanBorrowRepayRecords( - params: GetInstitutionalLoanBorrowRepayRecordsParams, -): Promise -⋮---- -getMarginInterestRebateBalance(): Promise -⋮---- -getMarginInterestRebateBalanceRecords( - params?: GetMarginInterestRebateBalanceRecordsParams, -): Promise -⋮---- -/** - * - * ALPHA TRADING - Market Data - * https://developers.binance.com/docs/alpha - */ -⋮---- -getAlphaTokenList(): Promise -⋮---- -getAlphaExchangeInfo(): Promise -⋮---- -getAlphaAggTrades(params: AlphaAggTradesParams): Promise -⋮---- -getAlphaKlines(params: AlphaKlinesParams): Promise -⋮---- -getAlphaTicker(params: -⋮---- -getAlphaFullDepth( - params: AlphaFullDepthParams, -): Promise -⋮---- -/** - * - * EXCHANGE LINK - Account Endpoints - * https://developers.binance.com/docs/binance_link - */ -⋮---- -createBrokerSubAccount( - params: CreateBrokerSubAccountParams, -): Promise -⋮---- -getBrokerSubAccount( - params: GetBrokerSubAccountParams, -): Promise -⋮---- -enableMarginBrokerSubAccount( - params: EnableMarginBrokerSubAccountParams, -): Promise -⋮---- -createApiKeyBrokerSubAccount( - params: CreateApiKeyBrokerSubAccountParams, -): Promise -⋮---- -changePermissionApiKeyBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise -⋮---- -changeComissionBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise -⋮---- -enableUniversalTransferApiKeyBrokerSubAccount( - params: EnableUniversalTransferApiKeyBrokerSubAccountParams, -): Promise -⋮---- -updateIpRestrictionForSubAccountApiKey( - params: UpdateIpRestrictionForSubApiKey, -): Promise< -⋮---- -deleteIPRestrictionForSubAccountApiKey(params: { - subAccountId: string; - subAccountApiKey: string; - ipAddress?: string; -}): Promise< -⋮---- -deleteApiKeyBrokerSubAccount( - params: DeleteApiKeyBrokerSubAccountParams, -): Promise -⋮---- -getSubAccountBrokerIpRestriction(params: { - subAccountId: string; - subAccountApiKey: string; -}): Promise< -⋮---- -getApiKeyBrokerSubAccount( - params: GetApiKeyBrokerSubAccountParams, -): Promise -⋮---- -getBrokerInfo(): Promise -⋮---- -updateSubAccountBNBBurn(params: { - subAccountId: string; - spotBNBBurn: 'true' | 'false'; -}): Promise< -⋮---- -updateSubAccountMarginInterestBNBBurn(params: { - subAccountId: string; - interestBNBBurn: 'true' | 'false'; -}): Promise< -⋮---- -getSubAccountBNBBurnStatus(params: -⋮---- -/** - * Caution: - * The operation will delete a sub account under your brokerage master account. - * Please transfer out all funds from the sub account and delete API key of the sub account before deleting it. - * The deleted sub account CANNOT be reverted. - * The daily deletion limit for a broker Master is 20 sub accounts. - * You need to enable "trade" option for the api key which requests this endpoint. - */ -deleteBrokerSubAccount(params: -⋮---- -/** - * - * EXCHANGE LINK - Asset Endpoints - * https://developers.binance.com/docs/binance_link - */ -⋮---- -transferBrokerSubAccount( - params: TransferBrokerSubAccountParams, -): Promise -⋮---- -getBrokerSubAccountHistory( - params: GetBrokerSubAccountHistoryParams, -): Promise -⋮---- -submitBrokerSubFuturesTransfer(params: { - fromId?: string; - toId?: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - asset: string; - amount: number; - clientTranId?: string; // The max length is 32 characters -}): Promise< -⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures -⋮---- -clientTranId?: string; // The max length is 32 characters -⋮---- -getSubAccountFuturesTransferHistory(params: { - subAccountId: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -}): Promise -⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures -⋮---- -getBrokerSubDepositHistory( - params: GetSubAccountDepositHistoryParams, -): Promise -⋮---- -getBrokerSubAccountSpotAssets( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< -⋮---- -getSubAccountMarginAssetInfo( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< -⋮---- -querySubAccountFuturesAssetInfo( - params: QuerySubAccountFuturesAssetInfoParams, -): Promise< -⋮---- -universalTransferBroker(params: UniversalTransferBrokerParams): Promise< -⋮---- -getUniversalTransferBroker( - params: GetUniversalTransferBrokerParams, -): Promise -⋮---- -/** - * - * EXCHANGE LINK - Fee Endpoints - * https://developers.binance.com/docs/binance_link - */ -⋮---- -updateBrokerSubAccountCommission( - params: ChangeSubAccountCommissionParams, -): Promise -⋮---- -updateBrokerSubAccountFuturesCommission( - params: ChangeSubAccountFuturesCommissionParams, -): Promise -⋮---- -getBrokerSubAccountFuturesCommission( - params: QuerySubAccountFuturesCommissionParams, -): Promise -⋮---- -updateBrokerSubAccountCoinFuturesCommission( - params: ChangeSubAccountCoinFuturesCommissionParams, -): Promise -⋮---- -getBrokerSubAccountCoinFuturesCommission( - params: QuerySubAccountCoinFuturesCommissionParams, -): Promise -⋮---- -getBrokerSpotCommissionRebate( - params: QueryBrokerSpotCommissionRebateParams, -): Promise -⋮---- -getBrokerFuturesCommissionRebate( - params: QueryBrokerFuturesCommissionRebateParams, -): Promise -⋮---- -/** - * - * @deprecated - */ -// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) -getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) -⋮---- -/** - * Broker Endpoints - only on old docs - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link - */ -⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerIfNewSpotUser(): Promise< -⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerSubAccountDepositHistory( - params?: GetBrokerSubAccountDepositHistoryParams, -): Promise -⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerUserCustomisedId(market: 'spot' | 'futures') -⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableFuturesBrokerSubAccount( - params: EnableFuturesBrokerSubAccountParams, -): Promise -⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableMarginApiKeyBrokerSubAccount( - params: EnableMarginApiKeyBrokerSubAccountParams, -): Promise -⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewSpotOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams - | NewOrderListParams, - orderIdProperty: OrderIdProperty, -): void -⋮---- -/** - * - * User Data Stream Endpoints - * - **/ -⋮---- -// spot -getSpotUserDataListenKey(): Promise< -⋮---- -keepAliveSpotUserDataListenKey(listenKey: string): Promise -⋮---- -closeSpotUserDataListenKey(listenKey: string): Promise -⋮---- -/** - * Get a cross margin user data listen key - */ -getMarginUserDataListenKey(): Promise< -⋮---- -keepAliveMarginUserDataListenKey(listenKey: string): Promise -⋮---- -closeMarginUserDataListenKey(listenKey: string): Promise -⋮---- -// isolated margin -getIsolatedMarginUserDataListenKey(params: { - symbol: string; -}): Promise< -⋮---- -keepAliveIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise -⋮---- -closeIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise -⋮---- -/** - * Get a cross margin risk data listen key - */ -getMarginRiskUserDataListenKey(): Promise< -⋮---- -keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise -⋮---- -closeMarginRiskUserDataListenKey(): Promise -⋮---- -/** - * Start a Margin user data stream (`POST /sapi/v2/margin/listen-key`). - * Weight(IP): 1. USER_STREAM. - * - * New and migrated accounts receive -3086 from - * `POST /sapi/v1/margin/listen-key` and `POST /sapi/v1/userListenToken`. - * Connect with `wss://fstream.binance.com/private/ws/`. - */ -getMarginUserDataListenKeyV2(): Promise< -⋮---- -/** - * Keepalive a Margin user data stream (`PUT /sapi/v2/margin/listen-key`). - * Weight(IP): 1. USER_STREAM. `listenKey` is a query parameter. - */ -keepAliveMarginUserDataListenKeyV2(listenKey: string): Promise -⋮---- -/** - * Close a Margin user data stream (`DELETE /sapi/v2/margin/listen-key`). - * Weight(IP): 1. USER_STREAM. The listen key is not a parameter. - */ -closeMarginUserDataListenKeyV2(): Promise -⋮---- -getMarginUtaUserDataListenKey(): Promise< -⋮---- -keepAliveMarginUtaUserDataListenKey(listenKey: string): Promise -⋮---- -closeMarginUtaUserDataListenKey(): Promise -⋮---- -/** - * Get/create margin account listenToken for the user data stream - * https://developers.binance.com/docs/margin_trading/trade-data-stream - */ -getMarginListenToken(params?: { - symbol?: string; - isIsolated?: boolean; - validity?: number; -}): Promise< -⋮---- -/** - * - * DEPRECATED ENDPOINTS - * - **/ -/** - * - * BSwap Endpoints - * @deprecated as of 2024-01-19 - **/ -⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -getBSwapLiquidity(params?: -⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -addBSwapLiquidity(params: AddBSwapLiquidityParams): Promise< -⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -removeBSwapLiquidity(params: RemoveBSwapLiquidityParams): Promise< -⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -getBSwapOperations( - params?: BSwapOperationsParams, -): Promise -⋮---- -/** - * - * Savings Endpoints - * @deprecated as of 2023-06-22, now Simple Earn - **/ -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyPurchaseQuotaFlexibleProduct(params: { - productId: string; -}): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyRedemptionQuotaFlexibleProduct(params: { - productId: string; - }): Promise< - LeftDailyPurchaseQuotaFlexibleProductResponse & { - dailyQuota: string; - minRedemptionAmount: string; - } - > { - return this.getPrivate('sapi/v1/lending/daily/userRedemptionQuota', params); -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -purchaseFixedAndActivityProject(params: { - projectId: string; - lot: number; -}): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProjects( - params: FixedAndActivityProjectParams, -): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProductPosition( - params: FixedAndActivityProjectPositionParams, -): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLendingAccount(): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getPurchaseRecord(params: PurchaseRecordParams): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getRedemptionRecord(params: PurchaseRecordParams): Promise -⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getInterestHistory(params: PurchaseRecordParams): 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 ⋮---- /** - * @deprecated as of 2023-06-22, now Simple Earn + * Subscribe to spot orderbook depth updates to locally manage an order book. */ -changeFixedAndActivityPositionToDailyPosition(params: { - projectId: string; - lot: number; - positionId?: number; -}): Promise -⋮---- -/** - * - * Wallet Endpoints - * @deprecated - **/ -⋮---- +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + wsKeyOverride?: WsKey, + ): Promise + +================ +File: README.md +================ +# Node.js & JavaScript SDK for Binance REST APIs & WebSockets + +[![Build & Test](https://github.com/sieblyio/binance/actions/workflows/test.yml/badge.svg)](https://github.com/sieblyio/binance/actions/workflows/test.yml) +[![npm version](https://img.shields.io/npm/v/binance)][1] +[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1] +[![users count](https://dependents.info/sieblyio/binance/badge?label=users)](https://dependents.info/sieblyio/binance) +[![npm downloads](https://img.shields.io/npm/dt/binance)][1] +[![last commit](https://img.shields.io/github/last-commit/sieblyio/binance)][1] +[![CodeFactor](https://www.codefactor.io/repository/github/sieblyio/binance/badge)](https://www.codefactor.io/repository/github/sieblyio/binance) +[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) +[![Binance Tutorial](https://img.shields.io/badge/Binance%20Tutorial-siebly.io-blue)](https://siebly.io/sdk/binance/javascript/tutorial) + +

+ + + + SDK Logo + + +

+ +[1]: https://www.npmjs.com/package/binance + +> [!TIP] +> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK is now hosted under our [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. + +Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets. + +Spot user data stream (listen key is created and kept alive for you): + +```javascript +import { WebsocketClient } from 'binance'; +const ws = new WebsocketClient({ api_key: 'key', api_secret: 'secret' }); +ws.on('formattedMessage', (data) => console.log(data)); +ws.subscribeSpotUserDataStream(); +``` + +- Professional, robust & performant Binance SDK with leading trading volume in production (livenet). +- Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. +- Complete TypeScript support (with type declarations for all API requests & responses). +- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. + - Strongly typed requests and responses. + - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. +- Actively maintained with a modern, promise-driven interface. +- Support for all authentication mechanisms available on Binance: + - HMAC + - RSA + - Ed25519 (required for WS API login, else each request is signed). + - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication. +- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures. + - Event driven messaging. + - Smart WebSocket persistence + - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. + - Automatically handle listenKey persistence and expiration/refresh. + - Emit `reconnected` event when dropped connection is restored. + - Strongly typed on most WebSocket events, with typeguards available for TypeScript users. + - Optional: + - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers). + - Automatic beautification of REST responses (parsing numbers in strings to numbers). +- Supports WebSocket API on all available product groups, including Spot & Futures: + - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or; + - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. +- Heavy automated end-to-end testing with real API calls. + - End-to-end testing before any release. + - Real API calls in e2e tests. +- Proxy support via axios integration. +- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). +- QuickStart Guide: [Binance JavaScript QuickStart Guide](https://siebly.io/sdk/binance/javascript) +- Binance JavaScript Tutorial: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) + +## Table of Contents + +- [Installation](#installation) +- [Examples](#examples) + - [REST API Examples](./examples/REST) + - [WebSocket Examples](./examples/WebSockets) + - [WebSocket Consumers](./examples/WebSockets/) + - [WebSocket API](./examples/WebSockets/ws-api-client.ts) +- [Issues & Discussion](#issues--discussion) +- [Related Projects](#related-projects) +- [Documentation Links](#documentation) +- [Usage](#usage) + - [Demo Trading vs Testnet](#demo-trading-vs-testnet) + - [REST API Clients](#rest-api-clients) + - [REST Main Client](#rest-main-client) + - [REST USD-M Futures](#rest-usd-m-futures) + - [REST COIN-M Futures](#rest-coin-m-futures) + - [REST Portfolio Margin](#rest-portfolio-margin) + - [WebSockets](#websockets) + - [WebSocket Consumers](#websocket-consumers) + - [WebSocket API](#websocket-api) + - [Event Driven API](#event-driven-api) + - [Promise Driven API](#async-await-api) + - [Market Maker Endpoints](#market-maker-endpoints) + - [Using Market Maker Endpoints](#using-market-maker-endpoints) + - [Best practice](#best-practice) + - [Customise Logging](#customise-logging) + - [Frontend Usage](#browserfrontend-usage) + - [Import](#import) + - [Webpack](#webpack) +- [LLMs & AI](#use-with-llms--ai) +- [Contributions & Thanks](#contributions--thanks) + +## Installation + +`npm install binance --save` + +## Examples + +Refer to the [examples](./examples) folder for implementation demos. + +## Issues & Discussion + +- Issues? Check the [issues tab](https://github.com/sieblyio/binance/issues). +- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. +- Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. +- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) + + + +## Related Projects + +Check out our JavaScript/TypeScript/Node.js SDKs & Projects: + +- Visit our website: [https://Siebly.io](https://siebly.io/) +- Try our REST API & WebSocket SDKs published on npmjs: + - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) + - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) + - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) + - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) + - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) + - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) + - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) + - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) + - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) +- Try my misc utilities: + - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) + - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) +- Check out my examples: + - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) + + +## Documentation + +Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. + +- Binance API Documentation + - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) + - [ Derivatives ](https://developers.binance.com/docs/derivatives) + - [ Margin ](https://developers.binance.com/docs/margin_trading) + - [ Wallet ](https://developers.binance.com/docs/wallet) +- [Find all products here](https://developers.binance.com/en) +- [REST Endpoint Function List](./docs/endpointFunctionList.md) +- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) + +## Structure + +This project uses typescript. Resources are stored in 3 key structures: + +- [src](./src) - the whole connector written in typescript +- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. +- [dist](./dist) - the packed bundle of the project for use in browser environments. + +--- + +# Usage + +Create API credentials at Binance + +- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) +- [Testnet](https://testnet.binance.vision/). +- [Testnet Futures](testnet.binancefuture.com). +- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading. + +### Demo Trading vs Testnet + +Binance offers two testing environments: + +- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures. +- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing. + +To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information. + +## REST API Clients + +There are several REST API modules as there are some differences in each API group. + +1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management. +2. `USDMClient` for USD-M futures APIs. +3. `CoinMClient` for COIN-M futures APIs. +4. `PortfolioClient` for Portfolio Margin APIs. + +Vanilla Options is not yet available. Please get in touch if you're looking for this. + +### REST Main Client + +The MainClient covers all endpoints under the main "api\*.binance.com" subdomains, including but not limited to endpoints in the following product groups: + +- Spot +- Cross & isolated margin +- Convert +- Wallet +- Futures management (transfers & history) +- Sub account management +- Misc transfers +- Auto & dual invest +- Staking +- Mining +- Loans & VIP loans +- Simple Earn +- NFTs +- C2C +- Exchange Link +- Alpha trading + +Refer to the following links for a complete list of available endpoints: + +- [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/sieblyio/binance/blob/master/docs/endpointFunctionList.md) +- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) + +Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. + +```javascript +import { MainClient } from 'binance'; + +// or, if you prefer `require()`: +// const { MainClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new MainClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getAccountTradeList({ symbol: 'BTCUSDT' }) + .then((result) => { + console.log('getAccountTradeList result: ', result); + }) + .catch((err) => { + console.error('getAccountTradeList error: ', err); + }); + +client + .getExchangeInfo() + .then((result) => { + console.log('getExchangeInfo inverse result: ', result); + }) + .catch((err) => { + console.error('getExchangeInfo inverse error: ', err); + }); +``` + +See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. + +### REST USD-M Futures + +Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. + +```javascript +import { USDMClient } from 'binance'; + +// or, if you prefer `require()`: +// const { USDMClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getBalance() + .then((result) => { + console.log('getBalance result: ', result); + }) + .catch((err) => { + console.error('getBalance error: ', err); + }); + +client + .submitNewOrder({ + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + }) + .then((result) => { + console.log('submitNewOrder result: ', result); + }) + .catch((err) => { + console.error('submitNewOrder error: ', err); + }); +``` + +See [usdm-client.ts](./src/usdm-client.ts) for further information. + +### REST COIN-M Futures + +Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. + +```javascript +import { CoinMClient } from 'binance'; + +// or, if you prefer `require()`: +// const { CoinMClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new CoinMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getSymbolOrderBookTicker() + .then((result) => { + console.log('getSymbolOrderBookTicker result: ', result); + }) + .catch((err) => { + console.error('getSymbolOrderBookTicker error: ', err); + }); +``` + +See [coinm-client.ts](./src/coinm-client.ts) for further information. + +### REST Portfolio Margin + +Start by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. + +```javascript +import { PortfolioClient } from 'binance'; + +// or, if you prefer `require()`: +// const { PortfolioClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new PortfolioClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getBalance() + .then((result) => { + console.log('getBalance result: ', result); + }) + .catch((err) => { + console.error('getBalance error: ', err); + }); + +client + .submitNewUMOrder({ + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + }) + .then((result) => { + console.log('submitNewUMOrder result: ', result); + }) + .catch((err) => { + console.error('submitNewUMOrder error: ', err); + }); +``` + +See [portfolio-client.ts](./src/portfolio-client.ts) for further information. + +## WebSockets + +### WebSocket Consumers + +All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. + +The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: + +```javascript +import { WebsocketClient } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + /** - * @deprecated - */ -enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise -⋮---- + * The WebsocketClient will manage individual connections for you, under the hood. + * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. + */ +const wsClient = new WebsocketClient({ + api_key: key, + api_secret: secret, + // Optional: when enabled, the SDK will try to format incoming data into more readable objects. + // Beautified data is emitted via the "formattedMessage" event + beautify: true, + // Disable ping/pong ws heartbeat mechanism (not recommended) + // disableHeartbeat: true, + // Connect to testnet environment + // testnet: true, +}); + +// receive raw events +wsClient.on('message', (data) => { + console.log('raw message received ', JSON.stringify(data, null, 2)); +}); + +// notification when a connection is opened +wsClient.on('open', (data) => { + console.log('connection opened open:', data.wsKey, data.wsUrl); +}); + +// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. +wsClient.on('formattedMessage', (data) => { + console.log('formattedMessage: ', data); +}); + +// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +wsClient.on('response', (data) => { + console.log('log response: ', JSON.stringify(data, null, 2)); +}); + +// receive notification when a ws connection is reconnecting automatically +wsClient.on('reconnecting', (data) => { + console.log('ws automatically reconnecting.... ', data?.wsKey); +}); + +// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) +wsClient.on('reconnected', (data) => { + console.log('ws has reconnected ', data?.wsKey); +}); + +// Recommended: receive error events (e.g. first reconnection failed) +wsClient.on('exception', (data) => { + console.log('ws saw error ', data?.wsKey); +}); + /** - * @deprecated - deleted as of 2024-11-21 - * - */ -convertBUSD(params: ConvertTransfer): Promise -⋮---- + * Subscribe to public topics either one at a time or many in an array + */ + +// E.g. one at a time, routed to the coinm futures websockets: +wsClient.subscribe('btcusd@indexPrice', 'coinm'); +wsClient.subscribe('btcusd@miniTicker', 'coinm'); + +// Or send many topics at once to a stream, e.g. the usdm futures stream: +wsClient.subscribe( + ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], + 'usdm', +); + +// spot & margin topics should go to "main" +// (similar how the MainClient is for REST APIs in that product group) +wsClient.subscribe( + [ + // All Market Rolling Window Statistics Streams + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams + '!ticker_1h@arr', + // Individual Symbol Book Ticker Streams + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams + 'btcusdt@bookTicker', + // Average Price + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price + 'btcusdt@avgPrice', + // Partial Book Depth Streams + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams + 'btcusdt@depth10@100ms', + // Diff. Depth Stream + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream + 'btcusdt@depth', + ], + // Look at the `WS_KEY_URL_MAP` for a list of values here: + // https://github.com/sieblyio/binance/blob/master/src/util/websockets/websocket-util.ts + // "main" connects to wss://stream.binance.com:9443/stream + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams + 'main', +); + /** - * @deprecated - */ -getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise< + * For the user data stream, these convenient subscribe methods open a dedicated + * connection with the listen key workflow: + */ + +wsClient.subscribeSpotUserDataStream(); +wsClient.subscribeMarginUserDataStream(); +wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); +wsClient.subscribeUsdFuturesUserDataStream(); +wsClient.subscribePortfolioMarginUserDataStream(); +``` -================ -File: README.md -================ -# Node.js & JavaScript SDK for Binance REST APIs & WebSockets +See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. -[![Build & Test](https://github.com/sieblyio/binance/actions/workflows/test.yml/badge.svg)](https://github.com/sieblyio/binance/actions/workflows/test.yml) -[![npm version](https://img.shields.io/npm/v/binance)][1] -[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1] -[![users count](https://dependents.info/sieblyio/binance/badge?label=users)](https://dependents.info/sieblyio/binance) -[![npm downloads](https://img.shields.io/npm/dt/binance)][1] -[![last commit](https://img.shields.io/github/last-commit/sieblyio/binance)][1] -[![CodeFactor](https://www.codefactor.io/repository/github/sieblyio/binance/badge)](https://www.codefactor.io/repository/github/sieblyio/binance) -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) -[![Binance Tutorial](https://img.shields.io/badge/Binance%20Tutorial-siebly.io-blue)](https://siebly.io/sdk/binance/javascript/tutorial) +#### Preserving large integers in WebSocket messages -

- - - - SDK Logo - - -

+By default, messages are parsed using `JSON.parse`, which cannot precisely represent integers larger than `Number.MAX_SAFE_INTEGER`. +If you need to preserve large integers (e.g., order IDs), provide a custom parser via `customParseJSONFn`. -[1]: https://www.npmjs.com/package/binance +Example using RegEx below, although alternatives are possible too if desired. For more exampes check [ws-custom-parser.ts](./examples/WebSockets/ws-custom-parser.ts) in the examples folder: -> [!TIP] -> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK is now hosted under our [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. +```ts +import { WebsocketClient } from 'binance'; -Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets. +/** + * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: + * https://github.com/sieblyio/binance/issues/208 + * + * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: + */ +const ws = new WebsocketClient({ + // Default behaviour, if you don't include this: + // customParseJSONFn: (rawEvent) => { + // return JSON.parse(rawEvent); + // }, -Spot user data stream (listen key is created and kept alive for you): + // Or, pre-process the raw event using RegEx, before using the same workflow: + customParseJSONFn: (rawEvent) => { + return JSON.parse( + rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), + ); + }, -```javascript -import { WebsocketClient } from 'binance'; -const ws = new WebsocketClient({ api_key: 'key', api_secret: 'secret' }); -ws.on('formattedMessage', (data) => console.log(data)); -ws.subscribeSpotUserDataStream(); + // Or, use a 3rd party library such as json-bigint: + // customParseJSONFn: (rawEvent) => { + // return JSONbig({ storeAsString: true }).parse(rawEvent); + // }, +}); + +ws.on('message', (msg) => { + console.log(msg); +}); + +// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values. +// Use a custom replacer or JSONbig.stringify if you need to log/serialize: +// const replacer = (_k: string, v: unknown) => typeof v === 'bigint' ? v.toString() : v; +// console.log(JSON.stringify(msg, replacer)); ``` -- Professional, robust & performant Binance SDK with leading trading volume in production (livenet). -- Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. -- Complete TypeScript support (with type declarations for all API requests & responses). -- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. - - Strongly typed requests and responses. - - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. -- Actively maintained with a modern, promise-driven interface. -- Support for all authentication mechanisms available on Binance: - - HMAC - - RSA - - Ed25519 (required for WS API login, else each request is signed). - - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication. -- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures. - - Event driven messaging. - - Smart WebSocket persistence - - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - - Automatically handle listenKey persistence and expiration/refresh. - - Emit `reconnected` event when dropped connection is restored. - - Strongly typed on most WebSocket events, with typeguards available for TypeScript users. - - Optional: - - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers). - - Automatic beautification of REST responses (parsing numbers in strings to numbers). -- Supports WebSocket API on all available product groups, including Spot & Futures: - - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or; - - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. -- Heavy automated end-to-end testing with real API calls. - - End-to-end testing before any release. - - Real API calls in e2e tests. -- Proxy support via axios integration. -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). -- QuickStart Guide: [Binance JavaScript QuickStart Guide](https://siebly.io/sdk/binance/javascript) -- Binance JavaScript Tutorial: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) +### WebSocket API -## Table of Contents +Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. -- [Installation](#installation) -- [Examples](#examples) - - [REST API Examples](./examples/REST) - - [WebSocket Examples](./examples/WebSockets) - - [WebSocket Consumers](./examples/WebSockets/) - - [WebSocket API](./examples/WebSockets/ws-api-client.ts) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation Links](#documentation) -- [Usage](#usage) - - [Demo Trading vs Testnet](#demo-trading-vs-testnet) - - [REST API Clients](#rest-api-clients) - - [REST Main Client](#rest-main-client) - - [REST USD-M Futures](#rest-usd-m-futures) - - [REST COIN-M Futures](#rest-coin-m-futures) - - [REST Portfolio Margin](#rest-portfolio-margin) - - [WebSockets](#websockets) - - [WebSocket Consumers](#websocket-consumers) - - [WebSocket API](#websocket-api) - - [Event Driven API](#event-driven-api) - - [Promise Driven API](#async-await-api) - - [Market Maker Endpoints](#market-maker-endpoints) - - [Using Market Maker Endpoints](#using-market-maker-endpoints) - - [Best practice](#best-practice) - - [Customise Logging](#customise-logging) - - [Frontend Usage](#browserfrontend-usage) - - [Import](#import) - - [Webpack](#webpack) -- [LLMs & AI](#use-with-llms--ai) -- [Contributions & Thanks](#contributions--thanks) +#### Authentication -## Installation +HMAC, RSA and Ed25519 keys are supported for the WebSocket API. However, only Ed25519 keys support WebSocket API login. When using HMAC or RSA keys, each WebSocket API command will need to be individually signed. -`npm install binance --save` +This is no issue for most use cases, but if you are latency sensitive, you should consider using Ed25519 keys. This will allow the WebSocket API client to authenticate once after the connection opens, and all commands can then be sent without additional request signatures. -## Examples +#### Event Driven API -Refer to the [examples](./examples) folder for implementation demos. +The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method. -## Issues & Discussion +Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. -- Issues? Check the [issues tab](https://github.com/sieblyio/binance/issues). -- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. -- Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. -- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) +#### Async Await API - +The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient). -## Related Projects +It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. -Check out our JavaScript/TypeScript/Node.js SDKs & Projects: +Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. -- Visit our website: [https://Siebly.io](https://siebly.io/) -- Try our REST API & WebSocket SDKs published on npmjs: - - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) - - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) - - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) - - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) - - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) - - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) - - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) - - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) - - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) -- Try my misc utilities: - - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) -- Check out my examples: - - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) - +```typescript +import { WebsocketAPIClient } from 'binance'; -## Documentation +// or, if you prefer `require()`: +// const { WebsocketAPIClient } = require('binance'); -Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. +/** + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. + */ -- Binance API Documentation - - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) - - [ Derivatives ](https://developers.binance.com/docs/derivatives) - - [ Margin ](https://developers.binance.com/docs/margin_trading) - - [ Wallet ](https://developers.binance.com/docs/wallet) -- [Find all products here](https://developers.binance.com/en) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) -- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) +const publicKey = `-----BEGIN PUBLIC KEY----- +MCexampleQTxwLU9o= +-----END PUBLIC KEY----- +`; -## Structure +const privateKey = `-----BEGIN PRIVATE KEY----- +MC4CAQAexamplewqj5CzUuTy1 +-----END PRIVATE KEY----- +`; -This project uses typescript. Resources are stored in 3 key structures: +// API Key returned by binance, generated using the publicKey (above) via Binance's website +const apiKey = 'TQpJexamplerobdG'; -- [src](./src) - the whole connector written in typescript -- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. -- [dist](./dist) - the packed bundle of the project for use in browser environments. +// Make an instance of the WS API Client +const wsClient = new WebsocketAPIClient({ + api_key: apiKey, + api_secret: privateKey, + beautify: true, + + // Enforce testnet ws connections, regardless of supplied wsKey + // testnet: true, +}); + +// Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! +// https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow +// wsClient.setTimeOffsetMs(-5000); + +// Optional, see above. Can be used to prepare a connection before sending commands +// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); + +// Make WebSocket API calls, very similar to a REST API: + +wsClient + .getFuturesAccountBalanceV2({ + timestamp: Date.now(), + recvWindow: 5000, + }) + .then((result) => { + console.log('getFuturesAccountBalanceV2 result: ', result); + }) + .catch((err) => { + console.error('getFuturesAccountBalanceV2 error: ', err); + }); + +wsClient + .submitNewFuturesOrder('usdm', { + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + timestamp: Date.now(), + // recvWindow: 5000, + }) + .then((result) => { + console.log('getFuturesAccountBalanceV2 result: ', result); + }) + .catch((err) => { + console.error('getFuturesAccountBalanceV2 error: ', err); + }); +``` --- -# Usage - -Create API credentials at Binance +## Market Maker Endpoints -- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) -- [Testnet](https://testnet.binance.vision/). -- [Testnet Futures](testnet.binancefuture.com). -- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading. +Binance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program. -### Demo Trading vs Testnet +These endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 -Binance offers two testing environments: +### Using Market Maker Endpoints -- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures. -- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing. +To use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients): -To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information. +#### Market Maker REST API Clients -## REST API Clients +```javascript +import { USDMClient, CoinMClient } from 'binance'; -There are several REST API modules as there are some differences in each API group. +// USD-M Futures with MM endpoints +const usdmClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); -1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management. -2. `USDMClient` for USD-M futures APIs. -3. `CoinMClient` for COIN-M futures APIs. -4. `PortfolioClient` for Portfolio Margin APIs. +// COIN-M Futures with MM endpoints +const coinmClient = new CoinMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); +``` -Vanilla Options is not yet available. Please get in touch if you're looking for this. +#### Market Maker WebSocket Clients -### REST Main Client +```javascript +import { WebsocketClient, WebsocketAPIClient } from 'binance'; -The MainClient covers all endpoints under the main "api\*.binance.com" subdomains, including but not limited to endpoints in the following product groups: +// WebSocket consumer with MM endpoints +const wsClient = new WebsocketClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); -- Spot -- Cross & isolated margin -- Convert -- Wallet -- Futures management (transfers & history) -- Sub account management -- Misc transfers -- Auto & dual invest -- Staking -- Mining -- Loans & VIP loans -- Simple Earn -- NFTs -- C2C -- Exchange Link -- Alpha trading +// WebSocket API client with MM endpoints +const wsApiClient = new WebsocketAPIClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); +``` -Refer to the following links for a complete list of available endpoints: +**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments. -- [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/sieblyio/binance/blob/master/docs/endpointFunctionList.md) -- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) +### Best practice -Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. +Since market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints. ```javascript -import { MainClient } from 'binance'; - -// or, if you prefer `require()`: -// const { MainClient } = require('binance'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +import { USDMClient } from 'binance'; -const client = new MainClient({ +// MM client for USD-M futures +const futuresMMClient = new USDMClient({ api_key: API_KEY, api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, + useMMEndpoints: true, // Use MM endpoints for futures }); -client - .getAccountTradeList({ symbol: 'BTCUSDT' }) - .then((result) => { - console.log('getAccountTradeList result: ', result); - }) - .catch((err) => { - console.error('getAccountTradeList error: ', err); - }); - -client - .getExchangeInfo() - .then((result) => { - console.log('getExchangeInfo inverse result: ', result); - }) - .catch((err) => { - console.error('getExchangeInfo inverse error: ', err); - }); +// Regular client for USD-M futures +const futuresRegularClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMEndpoints: false, // Use regular endpoints for futures +}); ``` -See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. - -### REST USD-M Futures +## Customise Logging -Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. +Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. ```javascript -import { USDMClient } from 'binance'; +import { WebsocketClient, DefaultLogger } from 'binance'; // or, if you prefer `require()`: -// const { USDMClient } = require('binance'); +// const { WebsocketClient, DefaultLogger } = require('binance'); -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +// Enable all logging on the trace level (disabled by default) +DefaultLogger.trace = (...params) => { + console.trace('trace: ', params); +}; -const client = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); +// Pass the updated logger as the 2nd parameter +const ws = new WebsocketClient( + { + api_key: key, + api_secret: secret, + beautify: true, + }, + DefaultLogger +); -client - .getBalance() - .then((result) => { - console.log('getBalance result: ', result); - }) - .catch((err) => { - console.error('getBalance error: ', err); - }); +// Or, create a completely custom logger with the 3 available functions +const customLogger = { + trace: (...params: LogParams): void => { + console.trace(new Date(), params); + }, + info: (...params: LogParams): void => { + console.info(new Date(), params); + }, + error: (...params: LogParams): void => { + console.error(new Date(), params); + }, +} -client - .submitNewOrder({ - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - }) - .then((result) => { - console.log('submitNewOrder result: ', result); - }) - .catch((err) => { - console.error('submitNewOrder error: ', err); - }); +// Pass the custom logger as the 2nd parameter +const ws = new WebsocketClient( + { + api_key: key, + api_secret: secret, + beautify: true, + }, + customLogger +); ``` -See [usdm-client.ts](./src/usdm-client.ts) for further information. +## Browser/Frontend Usage -### REST COIN-M Futures +### Import -Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. +This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. -```javascript -import { CoinMClient } from 'binance'; +1. Install these dependencies + ```sh + npm install crypto-browserify stream-browserify + ``` +2. Add this to your `tsconfig.json` + ```json + { + "compilerOptions": { + "paths": { + "crypto": [ + "./node_modules/crypto-browserify" + ], + "stream": [ + "./node_modules/stream-browserify" + ] + } + ``` +3. Declare this in the global context of your application (ex: in polyfills for angular) + ```js + (window as any).global = window; + ``` -// or, if you prefer `require()`: -// const { CoinMClient } = require('binance'); +### Webpack -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. -const client = new CoinMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); +Build a bundle using webpack: -client - .getSymbolOrderBookTicker() - .then((result) => { - console.log('getSymbolOrderBookTicker result: ', result); - }) - .catch((err) => { - console.error('getSymbolOrderBookTicker error: ', err); - }); -``` +- `npm install` +- `npm build` +- `npm pack` -See [coinm-client.ts](./src/coinm-client.ts) for further information. +The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. -### REST Portfolio Margin +## Use with LLMs & AI -Start by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. +This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. + +This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. + +--- -```javascript -import { PortfolioClient } from 'binance'; + -// or, if you prefer `require()`: -// const { PortfolioClient } = require('binance'); +### Contributions & Thanks -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; +Have my projects helped you? Share the love, there are many ways you can show your thanks: -const client = new PortfolioClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); +- Star & share my projects. +- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler +- Have an interesting project? Get in touch & invite me to it. +- Or buy me all the coffee: + - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` +- Sign up with my referral links: + - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 + - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ + - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY + - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 -client - .getBalance() - .then((result) => { - console.log('getBalance result: ', result); - }) - .catch((err) => { - console.error('getBalance error: ', err); - }); + + -See [portfolio-client.ts](./src/portfolio-client.ts) for further information. +### Contributions & Pull Requests -## WebSockets +Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. -### WebSocket Consumers +## Used By -All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. +[![Repository Users Preview Image](https://dependents.info/sieblyio/binance/image)](https://github.com/sieblyio/binance/network/dependents) -The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: + -```javascript -import { WebsocketClient } from 'binance'; +## Star History -// or, if you prefer `require()`: -// const { WebsocketClient } = require('binance'); +[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; + +================ +File: src/types/spot.ts +================ +import { + ExchangeFilter, + ExchangeSymbol, + GenericCodeMsgError, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRow, + OrderResponseType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SideEffects, + StringBoolean, + SymbolFilter, +} from './shared'; +⋮---- +export interface BasicTimeRangeParam { + startTime?: number; + endTime?: number; +} +⋮---- +export interface BasicFromPaginatedParams { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export type SymbolStatus = + | 'PRE_TRADING' + | 'TRADING' + | 'POST_TRADING' + | 'END_OF_DAY' + | 'HALT' + | 'AUCTION_MATCH' + | 'BREAK' + | 'CANCEL_ONLY'; +⋮---- +export interface SystemStatusResponse { + status: 0 | 1; + msg: 'normal' | 'system maintenance'; +} +⋮---- +export interface DailyAccountSnapshotParams { + type: 'SPOT' | 'MARGIN' | 'FUTURES'; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface SpotBalance { + asset: string; + free: numberInString; + locked: numberInString; +} +⋮---- +export interface MarginBalance { + asset: string; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; +} +⋮---- +export interface DailyFuturesBalance { + asset: string; + marginBalance: numberInString; + walletBalance: numberInString; +} +⋮---- +export interface DailyFuturesPositionState { + entryPrice: numberInString; + markPrice: numberInString; + positionAmt: numberInString; + symbol: string; + unRealizedProfit: numberInString; +} +⋮---- +export interface DailySpotAccountSnapshot { + data: { + balances: SpotBalance[]; + totalAssetOfBtc: numberInString; + }; + type: 'spot'; + updateTime: number; +} +⋮---- +export interface DailyMarginAccountSnapshot { + data: { + marginLevel: numberInString; + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; + userAssets: MarginBalance[]; + }; + type: 'margin'; + updateTime: number; +} +⋮---- +export interface DailyFuturesAccountSnapshot { + data: { + assets: DailyFuturesBalance[]; + position: DailyFuturesPositionState[]; + }; + type: 'futures'; + updateTime: number; +} +⋮---- +export type DailyAccountSnapshotElement = + | DailySpotAccountSnapshot + | DailyMarginAccountSnapshot + | DailyFuturesAccountSnapshot; +⋮---- +export interface DailyAccountSnapshot { + code: number; + msg: string; + snapshotVos: DailyAccountSnapshotElement[]; +} +⋮---- +export interface CoinNetwork { + addressRegex: string; + coin: string; + depositDesc: string; + depositEnable: boolean; + isDefault: boolean; + memoRegex: string; + minConfirm: number; + name: string; + network: string; + resetAddressStatus: boolean; + specialTips?: string; + specialWithdrawTips?: string; + unlockConfirm: number; + withdrawDesc: string; + withdrawEnable: boolean; + withdrawFee: numberInString; + withdrawMin: numberInString; + withdrawMax: numberInString; + withdrawInternalMin: numberInString; + withdrawIntegerMultiple: numberInString; + depositDust?: numberInString; + sameAddress: boolean; + estimatedArrivalTime: number; + busy: boolean; + contractAddressUrl?: string; + contractAddress?: string; +} +⋮---- +export interface AllCoinsInformationResponse { + coin: string; + depositAllEnable: boolean; + free: numberInString; + freeze: numberInString; + ipoable: numberInString; + ipoing: numberInString; + isLegalMoney: boolean; + locked: numberInString; + name: string; + networkList: CoinNetwork[]; + storage: numberInString; + trading: boolean; + withdrawAllEnable: boolean; + withdrawing: numberInString; +} +⋮---- +export interface WithdrawParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; + amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; +} +⋮---- +export interface TransferBrokerSubAccountParams { + fromId?: string; + toId?: string; + clientTranId?: string; + asset: string; + amount: number; +} +⋮---- +export interface ConvertQuoteRequestParams { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + walletType?: string; + validTime?: string; +} +⋮---- +export interface EnableConvertSubAccountParams { + subAccountId: string; + convert: boolean; +} +⋮---- +export interface AcceptQuoteRequestParams { + quoteId: string; +} +⋮---- +export interface GetOrderStatusParams { + orderId?: string; + quoteId?: string; +} +⋮---- +export interface GetConvertTradeHistoryParams { + startTime: number; + endTime?: number; + limit?: string; +} +⋮---- +export interface TransferBrokerSubAccount { + txnId: numberInString; +} +⋮---- +export enum EnumDepositStatus { + Pending = 0, + CreditedButCannotWithdraw = 6, + WrongDeposit = 7, + WaitingUserConfirm = 8, + Success = 1, + Rejected = 2, +} +⋮---- +export type DepositStatusCode = `${EnumDepositStatus}`; +⋮---- +export interface DepositHistoryParams { + coin?: string; // Optional: Filter by coin + status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) + startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) + endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) + offset?: number; // Optional: Pagination offset (Default: 0) + limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) + txId?: string; // Optional: Filter by transaction ID + includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +} +⋮---- +coin?: string; // Optional: Filter by coin +status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) +startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) +endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +offset?: number; // Optional: Pagination offset (Default: 0) +limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) +txId?: string; // Optional: Filter by transaction ID +includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +⋮---- +export interface DepositHistory { + amount: numberInString; + coin: string; + network: string; + status: number; + address: string; + addressTag: string; + txId: string; + insertTime: number; + transferType: number; + confirmTimes: string; +} +⋮---- +export enum EnumWithdrawStatus { + EmailSent = 0, + Cancelled = 1, + AwaitingApproval = 2, + Rejected = 3, + Processing = 4, + Failure = 5, + Completed = 6, +} +⋮---- +export type WithdrawStatusCode = `${EnumWithdrawStatus}`; +⋮---- +export interface WithdrawHistoryParams { + coin?: string; // Optional: Filter by coin + withdrawOrderId?: string; // Optional: Filter by withdraw order ID + status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) + offset?: number; // Optional: Pagination offset + limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) + idList?: string; // Optional: Comma-separated list of withdrawal IDs + startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) + endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +} +⋮---- +coin?: string; // Optional: Filter by coin +withdrawOrderId?: string; // Optional: Filter by withdraw order ID +status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) +offset?: number; // Optional: Pagination offset +limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) +idList?: string; // Optional: Comma-separated list of withdrawal IDs +startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) +endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +⋮---- +export enum EnumWithdrawTransferType { + External = 0, + Interal = 1, +} +⋮---- +export type WithdrawTransferType = `${EnumWithdrawTransferType}`; +⋮---- +export interface WithdrawHistory { + address: string; + amount: numberInString; + applyTime: string; + coin: string; + id: string; + withdrawOrderId: string; + network: string; + transferType: WithdrawTransferType; + status: number; + transactionFee: numberInString; + txId: string; +} +⋮---- +export interface DepositAddressParams { + coin: string; + network?: string; + amount?: number; +} +⋮---- +export interface DepositAddressResponse { + address: string; + coin: string; + tag: string; + url: string; +} +⋮---- +export interface ConvertDustParams { + asset: string[]; + accountType?: 'SPOT' | 'MARGIN'; +} +⋮---- +export type DustConvertAccountType = 'SPOT' | 'MARGIN'; +⋮---- +export interface DustConvertParams { + asset: string[]; + accountType?: DustConvertAccountType; + clientId?: string; + targetAsset?: string; + thirdPartyClientId?: string; + dustQuotaAssetToTargetAssetPrice?: numberInString; +} +⋮---- +export interface DustConvertibleAssetsParams { + targetAsset: string; + accountType?: DustConvertAccountType; + dustQuotaAssetToTargetAssetPrice?: numberInString; +} +⋮---- +export interface DustConvertibleAssetDetail { + asset: string; + assetFullName: string; + amountFree: numberInString; + exchange: numberInString; + toQuotaAssetAmount: numberInString; + toTargetAssetAmount: numberInString; + toTargetAssetOffExchange: numberInString; +} +⋮---- +export interface DustConvertibleAssetsResponse { + dribbletPercentage: numberInString; + totalTransferQuotaAssetAmount: numberInString; + totalTransferTargetAssetAmount: numberInString; + dribbletBase: numberInString; + details: DustConvertibleAssetDetail[]; +} +⋮---- +export interface DustInfoDetail { + asset: string; + assetFullName: string; + amountFree: numberInString; + toBTC: numberInString; + toBNB: numberInString; + toBNBOffExchange: numberInString; + exchange: numberInString; +} +⋮---- +export interface DustInfo { + details: DustInfoDetail[]; + totalTransferBtc: numberInString; + totalTransferBNB: numberInString; + dribbletPercentage: numberInString; +} +⋮---- +export interface DustConversionResult { + amount: numberInString; + fromAsset: string; + operateTime: number; + serviceChargeAmount: numberInString; + tranId: number; + transferedAmount: numberInString; +} +⋮---- +export interface DustConversion { + totalServiceCharge: numberInString; + totalTransfered: numberInString; + transferResult: DustConversionResult[]; +} +⋮---- +export interface UserAssetDribbletDetail { + transId: number; + serviceChargeAmount: numberInString; + amount: numberInString; + operateTime: number; + transferedAmount: numberInString; + fromAsset: string; +} +⋮---- +export interface UserAssetDribblet { + operateTime: number; + totalTransferedAmount: numberInString; + totalServiceChargeAmount: numberInString; + transId: number; + userAssetDribbletDetails: UserAssetDribbletDetail[]; +} +⋮---- +export interface DustLog { + total: number; + userAssetDribblets: UserAssetDribblet[]; +} +⋮---- +export enum EnumUniversalTransferType { + SpotToUSDM = 'MAIN_UMFUTURE', + SpotToCOINM = 'MAIN_CMFUTURE', + SpotToMargin = 'MAIN_MARGIN', + SpotToFunding = 'MAIN_FUNDING', + SpotToOptions = 'MAIN_OPTION', + FundingToSpot = 'FUNDING_MAIN', + FundingToUSDM = 'FUNDING_UMFUTURE', + FundingToCOINM = 'FUNDING_CMFUTURE', + FundingToMargin = 'FUNDING_MARGIN', + FundingToOptions = 'FUNDING_OPTION', + USDMToSpot = 'UMFUTURE_MAIN', + USDMToFunding = 'UMFUTURE_FUNDING', + USDMToMargin = 'UMFUTURE_MARGIN', + USDMToOptions = 'UMFUTURE_OPTION', + COINMToSpot = 'CMFUTURE_MAIN', + COINMToFunding = 'CMFUTURE_FUNDING', + COINMToMargin = 'CMFUTURE_MARGIN', + MarginToSpot = 'MARGIN_MAIN', + MarginToUSDM = 'MARGIN_UMFUTURE', + MarginToCOINM = 'MARGIN_CMFUTURE', + MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', + MarginToFunding = 'MARGIN_FUNDING', + MarginToOptions = 'MARGIN_OPTION', + IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', + IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', + OptionsToSpot = 'OPTION_MAIN', + OptionsToUSDM = 'OPTION_UMFUTURE', + OptionsToFunding = 'OPTION_FUNDING', + OptionsToMargin = 'OPTION_MARGIN', +} +⋮---- +export type UniversalTransferType = `${EnumUniversalTransferType}`; +⋮---- +export interface UniversalTransferParams { + type: UniversalTransferType; + asset: string; + amount: number; + fromSymbol: string; + toSymbol: string; +} +⋮---- +export interface UniversalTransferHistoryParams { + type: UniversalTransferType; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface ExchangeInfoParams { + symbol?: string; + symbols?: string[]; + permissions?: string | string[]; + showPermissionSets?: boolean; + symbolStatus?: string; +} +⋮---- +type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; +type SpotPegOffsetType = 'PRICE_LEVEL'; +⋮---- +export interface NewSpotOrderParams< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> { + symbol: string; + side: OrderSide; + type: T; + timeInForce?: OrderTimeInForce; + quantity?: number; + quoteOrderQty?: number; + price?: number; + newClientOrderId?: string; + strategyId?: number; + strategyType?: number; + stopPrice?: number; + trailingDelta?: number; + icebergQty?: number; + newOrderRespType?: RT; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + isIsolated?: StringBoolean; + sideEffectType?: SideEffects; + autoRepayAtCancel?: StringBoolean; +} +⋮---- +export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; +export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; +⋮---- +export interface ReplaceSpotOrderParams< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends NewSpotOrderParams { + cancelReplaceMode: CancelReplaceMode; + cancelNewClientOrderId?: string; + cancelOrigClientOrderId?: string; + cancelOrderId?: number; + cancelRestrictions?: CancelRestrictions; +} +⋮---- +export interface GetOCOParams { + symbol?: string; + orderListId?: number; + origClientOrderId?: string; +} +⋮---- +export interface NewSpotSOROrderParams { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + quantity: number; + price?: number; + newClientOrderId?: string; + strategyId?: number; + strategyType?: number; + icebergQty?: number; + newOrderRespType?: OrderResponseType; + selfTradePreventionMode?: SelfTradePreventionMode; +} +⋮---- +export type APILockTriggerCondition = 'GCR' | 'IFER' | 'UFR'; +⋮---- +export interface APITriggerConditionSymbolStatus { + i: APILockTriggerCondition; + c: number; + v: number; + t: number; +} +⋮---- +export interface APITradingStatus { + data: { + isLocked: boolean; + plannedRecoverTime: number; + triggerCondition: Record; + indicators: Record; + updateTime: number; + }; +} +⋮---- +export interface APIPermissions { + ipRestrict: boolean; + createTime: number; + enableReading: boolean; + enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals + enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly + enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed + enableFutures: boolean; // API Key created before your futures account opened does not support futures API service + permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization + enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading + enableSpotAndMarginTrading: boolean; // Spot and margin trading + tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission + enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading + enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading + enablePortfolioMarginTrading: true; +} +⋮---- +enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals +enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly +enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed +enableFutures: boolean; // API Key created before your futures account opened does not support futures API service +permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization +enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading +enableSpotAndMarginTrading: boolean; // Spot and margin trading +tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission +enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading +enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading +⋮---- +export interface AssetDetail { + minWithdrawAmount: numberInString; + depositStatus: boolean; + withdrawFee: number; + withdrawStatus: boolean; + depositTip?: string; +} +⋮---- +export interface SymbolTradeFee { + symbol: string; + makerCommission: numberInString; + takerCommission: numberInString; +} +⋮---- +export interface SymbolExchangeInfo { + symbol: string; + status: string; + baseAsset: string; + baseAssetPrecision: number; + quoteAsset: string; + quotePrecision: number; + quoteAssetPrecision: number; + baseCommissionPrecision: number; + quoteCommissionPrecision: number; + orderTypes: OrderType[]; + icebergAllowed: boolean; + ocoAllowed: boolean; + opoAllowed: boolean; + quoteOrderQtyMarketAllowed: boolean; + allowTrailingStop: boolean; + cancelReplaceAllowed: boolean; + isSpotTradingAllowed: boolean; + isMarginTradingAllowed: boolean; + filters: SymbolFilter[]; + permissions: ('SPOT' | 'MARGIN')[]; + defaultSelfTradePreventionMode: SelfTradePreventionMode; + allowedSelfTradePreventionModes: SelfTradePreventionMode[]; +} +⋮---- +export interface ExchangeInfo { + timezone: string; + serverTime: number; + rateLimits: RateLimiter[]; + exchangeFilters: ExchangeFilter[]; + symbols: SymbolExchangeInfo[]; +} +⋮---- +export interface OrderBookResponse { + lastUpdateId: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; +} +⋮---- +export interface RawTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; +} +⋮---- +export interface BlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} +⋮---- +export interface HistoricalBlockTradesParams { + symbol: string; + fromId: number; + limit?: number; +} +⋮---- +export interface RawAccountTrade { + symbol: string; + id: number; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isBestMatch: boolean; +} +⋮---- +export interface AggregateTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; + M: boolean; +} +⋮---- +export interface CurrentAvgPrice { + mins: number; + price: numberInString; + closeTime: number; +} +⋮---- +/** Spot PRICE_RANGE execution rule (GET /api/v3/executionRules). */ +export interface SpotPriceRangeExecutionRule { + ruleType: 'PRICE_RANGE'; + bidLimitMultUp: numberInString; + bidLimitMultDown: numberInString; + askLimitMultUp: numberInString; + askLimitMultDown: numberInString; +} +⋮---- +export interface SpotSymbolExecutionRules { + symbol: string; + rules: SpotPriceRangeExecutionRule[]; +} +⋮---- +export interface SpotExecutionRulesResponse { + symbolRules: SpotSymbolExecutionRules[]; +} +⋮---- +/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ +export interface SpotExecutionRulesParams { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; +} +⋮---- +/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ +export interface SpotReferencePriceResponse { + symbol: string; + referencePrice: numberInString | null; + timestamp: number; +} +⋮---- +/** GET /api/v3/referencePrice or /referencePrice/calculation when no reference price has ever been set (code -2043). */ +export interface SpotReferencePriceNeverSetError { + code: -2043; + msg: string; +} +⋮---- +export type SpotReferencePriceResult = + | SpotReferencePriceResponse + | SpotReferencePriceNeverSetError; +⋮---- +/** Reference price is computed as an arithmetic mean in the matching engine. */ +export interface SpotReferencePriceCalculationArithmeticMean { + symbol: string; + calculationType: 'ARITHMETIC_MEAN'; + bucketCount: number; + bucketWidthMs: number; +} +⋮---- +/** Reference price is computed outside the matching engine. */ +export interface SpotReferencePriceCalculationExternal { + symbol: string; + calculationType: 'EXTERNAL'; + externalCalculationId: number; +} +⋮---- +export type SpotReferencePriceCalculationResponse = + | SpotReferencePriceCalculationArithmeticMean + | SpotReferencePriceCalculationExternal + | SpotReferencePriceNeverSetError; +⋮---- +export interface DailyChangeStatistic { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + prevClosePrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} +⋮---- +export interface SymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; +} +⋮---- +export interface OrderResponseACK { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; +} +⋮---- +/** Conditional fields on POST /api/v3/order RESULT/FULL. Only present when the matching condition is met. */ +export interface SpotNewOrderConditionalFields { + icebergQty?: numberInString; + preventedMatchId?: number; + preventedQuantity?: numberInString; + stopPrice?: numberInString; + strategyId?: number; + strategyType?: number; + trailingDelta?: number; + trailingTime?: number; + pegPriceType?: SpotPegPriceType; + pegOffsetType?: SpotPegOffsetType; + pegOffsetValue?: number; + peggedPrice?: numberInString; +} +⋮---- +export interface OrderResponseResult extends SpotNewOrderConditionalFields { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; +} +⋮---- +/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +⋮---- +export interface OrderFill { + price: numberInString; + qty: numberInString; + commission: numberInString | null; + commissionAsset: string | null; + tradeId: number; +} +⋮---- +export interface OrderResponseFull extends SpotNewOrderConditionalFields { + symbol: string; + orderId: number; + orderListId?: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + marginBuyBorrowAmount?: number; + marginBuyBorrowAsset?: string; + isIsolated?: boolean; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; + fills: OrderFill[]; +} +⋮---- +/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +⋮---- +export type OrderResponse = + | OrderResponseACK + | OrderResponseResult + | OrderResponseFull; +⋮---- +export type OrderResponseTypeFor< + RT extends OrderResponseType | undefined = undefined, + T extends OrderType | undefined = undefined, +> = RT extends 'ACK' + ? OrderResponseACK + : RT extends 'RESULT' + ? OrderResponseResult + : RT extends 'FULL' + ? OrderResponseFull + : T extends 'MARKET' | 'LIMIT' + ? OrderResponseFull + : OrderResponseACK; +⋮---- +export interface OrderListOrder { + symbol: string; + orderId: number; + clientOrderId: string; + /** Present only for expired orders. */ + expiryReason?: string; +} +⋮---- +/** Present only for expired orders. */ +⋮---- +export interface OrderListResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: [OrderListOrder, OrderListOrder]; + orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; +} +⋮---- +export interface OrderList { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: [OrderListOrder, OrderListOrder]; +} +export interface SOROrderFill { + matchType: string; + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; + tradeId: number; + allocId: number; +} +⋮---- +export type SOROrderResponseFull = OrderResponseFull & { + workingTime: number; + fills: SOROrderFill[]; + workingFloor: string; + selfTradePreventionMode: string; + usedSor: true; +}; +⋮---- +export interface SORTestOrderResponse { + standardCommissionForOrder: { + //Standard commission rates on trades from the order. + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + //Tax commission rates for trades from the order. + maker: numberInString; + taker: numberInString; + }; + discount: { + //Discount on standard commissions when paying in BNB. + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ + 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. + }; +} +⋮---- +//Standard commission rates on trades from the order. +⋮---- +//Tax commission rates for trades from the order. +⋮---- +//Discount on standard commissions when paying in BNB. +⋮---- +/** + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ +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 { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + selfTradePreventionMode: SelfTradePreventionMode; +} +⋮---- +export interface CancelOrderListResult extends OrderList { + orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; +} +⋮---- +export interface GenericReplaceSpotOrderResult { + cancelResult: 'SUCCESS' | 'FAILURE'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: C; + newOrderResponse: N; +} +⋮---- +export interface ReplaceSpotOrderCancelStopFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'NOT_ATTEMPTED'; +} +⋮---- +export interface ReplaceSpotOrderNewFailure + extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + GenericCodeMsgError + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'FAILURE'; +} +⋮---- +export interface ReplaceSpotOrderCancelAllowFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'SUCCESS'; +} +⋮---- +export interface ReplaceSpotOrderCancelAllFailure + extends GenericReplaceSpotOrderResult< + GenericCodeMsgError, + GenericCodeMsgError + > { + cancelResult: 'FAILURE'; + newOrderResult: 'FAILURE'; +} +⋮---- +export interface ReplaceSpotOrderResultError { + data: + | ReplaceSpotOrderCancelStopFailure + | ReplaceSpotOrderNewFailure + | ReplaceSpotOrderCancelAllowFailure + | ReplaceSpotOrderCancelAllFailure; +} +⋮---- +export interface ReplaceSpotOrderResultSuccess< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + OrderResponseTypeFor + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'SUCCESS'; +} +⋮---- +export interface SpotOrder { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + stopPrice: numberInString; + icebergQty: numberInString; + time: number; + updateTime: number; + isWorking: boolean; + origQuoteOrderQty: numberInString; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present only for expired orders. */ + expiryReason?: string; +} +⋮---- +/** Present only for expired orders. */ +⋮---- +export interface SpotAmendKeepPriorityResult { + transactTime: number; + executionId: number; + amendedOrder: { + symbol: string; + orderId: number; + orderListId: number; + origClientOrderId: string; + clientOrderId: string; + price: string; + qty: string; + executedQty: string; + preventedQty: string; + quoteOrderQty: string; + cumulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }; + listStatus?: { + orderListId: number; + contingencyType: string; + listOrderStatus: string; + listClientOrderId: string; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + }; +} +⋮---- +export interface SpotAssetBalance { + asset: string; + free: numberInString; + locked: numberInString; +} +⋮---- +export interface AccountInformation { + makerCommission: number; + takerCommission: number; + buyerCommission: number; + sellerCommission: number; + commissionRates: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + canTrade: boolean; + canWithdraw: boolean; + canDeposit: boolean; + brokered: boolean; + requireSelfTradePrevention: boolean; + preventSor: boolean; + updateTime: number; + accoountType: string; + balances: SpotAssetBalance[]; + permissions: string[]; + uid: number; +} +⋮---- +export interface CrossMarginAccountTransferParams { + asset: string; + amount: number; + type: 1 | 2; +} +⋮---- +export interface MarginTransactionResponse { + tranId: number; +} +⋮---- +export interface MarginAccountLoanParams { + asset: string; + isIsolated: StringBoolean; + symbol: string; + amount: number; + type: 'BORROW' | 'REPAY'; +} +⋮---- +export interface QueryMarginAssetParams { + asset: string; +} +⋮---- +export interface QueryMarginAssetResponse { + assetFullName: string; + assetName: string; + isBorrowable: boolean; + isMortgageable: boolean; + userMinBorrow: numberInString; + userMinRepay: numberInString; + /** + * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. + * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. + */ + delistTime?: number; +} +⋮---- +/** + * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. + * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. + */ +⋮---- +export interface QueryCrossMarginPairParams { + symbol: string; +} +⋮---- +/** + * Row from `GET /sapi/v1/margin/allPairs`. + * Dev-confirmed: this response has no `delistTime`. Documentation examples that include it are wrong. + */ +export interface QueryCrossMarginPairResponse { + id: number; + symbol: string; + base: string; + quote: string; + isMarginTrade: boolean; + isBuyAllowed: boolean; + isSellAllowed: boolean; +} +⋮---- +export interface QueryMarginPriceIndexResponse { + calcTime: number; + price: numberInString; + symbol: string; +} +⋮---- +export interface QueryMarginRecordParams { + asset: string; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + archived?: boolean; +} +⋮---- +export interface GetMarginAccountBorrowRepayRecordsParams { + asset?: string; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + type: 'BORROW' | 'REPAY'; +} +⋮---- +export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; +⋮---- +export interface MarginAccountRecord { + isolatedSymbol?: string; + asset: string; + principal: numberInString; + status: LoanStatus; + timestamp: number; + txId: number; +} +⋮---- +export interface QueryCrossMarginAccountDetailsParams { + created: boolean; + borrowEnabled: boolean; + marginLevel: numberInString; + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; + totalCollateralValueInUSDT: numberInString; + totalOpenOrderLossInUSDT: numberInString; + tradeEnabled: boolean; + transferInEnabled: boolean; + transferOutEnabled: boolean; + accountType: string; + userAssets: MarginBalance[]; +} +⋮---- +export interface BasicMarginAssetParams { + asset: string; + isolatedSymbol?: string; +} +⋮---- +export interface QueryMaxBorrowResponse { + amount: numberInString; + borrowLimit: numberInString; +} +⋮---- +export interface QueryMaxTransferOutAmountResponse { + amount: numberInString; +} +⋮---- +export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; +⋮---- +export interface IsolatedMarginAccountTransferParams { + asset: string; + symbol: string; + transFrom: IsolatedMarginTransfer; + transTo: IsolatedMarginTransfer; + amount: number; +} +⋮---- +export interface IsolatedMarginAccountAsset { + asset: string; + borrowEnabled: boolean; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; + netAssetOfBtc: numberInString; + repayEnabled: boolean; + totalAsset: numberInString; +} +⋮---- +export type IsolatedMarginLevelStatus = + | 'EXCESSIVE' + | 'NORMAL' + | 'MARGIN_CALL' + | 'PRE_LIQUIDATION' + | 'FORCE_LIQUIDATION'; +⋮---- +export interface IsolatedMarginAccountAssets { + baseAsset: IsolatedMarginAccountAsset; + quoteAsset: IsolatedMarginAccountAsset; + symbol: string; + isolatedCreated: boolean; + enabled: boolean; + marginLevel: numberInString; + marginLevelStatus: IsolatedMarginLevelStatus; + marginRatio: numberInString; + indexPrice: numberInString; + liquidatePrice: numberInString; + liquidateRate: numberInString; + tradeEnabled: boolean; +} +⋮---- +export interface IsolatedMarginAccountInfo { + assets: IsolatedMarginAccountAssets[]; + totalAssetOfBtc?: numberInString; + totalLiabilityOfBtc?: numberInString; + totalNetAssetOfBtc?: numberInString; +} +⋮---- +export interface SpotSubUserAssetBtcList { + email: string; + totalAsset: numberInString; +} +⋮---- +export interface SubAccountList { + email: string; + isFreeze: boolean; + createTime: number; + isManagedSubAccount: boolean; + isAssetManagementSubAccount: boolean; +} +⋮---- +export interface SubAccountDepositHistoryList { + depositId: number; + subAccountId: string; + amount: string; + coin: string; + network: string; + status: number; + address: string; + addressTag: string; + txId: string; + insertTime: number; + sourceAddress: string; + confirmTimes: string; +} +⋮---- +export interface SubAccountTransferHistoryList { + fromId?: string; + toId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountBasicTransfer { + from: string; + to: string; + asset: string; + qty: numberInString; + tranId: number; + time: number; +} +⋮---- +export interface MarginTradeCoeffVo { + forceLiquidationBar: numberInString; + marginCallBar: numberInString; + normalBar: numberInString; +} +⋮---- +export interface SubAccountStatus { + email: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + insertTime: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + mobile: number; +} +⋮---- +export interface BasicBtcTotals { + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; +} +⋮---- +export interface FuturesSubAccountAssets { + asset: string; + initialMargin: numberInString; + maintenanceMargin: numberInString; + marginBalance: numberInString; + maxWithdrawAmount: numberInString; + openOrderInitialMargin: numberInString; + positionInitialMargin: numberInString; + unrealizedProfit: numberInString; + walletBalance: numberInString; +} +⋮---- +export interface FuturesSubAccountList { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + email: string; +} +⋮---- +export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; +⋮---- +export interface SubAccountTransferHistory { + counterParty: string; + email: string; + type: number; + asset: string; + qty: numberInString; + fromAccountType: AccountType; + toAccountType: AccountType; + status: string; + tranId: number; + time: number; +} +⋮---- +export interface SubAccountUniversalTransferHistory { + tranId: number; + fromEmail: string; + toEmail: string; + asset: string; + amount: numberInString; + createTimeStamp: number; + fromAccountType: AccountType; + toAccountType: AccountType; + status: string; + clientTranId?: string; +} +⋮---- +export interface BasicSubAccount { + email: string; + subAccountApiKey: string; +} +⋮---- +export interface CreateSubAccountParams { + subAccountString: string; +} +⋮---- +export interface GetSubAccountApiKeysParams { + email: string; + subAccountApiKey?: string; + /** Page number, default 1, minimum 1. */ + page?: number; + /** Page size, default 30, maximum 100. */ + size?: number; + recvWindow?: number; +} +⋮---- +/** Page number, default 1, minimum 1. */ +⋮---- +/** Page size, default 30, maximum 100. */ +⋮---- +export interface CreateSubAccountApiKeyParams { + email: string; + apiName: string; + /** 1: unrestricted, 2: trusted IPs only, 3: third-party IP restriction. */ + status: 1 | 2 | 3; + canTrade?: boolean; + canMarginLoanRepay?: boolean; + canFuturesTrade?: boolean; + canUniversalTransfer?: boolean; + canVanillaOptions?: boolean; + /** FIX trading requires an Ed25519 key; other key types return -9000 when enabled. */ + canFixApiTrading?: boolean; + /** FIX reading requires an Ed25519 key; other key types return -9000 when enabled. */ + canFixApiReading?: boolean; + /** Required when status is 2. Maximum 500 characters. */ + ipAddress?: string; + /** Required when status is 3. */ + thirdPartyName?: string; + /** Ed25519 public key. */ + publicKey?: string; + recvWindow?: number; +} +⋮---- +/** 1: unrestricted, 2: trusted IPs only, 3: third-party IP restriction. */ +⋮---- +/** FIX trading requires an Ed25519 key; other key types return -9000 when enabled. */ +⋮---- +/** FIX reading requires an Ed25519 key; other key types return -9000 when enabled. */ +⋮---- +/** Required when status is 2. Maximum 500 characters. */ +⋮---- +/** Required when status is 3. */ +⋮---- +/** Ed25519 public key. */ +⋮---- +export interface CreateSubAccountApiKeyResponse { + apiName: string; + apiKey: string; + /** Returned only on creation. */ + secretKey: string; + canTrade: boolean; + canMarginLoanRepay: boolean; + canFuturesTrade: boolean; + canUniversalTransfer: boolean; + canVanillaOptions: boolean; + canFixApiTrading: boolean; + canFixApiReading: boolean; + status: number; + ipList: string[]; +} +⋮---- +/** Returned only on creation. */ +⋮---- +export interface DeleteSubAccountApiKeyParams extends BasicSubAccount { + recvWindow?: number; +} +⋮---- +export type DeleteSubAccountApiKeyResponse = Record; +⋮---- +export interface ModifySubAccountApiKeyPermissionParams + extends BasicSubAccount { + canTrade?: boolean; + canMarginLoanRepay?: boolean; + canFuturesTrade?: boolean; + canUniversalTransfer?: boolean; + canVanillaOptions?: boolean; + /** Ed25519 keys only; omitted values remain unchanged. Other key types return -9000 when enabled. */ + canFixApiTrading?: boolean; + /** Ed25519 keys only; omitted values remain unchanged. Other key types return -9000 when enabled. */ + canFixApiReading?: boolean; + recvWindow?: number; +} +⋮---- +/** Ed25519 keys only; omitted values remain unchanged. Other key types return -9000 when enabled. */ +⋮---- +/** Ed25519 keys only; omitted values remain unchanged. Other key types return -9000 when enabled. */ +⋮---- +export interface ModifySubAccountApiKeyPermissionResponse { + apiName: string; + apikey: string; + canTrade: boolean; + canMarginLoanRepay: boolean; + canFuturesTrade: boolean; + canUniversalTransfer: boolean; + canVanillaOptions: boolean; + canFixApiTrading: boolean; + canFixApiReading: boolean; + timestamp: number; +} +⋮---- +export interface SubAccountApiKey + extends ModifySubAccountApiKeyPermissionResponse { + email: string; +} +⋮---- +export interface EnableOrDisableIPRestrictionForSubAccountParams + extends BasicSubAccount { + ipAddress?: string; +} +⋮---- +export interface GetBrokerSubAccountHistoryParams { + fromId?: string; + toId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; +} +⋮---- +export interface CreateBrokerSubAccountParams { + tag?: string; +} +⋮---- +export interface GetBrokerSubAccountParams { + subAccountId?: string; + page?: number; + size?: number; +} +⋮---- +export interface GetApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey?: string; + page?: number; + size?: number; +} +⋮---- +export interface CreateApiKeyBrokerSubAccountParams { + subAccountId: string; + canTrade: boolean; + marginTrade?: boolean; + futuresTrade?: boolean; +} +export interface ApiKeyBrokerSubAccount { + subAccountId: string; + apiKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface UpdateIpRestrictionForSubApiKey { + subAccountId: string; + ipAddress?: string; + subAccountApiKey: string; + status: string; +} +⋮---- +export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canUniversalTransfer: boolean; +} +⋮---- +export interface EnableMarginBrokerSubAccountParams { + subAccountId: string; + margin: boolean; +} +⋮---- +export interface EnableMarginBrokerSubAccountResponse { + subAccountId: string; + enableMargin: boolean; + updateTime: number; +} +⋮---- +export interface EnableFuturesBrokerSubAccountParams { + subAccountId: string; + futures: boolean; +} +⋮---- +export interface EnableFuturesBrokerSubAccountResponse { + subAccountId: string; + enableFutures: boolean; + updateTime: number; +} +⋮---- +export interface EnableMarginApiKeyBrokerSubAccountParams { + subAccountId: string; + margin: boolean; +} +export interface UniversalTransferBrokerParams { + fromId?: string; + toId?: string; + fromAccountType: string; + toAccountType: string; + asset: string; + amount: number; +} +⋮---- +export interface GetUniversalTransferBrokerParams { + fromId?: string; + toId?: string; + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; +} +⋮---- +export interface GetBrokerSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; +} +⋮---- +export interface DeleteApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; +} +⋮---- +export interface ChangePermissionApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface ChangePermissionApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface VirtualSubAccount { + email: string; +} +⋮---- +export interface BrokerSubAccountHistory { + subAccountsHistory: SubAccountTransferHistoryList[]; +} +⋮---- +export interface BrokerSubAccount { + subaccountId: string; + email: string; + makerCommission?: string; + takerCommission?: string; + marginMakerCommission?: string; + marginTakerCommission?: string; + createTime?: number; + tag: string; +} +⋮---- +export interface CreateApiKeyBrokerSubAccountResponse { + subaccountId: string; + apiKey: string; + secretKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} +⋮---- +export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canUniversalTransfer: boolean; +} +⋮---- +export interface GetBrokerInfoResponse { + maxMakerCommission: string; + minMakerCommission: string; + maxTakerCommission: string; + minTakerCommission: string; + subAccountQty: number; + maxSubAccountQty: number; +} +export interface SubAccountListParams { + email?: string; + isFreeze?: StringBoolean; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountListResponse { + subAccounts: SubAccountList[]; +} +⋮---- +export interface SubAccountSpotAssetTransferHistoryParams { + fromEmail?: string; + toEmail?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountSpotAssetTransferHistory + extends SubAccountBasicTransfer { + status: string; +} +⋮---- +export interface SubAccountFuturesAssetTransferHistoryParams { + email: string; + futuresType: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountFuturesAssetTransferHistory { + success: boolean; + futuresType: number; + transfers: SubAccountBasicTransfer[]; +} +⋮---- +export interface SubAccountFuturesAssetTransferParams { + fromEmail: string; + toEmail: string; + futuresType: number; + asset: string; + amount: number; +} +⋮---- +export interface SubAccountFuturesAssetTransfer { + success: boolean; + txnId: numberInString; +} +⋮---- +export interface SubAccountAssetsParams { + email: string; +} +⋮---- +export interface SubAccountAssets { + balances: SpotBalance[]; +} +⋮---- +export interface SubAccountSpotAssetsSummaryParams { + email?: string; + page?: number; + size?: number; +} +⋮---- +export interface SubAccountSpotAssetsSummary { + totalCount: number; + masterAccountTotalAsset: numberInString; + spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; +} +⋮---- +export interface SubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; +} +⋮---- +export interface SubAccountDepositAddress { + address: string; + coin: string; + tag: string; + url: string; +} +⋮---- +export interface SubAccountDepositHistoryParams extends DepositHistoryParams { + email: string; +} +⋮---- +export interface SubAccountEnableMargin { + email: string; + isMarginEnabled: boolean; +} +⋮---- +export interface SubAccountMarginAccountDetail extends BasicBtcTotals { + email: string; + marginLevel: numberInString; + marginTradeCoeffVo: MarginTradeCoeffVo; + marginUserAssetVoList: MarginBalance[]; +} +⋮---- +export interface SubAccountListBtc extends BasicBtcTotals { + email: string; +} +⋮---- +export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { + subAccountList: SubAccountListBtc; +} +⋮---- +export interface SubAccountEnableFutures { + email: string; + isFuturesEnabled: boolean; +} +⋮---- +export interface SubAccountFuturesAccountDetail { + email: string; + asset: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + maxWithdrawAmount: numberInString; + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + updateTime: number; +} +⋮---- +export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { + subAccountList: FuturesSubAccountList[]; +} +⋮---- +export interface FuturesPositionRisk { + entryPrice: numberInString; + leverage: numberInString; + maxNotional: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + positionAmount: numberInString; + symbol: string; + unrealizedProfit: numberInString; +} +⋮---- +export interface SubAccountTransferParams { + email: string; + asset: string; + amount: number; + type: number; +} +⋮---- +export interface SubAccountTransfer { + txnId: numberInString; +} +⋮---- +export interface SubAccountTransferToSameMasterParams { + toEmail: string; + asset: string; + amount: number; +} +⋮---- +export interface SubAccountTransferToMasterParams { + asset: string; + amount: number; +} +⋮---- +export interface SubAccountTransferHistoryParams { + asset?: string; + type?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface SubAccountUniversalTransferParams { + fromEmail?: string; + toEmail?: string; + fromAccountType: AccountType; + toAccountType: AccountType; + clientTranId?: string; + asset: string; + amount: number; +} +⋮---- +export interface SubAccountMovePositionParams { + fromUserEmail: string; + toUserEmail: string; + productType: 'UM' | 'OPTION'; + orderArgs: { + symbol: string; + quantity: number; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + }[]; +} +export interface SubAccountUniversalTransfer extends SubAccountTransfer { + clientTranId?: string; +} +⋮---- +export interface SubAccountMovePosition { + fromUserEmail: string; + toUserEmail: string; + productType: 'UM' | 'OPTION'; + symbol: string; + priceType: string; + price: string; + quantity: string; + positionSide: string | null; + side: string; + success: boolean; +} +⋮---- +export interface SubAccountMovePositionHistoryParams { + symbol: string; + productType?: 'UM' | 'OPTION'; + startTime?: number; + endTime?: number; + page: number; + row: number; +} +⋮---- +export interface SubAccountMovePositionHistory { + fromUserEmail: string; + toUserEmail: string; + productType: 'UM' | 'OPTION'; + symbol: string; + price: string; + quantity: string; + positionSide: string | null; + side: string; + timeStamp: number; +} +⋮---- +export interface SubAccountUniversalTransferHistoryParams { + fromEmail?: string; + toEmail?: string; + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountUniversalTransferHistoryResponse { + result: SubAccountUniversalTransferHistory[]; + totalCount: number; +} +⋮---- +export interface SubAccountEnableLeverageToken { + email: string; + enableBlvt: boolean; +} +⋮---- +export interface AddIpRestriction extends BasicSubAccount { + status: string; + ipAddress: string; +} +⋮---- +export interface SubAccountEnableOrDisableIPRestriction { + ipRestrict: boolean; + ipList: string[]; + updateTime: number; + apiKey: string; +} +⋮---- +export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { + ipAddress: string; +} +⋮---- +export interface AddIPListForSubAccountResponseParams { + ip: string; + updateTime: number; + apiKey: string; +} +⋮---- +export interface SubAccountAssetDetails { + coin: string; + name: string; + totalBalance: numberInString; + availableBalance: numberInString; + inOrder: numberInString; + btcValue: numberInString; +} +⋮---- +export interface WithdrawAssetsFromManagedSubAccountParams { + fromEmail: string; + asset: string; + amount: number; + transferDate?: number; +} +⋮---- +export interface BasicFuturesSubAccountParams { + email: string; + futuresType: 1 | 2; +} +⋮---- +export interface SubAccountSummaryOnFuturesAccountV2Params { + futuresType: 1 | 2; + page?: number; + limit?: number; +} +⋮---- +export interface SubAccountUSDMDetail { + futureAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + maxWithdrawAmount: numberInString; + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + updateTime: number; + }; +} +⋮---- +export interface COINMSubAccount { + email: string; + totalMarginBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; +} +⋮---- +export interface SubAccountCOINMDetail { + deliveryAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; + }; +} +⋮---- +export interface SubAccountUSDMSummary { + futureAccountSummaryResp: { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + subAccountList: FuturesSubAccountList[]; + }; +} +⋮---- +export interface SubAccountCOINMSummary { + deliveryAccountSummaryResp: { + totalMarginBalanceOfBTC: numberInString; + totalUnrealizedProfitOfBTC: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; + subAccountList: COINMSubAccount[]; + }; +} +⋮---- +export interface COINMPositionRisk { + entryPrice: numberInString; + markPrice: numberInString; + leverage: numberInString; + isolated: numberInString; + isolatedWallet: numberInString; + isolatedMargin: numberInString; + isAutoAddMargin: numberInString; + positionSide: string; + positionAmount: numberInString; + symbol: string; + unrealizedProfit: numberInString; +} +⋮---- +export interface SubAccountUSDMPositionRisk { + futurePositionRiskVos: FuturesPositionRisk[]; +} +⋮---- +export interface SubAccountCOINMPositionRisk { + deliveryPositionRiskVos: COINMPositionRisk[]; +} +⋮---- +export interface StakingProductDetail { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + apy: numberInString; +} +⋮---- +export interface StakingProductQuota { + totalPersonalQuota: numberInString; + minimum: numberInString; +} +⋮---- +export interface StakingProduct { + projectId: string; + detail: StakingProductDetail; + quota: StakingProductQuota; +} +⋮---- +export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; +export type StakingStatus = 'HOLDING' | 'REDEEMED'; +export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; +export type BSwapType = 'SINGLE' | 'COMBINATION'; +export type BSwapOperationType = 'ADD' | 'REMOVE'; +⋮---- +export interface StakingProductPosition { + positionId: numberInString; + projectId: string; + asset: string; + amount: numberInString; + purchaseTime: numberInString; + duration: numberInString; + accrualDays: numberInString; + rewardAsset: string; + APY: numberInString; + rewardAmt: numberInString; + extraRewardAsset: string; + extraRewardAPY: numberInString; + estExtraRewardAmt: numberInString; + nextInterestPay: numberInString; + nextInterestPayDate: numberInString; + payInterestPeriod: numberInString; + redeemAmountEarly: numberInString; + interestEndDate: numberInString; + deliverDate: numberInString; + redeemPeriod: numberInString; + redeemingAmt: numberInString; + partialAmtDeliverDate: numberInString; + canRedeemEarly: boolean; + renewable: boolean; + type: string; + status: StakingStatus; +} +export interface StakingBasicParams { + product: StakingProductType; + current?: number; + size?: number; +} +⋮---- +export interface FlexibleSavingBasicParams { + status?: string; + featured?: number; + current?: number; + size?: number; + asset?: string; +} +⋮---- +export interface FlexibleProductPositionParams { + status?: string; + featured?: number; + current?: number; + size?: number; +} +⋮---- +export interface PurchaseFlexibleProductParams { + productId: string; + amount: number; + autoSubscribe: boolean; +} +⋮---- +export interface PurchaseFlexibleProductResponse { + purchaseId: number; +} +⋮---- +export interface RedeemFlexibleProductParams { + productId: string; + amount: number; + type: 'FAST' | 'NORMAL'; +} +⋮---- +export interface LeftDailyPurchaseQuotaFlexibleProductResponse { + asset: string; + leftQuota: string; +} +⋮---- +export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; +export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +export type ProjectSortBy = + | 'START_TIME' + | 'LOT_SIZE' + | 'INTEREST_RATE' + | 'DURATION'; +⋮---- +export interface FixedAndActivityProjectParams { + asset?: string; + type: ProjectType; + status?: ProjectStatus; + isSortAsc?: boolean; + sortBy?: ProjectSortBy; + current?: number; + size?: number; +} +export interface FixedAndActivityProjectPositionParams { + asset?: string; + projectId?: string; + status?: StakingStatus; +} +⋮---- +export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +⋮---- +export interface PurchaseRecordParams { + lendingType: LendingType; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface NewFutureAccountTransferParams { + asset: string; + amount: number; + type: 1 | 2 | 3 | 4; +} +⋮---- +export interface GetFutureAccountTransferHistoryParams { + asset: string; + startTime: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface FutureAccountTransfer { + asset: string; + tranId: number; + amount: string; + type: string; + timestamp: number; + status: 'PENDING' | 'CONFIRMED' | 'FAILED'; +} +⋮---- +export interface GetLoanCoinPaginatedHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +/** + * + * STAKING + * + */ +⋮---- +export interface StakingHistory { + positionId: numberInString; + time: number; + asset: string; + project?: string; + amount: numberInString; + lockPeriod?: numberInString; + deliverDate?: numberInString; + type?: string; + status: string; +} +⋮---- +export interface StakingPersonalLeftQuota { + leftPersonalQuota: numberInString; +} +⋮---- +export interface StakingHistoryParams extends StakingBasicParams { + txnType: StakingTxnType; + asset?: string; + startTime?: number; + endTime?: number; +} +export interface BSwapOperationsParams { + operationId?: number; + poolId?: number; + operation: BSwapOperationType; + startTime?: number; + endTime?: number; + limit: number; +} +⋮---- +export interface BSwapOperations { + operationId: number; + poolId: number; + poolName: string; + operation: BSwapOperationType; + status: number; + updateTime: number; + shareAmount: numberInString; +} +export interface RemoveBSwapLiquidityParams { + poolId: number; + type: BSwapType; + asset?: string; + shareAmount: number; +} +⋮---- +export interface AddBSwapLiquidityParams { + poolId: number; + type?: BSwapType; + asset: string; + quantity: number; +} +⋮---- +export interface BSwapShare { + shareAmount: number; + sharePercentage: number; + asset: { [k: string]: number }; +} +⋮---- +export interface BSwapLiquidity { + poolId: number; + poolNmae: string; + updateTime: number; + liquidity: { [k: string]: number }; + share: BSwapShare; +} +⋮---- +export interface FundingAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + btcValuation: string; +} +⋮---- +export interface GetAssetParams { + asset?: string; + needBtcValuation?: boolean; +} +⋮---- +export interface UserAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + ipoable: string; + btcValuation: string; +} +⋮---- +export interface SpotAssetTagsParams { + tag?: string; +} +⋮---- +export interface SpotAssetTag { + assetCode: string; + assetName: string; + trading: boolean; + tags: string[]; +} +⋮---- +export interface ConvertTransfer { + clientTranId: string; + asset: string; + amount: number; + targetAsset: string; + accountType?: string; +} +⋮---- +export interface ConvertTransferResponse { + tranId: number; + status: string; +} +⋮---- +export interface GetConvertBUSDHistoryParams { + tranId?: number; + clientTranId?: string; + asset?: string; + startTime: number; + endTime: number; + accountType?: string; + current?: number; + size?: number; +} +⋮---- +export interface BUSDConversionRecord { + tranId: number; + type: number; + time: number; + deductedAsset: string; + deductedAmount: string; + targetAsset: string; + targetAmount: string; + status: string; + accountType: string; +} +⋮---- +export interface CloudMiningHistoryParams { + tranId?: number; + clientTranId?: string; + asset?: string; + startTime: number; + endTime: number; + current?: number; + size?: number; +} +⋮---- +export interface CloudMining { + createTime: number; + tranId: number; + type: number; + asset: string; + amount: string; + status: string; +} +⋮---- +export interface ConvertibleCoinsResponse { + convertEnabled: boolean; + coins: string[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exchangeRates: any; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface ConvertibleCoinsParams { + coin: string; + enable: boolean; +} +⋮---- +export interface SubmitDepositCreditParams { + depositId?: number; + txId?: string; + subAccountId?: number; + subUserId?: number; +} +⋮---- +export interface SubmitDepositCreditResponse { + code: string; + message: string; + data: boolean; + success: boolean; +} +⋮---- +export interface DepositAddressListParams { + coin: string; + network?: string; +} +⋮---- +export interface DepositAddress { + coin: string; + address: string; + tag: string; + isDefault: number; +} +⋮---- +export interface WalletBalance { + activate: boolean; + balance: string; + walletName: string; +} +⋮---- +export interface DelegationHistoryParams { + email: string; + startTime: number; + endTime: number; + type?: 'Delegate' | 'Undelegate'; + asset?: string; + current?: number; + size?: number; +} +⋮---- +export interface DelegationHistory { + clientTranId: string; + transferType: 'Delegate' | 'Undelegate'; + asset: string; + amount: string; + time: number; +} +⋮---- +export interface DelistScheduleResponse { + delistTime: number; + symbols: string[]; +} +⋮---- +export interface WithdrawAddress { + address: string; + addressTag: string; + coin: string; + name: string; + network: string; + origin: string; + originType: string; + whiteStatus: boolean; +} +⋮---- +export interface AccountInfo { + vipLevel: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + isOptionsEnabled: boolean; + isPortfolioMarginRetailEnabled: boolean; +} +⋮---- +export interface ManagedSubAccountSnapshotParams { + email: string; + type: 'SPOT' | 'MARGIN' | 'FUTURES'; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface SubaccountBalances { + asset: string; + free: string; + locked: string; +} +⋮---- +export interface SubaccountUserAssets { + asset: string; + borrowed: string; + free: string; + interest: string; + locked: string; + netAsset: string; +} +⋮---- +export interface SubaccountAssets { + asset: string; + marginBalance: string; + walletBalance: string; +} +⋮---- +export interface SubaccountPosition { + entryPrice: string; + markPrice: string; + positionAmt: string; + symbol: string; + unRealizedProfit: string; +} +⋮---- +export interface ManagedSubAccountSnapshot { + code: number; + msg: string; + snapshotVos: { + data: { + balances?: SubaccountBalances[]; + totalAssetOfBtc?: string; + marginLevel?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + userAssets?: SubaccountUserAssets[]; + assets?: SubaccountAssets[]; + position?: SubaccountPosition[]; + }; + type: string; + updateTime: number; + }[]; +} +⋮---- +export interface ManagedSubAccountTransferLogParams { + email: string; + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: 'from' | 'to'; + transferFunctionAccountType?: + | 'SPOT' + | 'MARGIN' + | 'ISOLATED_MARGIN' + | 'USDT_FUTURE' + | 'COIN_FUTURE'; +} +⋮---- +export interface ManagerSubTransferHistoryVos { + fromEmail: string; + fromAccountType: string; + toEmail: string; + toAccountType: string; + asset: string; + amount: string; + scheduledData: number; + createTime: number; + status: string; + tranId: number; +} +⋮---- +export interface ManagedSubAccountFuturesAssetsResponse { + code: string; + message: string; + snapshotVos: { + type: string; + updateTime: number; + data: { + assets: SubaccountAssets[]; + position: SubaccountPosition[]; + }; + }[]; +} +⋮---- +export interface ManagedSubAccountMarginAssetsResponse { + marginLevel: string; + totalAssetOfBtc: string; + totalLiabilityOfBtc: string; + totalNetAssetOfBtc: string; + userAssets: SubaccountUserAssets[]; +} +⋮---- +export interface ManagedSubAccountListParams { + email?: string; + page?: number; + limit?: number; +} +⋮---- +export interface ManagerSubUserInfoVo { + rootUserId: number; + managersubUserId: number; + bindParentUserId: number; + email: string; + insertTimeStamp: number; + bindParentEmail: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + isSignedLVTRiskAgreement: boolean; +} +⋮---- +export interface SubaccountTradeInfoVos { + userId: number; + btc: number; + btcFutures: number; + btcMargin: number; + busd: number; + busdFutures: number; + busdMargin: number; + date: number; +} +export interface SubAccountTransactionStatistics { + recent30BtcTotal: string; + recent30BtcFuturesTotal: string; + recent30BtcMarginTotal: string; + recent30BusdTotal: string; + recent30BusdFuturesTotal: string; + recent30BusdMarginTotal: string; + tradeInfoVos: SubaccountTradeInfoVos[]; +} +⋮---- +export interface ManagedSubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; +} +⋮---- +export interface ManagedSubAccountDepositAddress { + coin: string; + address: string; + tag: string; + url: string; +} +⋮---- +export interface EnableOptionsForSubAccountResponse { + email: string; + isEOptionsEnabled: boolean; +} +⋮---- +export interface ManagedSubAccountTransferTTLogParams { + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: string; + transferFunctionAccountType?: string; +} +⋮---- +export interface UIKlinesParams { + symbol: string; + interval: string; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} +⋮---- +export interface Ticker24hrFull { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + prevClosePrice: string; + lastPrice: string; + lastQty: string; + bidPrice: string; + bidQty: string; + askPrice: string; + askQty: string; + openPrice: string; + highPrice: string; + lowPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} +⋮---- +export interface Ticker24hrMini { + symbol: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} +⋮---- +export type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; +⋮---- +export interface TradingDayTickerParams { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +export interface TradingDayTickerFull { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} +⋮---- +export interface TradingDayTickerMini { + symbol: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} +⋮---- +export type TradingDayTickerSingle = + | TradingDayTickerFull + | TradingDayTickerMini; +⋮---- +export type TradingDayTickerArray = + | TradingDayTickerFull[] + | TradingDayTickerMini[]; +⋮---- +export interface RollingWindowTickerParams { + symbol?: string; + symbols?: string[]; + windowSize?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +export interface NewOrderListOTOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: string; + pendingStopPrice?: string; + pendingTrailingDelta?: string; + pendingQuantity: string; + pendingIcebergQty?: string; + pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingStrategyId?: number; + pendingStrategyType?: number; +} +⋮---- +export interface NewOrderListOTOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} +⋮---- +export interface NewOrderListOTOCOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESPONSE'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + workingStrategyId?: number; + workingStrategyType?: number; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: string; + pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; +} +⋮---- +export interface NewOrderListOTOCOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} +⋮---- +export interface NewOrderListOPOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: string; + pendingStopPrice?: string; + pendingTrailingDelta?: string; + pendingIcebergQty?: string; + pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; +} +⋮---- +export interface NewOrderListOPOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty?: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} +⋮---- +export interface NewOrderListOPOCOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingSide: 'BUY' | 'SELL'; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingAbovePegPriceType?: string; + pendingAbovePegOffsetType?: string; + pendingAbovePegOffsetValue?: number; + pendingBelowType?: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; +} +⋮---- +export interface NewOrderListOPOCOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty?: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} +⋮---- +export interface OrderRateLimitUsage { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} +⋮---- +export interface PreventedMatchesParams { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} +⋮---- +export interface PreventedMatch { + symbol: string; + preventedMatchId: number; + takerOrderId: number; + makerSymbol: string; + makerOrderId: number; + tradeGroupId: number; + selfTradePreventionMode: SelfTradePreventionMode; + price: string; + makerPreventedQuantity: string; + transactTime: number; +} +⋮---- +export interface AllocationsParams { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; +} +⋮---- +export interface Allocation { + symbol: string; + allocationId: number; + allocationType: string; + orderId: number; + orderListId: number; + price: string; + qty: string; + quoteQty: string; + commission: string; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isAllocator: boolean; +} +⋮---- +export interface CommissionRates { + symbol: string; + standardCommission: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + taxCommission: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). + * `0.75` means pay 75% of the standard commission. It is not a reduction rate. + * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. + * Does not apply to tax or special commission. + */ + discount: string; + }; +} +⋮---- +/** + * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). + * `0.75` means pay 75% of the standard commission. It is not a reduction rate. + * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. + * Does not apply to tax or special commission. + */ +⋮---- +export interface GetCrossMarginTransferHistoryParams { + asset?: string; + type?: 'ROLL_IN' | 'ROLL_OUT'; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + isolatedSymbol?: string; +} +⋮---- +export interface CrossMarginTransferHistory { + amount: string; + asset: string; + status: string; + timestamp: number; + txId: number; + type: 'ROLL_IN' | 'ROLL_OUT'; + transFrom?: string; + transTo?: string; + fromSymbol?: string; + toSymbol?: string; +} +⋮---- +export interface GetMarginInterestHistoryParams { + asset?: string; + isolatedSymbol?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface MarginInterestHistory { + txId: number; + interestAccuredTime: number; + asset: string; + rawAsset?: string; + principal: string; + interest: string; + interestRate: string; + type: + | 'PERIODIC' + | 'ON_BORROW' + | 'PERIODIC_CONVERTED' + | 'ON_BORROW_CONVERTED' + | 'PORTFOLIO'; + isolatedSymbol?: string; +} +⋮---- +export interface GetForceLiquidationRecordParams { + startTime?: number; + endTime?: number; + isolatedSymbol?: string; + current?: number; + size?: number; +} +⋮---- +export interface ForceLiquidationRecord { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + isIsolated: boolean; + updatedTime: number; +} +⋮---- +export interface QueryMarginAccountAllOCOParams { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface QueryMarginAccountTradeListParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface IsolatedMarginSymbol { + base: string; + isBuyAllowed: boolean; + isMarginTrade: boolean; + isSellAllowed: boolean; + quote: string; + symbol: string; + delistTime?: number; +} +⋮---- +export interface ToggleBNBBurnParams { + spotBNBBurn?: 'true' | 'false'; + interestBNBBurn?: 'true' | 'false'; +} +⋮---- +export interface BNBBurnResponse { + spotBNBBurn: boolean; + interestBNBBurn: boolean; +} +⋮---- +export interface QueryMarginInterestRateHistoryParams { + asset: string; + vipLevel?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface MarginInterestRateHistory { + asset: string; + dailyInterestRate: string; + timestamp: number; + vipLevel: number; +} +⋮---- +export interface QueryCrossMarginFeeDataParams { + vipLevel?: number; + coin?: string; +} +⋮---- +export interface CrossMarginFeeData { + vipLevel: number; + coin: string; + transferIn: boolean; + borrowable: boolean; + dailyInterest: string; + yearlyInterest: string; + borrowLimit: string; + marginablePairs: string[]; +} +⋮---- +export interface IsolatedMarginFeeData { + vipLevel: number; + symbol: string; + leverage: string; + data: { + coin: string; + dailyInterest: string; + borrowLimit: string; + }[]; +} +⋮---- +export interface QueryIsolatedMarginTierDataParams { + symbol: string; + tier?: number; +} +⋮---- +export interface IsolatedMarginTierData { + symbol: string; + tier: number; + effectiveMultiple: string; + initialRiskRatio: string; + liquidationRiskRatio: string; + baseAssetMaxBorrowable: string; + quoteAssetMaxBorrowable: string; +} +⋮---- +export interface GetMarginOrderCountUsageParams { + isIsolated?: string; + symbol?: string; +} +⋮---- +export interface MarginOrderCountUsageResponse { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} +⋮---- +export interface Collateral { + minUsdValue: string; + /** Omitted for the highest tier (no upper limit), confirmed by Binance staff on Dev Vision. */ + maxUsdValue?: string; + discountRate: string; +} +⋮---- +/** Omitted for the highest tier (no upper limit), confirmed by Binance staff on Dev Vision. */ +⋮---- +export interface SmallLiabilityExchangeCoin { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; +} +export interface GetSmallLiabilityExchangeHistoryParams { + current: number; + size: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface SmallLiabilityExchangeHistory { + asset: string; + amount: string; + targetAsset: string; + targetAmount: string; + bizType: string; + timestamp: number; +} +⋮---- +export interface GetNextHourlyInterestRateParams { + assets: string; + isIsolated: boolean; +} +⋮---- +export interface NextHourlyInterestRate { + asset: string; + nextHourlyInterestRate: string; +} +⋮---- +export interface GetMarginCapitalFlowParams { + asset?: string; + symbol?: string; + type?: string; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface MarginCapitalFlow { + id: number; + tranId: number; + timestamp: number; + asset: string; + symbol: string; + type: string; + amount: string; +} +⋮---- +export interface MarginDelistSchedule { + delistTime: number; + crossMarginAssets: string[]; + isolatedMarginSymbols: string[]; + updateTime: number; +} +⋮---- +export interface MarginAvailableInventoryResponse { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any; + updateTime: number; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface ManualLiquidationParams { + type: string; + symbol?: string; +} +⋮---- +export interface ManualLiquidationResponse { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; +} +⋮---- +export interface LeverageBracket { + leverage: number; + maxDebt: number; + maintenanceMarginRate: number; + initialMarginRate: number; + fastNum: number; +} +⋮---- +export interface LiabilityCoinLeverageBracket { + assetNames: string[]; + rank: number; + brackets: LeverageBracket[]; +} +export interface GetFlexibleSubscriptionRecordParams { + productId?: string; + purchaseId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface GetFlexibleSubscriptionRecordResponse { + amount: string; + asset: string; + time: number; + purchaseId: number; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; +} +⋮---- +export interface GetLockedSubscriptionRecordParams { + purchaseId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface LockedSubscriptionRecord { + positionId: string; + purchaseId: number; + time: number; + asset: string; + amount: string; + lockPeriod: string; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; +} +⋮---- +export interface GetFlexibleRedemptionRecordParams { + productId?: string; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface FlexibleRedemptionRecord { + amount: string; + asset: string; + time: number; + productId: string; + redeemId: number; + destAccount: string; + status: string; +} +⋮---- +export interface GetLockedRedemptionRecordParams { + positionId?: string; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface LockedRedemptionRecord { + positionId: string; + redeemId: number; + time: number; + asset: string; + lockPeriod: string; + amount: string; + type: string; + deliverDate: string; + status: string; +} +⋮---- +export interface GetFlexibleRewardsHistoryParams { + productId?: string; + asset?: string; + startTime?: number; + endTime?: number; + type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; + current?: number; + size?: number; +} +⋮---- +export interface FlexibleRewardsHistory { + asset: string; + rewards: string; + projectId: string; + type: string; + time: number; +} +⋮---- +export interface GetLockedRewardsHistoryParams { + positionId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface GetLockedRewardsHistory { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; + type: string; +} +⋮---- +export interface SetAutoSubscribeParams { + productId: string; + autoSubscribe: boolean; +} +⋮---- +export interface GetFlexibleSubscriptionPreviewParams { + productId: string; + amount: number; +} +⋮---- +export interface FlexibleSubscriptionPreview { + totalAmount: string; + rewardAsset: string; + airDropAsset: string; + estDailyBonusRewards: string; + estDailyRealTimeRewards: string; + estDailyAirdropRewards: string; +} +⋮---- +export interface GetLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; +} +⋮---- +export interface LockedSubscriptionPreview { + rewardAsset: string; + totalRewardAmt: string; + extraRewardAsset: string; + estTotalExtraRewardAmt: string; + nextPay: string; + nextPayDate: string; + valueDate: string; + rewardsEndDate: string; + deliverDate: string; + nextSubscriptionDate: string; + boostRewardAsset: string; + estDailyRewardAmt: string; +} +⋮---- +export interface GetRateHistoryParams { + productId: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface GetRateHistory { + productId: string; + asset: string; + annualPercentageRate: string; + time: number; +} +⋮---- +export interface GetCollateralRecordParams { + productId?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface CollateralRecord { + amount: string; + productId: string; + asset: string; + createTime: number; + type: string; + productName: string; + orderId: number; +} +⋮---- +export interface GetDualInvestmentProductListParams { + optionType: string; + exercisedCoin: string; + investCoin: string; + pageSize?: number; + pageIndex?: number; +} +⋮---- +export interface DualInvestmentProduct { + id: string; + investCoin: string; + exercisedCoin: string; + strikePrice: string; + duration: number; + settleDate: number; + purchaseDecimal: number; + purchaseEndTime: number; + canPurchase: boolean; + apr: string; + orderId: number; + minAmount: string; + maxAmount: string; + createTimestamp: number; + optionType: string; + isAutoCompoundEnable: boolean; + autoCompoundPlanList: string[]; +} +⋮---- +export interface SubscribeDualInvestmentProductParams { + id: string; + orderId: string; + depositAmount: number; + /** + * @deprecated Binance removed the `autoCompoundPlan` request parameter from + * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. + * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says + * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec + * still lists the parameter, so this field stays deprecated. + */ + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} +⋮---- /** - * The WebsocketClient will manage individual connections for you, under the hood. - * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. - */ -const wsClient = new WebsocketClient({ - api_key: key, - api_secret: secret, - // Optional: when enabled, the SDK will try to format incoming data into more readable objects. - // Beautified data is emitted via the "formattedMessage" event - beautify: true, - // Disable ping/pong ws heartbeat mechanism (not recommended) - // disableHeartbeat: true, - // Connect to testnet environment - // testnet: true, -}); - -// receive raw events -wsClient.on('message', (data) => { - console.log('raw message received ', JSON.stringify(data, null, 2)); -}); - -// notification when a connection is opened -wsClient.on('open', (data) => { - console.log('connection opened open:', data.wsKey, data.wsUrl); -}); - -// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. -wsClient.on('formattedMessage', (data) => { - console.log('formattedMessage: ', data); -}); - -// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -wsClient.on('response', (data) => { - console.log('log response: ', JSON.stringify(data, null, 2)); -}); - -// receive notification when a ws connection is reconnecting automatically -wsClient.on('reconnecting', (data) => { - console.log('ws automatically reconnecting.... ', data?.wsKey); -}); - -// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) -wsClient.on('reconnected', (data) => { - console.log('ws has reconnected ', data?.wsKey); -}); - -// Recommended: receive error events (e.g. first reconnection failed) -wsClient.on('exception', (data) => { - console.log('ws saw error ', data?.wsKey); -}); - + * @deprecated Binance removed the `autoCompoundPlan` request parameter from + * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. + * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says + * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec + * still lists the parameter, so this field stays deprecated. + */ +⋮---- +export interface SubscribeDualInvestmentProductResponse { + positionId: number; + investCoin: string; + exercisedCoin: string; + subscriptionAmount: string; + duration: number; + autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; + strikePrice: string; + settleDate: number; + purchaseStatus: string; + apr: string; + orderId: number; + purchaseTime: number; + optionType: string; +} +⋮---- +export interface GetDualInvestmentPositionsParams { + status?: + | 'PENDING' + | 'PURCHASE_SUCCESS' + | 'SETTLED' + | 'PURCHASE_FAIL' + | 'REFUNDING' + | 'REFUND_SUCCESS' + | 'SETTLING'; + pageSize?: number; + pageIndex?: number; +} +⋮---- +export interface DualInvestmentPosition { + id: string; + investCoin: string; + exercisedCoin: string; + subscriptionAmount: string; + strikePrice: string; + duration: number; + settleDate: number; + purchaseStatus: string; + apr: string; + orderId: number; + purchaseEndTime: number; + optionType: string; + autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; + settlePrice?: string; + isExercised?: boolean; + settleAsset?: string; + settleAmount?: string; + subscriptionTime?: number; +} +⋮---- +export interface CheckDualInvestmentAccountsResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; +} +⋮---- /** - * Subscribe to public topics either one at a time or many in an array + * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. + * Configure auto-compound for Dual Investment positions in the Binance web UI. + * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published + * binance-api-swagger spec still lists the endpoint, so this type stays deprecated. */ - -// E.g. one at a time, routed to the coinm futures websockets: -wsClient.subscribe('btcusd@indexPrice', 'coinm'); -wsClient.subscribe('btcusd@miniTicker', 'coinm'); - -// Or send many topics at once to a stream, e.g. the usdm futures stream: -wsClient.subscribe( - ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], - 'usdm', -); - -// spot & margin topics should go to "main" -// (similar how the MainClient is for REST APIs in that product group) -wsClient.subscribe( - [ - // All Market Rolling Window Statistics Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams - '!ticker_1h@arr', - // Individual Symbol Book Ticker Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams - 'btcusdt@bookTicker', - // Average Price - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price - 'btcusdt@avgPrice', - // Partial Book Depth Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams - 'btcusdt@depth10@100ms', - // Diff. Depth Stream - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream - 'btcusdt@depth', - ], - // Look at the `WS_KEY_URL_MAP` for a list of values here: - // https://github.com/sieblyio/binance/blob/master/src/util/websockets/websocket-util.ts - // "main" connects to wss://stream.binance.com:9443/stream - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams - 'main', -); - +export interface ChangeAutoCompoundStatusParams { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} +⋮---- +export interface ChangeAutoCompoundStatusResponse { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} +⋮---- +export interface GetTargetAssetListParams { + targetAsset?: string; + size?: number; + current?: number; +} +⋮---- +export interface RoiAndDimensionType { + simulateRoi: string; + dimensionValue: string; + dimensionUnit: string; +} +⋮---- +export interface AutoInvestAsset { + targetAsset: string; + roiAndDimensionTypeList: RoiAndDimensionType[]; +} +⋮---- +export interface GetTargetAssetListResponse { + targetAssets: string[]; + autoInvestAssetList: AutoInvestAsset[]; +} +⋮---- +export interface GetTargetAssetROIParams { + targetAsset: string; + hisRoiType: + | 'FIVE_YEAR' + | 'THREE_YEAR' + | 'ONE_YEAR' + | 'SIX_MONTH' + | 'THREE_MONTH' + | 'SEVEN_DAY'; +} +⋮---- +export interface TargetAssetROI { + date: string; + simulateRoi: string; +} +⋮---- +export interface GetSourceAssetListParams { + targetAsset?: string[]; + indexId?: number; + usageType: 'RECURRING' | 'ONE_TIME'; + flexibleAllowedToUse?: boolean; + sourceType?: 'MAIN_SITE' | 'TR'; +} +⋮---- +export interface SourceAsset { + sourceAsset: string; + assetMinAmount: string; + assetMaxAmount: string; + scale: string; + flexibleAmount: string; +} +⋮---- +export interface GetSourceAssetListResponse { + feeRate: string; + taxRate: string; + sourceAssets: SourceAsset[]; +} +⋮---- +export interface AutoInvestPortfolioDetail { + targetAsset: string; + percentage: number; +} +⋮---- +export interface CreateInvestmentPlanParams { + UID: string; + sourceType: 'MAIN_SITE' | 'TR'; + requestId?: string; + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; + indexId?: number; + subscriptionAmount: number; + subscriptionCycle: + | 'H1' + | 'H4' + | 'H8' + | 'H12' + | 'WEEKLY' + | 'DAILY' + | 'MONTHLY' + | 'BI_WEEKLY'; + subscriptionStartDay?: number; + subscriptionStartWeekday?: + | 'MON' + | 'TUE' + | 'WED' + | 'THU' + | 'FRI' + | 'SAT' + | 'SUN'; + subscriptionStartTime: number; + sourceAsset: string; + flexibleAllowedToUse: boolean; + details: AutoInvestPortfolioDetail[]; +} +⋮---- +export interface CreateInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; +} +⋮---- +export interface EditInvestmentPlanParams { + planId: number; + subscriptionAmount: number; + subscriptionCycle: + | 'H1' + | 'H4' + | 'H8' + | 'H12' + | 'WEEKLY' + | 'DAILY' + | 'MONTHLY' + | 'BI_WEEKLY'; + subscriptionStartDay?: number; + subscriptionStartWeekday?: + | 'MON' + | 'TUE' + | 'WED' + | 'THU' + | 'FRI' + | 'SAT' + | 'SUN'; + subscriptionStartTime: number; + sourceAsset: string; + flexibleAllowedToUse?: boolean; + details: AutoInvestPortfolioDetail[]; +} +⋮---- +export interface EditInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; +} +⋮---- +export interface ChangePlanStatusParams { + planId: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +} +⋮---- +export interface ChangePlanStatusResponse { + planId: number; + nextExecutionDateTime: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +} +⋮---- +export interface GetPlanDetailsParams { + planId?: number; + requestId?: string; +} +⋮---- +export interface GetSubscriptionTransactionHistoryParams { + planId?: number; + startTime?: number; + endTime?: number; + targetAsset?: string; + planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; + size?: number; + current?: number; +} +⋮---- +export interface AssetAllocation { + targetAsset: string; + allocation: string; +} +⋮---- +export interface GetIndexDetailsResponse { + indexId: number; + indexName: string; + status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; + assetAllocation: AssetAllocation[]; +} +⋮---- +export interface IndexLinkedPlanDetail { + targetAsset: string; + averagePriceInUSD: string; + totalInvestedInUSD: string; + currentInvestedInUSD: string; + purchasedAmount: string; + pnlInUSD: string; + roi: string; + percentage: string; + availableAmount: string; + redeemedAmount: string; + assetValueInUSD: string; +} +⋮---- +export interface GetIndexLinkedPlanPositionDetailsResponse { + indexId: number; + totalInvestedInUSD: string; + currentInvestedInUSD: string; + pnlInUSD: string; + roi: string; + assetAllocation: { targetAsset: string; allocation: string }[]; + details: IndexLinkedPlanDetail[]; +} +⋮---- +export interface SubmitOneTimeTransactionParams { + sourceType: 'MAIN_SITE' | 'TR'; + requestId?: string; + subscriptionAmount: number; + sourceAsset: string; + flexibleAllowedToUse?: boolean; + planId?: number; + indexId?: number; + details: AutoInvestPortfolioDetail[]; +} +⋮---- +export interface SubmitOneTimeTransactionResponse { + transactionId: number; + waitSecond: number; +} +⋮---- +export interface GetOneTimeTransactionStatusParams { + transactionId: number; + requestId?: string; +} +⋮---- +export interface GetOneTimeTransactionStatusResponse { + transactionId: number; + status: 'SUCCESS' | 'CONVERTING'; +} +⋮---- +export interface SubmitIndexLinkedPlanRedemptionParams { + indexId: number; + requestId?: string; + redemptionPercentage: number; +} +⋮---- +export interface GetIndexLinkedPlanRedemptionHistoryParams { + requestId: number; + startTime?: number; + endTime?: number; + current?: number; + asset?: string; + size?: number; +} +⋮---- +export interface IndexLinkedPlanRedemptionRecord { + indexId: number; + indexName: string; + redemptionId: number; + status: 'SUCCESS' | 'FAILED'; + asset: string; + amount: string; + redemptionDateTime: number; + transactionFee: string; + transactionFeeUnit: string; +} +⋮---- +export interface GetIndexLinkedPlanRebalanceHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RebalanceTransactionDetail { + asset: string; + transactionDateTime: number; + rebalanceDirection: 'BUY' | 'SELL'; + rebalanceAmount: string; +} +⋮---- +export interface IndexLinkedPlanRebalanceRecord { + indexId: number; + indexName: string; + rebalanceId: number; + status: 'SUCCESS' | 'INIT'; + rebalanceFee: string; + rebalanceFeeUnit: string; + transactionDetails: RebalanceTransactionDetail[]; +} +⋮---- +export interface SubscribeEthStakingV2Response { + success: boolean; + wbethAmount: string; + conversionRatio: string; +} +⋮---- +export interface RedeemEthParams { + asset?: string; + amount: number; +} +⋮---- +export interface RedeemEthResponse { + success: boolean; + arrivalTime: number; + ethAmount: string; + conversionRatio: string; +} +⋮---- +export interface GetEthStakingHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface EthStakingHistory { + time: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAmount: string; + conversionRatio: string; +} +⋮---- +export interface GetEthRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface EthRedemptionHistory { + time: number; + arrivalTime: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAsset: string; + distributeAmount: string; + conversionRatio: string; +} +⋮---- +export interface GetBethRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BethRewardsHistory { + time: number; + asset: string; + holding: string; + amount: string; + annualPercentageRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; +} +⋮---- +export interface GetEthStakingQuotaResponse { + leftStakingPersonalQuota: string; + leftRedemptionPersonalQuota: string; +} +⋮---- +export interface GetETHRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface ETHRateHistory { + annualPercentageRate: string; + exchangeRate: string; + time: number; +} +⋮---- +export interface GetEthStakingAccountResponse { + cumulativeProfitInBETH: string; + lastDayProfitInBETH: string; +} +⋮---- +export interface GetEthStakingAccountV2Response { + holdingInETH: string; + holdings: { + wbethAmount: string; + bethAmount: string; + }; + thirtyDaysProfitInETH: string; + profit: { + amountFromWBETH: string; + amountFromBETH: string; + }; +} +⋮---- +export interface WrapBethResponse { + success: boolean; + wbethAmount: string; + exchangeRate: string; +} +⋮---- +export interface GetWrapHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface WrapHistory { + time: number; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + exchangeRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; +} +⋮---- +export interface WbethRewardsHistory { + time: number; + amountInETH: string; + holding: string; + holdingInETH: string; + annualPercentageRate: string; +} +⋮---- +export interface GetWbethRewardsHistoryResponse { + estRewardsInETH: string; + rows: WbethRewardsHistory[]; + total: number; +} +⋮---- /** - * For the user data stream, these convenient subscribe methods open a dedicated - * connection with the listen key workflow: + * BFUSD (sapi/v1/bfusd/*) */ - -wsClient.subscribeSpotUserDataStream(); -wsClient.subscribeMarginUserDataStream(); -wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); -wsClient.subscribeUsdFuturesUserDataStream(); -wsClient.subscribePortfolioMarginUserDataStream(); -``` - -See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. - -#### Preserving large integers in WebSocket messages - -By default, messages are parsed using `JSON.parse`, which cannot precisely represent integers larger than `Number.MAX_SAFE_INTEGER`. -If you need to preserve large integers (e.g., order IDs), provide a custom parser via `customParseJSONFn`. - -Example using RegEx below, although alternatives are possible too if desired. For more exampes check [ws-custom-parser.ts](./examples/WebSockets/ws-custom-parser.ts) in the examples folder: - -```ts -import { WebsocketClient } from 'binance'; - +⋮---- +export interface BfusdAccountResponse { + bfusdAmount: string; + usdtProfit: string; + bfusdProfit: string; +} +⋮---- +export interface BfusdSubscriptionQuota { + leftQuota: string; +} +⋮---- +export interface BfusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; +} +⋮---- +export interface BfusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; +} +⋮---- +export interface BfusdQuotaResponse { + subscriptionQuota: BfusdSubscriptionQuota; + fastRedemptionQuota: BfusdFastRedemptionQuota; + standardRedemptionQuota: BfusdStandardRedemptionQuota; +} +⋮---- +export interface BfusdSubscribeParams { + asset: string; + amount: number; +} +⋮---- +export interface BfusdSubscribeResponse { + success: boolean; + bfusdAmount: string; +} +⋮---- +export interface BfusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; +} +⋮---- +export interface BfusdRedeemResponse { + success: boolean; + receiveAmount: string; + fee: string; + arrivalTime: number; +} +⋮---- +export interface GetBfusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BfusdSubscriptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetBfusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BfusdRedemptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + fee: string; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetBfusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BfusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + annualPercentageRate: string; + rewardAsset?: string; + /** API may return this casing per Binance docs. */ + BFUSDPosition?: string; +} +⋮---- +/** API may return this casing per Binance docs. */ +⋮---- +export interface GetBfusdRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface BfusdRateHistoryRow { + annualPercentageRate: string; + time: number; +} +⋮---- /** - * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: - * https://github.com/sieblyio/binance/issues/208 - * - * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: + * RWUSD (sapi/v1/rwusd/*) */ -const ws = new WebsocketClient({ - // Default behaviour, if you don't include this: - // customParseJSONFn: (rawEvent) => { - // return JSON.parse(rawEvent); - // }, - - // Or, pre-process the raw event using RegEx, before using the same workflow: - customParseJSONFn: (rawEvent) => { - return JSON.parse( - rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), - ); - }, - - // Or, use a 3rd party library such as json-bigint: - // customParseJSONFn: (rawEvent) => { - // return JSONbig({ storeAsString: true }).parse(rawEvent); - // }, -}); - -ws.on('message', (msg) => { - console.log(msg); -}); - -// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values. -// Use a custom replacer or JSONbig.stringify if you need to log/serialize: -// const replacer = (_k: string, v: unknown) => typeof v === 'bigint' ? v.toString() : v; -// console.log(JSON.stringify(msg, replacer)); -``` - -### WebSocket API - -Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. - -#### Authentication - -HMAC, RSA and Ed25519 keys are supported for the WebSocket API. However, only Ed25519 keys support WebSocket API login. When using HMAC or RSA keys, each WebSocket API command will need to be individually signed. - -This is no issue for most use cases, but if you are latency sensitive, you should consider using Ed25519 keys. This will allow the WebSocket API client to authenticate once after the connection opens, and all commands can then be sent without additional request signatures. - -#### Event Driven API - -The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method. - -Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. - -#### Async Await API - -The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient). - -It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. - -Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. - -```typescript -import { WebsocketAPIClient } from 'binance'; - -// or, if you prefer `require()`: -// const { WebsocketAPIClient } = require('binance'); - +⋮---- +export interface RwusdAccountResponse { + rwusdAmount: string; + totalProfit: string; +} +⋮---- +export interface RwusdSubscriptionQuota { + assets: string[]; + leftQuota: string; + minimum: string; +} +⋮---- +export interface RwusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; +} +⋮---- +export interface RwusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; +} +⋮---- +export interface RwusdQuotaResponse { + subscriptionQuota: RwusdSubscriptionQuota; + fastRedemptionQuota: RwusdFastRedemptionQuota; + standardRedemptionQuota: RwusdStandardRedemptionQuota; + subscribeEnable: boolean; + redeemEnable: boolean; +} +⋮---- +export interface RwusdSubscribeParams { + asset: string; + amount: number; +} +⋮---- +export interface RwusdSubscribeResponse { + success: boolean; + rwusdAmount: string; +} +⋮---- +export interface RwusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; +} +⋮---- +export interface RwusdRedeemResponse { + success: boolean; + receiveAmount: string; + fee: string; + arrivalTime: number; +} +⋮---- +export interface GetRwusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdSubscriptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetRwusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdRedemptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + fee: string; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; +} +⋮---- +export interface GetRwusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + rwusdPosition: string; + annualPercentageRate: string; +} +⋮---- +export interface GetRwusdRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RwusdRateHistoryRow { + annualPercentageRate: string; + time: number; +} +⋮---- +export interface GetMiningAlgoListResponse { + algoName: string; // Algorithm name + algoId: number; // Algorithm ID + poolIndex: number; // Sequence + unit: string; // Unit +} +⋮---- +algoName: string; // Algorithm name +algoId: number; // Algorithm ID +poolIndex: number; // Sequence +unit: string; // Unit +⋮---- +export interface GetMiningCoinListResponse { + coinName: string; // Coin name + coinId: number; // Coin ID + poolIndex: number; // Sequence + unit: string; // Unit +} +⋮---- +coinName: string; // Coin name +coinId: number; // Coin ID +poolIndex: number; // Sequence +unit: string; // Unit +⋮---- +export interface GetMinerDetailsParams { + algo: string; + userName: string; + workerName: string; +} +⋮---- +export interface HashrateData { + time: number; + hashrate: string; + reject: number; +} +⋮---- +export interface MinerDetail { + workerName: string; + type: string; + hashrateDatas: HashrateData[]; +} +⋮---- +export interface GetMinerDetailsResponse { + code: number; + msg: string; + data: MinerDetail[]; +} +⋮---- +export interface GetMinerListParams { + algo: string; + userName: string; + pageIndex?: number; + sort?: number; + sortColumn?: number; + workerStatus?: number; +} +⋮---- +export interface WorkerData { + workerId: string; + workerName: string; + status: number; + hashRate: number; + dayHashRate: number; + rejectRate: number; + lastShareTime: number; +} +⋮---- +export interface GetMinerListResponse { + code: number; + msg: string; + data: { + workerDatas: WorkerData[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetEarningsListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface AccountEarningsProfit { + time: number; + type: number; + hashTransfer: number | null; + transferAmount: number | null; + dayHashRate: number; + profitAmount: number; + coinName: string; + status: number; +} +⋮---- +export interface GetEarningsListResponse { + code: number; + msg: string; + data: { + accountProfits: AccountEarningsProfit[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetExtraBonusListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface OtherProfit { + time: number; + coinName: string; + type: number; + profitAmount: number; + status: number; +} +⋮---- +export interface GetExtraBonusListResponse { + code: number; + msg: string; + data: { + otherProfits: OtherProfit[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetHashrateResaleListParams { + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface ConfigDetail { + configId: number; + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + startDay: number; + endDay: number; + status: number; +} +⋮---- +export interface GetHashrateResaleListResponse { + code: number; + msg: string; + data: { + configDetails: ConfigDetail[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetHashrateResaleDetailParams { + configId: number; + userName: string; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface ProfitTransferDetail { + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + day: number; + amount: number; + coinName: string; +} +⋮---- +export interface GetHashrateResaleDetailResponse { + code: number; + msg: string; + data: { + profitTransferDetails: ProfitTransferDetail[]; + totalNum: number; + pageSize: number; + }; +} +export interface SubmitHashrateResaleParams { + userName: string; + algo: string; + endDate: number; + startDate: number; + toPoolUser: string; + hashRate: number; +} +⋮---- +export interface CancelHashrateResaleConfigParams { + configId: number; + userName: string; +} +⋮---- +export interface GetStatisticListParams { + algo: string; + userName: string; +} +⋮---- +export interface Profit { + BTC: string; + BSV: string; + BCH: string; +} +⋮---- +export interface GetStatisticListResponse { + code: number; + msg: string; + data: { + fifteenMinHashRate: string; + dayHashRate: string; + validNum: number; + invalidNum: number; + profitToday: Profit; + profitYesterday: Profit; + userName: string; + unit: string; + algo: string; + }; +} +⋮---- +export interface getMiningAccountsListParams { + algo: string; + userName: string; +} +⋮---- +export interface MiningHashrateData { + time: number; + hashrate: string; + reject: string; +} +⋮---- +export interface MiningAccountData { + type: string; + userName: string; + list: MiningHashrateData[]; +} +⋮---- +export interface getMiningAccountsListResponse { + code: number; + msg: string; + data: MiningAccountData[]; +} +⋮---- +export interface GetMiningAccountEarningParams { + algo: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} +⋮---- +export interface AccountMiningProfit { + time: number; + coinName: string; + type: number; + puid: number; + subName: string; + amount: number; +} +⋮---- +export interface GetMiningAccountEarningResponse { + code: number; + msg: string; + data: { + accountProfits: AccountMiningProfit[]; + totalNum: number; + pageSize: number; + }; +} +⋮---- +export interface GetFutureTickLevelOrderbookDataLinkParams { + symbol: string; + dataType: 'T_DEPTH' | 'S_DEPTH'; + startTime: number; + endTime: number; +} +⋮---- +export interface HistoricalDataLink { + day: string; + url: string; +} +⋮---- +export interface SubmitVpNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + quantity: number; + urgency: 'LOW' | 'MEDIUM' | 'HIGH'; + clientAlgoId?: string; + reduceOnly?: boolean; + limitPrice?: number; +} +⋮---- +export interface SubmitVpNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface SubmitTwapNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + quantity: number; + duration: number; + clientAlgoId?: string; + reduceOnly?: boolean; + limitPrice?: number; +} +⋮---- +export interface SubmitTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface CancelAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface AlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; +} +⋮---- +export interface GetAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; + startTime?: number; + endTime?: number; + page?: number; + pageSize?: number; +} +⋮---- +export interface HistoricalAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; +} +⋮---- +export interface GetAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: number; +} +⋮---- +export interface SubOrder { + algoId: number; + orderId: number; + orderStatus: string; + executedQty: string; + executedAmt: string; + feeAmt: string; + feeAsset: string; + bookTime: number; + avgPrice: string; + side: 'BUY' | 'SELL'; + symbol: string; + subId: number; + timeInForce: string; + origQty: string; +} +⋮---- +export interface GetAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SubOrder[]; +} +⋮---- +export interface SubmitSpotTwapNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: number; + duration: number; + clientAlgoId?: string; + limitPrice?: number; + stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; +} +⋮---- +export interface SubmitSpotTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface CancelSpotAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: string; +} +⋮---- +export interface SpotAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; + /** Order duration in seconds. Only returned for TWAP orders. */ + duration?: number; +} +⋮---- +/** Order duration in seconds. Only returned for TWAP orders. */ +⋮---- +export interface GetSpotAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; + startTime?: number; + endTime?: number; + page?: number; + pageSize?: number; +} +⋮---- +export interface HistoricalSpotAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; + /** Order duration in seconds. Only returned for TWAP orders. */ + duration?: number; +} +⋮---- +/** Order duration in seconds. Only returned for TWAP orders. */ +⋮---- +export interface GetSpotAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: number; +} +⋮---- +export interface SpotSubOrder { + algoId: number; + orderId: number; + orderStatus: string; + executedQty: string; + executedAmt: string; + feeAmt: string; + feeAsset: string; + bookTime: number; + avgPrice: string; + side: 'BUY' | 'SELL'; + symbol: string; + subId: number; + timeInForce: string; + origQty: string; +} +⋮---- +export interface GetSpotAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SpotSubOrder[]; +} +⋮---- +export interface GetPortfolioMarginProAccountInfoResponse { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + accountStatus: string; + accountType: string; +} +⋮---- +export interface PortfolioDeltaModeStatus { + deltaEnabled: boolean; +} +⋮---- +export interface SwitchPortfolioDeltaModeParams { + deltaEnabled: 'true' | 'false'; +} +⋮---- +export interface GetPortfolioMarginProCollateralRateResponse { + asset: string; + collateralRate: string; +} +⋮---- +export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { + asset: string; + amount: string; +} +⋮---- +export interface GetPortfolioMarginProInterestHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; +} +⋮---- +export interface GetPortfolioMarginProInterestHistoryResponse { + asset: string; + interest: string; + interestAccruedTime: number; + interestRate: string; + principal: string; +} +⋮---- +export interface GetPortfolioMarginAssetIndexPriceResponse { + asset: string; + assetIndexPrice: string; + time: number; +} +⋮---- +export interface BnbTransferParams { + amount: number; + transferSide: 'TO_UM' | 'FROM_UM'; +} +⋮---- +export interface GetPortfolioMarginAssetLeverageResponse { + asset: string; + leverage: number; +} +⋮---- +export interface SetPortfolioMarginMarginCallLevelParams { + marginCallLevel: number; +} +⋮---- +export interface PortfolioMarginMarginCallLevelResponse { + marginCallLevel: string; +} +⋮---- +export type PortfolioMarginMarginCallLevelGetResponse = + | PortfolioMarginMarginCallLevelResponse + | Record; +⋮---- +export interface PortfolioMarginMarginCallLevelDeleteResponse { + msg: string; +} +⋮---- +export interface SubscribeBlvtParams { + tokenName: string; + cost: number; +} +⋮---- +export interface SubscribeBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + amount: string; + cost: string; + timestamp: number; +} +⋮---- +export interface GetBlvtSubscriptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface BlvtSubscriptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + totalCharge: string; + timestamp: number; +} +⋮---- +export interface RedeemBlvtParams { + tokenName: string; + amount: number; +} +⋮---- +export interface RedeemBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + redeemAmount: string; + amount: string; + timestamp: number; +} +⋮---- +export interface GetBlvtRedemptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface BlvtRedemptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + netProceed: string; + timestamp: number; +} +⋮---- +export interface BlvtUserLimitInfo { + tokenName: string; + userDailyTotalPurchaseLimit: string; + userDailyTotalRedeemLimit: string; +} +⋮---- +export interface GetFiatOrderHistoryParams { + transactionType: string; + beginTime?: number; + endTime?: number; + page?: number; + rows?: number; +} +⋮---- +export interface GetFiatOrderHistoryResponse { + code: string; + message: string; + data: { + orderNo: string; + fiatCurrency: string; + indicatedAmount: string; + amount: string; + totalFee: string; + method: string; + status: string; + createTime: number; + updateTime: number; + }[]; + total: number; + success: boolean; +} +⋮---- +export interface GetFiatPaymentsHistoryResponse { + code: string; + message: string; + data: { + orderNo: string; + sourceAmount: string; + fiatCurrency: string; + obtainAmount: string; + cryptoCurrency: string; + totalFee: string; + price: string; + status: string; + paymentMethod?: string; + createTime: number; + updateTime: number; + }[]; + total: number; + success: boolean; +} +⋮---- +export interface WithdrawFiatAccountInfo { + accountNumber: string; + agency: string; + bankCodeForPix: string; + accountType: string; +} +⋮---- +export interface WithdrawFiatParams { + currency: string; + apiPaymentMethod: string; + amount: number; + accountInfo?: WithdrawFiatAccountInfo; +} +⋮---- +export interface FiatDepositParams { + currency: string; + apiPaymentMethod: string; + amount: number; + ext?: object; + recvWindow?: number; + timestamp?: number; +} +⋮---- +export interface FiatDepositResponse { + code: string; + message: string; + data: { + orderId: string; + }; +} +⋮---- +export interface GetFiatOrderDetailParams { + orderNo: string; + recvWindow?: number; + timestamp?: number; +} +⋮---- +export interface GetFiatOrderDetailResponse { + code: string; + message: string; + data: { + orderId: string; + orderStatus: string; + amount: string; + fee: string; + fiatCurrency: string; + errorCode: string; + errorMessage: string; + ext: object; + }; +} +⋮---- +export interface GetC2CTradeHistoryParams { + tradeType: string; + startTimestamp?: number; + endTimestamp?: number; + page?: number; + rows?: number; +} +⋮---- +export interface c2cTradeData { + orderNumber: string; + advNo: string; + tradeType: string; + asset: string; + fiat: string; + fiatSymbol: string; + amount: string; + totalPrice: string; + unitPrice: string; + orderStatus: string; + createTime: number; + commission: string; + counterPartNickName: string; + advertisementRole: string; +} +export interface GetC2CTradeHistoryResponse { + code: string; + message: string; + data: c2cTradeData[]; + total: number; + success: boolean; +} +⋮---- +export interface GetVipLoanOngoingOrdersParams { + orderId?: number; + collateralAccountId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} +⋮---- +export interface VipOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + loanRate: string; + residualInterest: string; + collateralAccountId: string; + collateralCoin: string; + totalCollateralValueAfterHaircut: string; + lockedCollateralValue: string; + currentLTV: string; + expirationTime: number; + loanDate: string; + loanTerm: string; + initialLtv: string; + marginCallLtv: string; + liquidationLtv: string; +} +⋮---- +export interface VipLoanRepayParams { + orderId: number; + amount: number; +} +⋮---- +export interface VipLoanRepayResponse { + loanCoin: string; + repayAmount: string; + remainingPrincipal: string; + remainingInterest: string; + collateralCoin: string; + currentLTV: string; + repayStatus: string; +} +⋮---- +export interface GetVipLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface VipLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + repayInterest: string; + repayPrincipal: string; + collateralCoin: string; + repayStatus: string; + loanDate: string; + repayTime: string; + orderId: string; +} +⋮---- +export interface VipLoanRenewParams { + orderId: number; + loanTerm?: number; +} +⋮---- +export interface VipLoanRenewResponse { + loanAccountId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; +} +⋮---- +export interface CheckVipCollateralAccountParams { + orderId?: number; + collateralAccountId?: number; +} +⋮---- +export interface VipCollateralAccount { + collateralAccountId: string; + collateralCoin: string; +} +⋮---- +export interface VipLoanBorrowParams { + loanAccountId: number; + loanCoin: string; + loanAmount: number; + collateralAccountId: string; + collateralCoin: string; + isFlexibleRate: boolean; + loanTerm?: number; +} +⋮---- +export interface VipLoanBorrowResponse { + loanAccountId: string; + requestId: string; + loanCoin: string; + isFlexibleRate: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm?: string; +} +⋮---- +export interface GetLoanableAssetsDataParams { + loanCoin?: string; + vipLevel?: number; +} +⋮---- +export interface GetApplicationStatusParams { + current?: number; + limit?: number; +} +⋮---- +export interface ApplicationStatus { + loanAccountId: string; + orderId: string; + requestId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; + status: string; + loanDate: string; +} +⋮---- +export interface BorrowInterestRate { + asset: string; + flexibleDailyInterestRate: string; + flexibleYearlyInterestRate: string; + time: number; +} +⋮---- +export interface GetCryptoLoansIncomeHistoryParams { + asset?: string; + type?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetCryptoLoansIncomeHistoryResponse { + asset: string; + type: string; + amount: string; + timestamp: number; + tranId: string; +} +⋮---- +export interface BorrowCryptoLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; + loanTerm: number; +} +⋮---- +export interface BorrowCryptoLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + hourlyInterestRate: string; + orderId: string; +} +⋮---- +export interface GetLoanBorrowHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface LoanBorrowHistory { + orderId: number; + loanCoin: string; + initialLoanAmount: string; + hourlyInterestRate: string; + loanTerm: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: string; +} +⋮---- +export interface GetLoanOngoingOrdersParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} +⋮---- +export interface LoanOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + residualInterest: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; + expirationTime: number; +} +⋮---- +export interface RepayCryptoLoanParams { + orderId: number; + amount: number; + type?: number; + collateralReturn?: boolean; +} +⋮---- +export interface RepayCryptoLoanResponse { + loanCoin: string; + remainingPrincipal?: string; + remainingInterest?: string; + collateralCoin: string; + remainingCollateral?: string; + currentLTV?: string; + repayStatus: string; +} +⋮---- +export interface GetLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface LoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralUsed: string; + collateralReturn: string; + repayType: string; + repayStatus: string; + repayTime: number; + orderId: number; +} +⋮---- +export interface AdjustCryptoLoanLTVParams { + orderId: number; + amount: number; + direction: 'ADDITIONAL' | 'REDUCED'; +} +⋮---- +export interface AdjustCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + amount: string; + currentLTV: string; +} +⋮---- +export interface GetLoanLTVAdjustmentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface LoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + amount: string; + preLTV: string; + afterLTV: string; + adjustTime: number; + orderId: number; +} +⋮---- +export interface LoanableAssetData { + loanCoin: string; + _7dHourlyInterestRate: string; + _7dDailyInterestRate: string; + _14dHourlyInterestRate: string; + _14dDailyInterestRate: string; + _30dHourlyInterestRate: string; + _30dDailyInterestRate: string; + _90dHourlyInterestRate: string; + _90dDailyInterestRate: string; + _180dHourlyInterestRate: string; + _180dDailyInterestRate: string; + minLimit: string; + maxLimit: string; + vipLevel: number; +} +⋮---- +export interface GetCollateralAssetDataParams { + collateralCoin?: string; + vipLevel?: number; +} +⋮---- +export interface CollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; + vipLevel: number; +} +⋮---- +export interface CheckCollateralRepayRateParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; +} +⋮---- +export interface CheckCollateralRepayRateResponse { + loanCoin: string; + collateralCoin: string; + repayAmount: string; + rate: string; +} +⋮---- +export interface CustomizeMarginCallParams { + orderId?: number; + collateralCoin?: string; + marginCall: number; +} +⋮---- +export interface CustomizeMarginCall { + orderId: string; + collateralCoin: string; + preMarginCall: string; + afterMarginCall: string; + customizeTime: number; +} +⋮---- +export interface BorrowFlexibleLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; +} +⋮---- +export interface BorrowFlexibleLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + status: 'Succeeds' | 'Failed' | 'Processing'; +} +⋮---- +export interface GetFlexibleLoanOngoingOrdersParams { + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} +⋮---- +export interface FlexibleLoanOngoingOrder { + loanCoin: string; + totalDebt: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; +} +⋮---- +export interface GetFlexibleLoanLiquidationHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; // Default: 1, max: 1000 + limit?: number; // Default: 10, max: 100 + recvWindow?: number; +} +⋮---- +current?: number; // Default: 1, max: 1000 +limit?: number; // Default: 10, max: 100 +⋮---- +export interface FlexibleLoanLiquidationHistoryRecord { + loanCoin: string; + liquidationDebt: string; + collateralCoin: string; + liquidationCollateralAmount: string; + returnCollateralAmount: string; + liquidationFee: string; + liquidationStartingPrice: string; + liquidationStartingTime: number; + status: 'Liquidated' | 'Liquidating'; +} +⋮---- +export interface GetFlexibleCryptoLoanBorrowHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface FlexibleCryptoLoanBorrowHistory { + loanCoin: string; + initialLoanAmount: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: 'Succeeds' | 'Failed' | 'Processing'; +} +⋮---- +export interface RepayCryptoFlexibleLoanParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; + collateralReturn?: boolean; + fullRepayment?: boolean; +} +⋮---- +export interface RepayCryptoFlexibleLoanResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +} +⋮---- +export interface RepayCryptoLoanFlexibleWithCollateralParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; // Amount of loan to repay + fullRepayment?: boolean; // Default: FALSE +} +⋮---- +repayAmount: number; // Amount of loan to repay +fullRepayment?: boolean; // Default: FALSE +⋮---- +export interface RepayCryptoLoanFlexibleWithCollateralResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +} +export interface GetFlexibleCryptoLoanRepaymentHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface FlexibleCryptoLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralReturn: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; + repayTime: number; +} +⋮---- +export interface AdjustFlexibleCryptoLoanLTVParams { + loanCoin: string; + collateralCoin: string; + adjustmentAmount: number; + direction: 'ADDITIONAL' | 'REDUCED'; +} +⋮---- +export interface AdjustFlexibleCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + adjustmentAmount: string; + currentLTV: string; +} +⋮---- +export interface GetFlexibleLoanLTVAdjustmentHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface FlexibleLoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + collateralAmount: string; + preLTV: string; + afterLTV: string; + adjustTime: number; +} +⋮---- +export interface FlexibleLoanAssetData { + loanCoin: string; + flexibleInterestRate: string; + flexibleMinLimit: string; + flexibleMaxLimit: string; +} +⋮---- +export interface FlexibleLoanCollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; +} +⋮---- +export interface GetFuturesLeadTraderStatusResponse { + code: string; + message: string; + data: { + isLeadTrader: boolean; + time: number; + }; + success: boolean; +} +⋮---- +export interface GetFuturesLeadTradingSymbolWhitelistResponse { + code: string; + message: string; + data: { + symbol: string; + baseAsset: string; + quoteAsset: string; + }[]; +} +⋮---- +export interface GetPayTradeHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface GetAllConvertPairsParams { + fromAsset?: string; + toAsset?: string; +} +⋮---- +export interface SubmitConvertLimitOrderParams { + baseAsset: string; + quoteAsset: string; + limitPrice: number; + baseAmount?: number; + quoteAmount?: number; + side: 'BUY' | 'SELL'; + walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; + expiredType: '1_D' | '3_D' | '7_D' | '30_D'; +} +⋮---- +export interface ConvertLimitOpenOrder { + quoteId: string; + orderId: number; + orderStatus: string; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; + expiredTimestamp: number; +} +⋮---- +export interface GetSpotRebateHistoryRecordsParams { + startTime?: number; + endTime?: number; + page?: number; +} +⋮---- +export interface SpotRebateHistoryRecord { + asset: string; + type: number; + amount: string; + updateTime: number; +} +⋮---- +export interface GetSpotRebateHistoryRecordsResponse { + status: string; + type: string; + code: string; + data: { + page: number; + totalRecords: number; + totalPageNum: number; + data: SpotRebateHistoryRecord[]; + }; +} +⋮---- +export interface GetNftTransactionHistoryParams { + orderType: number; + startTime?: number; + endTime?: number; + limit?: number; + page?: number; +} +⋮---- +export interface NftToken { + network: string; + tokenId: string; + contractAddress: string; +} +⋮---- +export interface NftTransaction { + orderNo: string; + tokens: NftToken[]; + tradeTime: number; + tradeAmount: string; + tradeCurrency: string; +} +⋮---- +export interface GetNftDepositHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; + page?: number; +} +⋮---- +export interface NftDeposit { + network: string; + txID: string | null; + contractAdrress: string; + tokenId: string; + timestamp: number; +} +⋮---- +export interface GetNftWithdrawHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; + page?: number; +} +⋮---- +export interface NftWithdraw { + network: string; + txID: string; + contractAdrress: string; + tokenId: string; + timestamp: number; + fee: number; + feeAsset: string; +} +⋮---- +export interface GetNftAssetParams { + limit?: number; + page?: number; +} +⋮---- +export interface NftAsset { + network: string; + contractAddress: string; + tokenId: string; +} +⋮---- +export interface CreateGiftCardParams { + token: string; + amount: number; +} +⋮---- +export interface CreateDualTokenGiftCardParams { + baseToken: string; + faceToken: string; + baseTokenAmount: number; + discount?: number; +} +⋮---- +export interface RedeemGiftCardParams { + code: string; + externalUid?: string; +} +⋮---- +export interface SimpleEarnProductListParams { + asset?: string; + current?: number; + size?: number; +} +⋮---- +export interface SimpleEarnFlexibleProduct { + asset: string; + latestAnnualInterestRate: string; + tierAnnualPercentageRate: Record; + airDropPercentageRate: string; + canPurchase: boolean; + canRedeem: boolean; + isSoldOut: boolean; + hot: boolean; + minPurchaseAmount: string; + productId: string; + subscriptionStartTime: number; + status: string; +} +⋮---- +export interface SimpleEarnLockedProduct { + projectId: string; + detail: { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: string; + subscriptionStartTime: number; + extraRewardAsset: string; + extraRewardAPR: string; + boostRewardAsset: string; + boostApr: string; + boostEndTime: string; + }; + quota: { + totalPersonalQuota: string; + minimum: string; + }; +} +⋮---- +export interface SimpleEarnSubscribeProductParams { + productId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; +} +⋮---- +export interface SimpleEarnSubscribeFlexibleProductResponse { + purchaseId: string; + success: boolean; +} +⋮---- +export interface SimpleEarnSubscribeLockedProductResponse { + purchaseId: string; + positionId: string; + success: boolean; +} +⋮---- +export interface SimpleEarnRedeemFlexibleProductParams { + productId: string; + redeemAll?: boolean; + amount?: number; + destAccount?: 'SPOT' | 'FUND'; +} +⋮---- +export interface SimpleEarnRedeemResponse { + success: boolean; + redeemId: string; +} +⋮---- +export interface SimpleEarnFlexibleProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; +} +⋮---- +export interface SimpleEarnLockedProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; + positionId?: string; +} +⋮---- +export interface SimpleEarnLockedProductPosition { + positionId: string; + projectId: string; + asset: string; + amount: string; + purchaseTime: string; + duration: string; + accrualDays: string; + rewardAsset: string; + APY: string; + isRenewable: boolean; + isAutoRenew: boolean; + redeemDate: string; + boostRewardAsset: string; + boostApr: string; + totalBoostRewardAmt: string; +} +⋮---- +export interface SimpleEarnAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedinBTC: string; + totalLockedinUSDT: string; +} +⋮---- +export interface GetSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; +} +⋮---- +export interface SubAccountDeposit { + depositId: number; + subAccountId: string; + address: string; + addressTag: string; + amount: string; + coin: string; + insertTime: number; + transferType: number; + network: string; + status: number; + txId: string; + sourceAddress: string; + confirmTimes: string; + selfReturnStatus: number; +} +⋮---- +// Request interface for querying sub account spot asset info +export interface QuerySubAccountSpotMarginAssetInfoParams { + subAccountId?: string; + page?: number; + size?: number; +} +⋮---- +export interface SubaccountBrokerSpotAsset { + subAccountId: string; + totalBalanceOfBtc: string; +} +⋮---- +export interface SubAccountBrokerMarginAsset { + marginEnable: boolean; + subAccountId: string; + totalAssetOfBtc?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + marginLevel?: string; +} +⋮---- +// Request interface for querying sub account futures asset info +export interface QuerySubAccountFuturesAssetInfoParams { + subAccountId?: string; + futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures + page?: number; + size?: number; +} +⋮---- +futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures +⋮---- +// Response interface for querying sub account futures asset info (USD Margined Futures) +export interface UsdtMarginedFuturesResponse { + subAccountId: string; + totalInitialMargin: string; + totalMaintenanceMargin: string; + totalWalletBalance: string; + totalUnrealizedProfit: string; + totalMarginBalance: string; + totalPositionInitialMargin: string; + totalOpenOrderInitialMargin: string; + futuresEnable: boolean; + asset: string; +} +⋮---- +// Response interface for querying sub account futures asset info (COIN Margined Futures) +export interface CoinMarginedFuturesResponse { + subAccountId: string; + totalWalletBalanceOfUsdt: string; + totalUnrealizedProfitOfUsdt: string; + totalMarginBalanceOfUsdt: string; + futuresEnable: boolean; +} +⋮---- +// Combined response interface for querying sub account futures asset info +export interface BrokerFuturesSubAccountAssets { + data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; + timestamp: number; +} +⋮---- +export interface BrokerUniversalTransfer { + toId: string; + asset: string; + qty: string; + time: number; + status: string; + txnId: string; + clientTranId: string; + fromAccountType: string; + toAccountType: string; +} +⋮---- +// Request interface for changing sub account commission +export interface ChangeSubAccountCommissionParams { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission?: number; + marginTakerCommission?: number; +} +⋮---- +// Response interface for changing sub account commission +export interface ChangeSubAccountCommissionResponse { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission: number; + marginTakerCommission: number; +} +⋮---- +// Request interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionParams { + subAccountId: string; + symbol: string; + makerAdjustment: number; + takerAdjustment: number; +} +⋮---- +// Response interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionResponse { + subAccountId: string; + symbol: string; + makerAdjustment: number; + takerAdjustment: number; + makerCommission: number; + takerCommission: number; +} +⋮---- +// Request interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface QuerySubAccountFuturesCommissionParams { + subAccountId: string; + symbol?: string; +} +⋮---- +// Response interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface BrokerSubAccountFuturesCommission { + subAccountId: string; + symbol: string; + makerCommission: number; + takerCommission: number; +} +⋮---- +export interface ChangeSubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair: string; + makerAdjustment: number; + takerAdjustment: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface QuerySubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +// Response interface for querying sub account COIN-Ⓜ futures commission adjustment +export interface BrokerSubAccountCoinFuturesCommission { + subAccountId: string; + pair: string; + makerCommission: number; + takerCommission: number; +} +⋮---- +export interface QueryBrokerSpotCommissionRebateParams { + subAccountId?: string; + startTime?: number; + endTime?: number; + page?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +// Response interface for querying spot commission rebate recent record +export interface BrokerCommissionRebate { + subaccountId: string; + income: string; + asset: string; + symbol: string; + tradeId: number; + time: number; + status: number; +} +⋮---- +export interface QueryBrokerFuturesCommissionRebateParams { + futuresType: number; // 1: USDT Futures, 2: Coin Futures + startTime: number; + endTime: number; + page?: number; + size?: number; + filterResult?: boolean; + recvWindow?: number; + timestamp: number; +} +⋮---- +futuresType: number; // 1: USDT Futures, 2: Coin Futures +⋮---- +export interface SubmitMarginOTOOrderParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + sideEffectType?: SideEffects; + selfTradePreventionMode?: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + autoRepayAtCancel?: boolean; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: number; + workingQuantity: number; + workingIcebergQty?: number; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingType: OrderType; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: number; + pendingStopPrice?: number; + pendingTrailingDelta?: number; + pendingQuantity: number; + pendingIcebergQty?: number; + pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; +} +⋮---- +export interface MarginOTOOrder { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + selfTradePreventionMode: string; + }[]; +} +⋮---- +export interface SubmitMarginOTOCOOrderParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + sideEffectType?: SideEffects; + autoRepayAtCancel?: boolean; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: string; + pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; +} +⋮---- +export interface QueryMarginOpenOTOOrderListsParams { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; +} +⋮---- +export interface MarginOpenOTOOrderList { + orderListId: number; + contingencyType: 'OTO' | 'OTOCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; +} +⋮---- +export interface MarginOTOCOOrder { + orderListId: number; + contingencyType: 'OTO' | 'OTOCO'; + listStatusType: 'EXEC_STARTED'; + listOrderStatus: 'EXECUTING'; + listClientOrderId: string; + transactionTime: number; + symbol: string; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: + | 'NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'PENDING_NEW'; + timeInForce: 'GTC' | 'IOC' | 'FOK'; + type: + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + side: 'BUY' | 'SELL'; + stopPrice?: string; + selfTradePreventionMode: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + }[]; +} +⋮---- +export interface CreateSpecialLowLatencyKeyParams { + apiName: string; + symbol?: string; + ip?: string; + publicKey?: string; +} +⋮---- +export interface SpecialLowLatencyKeyResponse { + apiKey: string; + secretKey: string | null; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +} +⋮---- +export interface SpecialLowLatencyKeyInfo { + apiName: string; + apiKey: string; + ip: string; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +} +⋮---- +export interface MarginLiquidationLoan { + asset: string; + amount: string; + repaidAmount: string; + remainingAmount: string; +} +⋮---- +export interface RepayMarginLiquidationLoanParams { + asset: string; + amount: string; +} +⋮---- +export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; +⋮---- +export interface MarginLiquidationLoanRepayResponse { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; +} +⋮---- +export interface GetMarginLiquidationLoanRepayHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface MarginLiquidationLoanRepayHistoryRecord { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; +} +⋮---- +export interface MarginLiquidationLoanRepayHistoryResponse { + total: number; + rows: MarginLiquidationLoanRepayHistoryRecord[]; +} +⋮---- +export interface SolStakingAccount { + bnsolAmount: string; // Amount in bNSOL + holdingInSOL: string; // Holding in SOL + thirtyDaysProfitInSOL: string; // 30 days profit in SOL +} +⋮---- +bnsolAmount: string; // Amount in bNSOL +holdingInSOL: string; // Holding in SOL +thirtyDaysProfitInSOL: string; // 30 days profit in SOL +⋮---- +export interface SolStakingQuota { + leftStakingPersonalQuota: string; // Remaining personal staking quota + leftRedemptionPersonalQuota: string; // Remaining personal redemption quota + minStakeAmount: string; // Minimum stake amount + minRedeemAmount: string; // Minimum redeem amount + redeemPeriod: number; // Redemption period in days + stakeable: boolean; // Whether staking is possible + redeemable: boolean; // Whether redemption is possible + soldOut: boolean; // Whether the staking is sold out + commissionFee: string; // Commission fee + nextEpochTime: number; // Time for the next epoch + calculating: boolean; // Whether calculations are ongoing +} +⋮---- +leftStakingPersonalQuota: string; // Remaining personal staking quota +leftRedemptionPersonalQuota: string; // Remaining personal redemption quota +minStakeAmount: string; // Minimum stake amount +minRedeemAmount: string; // Minimum redeem amount +redeemPeriod: number; // Redemption period in days +stakeable: boolean; // Whether staking is possible +redeemable: boolean; // Whether redemption is possible +soldOut: boolean; // Whether the staking is sold out +commissionFee: string; // Commission fee +nextEpochTime: number; // Time for the next epoch +calculating: boolean; // Whether calculations are ongoing +⋮---- +export interface SubscribeSolStakingResponse { + success: boolean; // Indicates if the subscription was successful + bnsolAmount: string; // Amount in bNSOL received + exchangeRate: string; // SOL amount per 1 BNSOL +} +⋮---- +success: boolean; // Indicates if the subscription was successful +bnsolAmount: string; // Amount in bNSOL received +exchangeRate: string; // SOL amount per 1 BNSOL +⋮---- +export interface RedeemSolResponse { + success: boolean; // Indicates if the redemption was successful + solAmount: string; // Amount in SOL received + exchangeRate: string; // SOL amount per 1 BNSOL + arrivalTime: number; // Time of arrival for the redeemed SOL +} +⋮---- +success: boolean; // Indicates if the redemption was successful +solAmount: string; // Amount in SOL received +exchangeRate: string; // SOL amount per 1 BNSOL +arrivalTime: number; // Time of arrival for the redeemed SOL +⋮---- +export interface GetSolStakingHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory +} +⋮---- +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory +⋮---- +export interface SolStakingHistoryRecord { + time: number; // Time of the staking event + asset: string; // Asset involved, e.g., SOL + amount: string; // Amount staked + distributeAsset: string; // Asset distributed, e.g., BNSOL + distributeAmount: string; // Amount distributed + exchangeRate: string; // Exchange rate at the time + status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +} +⋮---- +time: number; // Time of the staking event +asset: string; // Asset involved, e.g., SOL +amount: string; // Amount staked +distributeAsset: string; // Asset distributed, e.g., BNSOL +distributeAmount: string; // Amount distributed +exchangeRate: string; // Exchange rate at the time +status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +⋮---- +export interface GetSolRedemptionHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory +} +⋮---- +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory +⋮---- +export interface SolRedemptionHistoryRecord { + time: number; // Time of the redemption event + arrivalTime: number; // Time of arrival for the redeemed SOL + asset: string; // Asset redeemed, e.g., BNSOL + amount: string; // Amount redeemed + distributeAsset: string; // Asset distributed, e.g., SOL + distributeAmount: string; // Amount distributed + exchangeRate: string; // Exchange rate at the time + status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event +} +⋮---- +time: number; // Time of the redemption event +arrivalTime: number; // Time of arrival for the redeemed SOL +asset: string; // Asset redeemed, e.g., BNSOL +amount: string; // Amount redeemed +distributeAsset: string; // Asset distributed, e.g., SOL +distributeAmount: string; // Amount distributed +exchangeRate: string; // Exchange rate at the time +status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event +⋮---- +export interface GetBnsolRewardsHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory +} +⋮---- +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory +⋮---- +export interface BnsolRewardHistoryRecord { + time: number; // Time of the reward event + amountInSOL: string; // Reward amount in SOL + holding: string; // BNSOL holding balance + holdingInSOL: string; // BNSOL holding balance in SOL + annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) +} +⋮---- +time: number; // Time of the reward event +amountInSOL: string; // Reward amount in SOL +holding: string; // BNSOL holding balance +holdingInSOL: string; // BNSOL holding balance in SOL +annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) +⋮---- +export interface GetBnsolRateHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory +} +⋮---- +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory +⋮---- +export interface SolBoostRewardsHistoryReq { + type: 'CLAIM' | 'DISTRIBUTE'; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface SolBoostRewardsHistoryRecord { + time: number; + token: string; + amount: string; + bnsolHolding?: string; // Only present if type is "DISTRIBUTE" + status?: string; // Only present if type is "CLAIM" +} +⋮---- +bnsolHolding?: string; // Only present if type is "DISTRIBUTE" +status?: string; // Only present if type is "CLAIM" +⋮---- +export interface BnsolRateHistoryRecord { + annualPercentageRate: string; // BNSOL APR + exchangeRate: string; // SOL amount per 1 BNSOL + time: number; // Time of the rate record +} +⋮---- +annualPercentageRate: string; // BNSOL APR +exchangeRate: string; // SOL amount per 1 BNSOL +time: number; // Time of the rate record +⋮---- +export interface RiskUnitMM { + asset: string; + uniMaintainUsd: string; +} +⋮---- +export interface PortfolioMarginProSpanAccountInfo { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + riskUnitMMList: RiskUnitMM[]; + marginMM: string; + otherMM: string; + accountStatus: + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; + accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) +} +⋮---- +accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) +⋮---- +export interface PortfolioMarginProAccountBalance { + asset: string; + totalWalletBalance: string; + crossMarginAsset: string; + crossMarginBorrowed: string; + crossMarginFree: string; + crossMarginInterest: string; + crossMarginLocked: string; + umWalletBalance: string; + umUnrealizedPNL: string; + cmWalletBalance: string; + cmUnrealizedPNL: string; + updateTime: number; + negativeBalance: string; + optionWalletBalance: string; // only for PM PRO SPAN + optionEquity: string; // only for PM PRO SPAN +} +⋮---- +optionWalletBalance: string; // only for PM PRO SPAN +optionEquity: string; // only for PM PRO SPAN +⋮---- +export interface PMProMintBFUSDParams { + fromAsset: string; // USDT only + targetAsset: string; // BFUSD only + amount: number; +} +⋮---- +fromAsset: string; // USDT only +targetAsset: string; // BFUSD only +⋮---- +export interface PMProMintBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; +} +⋮---- +export interface PMProRedeemBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; +} +⋮---- +export interface PMProBankruptcyLoanRepaymentHistory { + asset: string; + amount: string; + repayTime: number; +} +⋮---- +export interface VipLoanInterestRateHistoryParams { + coin: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface VipLoanInterestRateRecord { + coin: string; + annualizedInterestRate: string; + time: number; +} +⋮---- +export interface VipLoanAccruedInterestParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} +⋮---- +export interface VipLoanAccruedInterestRecord { + loanCoin: string; + principalAmount: string; + interestAmount: string; + annualInterestRate: string; + accrualTime: number; + orderId: number; +} +⋮---- +export interface WithdrawTravelRuleParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; + amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; + questionnaire: string; +} +⋮---- +export interface GetTravelRuleWithdrawHistoryParams { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface GetTravelRuleWithdrawHistoryV2Params { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface SubmitTravelRuleDepositQuestionnaireParams { + tranId: number; + questionnaire: string; +} +⋮---- +export interface GetTravelRuleDepositHistoryParams { + trId?: string; + txId?: string; + tranId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + pendingQuestionnaire?: boolean; + startTime?: number; + endTime?: number; + offset?: number; + limit?: number; +} +⋮---- +export interface TravelRuleWithdrawHistoryRecord { + id: string; + trId: number; + amount: string; + transactionFee: string; + coin: string; + withdrawalStatus: number; + travelRuleStatus: number; + address: string; + addressTag?: string; + txId: string; + applyTime: string; + network?: string; + transferType: number; + withdrawOrderId?: string; + info: string; + confirmNo: number; + walletType: number; + txKey: string; + questionnaire: string; + completeTime?: string; +} +⋮---- +export interface SubmitTravelRuleDepositQuestionnaireResponse { + trId: number; + accepted: boolean; + info: string; +} +⋮---- +export interface TravelRuleDepositHistoryRecord { + trId: number; + tranId: number; + amount: string; + coin: string; + network: string; + depositStatus: number; + travelRuleStatus: number; + address: string; + addressTag?: string; + txId: string; + insertTime: number; + transferType: number; + confirmTimes: string; + unlockConfirm: number; + walletType: number; + requireQuestionnaire: boolean; + questionnaire: string | null; +} +⋮---- +export interface VASPInfo { + vaspName: string; + vaspCode?: string; + /** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ + identifier?: string; +} +⋮---- +/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ +⋮---- +export interface TravelRuleCountryInfo { + countryCode: string; + countryName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; + hasRegionRestrictions: boolean; +} +⋮---- +export interface TravelRuleCountryListResponse { + countries: TravelRuleCountryInfo[]; + lastUpdated: number; +} +⋮---- +export interface GetTravelRuleRegionListParams { + countryCode: string; +} +⋮---- +export interface TravelRuleRegionInfo { + regionName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; +} +⋮---- +export interface TravelRuleRegionListResponse { + countryCode: string; + regions: TravelRuleRegionInfo[]; + lastUpdated: number; +} +⋮---- +export interface GetVipLoanFixedRateMarketParams { + loanCoin: string; + duration?: number; + current?: number; + size?: number; +} +⋮---- +export interface VipLoanFixedRateMarketRecord { + requestId: number; + requestNo: number; + coin: string; + interestRate: numberInString; + duration: number; + minimumAmount: numberInString; + availableAmount: numberInString; + estimatedInterest: numberInString; +} +⋮---- +export interface VipLoanFixedRateBorrowParams { + supplyRequest: string; + borrowCoin: string; + loanTerm: number; + borrowUid: number; + collateralCoin: string; + collateralAccountId: string; + autoRepay?: boolean; +} +⋮---- +export interface VipLoanFixedRateBorrowResponse { + borrowCoin: string; + borrowAmount: numberInString; + actualReceivedAmount: numberInString; + collateralCoin: string; + collateralAccountId: string; + borrowInterestRate: numberInString; + duration: string; + autoRepay: boolean; + orderId: number; + status: 'Succeeds' | 'Failed' | 'Processing'; +} +⋮---- +// Institutional Loan types +export interface InstitutionalLoanLiability { + assetName: string; + principal: string; + interest: string; +} +⋮---- +export interface InstitutionalLoanWallet { + accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; +} +⋮---- +export interface InstitutionalLoanCollateralAccount { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + wallets: InstitutionalLoanWallet[]; +} +⋮---- +export interface InstitutionalLoanRiskUnitDetails { + groupId: number; + leverageTier: string; + initialLtv: string; + marginCallLtv: string; + liquidationLtv: string; + liquidationExitLtv: string; + maxTransferOutLtv: string; + parentEmail: string; + creditEmail: string; + updateTime: number; + ltv: string; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + // Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. + transferOutLtv: string; + parentAccountFrozenAmount: string; + maxTransferOutAmount: string; + maxAllowedBorrowLimit: string; + liabilities: InstitutionalLoanLiability[]; + collateralAccounts: InstitutionalLoanCollateralAccount[]; +} +⋮---- +// Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. +⋮---- +export interface GetInstitutionalLoanRiskUnitDetailsParams { + groupId?: number; +} +⋮---- +export interface CloseInstitutionalLoanRiskUnitResponse { + groupId: number; + status: 'CLOSED'; +} +⋮---- +export interface AddInstitutionalLoanCollateralAccountParams { + groupId: number; + subEmail: string; + enableSpot: boolean; + enableMargin: boolean; +} +⋮---- +export interface InstitutionalLoanRiskUnitMember { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + enableMargin: boolean; + enableSpot: boolean; +} +⋮---- +export interface ActiveInstitutionalLoanRiskUnit { + groupId: number; + members: InstitutionalLoanRiskUnitMember[]; + createTime: number; +} +export interface ClosedInstitutionalLoanRiskUnit { + groupId: number; + parentEmail: string; + creditEmail: string; + enabled: boolean; + createTime: number; + closeTime: number; +} +⋮---- +export interface GetClosedInstitutionalLoanRiskUnitsParams { + current?: number; + size?: number; +} +⋮---- +export interface GetClosedInstitutionalLoanRiskUnitsResponse { + total: number; + rows: ClosedInstitutionalLoanRiskUnit[]; +} +⋮---- +// Institutional Loan Force Liquidation interfaces +export interface InstitutionalLoanLiquidationSnapshot { + subEmail: string; + memberType: 'CREDIT' | 'COLLATERAL'; + walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; +} +⋮---- +export interface InstitutionalLoanLiquidationSnapshotData { + snapshots: InstitutionalLoanLiquidationSnapshot[]; + liabilities: InstitutionalLoanLiability[]; +} +⋮---- +export interface InstitutionalLoanForceLiquidationRecord { + groupId: number; + startLtv: number; + endLtv: number; + liquidationStartTime: number; + liquidationEndTime: number; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; +} +⋮---- +export interface GetInstitutionalLoanForceLiquidationParams { + groupId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface GetInstitutionalLoanForceLiquidationResponse { + total: number; + rows: InstitutionalLoanForceLiquidationRecord[]; +} +⋮---- +// Risk Unit Transfer interfaces +export interface InstitutionalLoanRiskUnitTransferParams { + subEmail?: string; // Optional: subEmail can be credit account or collateral account + asset: string; // Asset Name + amount: number; // Transfer amount of the asset +} +⋮---- +subEmail?: string; // Optional: subEmail can be credit account or collateral account +asset: string; // Asset Name +amount: number; // Transfer amount of the asset +⋮---- +// Additional institutional loan types for borrow, repay, and interest history +export interface GetInstitutionalLoanMaxBorrowableParams { + groupId?: number; + assetName: string; +} +⋮---- +export interface InstitutionalLoanMaxBorrowableResponse { + maxBorrowableAmount: numberInString | null; +} +⋮---- +export interface InstitutionalLoanBorrowParams { + groupId: number; + assetName: string; + amount: number; +} +⋮---- +export interface InstitutionalLoanBorrowResponse { + transactionId: string; + amount: number; + status: string; +} +⋮---- +export interface InstitutionalLoanRepayParams { + groupId: number; + assetName: string; + amount: number; +} +⋮---- +export interface InstitutionalLoanRepayResponse { + transactionId: string; + amount: number; +} +⋮---- +export interface GetInstitutionalLoanInterestHistoryParams { + groupId?: number; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface InstitutionalLoanInterestHistoryRecord { + groupId: number; + assetName: string; + principal: string; + interestRate: string; + interest: string; + interestTimestamp: number; +} +⋮---- +export interface InstitutionalLoanInterestHistoryResponse { + total: number; + rows: InstitutionalLoanInterestHistoryRecord[]; +} +⋮---- +export interface GetInstitutionalLoanBorrowRepayRecordsParams { + groupId?: number; // Optional: Risk unit unique identifier + type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY + asset?: string; // Optional: Asset name + startTime?: number; // Optional: Start time + endTime?: number; // Optional: End time + current?: number; // Optional: The currently querying page. Start from 1. Default:1 + size?: number; // Optional: Default:10 Max:100 + recvWindow?: number; // Optional: The value cannot be greater than 60000 + timestamp: number; // Required +} +⋮---- +groupId?: number; // Optional: Risk unit unique identifier +type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY +asset?: string; // Optional: Asset name +startTime?: number; // Optional: Start time +endTime?: number; // Optional: End time +current?: number; // Optional: The currently querying page. Start from 1. Default:1 +size?: number; // Optional: Default:10 Max:100 +recvWindow?: number; // Optional: The value cannot be greater than 60000 +timestamp: number; // Required +⋮---- +export interface InstitutionalLoanBorrowRepayRecord { + tranId: number; // Transaction ID + assetName: string; // Asset name + amount: number; // Amount + status: 'CONFIRM' | 'FAILED'; // Status + type: 'BORROW' | 'REPAY'; // Type + timestamp: number; // Create Time + principal?: number; // Only present for REPAY type + interest?: number; // Only present for REPAY type +} +⋮---- +tranId: number; // Transaction ID +assetName: string; // Asset name +amount: number; // Amount +status: 'CONFIRM' | 'FAILED'; // Status +type: 'BORROW' | 'REPAY'; // Type +timestamp: number; // Create Time +principal?: number; // Only present for REPAY type +interest?: number; // Only present for REPAY type +⋮---- +export interface GetInstitutionalLoanBorrowRepayRecordsResponse { + total: number; + rows: InstitutionalLoanBorrowRepayRecord[]; +} +⋮---- +export interface MarginInterestRebateBalanceResponse { + asset: string; + balance: string; + totalGranted: string; + totalConsumed: string; +} +⋮---- +export interface GetMarginInterestRebateBalanceRecordsParams { + type?: 0 | 1 | 2; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface MarginInterestRebateBalanceRecord { + type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; + rebateAsset: string; + delta: string; + createTime: number; + groupId?: number; + liabilityAsset?: string; + deductedInterest?: string; + exchangeRate?: string; +} +⋮---- +export interface MarginInterestRebateBalanceRecordsResponse { + total: number; + rows: MarginInterestRebateBalanceRecord[]; +} +⋮---- +// On-chain Yields types +⋮---- +export interface OnchainYieldsLockedProductListParams { + asset?: string; + current?: number; + size?: number; +} +⋮---- +export interface OnchainYieldsLockedProductDetail { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: 'PREHEATING' | 'PURCHASING'; + subscriptionStartTime: string; + canRedeemToFlex: boolean; +} +⋮---- +export interface OnchainYieldsLockedProductQuota { + totalPersonalQuota: string; + minimum: string; +} +⋮---- +export interface OnchainYieldsLockedProduct { + projectId: string; + detail: OnchainYieldsLockedProductDetail; + quota: OnchainYieldsLockedProductQuota; +} +⋮---- +export interface OnchainYieldsLockedProductListResponse { + rows: OnchainYieldsLockedProduct[]; + total: number; +} +⋮---- +export interface OnchainYieldsLockedPersonalLeftQuotaParams { + projectId: string; +} +⋮---- +export interface OnchainYieldsLockedPersonalLeftQuotaResponse { + leftPersonalQuota: string; +} +⋮---- +export interface OnchainYieldsLockedPositionParams { + asset?: string; + positionId?: number; + projectId?: string; + current?: number; + size?: number; +} +⋮---- +export interface OnchainYieldsLockedPosition { + positionId: string; + projectId: string; + asset: string; + amount: string; + purchaseTime: string; + duration: string; + accrualDays: string; + rewardAsset: string; + APY: string; + rewardAmt: string; + nextPay?: string; + nextPayDate?: string; + payPeriod?: string; + rewardsPayDate?: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; + redeemingAmt?: string; + redeemTo?: 'FLEXIBLE' | 'SPOT'; + canRedeemEarly: boolean; + autoSubscribe: boolean; + type: 'AUTO' | 'NORMAL'; + status: 'HOLDING' | 'REDEEMING' | 'RENEWING' | 'NEW_TRANSFERRING'; +} +⋮---- +export interface OnchainYieldsLockedPositionResponse { + rows: OnchainYieldsLockedPosition[]; + total: number; +} +⋮---- +export interface OnchainYieldsAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedInBTC: string; + totalLockedInUSDT: string; +} +⋮---- +// On-chain Yields Earn types +⋮---- +export interface OnchainYieldsLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; +} +⋮---- +export interface OnchainYieldsLockedSubscriptionPreviewResponse { + rewardAsset: string; + totalRewardAmt: string; + nextPay?: string; + nextPayDate?: string; + rewardsPayDate?: string; + valueDate: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; +} +⋮---- +export interface OnchainYieldsLockedSubscribeParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; + redeemTo?: 'SPOT' | 'FLEXIBLE'; + channelId?: string; + clientId?: string; +} +⋮---- +export interface OnchainYieldsLockedSubscribeResponse { + purchaseId: number; + positionId: string; + amount: string; + success: boolean; +} +⋮---- +export interface OnchainYieldsLockedSetAutoSubscribeParams { + positionId: string; + autoSubscribe: boolean; +} +⋮---- +export interface OnchainYieldsLockedSetAutoSubscribeResponse { + success: boolean; +} +⋮---- +export interface OnchainYieldsLockedSetRedeemOptionParams { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; +} +⋮---- +export interface OnchainYieldsLockedSetRedeemOptionResponse { + success: boolean; +} +⋮---- +export interface OnchainYieldsLockedRedeemParams { + positionId: number; + channelId?: string; +} +⋮---- +export interface OnchainYieldsLockedRedeemResponse { + redeemId: number; + success: boolean; +} +⋮---- +// On-chain Yields History types +⋮---- +export interface OnchainYieldsLockedSubscriptionRecordParams { + purchaseId?: string; + clientId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface OnchainYieldsLockedSubscriptionRecord { + positionId: string; + purchaseId: string; + projectId: string; + clientId: string; + time: number; + asset: string; + amount: string; + lockPeriod: string; + type: 'NORMAL' | 'AUTO'; + sourceAccount: 'SPOT' | 'FUNDING' | 'SPOTANDFUNDING'; + amtFromSpot?: string; + amtFromFunding?: string; + status: 'PURCHASING' | 'SUCCESS' | 'FAILED'; +} +⋮---- +export interface OnchainYieldsLockedSubscriptionRecordResponse { + rows: OnchainYieldsLockedSubscriptionRecord[]; + total: number; +} +⋮---- +export interface OnchainYieldsLockedRewardsHistoryParams { + positionId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface OnchainYieldsLockedRewardsRecord { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; +} +⋮---- +export interface OnchainYieldsLockedRewardsHistoryResponse { + rows: OnchainYieldsLockedRewardsRecord[]; + total: number; +} +⋮---- +export interface OnchainYieldsLockedRedemptionRecordParams { + positionId?: number; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface OnchainYieldsLockedRedemptionRecord { + positionId: string; + redeemId: number; + time: number; + asset: string; + lockPeriod: string; + amount: string; + originalAmount: string; + type: 'NORMAL' | 'EARLY' | 'CONVERT'; + deliverDate: string; + lossAmount: string; + isComplete: boolean; + rewardAsset: string; + rewardAmt: string; + status: 'CREATED' | 'PAID'; +} +⋮---- +export interface OnchainYieldsLockedRedemptionRecordResponse { + rows: OnchainYieldsLockedRedemptionRecord[]; + total: number; +} +⋮---- /** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. + * ALPHA TRADING INTERFACES */ - -const publicKey = `-----BEGIN PUBLIC KEY----- -MCexampleQTxwLU9o= ------END PUBLIC KEY----- -`; - -const privateKey = `-----BEGIN PRIVATE KEY----- -MC4CAQAexamplewqj5CzUuTy1 ------END PRIVATE KEY----- -`; - -// API Key returned by binance, generated using the publicKey (above) via Binance's website -const apiKey = 'TQpJexamplerobdG'; - -// Make an instance of the WS API Client -const wsClient = new WebsocketAPIClient({ - api_key: apiKey, - api_secret: privateKey, - beautify: true, - - // Enforce testnet ws connections, regardless of supplied wsKey - // testnet: true, -}); - -// Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! -// https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow -// wsClient.setTimeOffsetMs(-5000); - -// Optional, see above. Can be used to prepare a connection before sending commands -// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); - -// Make WebSocket API calls, very similar to a REST API: - -wsClient - .getFuturesAccountBalanceV2({ - timestamp: Date.now(), - recvWindow: 5000, - }) - .then((result) => { - console.log('getFuturesAccountBalanceV2 result: ', result); - }) - .catch((err) => { - console.error('getFuturesAccountBalanceV2 error: ', err); - }); - -wsClient - .submitNewFuturesOrder('usdm', { - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - timestamp: Date.now(), - // recvWindow: 5000, - }) - .then((result) => { - console.log('getFuturesAccountBalanceV2 result: ', result); - }) - .catch((err) => { - console.error('getFuturesAccountBalanceV2 error: ', err); - }); -``` - ---- - -## Market Maker Endpoints - -Binance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program. - -These endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 - -### Using Market Maker Endpoints - -To use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients): - -#### Market Maker REST API Clients - -```javascript -import { USDMClient, CoinMClient } from 'binance'; - -// USD-M Futures with MM endpoints -const usdmClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); - -// COIN-M Futures with MM endpoints -const coinmClient = new CoinMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); -``` - -#### Market Maker WebSocket Clients - -```javascript -import { WebsocketClient, WebsocketAPIClient } from 'binance'; - -// WebSocket consumer with MM endpoints -const wsClient = new WebsocketClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); - -// WebSocket API client with MM endpoints -const wsApiClient = new WebsocketAPIClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); -``` - -**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments. - -### Best practice - -Since market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints. - -```javascript -import { USDMClient } from 'binance'; - -// MM client for USD-M futures -const futuresMMClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMEndpoints: true, // Use MM endpoints for futures -}); - -// Regular client for USD-M futures -const futuresRegularClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMEndpoints: false, // Use regular endpoints for futures -}); -``` - -## Customise Logging - -Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. - -```javascript -import { WebsocketClient, DefaultLogger } from 'binance'; - -// or, if you prefer `require()`: -// const { WebsocketClient, DefaultLogger } = require('binance'); - -// Enable all logging on the trace level (disabled by default) -DefaultLogger.trace = (...params) => { - console.trace('trace: ', params); -}; - -// Pass the updated logger as the 2nd parameter -const ws = new WebsocketClient( - { - api_key: key, - api_secret: secret, - beautify: true, - }, - DefaultLogger -); - -// Or, create a completely custom logger with the 3 available functions -const customLogger = { - trace: (...params: LogParams): void => { - console.trace(new Date(), params); - }, - info: (...params: LogParams): void => { - console.info(new Date(), params); - }, - error: (...params: LogParams): void => { - console.error(new Date(), params); - }, +⋮---- +export interface AlphaToken { + alphaId: number; + symbol: string; + name: string; + chainId: string; + contractAddress: string; + decimals?: number; +} +⋮---- +export interface AlphaExchangeFilter { + filterType: string; + minPrice?: string; + maxPrice?: string; + tickSize?: string; + stepSize?: string; + maxQty?: string; + minQty?: string; + limit?: number; + minNotional?: string; + maxNotional?: string; + multiplierDown?: string; + multiplierUp?: string; + bidMultiplierUp?: string; + askMultiplierUp?: string; + bidMultiplierDown?: string; + askMultiplierDown?: string; +} +⋮---- +export interface AlphaSymbol { + symbol: string; + status: string; + baseAsset: string; + quoteAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + filters: AlphaExchangeFilter[]; + orderTypes: string[]; +} +⋮---- +export interface AlphaAsset { + asset: string; +} +⋮---- +export interface AlphaExchangeInfo { + timezone: string; + assets: AlphaAsset[]; + symbols: AlphaSymbol[]; +} +⋮---- +export interface AlphaAggTradesParams { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface AlphaAggTrade { + a: number; // aggregate trade ID + p: string; // price + q: string; // quantity + f: number; // first trade ID + l: number; // last trade ID + T: number; // timestamp + m: boolean; // is buyer market maker +} +⋮---- +a: number; // aggregate trade ID +p: string; // price +q: string; // quantity +f: number; // first trade ID +l: number; // last trade ID +T: number; // timestamp +m: boolean; // is buyer market maker +⋮---- +export interface AlphaKlinesParams { + symbol: string; + interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M +⋮---- +export type AlphaKline = [ + string, // Open time + string, // Open price + string, // High price + string, // Low price + string, // Close price + string, // Volume + string, // Close time + string, // Quote asset volume + string, // Number of trades + string, // Taker buy base asset volume + string, // Taker buy quote asset volume + string, // Ignore (always "0") +]; +⋮---- +string, // Open time +string, // Open price +string, // High price +string, // Low price +string, // Close price +string, // Volume +string, // Close time +string, // Quote asset volume +string, // Number of trades +string, // Taker buy base asset volume +string, // Taker buy quote asset volume +string, // Ignore (always "0") +⋮---- +export interface AlphaTickerParams { + symbol: string; +} +⋮---- +export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; +⋮---- +export interface AlphaFullDepthParams { + symbol: string; + limit?: AlphaFullDepthLimit; +} +⋮---- +export interface AlphaFullDepthData { + lastUpdateId: number; + symbol: string; + bids: [string, string][]; + asks: [string, string][]; + E: number; + T: number; +} +⋮---- +export interface AlphaFullDepthResponse { + code: string; + message: string | null; + messageDetail: string | null; + success: boolean; + data: AlphaFullDepthData; +} +⋮---- +export interface AlphaTicker { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + lastPrice: string; + lastQty: string; + openPrice: string; + highPrice: string; + lowPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} +⋮---- +/** + * Soft Staking interfaces + */ +export interface GetSoftStakingProductListParams { + asset?: string; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface SoftStakingProduct { + asset: string; + minAmount: string; + maxCap: string; + apr: string; + stakedAmount: string; + totalProfit: string; +} +⋮---- +export interface GetSoftStakingProductListResponse { + status: boolean; + totalRewardsUsdt: string; + rows: SoftStakingProduct[]; + total: number; +} +⋮---- +export interface SetSoftStakingParams { + softStaking: boolean; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface SetSoftStakingResponse { + success: boolean; +} +⋮---- +export interface GetSoftStakingRewardsHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface SoftStakingRewardsRecord { + asset: string; + rewards: string; + rewardAsset: string; + avgAmount: string; + time: number; +} +⋮---- +export interface GetSoftStakingRewardsHistoryResponse { + rows: SoftStakingRewardsRecord[]; + total: number; } -// Pass the custom logger as the 2nd parameter -const ws = new WebsocketClient( - { - api_key: key, - api_secret: secret, - beautify: true, - }, - customLogger -); -``` - -## Browser/Frontend Usage - -### Import - -This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. - -1. Install these dependencies - ```sh - npm install crypto-browserify stream-browserify - ``` -2. Add this to your `tsconfig.json` - ```json - { - "compilerOptions": { - "paths": { - "crypto": [ - "./node_modules/crypto-browserify" - ], - "stream": [ - "./node_modules/stream-browserify" - ] - } - ``` -3. Declare this in the global context of your application (ex: in polyfills for angular) - ```js - (window as any).global = window; - ``` - -### Webpack - -This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. - -Build a bundle using webpack: - -- `npm install` -- `npm build` -- `npm pack` - -The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. - -## Use with LLMs & AI - -This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. - -This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. - ---- - - - -### Contributions & Thanks - -Have my projects helped you? Share the love, there are many ways you can show your thanks: - -- Star & share my projects. -- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler -- Have an interesting project? Get in touch & invite me to it. -- Or buy me all the coffee: - - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` -- Sign up with my referral links: - - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 - - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ - - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY - - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 - - - - -### Contributions & Pull Requests - -Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. - -## Used By - -[![Repository Users Preview Image](https://dependents.info/sieblyio/binance/image)](https://github.com/sieblyio/binance/network/dependents) - - - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) - - +================ +File: src/main-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; +⋮---- +import { + AmendKeepPriorityParams, + BasicAssetPaginatedParams, + BasicAssetParam, + BasicSymbolParam, + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + CoinStartEndLimit, + ExchangeSymbol, + GetAllOrdersParams, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, + NewOCOParams, + NewOrderListParams, + OrderBookParams, + OrderIdProperty, + OrderResponseType, + OrderType, + RecentTradesParams, + RowsWithTotal, + SymbolFromPaginatedRequestFromId, + SymbolPrice, +} from './types/shared'; +import { + AcceptQuoteRequestParams, + AccountInfo, + AccountInformation, + ActiveInstitutionalLoanRiskUnit, + AddBSwapLiquidityParams, + AddInstitutionalLoanCollateralAccountParams, + AddIpRestriction, + AdjustCryptoLoanLTVParams, + AdjustCryptoLoanLTVResponse, + AdjustFlexibleCryptoLoanLTVParams, + AdjustFlexibleCryptoLoanLTVResponse, + AggregateTrade, + AlgoOrder, + AllCoinsInformationResponse, + Allocation, + AllocationsParams, + AlphaAggTrade, + AlphaAggTradesParams, + AlphaExchangeInfo, + AlphaFullDepthParams, + AlphaFullDepthResponse, + AlphaKline, + AlphaKlinesParams, + AlphaTicker, + AlphaToken, + ApiKeyBrokerSubAccount, + APIPermissions, + APITradingStatus, + ApplicationStatus, + AssetDetail, + BasicFromPaginatedParams, + BasicFuturesSubAccountParams, + BasicMarginAssetParams, + BasicSubAccount, + BasicTimeRangeParam, + BethRewardsHistory, + BfusdAccountResponse, + BfusdQuotaResponse, + BfusdRateHistoryRow, + BfusdRedeemParams, + BfusdRedeemResponse, + BfusdRedemptionHistoryRow, + BfusdRewardsHistoryRow, + BfusdSubscribeParams, + BfusdSubscribeResponse, + BfusdSubscriptionHistoryRow, + BlockTrade, + BlvtRedemptionRecord, + BlvtSubscriptionRecord, + BlvtUserLimitInfo, + BNBBurnResponse, + BnbTransferParams, + BnsolRateHistoryRecord, + BnsolRewardHistoryRecord, + BorrowCryptoLoanParams, + BorrowCryptoLoanResponse, + BorrowFlexibleLoanParams, + BorrowFlexibleLoanResponse, + BorrowInterestRate, + BrokerCommissionRebate, + BrokerSubAccount, + BrokerSubAccountCoinFuturesCommission, + BrokerSubAccountFuturesCommission, + BrokerSubAccountHistory, + BrokerUniversalTransfer, + BSwapLiquidity, + BSwapOperations, + BSwapOperationsParams, + BUSDConversionRecord, + CancelAlgoOrderResponse, + CancelHashrateResaleConfigParams, + CancelOrderListResult, + CancelSpotAlgoOrderResponse, + CancelSpotOrderResult, + ChangeAutoCompoundStatusParams, + ChangeAutoCompoundStatusResponse, + ChangePermissionApiKeyBrokerSubAccountParams, + ChangePermissionApiKeyBrokerSubAccountResponse, + ChangePlanStatusParams, + ChangePlanStatusResponse, + ChangeSubAccountCoinFuturesCommissionParams, + ChangeSubAccountCommissionParams, + ChangeSubAccountCommissionResponse, + ChangeSubAccountFuturesCommissionParams, + ChangeSubAccountFuturesCommissionResponse, + CheckCollateralRepayRateParams, + CheckCollateralRepayRateResponse, + CheckDualInvestmentAccountsResponse, + CheckVipCollateralAccountParams, + CloseInstitutionalLoanRiskUnitResponse, + CloudMining, + CloudMiningHistoryParams, + CoinMarginedFuturesResponse, + Collateral, + CollateralAssetData, + CollateralRecord, + CommissionRates, + ConvertDustParams, + ConvertibleCoinsParams, + ConvertibleCoinsResponse, + ConvertLimitOpenOrder, + ConvertQuoteRequestParams, + ConvertTransfer, + ConvertTransferResponse, + CreateApiKeyBrokerSubAccountParams, + CreateApiKeyBrokerSubAccountResponse, + CreateBrokerSubAccountParams, + CreateDualTokenGiftCardParams, + CreateGiftCardParams, + CreateInvestmentPlanParams, + CreateInvestmentPlanResponse, + CreateSpecialLowLatencyKeyParams, + CreateSubAccountApiKeyParams, + CreateSubAccountApiKeyResponse, + CreateSubAccountParams, + CrossMarginFeeData, + CrossMarginTransferHistory, + CurrentAvgPrice, + CustomizeMarginCall, + CustomizeMarginCallParams, + DailyAccountSnapshot, + DailyAccountSnapshotParams, + DelegationHistory, + DelegationHistoryParams, + DeleteApiKeyBrokerSubAccountParams, + DeleteSubAccountApiKeyParams, + DeleteSubAccountApiKeyResponse, + DelistScheduleResponse, + DepositAddress, + DepositAddressListParams, + DepositAddressParams, + DepositAddressResponse, + DepositHistory, + DepositHistoryParams, + DualInvestmentPosition, + DualInvestmentProduct, + DustConversion, + DustConvertibleAssetsParams, + DustConvertibleAssetsResponse, + DustConvertParams, + DustInfo, + DustLog, + EditInvestmentPlanParams, + EditInvestmentPlanResponse, + EnableConvertSubAccountParams, + EnableFuturesBrokerSubAccountParams, + EnableFuturesBrokerSubAccountResponse, + EnableMarginApiKeyBrokerSubAccountParams, + EnableMarginBrokerSubAccountParams, + EnableMarginBrokerSubAccountResponse, + EnableOptionsForSubAccountResponse, + EnableOrDisableIPRestrictionForSubAccountParams, + EnableUniversalTransferApiKeyBrokerSubAccountParams, + EnableUniversalTransferApiKeyBrokerSubAccountResponse, + ETHRateHistory, + EthRedemptionHistory, + EthStakingHistory, + ExchangeInfo, + ExchangeInfoParams, + FiatDepositParams, + FiatDepositResponse, + FixedAndActivityProjectParams, + FixedAndActivityProjectPositionParams, + FlexibleCryptoLoanBorrowHistory, + FlexibleLoanAssetData, + FlexibleLoanCollateralAssetData, + FlexibleLoanLiquidationHistoryRecord, + FlexibleLoanLTVAdjustmentHistory, + FlexibleLoanOngoingOrder, + FlexibleRedemptionRecord, + FlexibleRewardsHistory, + FlexibleSubscriptionPreview, + ForceLiquidationRecord, + FundingAsset, + FutureAccountTransfer, + FuturesPositionRisk, + GetAlgoHistoricalOrdersParams, + GetAlgoSubOrdersParams, + GetAlgoSubOrdersResponse, + GetAllConvertPairsParams, + GetApiKeyBrokerSubAccountParams, + GetApplicationStatusParams, + GetAssetParams, + GetBethRewardsHistoryParams, + GetBfusdRateHistoryParams, + GetBfusdRedemptionHistoryParams, + GetBfusdRewardsHistoryParams, + GetBfusdSubscriptionHistoryParams, + GetBlvtRedemptionRecordParams, + GetBlvtSubscriptionRecordParams, + GetBnsolRateHistoryReq, + GetBnsolRewardsHistoryReq, + GetBrokerInfoResponse, + GetBrokerSubAccountDepositHistoryParams, + GetBrokerSubAccountHistoryParams, + GetBrokerSubAccountParams, + GetC2CTradeHistoryParams, + GetC2CTradeHistoryResponse, + GetClosedInstitutionalLoanRiskUnitsParams, + GetClosedInstitutionalLoanRiskUnitsResponse, + GetCollateralAssetDataParams, + GetCollateralRecordParams, + GetConvertBUSDHistoryParams, + GetConvertTradeHistoryParams, + GetCrossMarginTransferHistoryParams, + GetCryptoLoansIncomeHistoryParams, + GetCryptoLoansIncomeHistoryResponse, + GetDualInvestmentPositionsParams, + GetDualInvestmentProductListParams, + GetEarningsListParams, + GetEarningsListResponse, + GetETHRateHistoryParams, + GetEthRedemptionHistoryParams, + GetEthStakingAccountResponse, + GetEthStakingAccountV2Response, + GetEthStakingHistoryParams, + GetEthStakingQuotaResponse, + GetExtraBonusListParams, + GetExtraBonusListResponse, + GetFiatOrderDetailParams, + GetFiatOrderDetailResponse, + GetFiatOrderHistoryParams, + GetFiatOrderHistoryResponse, + GetFiatPaymentsHistoryResponse, + GetFlexibleCryptoLoanBorrowHistoryParams, + GetFlexibleLoanLiquidationHistoryParams, + GetFlexibleLoanLTVAdjustmentHistoryParams, + GetFlexibleLoanOngoingOrdersParams, + GetFlexibleRedemptionRecordParams, + GetFlexibleRewardsHistoryParams, + GetFlexibleSubscriptionPreviewParams, + GetFlexibleSubscriptionRecordParams, + GetFlexibleSubscriptionRecordResponse, + GetForceLiquidationRecordParams, + GetFutureAccountTransferHistoryParams, + GetFuturesLeadTraderStatusResponse, + GetFuturesLeadTradingSymbolWhitelistResponse, + GetFutureTickLevelOrderbookDataLinkParams, + GetHashrateResaleDetailParams, + GetHashrateResaleDetailResponse, + GetHashrateResaleListParams, + GetHashrateResaleListResponse, + GetIndexDetailsResponse, + GetIndexLinkedPlanPositionDetailsResponse, + GetIndexLinkedPlanRebalanceHistoryParams, + GetIndexLinkedPlanRedemptionHistoryParams, + GetInstitutionalLoanBorrowRepayRecordsParams, + GetInstitutionalLoanBorrowRepayRecordsResponse, + GetInstitutionalLoanForceLiquidationParams, + GetInstitutionalLoanForceLiquidationResponse, + GetInstitutionalLoanInterestHistoryParams, + GetInstitutionalLoanMaxBorrowableParams, + GetInstitutionalLoanRiskUnitDetailsParams, + GetLoanableAssetsDataParams, + GetLoanBorrowHistoryParams, + GetLoanCoinPaginatedHistoryParams, + GetLoanLTVAdjustmentHistoryParams, + GetLoanOngoingOrdersParams, + GetLoanRepaymentHistoryParams, + GetLockedRedemptionRecordParams, + GetLockedRewardsHistory, + GetLockedRewardsHistoryParams, + GetLockedSubscriptionPreviewParams, + GetLockedSubscriptionRecordParams, + GetMarginAccountBorrowRepayRecordsParams, + GetMarginCapitalFlowParams, + GetMarginInterestHistoryParams, + GetMarginInterestRebateBalanceRecordsParams, + GetMarginLiquidationLoanRepayHistoryParams, + GetMarginOrderCountUsageParams, + GetMinerDetailsParams, + GetMinerDetailsResponse, + GetMinerListParams, + GetMinerListResponse, + GetMiningAccountEarningParams, + GetMiningAccountEarningResponse, + getMiningAccountsListParams, + getMiningAccountsListResponse, + GetMiningAlgoListResponse, + GetMiningCoinListResponse, + GetNextHourlyInterestRateParams, + GetNftAssetParams, + GetNftDepositHistoryParams, + GetNftTransactionHistoryParams, + GetNftWithdrawHistoryParams, + GetOCOParams, + GetOneTimeTransactionStatusParams, + GetOneTimeTransactionStatusResponse, + GetOrderStatusParams, + GetPayTradeHistoryParams, + GetPlanDetailsParams, + GetPortfolioMarginAssetIndexPriceResponse, + GetPortfolioMarginAssetLeverageResponse, + GetPortfolioMarginProAccountInfoResponse, + GetPortfolioMarginProBankruptcyLoanAmountResponse, + GetPortfolioMarginProCollateralRateResponse, + GetPortfolioMarginProInterestHistoryParams, + GetPortfolioMarginProInterestHistoryResponse, + GetRateHistory, + GetRateHistoryParams, + GetRwusdRateHistoryParams, + GetRwusdRedemptionHistoryParams, + GetRwusdRewardsHistoryParams, + GetRwusdSubscriptionHistoryParams, + GetSmallLiabilityExchangeHistoryParams, + GetSoftStakingProductListParams, + GetSoftStakingProductListResponse, + GetSoftStakingRewardsHistoryParams, + GetSoftStakingRewardsHistoryResponse, + GetSolStakingHistoryReq, + GetSourceAssetListParams, + GetSourceAssetListResponse, + GetSpotAlgoHistoricalOrdersParams, + GetSpotAlgoSubOrdersParams, + GetSpotAlgoSubOrdersResponse, + GetSpotRebateHistoryRecordsParams, + GetSpotRebateHistoryRecordsResponse, + GetStatisticListParams, + GetStatisticListResponse, + GetSubAccountApiKeysParams, + GetSubAccountDepositHistoryParams, + GetSubscriptionTransactionHistoryParams, + GetTargetAssetListParams, + GetTargetAssetListResponse, + GetTargetAssetROIParams, + GetTravelRuleDepositHistoryParams, + GetTravelRuleRegionListParams, + GetTravelRuleWithdrawHistoryParams, + GetTravelRuleWithdrawHistoryV2Params, + GetUniversalTransferBrokerParams, + GetVipLoanFixedRateMarketParams, + GetVipLoanOngoingOrdersParams, + GetVipLoanRepaymentHistoryParams, + GetWbethRewardsHistoryResponse, + GetWrapHistoryParams, + HistoricalAlgoOrder, + HistoricalBlockTradesParams, + HistoricalDataLink, + HistoricalSpotAlgoOrder, + IndexLinkedPlanRedemptionRecord, + InstitutionalLoanBorrowParams, + InstitutionalLoanBorrowResponse, + InstitutionalLoanInterestHistoryResponse, + InstitutionalLoanMaxBorrowableResponse, + InstitutionalLoanRepayParams, + InstitutionalLoanRepayResponse, + InstitutionalLoanRiskUnitDetails, + InstitutionalLoanRiskUnitTransferParams, + IsolatedMarginAccountInfo, + IsolatedMarginAccountTransferParams, + IsolatedMarginFeeData, + IsolatedMarginSymbol, + IsolatedMarginTierData, + LeftDailyPurchaseQuotaFlexibleProductResponse, + LiabilityCoinLeverageBracket, + LoanableAssetData, + LoanBorrowHistory, + LoanLTVAdjustmentHistory, + LoanOngoingOrder, + LoanRepaymentHistory, + LockedRedemptionRecord, + LockedSubscriptionPreview, + LockedSubscriptionRecord, + ManagedSubAccountDepositAddress, + ManagedSubAccountDepositAddressParams, + ManagedSubAccountFuturesAssetsResponse, + ManagedSubAccountListParams, + ManagedSubAccountMarginAssetsResponse, + ManagedSubAccountSnapshot, + ManagedSubAccountSnapshotParams, + ManagedSubAccountTransferLogParams, + ManagedSubAccountTransferTTLogParams, + ManagerSubTransferHistoryVos, + ManagerSubUserInfoVo, + ManualLiquidationParams, + ManualLiquidationResponse, + MarginAccountLoanParams, + MarginAccountRecord, + MarginAvailableInventoryResponse, + MarginCapitalFlow, + MarginDelistSchedule, + MarginInterestHistory, + MarginInterestRateHistory, + MarginInterestRebateBalanceRecordsResponse, + MarginInterestRebateBalanceResponse, + MarginLiquidationLoan, + MarginLiquidationLoanRepayHistoryResponse, + MarginLiquidationLoanRepayResponse, + MarginOpenOTOOrderList, + MarginOrderCountUsageResponse, + MarginOTOCOOrder, + MarginOTOOrder, + MarginTransactionResponse, + ModifySubAccountApiKeyPermissionParams, + ModifySubAccountApiKeyPermissionResponse, + NewFutureAccountTransferParams, + NewOrderListOPOCOParams, + NewOrderListOPOCOResponse, + NewOrderListOPOParams, + NewOrderListOPOResponse, + NewOrderListOTOCOParams, + NewOrderListOTOCOResponse, + NewOrderListOTOParams, + NewOrderListOTOResponse, + NewSpotOrderParams, + NewSpotSOROrderParams, + NextHourlyInterestRate, + NftAsset, + NftDeposit, + NftTransaction, + NftWithdraw, + OnchainYieldsAccountResponse, + OnchainYieldsLockedPersonalLeftQuotaParams, + OnchainYieldsLockedPersonalLeftQuotaResponse, + OnchainYieldsLockedPositionParams, + OnchainYieldsLockedPositionResponse, + OnchainYieldsLockedProductListParams, + OnchainYieldsLockedProductListResponse, + OnchainYieldsLockedRedeemParams, + OnchainYieldsLockedRedeemResponse, + OnchainYieldsLockedRedemptionRecordParams, + OnchainYieldsLockedRedemptionRecordResponse, + OnchainYieldsLockedRewardsHistoryParams, + OnchainYieldsLockedRewardsHistoryResponse, + OnchainYieldsLockedSetAutoSubscribeParams, + OnchainYieldsLockedSetAutoSubscribeResponse, + OnchainYieldsLockedSetRedeemOptionParams, + OnchainYieldsLockedSetRedeemOptionResponse, + OnchainYieldsLockedSubscribeParams, + OnchainYieldsLockedSubscribeResponse, + OnchainYieldsLockedSubscriptionPreviewParams, + OnchainYieldsLockedSubscriptionPreviewResponse, + OnchainYieldsLockedSubscriptionRecordParams, + OnchainYieldsLockedSubscriptionRecordResponse, + OrderBookResponse, + OrderList, + OrderListResponse, + OrderRateLimitUsage, + OrderResponseTypeFor, + PMProBankruptcyLoanRepaymentHistory, + PMProMintBFUSDParams, + PMProMintBFUSDResponse, + PMProRedeemBFUSDResponse, + PortfolioDeltaModeStatus, + PortfolioMarginMarginCallLevelDeleteResponse, + PortfolioMarginMarginCallLevelGetResponse, + PortfolioMarginMarginCallLevelResponse, + PortfolioMarginProAccountBalance, + PortfolioMarginProSpanAccountInfo, + PreventedMatch, + PreventedMatchesParams, + PurchaseFlexibleProductResponse, + PurchaseRecordParams, + QueryBrokerFuturesCommissionRebateParams, + QueryBrokerSpotCommissionRebateParams, + QueryCrossMarginAccountDetailsParams, + QueryCrossMarginFeeDataParams, + QueryCrossMarginPairResponse, + QueryIsolatedMarginTierDataParams, + QueryMarginAccountAllOCOParams, + QueryMarginAccountTradeListParams, + QueryMarginAssetResponse, + QueryMarginInterestRateHistoryParams, + QueryMarginOpenOTOOrderListsParams, + QueryMarginPriceIndexResponse, + QueryMarginRecordParams, + QueryMaxBorrowResponse, + QueryMaxTransferOutAmountResponse, + QuerySubAccountCoinFuturesCommissionParams, + QuerySubAccountFuturesAssetInfoParams, + QuerySubAccountFuturesCommissionParams, + QuerySubAccountSpotMarginAssetInfoParams, + RawAccountTrade, + RawTrade, + RedeemBlvtParams, + RedeemBlvtResponse, + RedeemEthParams, + RedeemEthResponse, + RedeemGiftCardParams, + RedeemSolResponse, + RemoveBSwapLiquidityParams, + RepayCryptoFlexibleLoanParams, + RepayCryptoFlexibleLoanResponse, + RepayCryptoLoanFlexibleWithCollateralParams, + RepayCryptoLoanFlexibleWithCollateralResponse, + RepayCryptoLoanParams, + RepayCryptoLoanResponse, + RepayMarginLiquidationLoanParams, + ReplaceSpotOrderParams, + ReplaceSpotOrderResultSuccess, + RollingWindowTickerParams, + RwusdAccountResponse, + RwusdQuotaResponse, + RwusdRateHistoryRow, + RwusdRedeemParams, + RwusdRedeemResponse, + RwusdRedemptionHistoryRow, + RwusdRewardsHistoryRow, + RwusdSubscribeParams, + RwusdSubscribeResponse, + RwusdSubscriptionHistoryRow, + SetAutoSubscribeParams, + SetPortfolioMarginMarginCallLevelParams, + SetSoftStakingParams, + SetSoftStakingResponse, + SimpleEarnAccountResponse, + SimpleEarnFlexibleProduct, + SimpleEarnFlexibleProductPositionParams, + SimpleEarnLockedProduct, + SimpleEarnLockedProductPosition, + SimpleEarnLockedProductPositionParams, + SimpleEarnProductListParams, + SimpleEarnRedeemFlexibleProductParams, + SimpleEarnRedeemResponse, + SimpleEarnSubscribeFlexibleProductResponse, + SimpleEarnSubscribeLockedProductResponse, + SimpleEarnSubscribeProductParams, + SmallLiabilityExchangeCoin, + SmallLiabilityExchangeHistory, + SolBoostRewardsHistoryRecord, + SolBoostRewardsHistoryReq, + SolRedemptionHistoryRecord, + SolStakingAccount, + SolStakingHistoryRecord, + SolStakingQuota, + SOROrderResponseFull, + SORTestOrderResponse, + SpecialLowLatencyKeyInfo, + SpecialLowLatencyKeyResponse, + SpotAlgoOrder, + SpotAmendKeepPriorityResult, + SpotAssetTag, + SpotAssetTagsParams, + SpotExecutionRulesParams, + SpotExecutionRulesResponse, + SpotOrder, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, + StakingBasicParams, + StakingHistory, + StakingHistoryParams, + StakingPersonalLeftQuota, + StakingProduct, + StakingProductPosition, + StakingProductType, + SubAccountAddOrDeleteIPList, + SubAccountApiKey, + SubAccountAssetDetails, + SubAccountAssets, + SubAccountAssetsParams, + SubaccountBalances, + SubAccountBrokerMarginAsset, + SubaccountBrokerSpotAsset, + SubAccountCOINMDetail, + SubAccountCOINMPositionRisk, + SubAccountCOINMSummary, + SubAccountDeposit, + SubAccountDepositAddress, + SubAccountDepositAddressParams, + SubAccountDepositHistoryList, + SubAccountDepositHistoryParams, + SubAccountEnableFutures, + SubAccountEnableLeverageToken, + SubAccountEnableMargin, + SubAccountEnableOrDisableIPRestriction, + SubAccountFuturesAccountDetail, + SubAccountFuturesAccountSummary, + SubAccountFuturesAssetTransfer, + SubAccountFuturesAssetTransferHistory, + SubAccountFuturesAssetTransferHistoryParams, + SubAccountFuturesAssetTransferParams, + SubAccountListParams, + SubAccountListResponse, + SubAccountMarginAccountDetail, + SubAccountMovePosition, + SubAccountMovePositionHistory, + SubAccountMovePositionHistoryParams, + SubAccountMovePositionParams, + SubAccountsMarginAccountSummary, + SubAccountSpotAssetsSummary, + SubAccountSpotAssetsSummaryParams, + SubAccountSpotAssetTransferHistory, + SubAccountSpotAssetTransferHistoryParams, + SubAccountStatus, + SubAccountSummaryOnFuturesAccountV2Params, + SubAccountTransactionStatistics, + SubAccountTransfer, + SubAccountTransferHistory, + SubAccountTransferHistoryParams, + SubAccountTransferParams, + SubAccountTransferToMasterParams, + SubAccountTransferToSameMasterParams, + SubAccountUniversalTransfer, + SubAccountUniversalTransferHistoryParams, + SubAccountUniversalTransferHistoryResponse, + SubAccountUniversalTransferParams, + SubAccountUSDMDetail, + SubAccountUSDMPositionRisk, + SubAccountUSDMSummary, + SubmitConvertLimitOrderParams, + SubmitDepositCreditParams, + SubmitDepositCreditResponse, + SubmitHashrateResaleParams, + SubmitIndexLinkedPlanRedemptionParams, + SubmitMarginOTOCOOrderParams, + SubmitMarginOTOOrderParams, + SubmitOneTimeTransactionParams, + SubmitOneTimeTransactionResponse, + SubmitSpotTwapNewOrderParams, + SubmitSpotTwapNewOrderResponse, + SubmitTravelRuleDepositQuestionnaireParams, + SubmitTravelRuleDepositQuestionnaireResponse, + SubmitTwapNewOrderParams, + SubmitTwapNewOrderResponse, + SubmitVpNewOrderParams, + SubmitVpNewOrderResponse, + SubscribeBlvtParams, + SubscribeBlvtResponse, + SubscribeDualInvestmentProductParams, + SubscribeDualInvestmentProductResponse, + SubscribeEthStakingV2Response, + SubscribeSolStakingResponse, + SwitchPortfolioDeltaModeParams, + SymbolOrderBookTicker, + SymbolTradeFee, + SystemStatusResponse, + TargetAssetROI, + Ticker24hrResponse, + ToggleBNBBurnParams, + TradingDayTickerArray, + TradingDayTickerFull, + TradingDayTickerMini, + TradingDayTickerParams, + TradingDayTickerSingle, + TransferBrokerSubAccount, + TransferBrokerSubAccountParams, + TravelRuleCountryListResponse, + TravelRuleDepositHistoryRecord, + TravelRuleRegionListResponse, + TravelRuleWithdrawHistoryRecord, + UniversalTransferBrokerParams, + UniversalTransferHistoryParams, + UniversalTransferParams, + UpdateIpRestrictionForSubApiKey, + UsdtMarginedFuturesResponse, + UserAsset, + VASPInfo, + VipCollateralAccount, + VipLoanAccruedInterestParams, + VipLoanAccruedInterestRecord, + VipLoanBorrowParams, + VipLoanBorrowResponse, + VipLoanFixedRateBorrowParams, + VipLoanFixedRateBorrowResponse, + VipLoanFixedRateMarketRecord, + VipLoanInterestRateHistoryParams, + VipLoanInterestRateRecord, + VipLoanRenewParams, + VipLoanRenewResponse, + VipLoanRepaymentHistory, + VipLoanRepayParams, + VipLoanRepayResponse, + VipOngoingOrder, + VirtualSubAccount, + WalletBalance, + WithdrawAddress, + WithdrawAssetsFromManagedSubAccountParams, + WithdrawFiatParams, + WithdrawHistory, + WithdrawHistoryParams, + WithdrawParams, + WithdrawTravelRuleParams, + WrapBethResponse, + WrapHistory, +} from './types/spot'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, + serialiseParams, +} from './util/requestUtils'; +⋮---- +export class MainClient extends BaseRestClient +⋮---- +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, + ) +⋮---- +/** + * This method is used to get the latency and time sync between the client and the server. + * This is not official API endpoint and is only used for internal testing purposes. + * Use this method to check the latency and time sync between the client and the server. + * Final values might vary slightly, but it should be within few ms difference. + * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. + */ +async fetchLatencySummary(): Promise +⋮---- +// Adjust server time by adding estimated one-way latency +⋮---- +// Calculate time difference between adjusted server time and local time +⋮---- +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - General endpoints + * + **/ +⋮---- +testConnectivity(): Promise +⋮---- +getExchangeInfo(params?: ExchangeInfoParams): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - Market endpoints + * + **/ +⋮---- +getOrderBook(params: OrderBookParams): Promise +⋮---- +getRecentTrades(params: RecentTradesParams): Promise +⋮---- +getHistoricalTrades(params: HistoricalTradesParams): Promise +⋮---- +getHistoricalBlockTrades( + params: HistoricalBlockTradesParams, + ): Promise +⋮---- +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, + ): Promise +⋮---- +getKlines(params: KlinesParams): Promise +⋮---- +getUIKlines(params: KlinesParams): Promise +⋮---- +getAvgPrice(params: { symbol: string }): Promise +⋮---- +getExecutionRules( + params?: SpotExecutionRulesParams, + ): Promise +⋮---- +getReferencePrice(params: { + symbol: string; + }): Promise +⋮---- +getReferencePriceCalculation(params: { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK' | 'CANCEL_ONLY'; + }): Promise +⋮---- +get24hrChangeStatistics(params?: { + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; +⋮---- +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL +⋮---- +get24hrChangeStatistics(params: { + symbol: string; // use for single symbol + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; +⋮---- +symbol: string; // use for single symbol +type?: 'FULL' | 'MINI'; // default is FULL +⋮---- +get24hrChangeStatistics(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise +⋮---- +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL +⋮---- +getTradingDayTicker( + params: TradingDayTickerParams, + ): Promise +⋮---- +getSymbolPriceTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; + }): Promise +⋮---- +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +⋮---- +getSymbolOrderBookTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; + }): Promise +⋮---- +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +⋮---- +getRollingWindowTicker( + params: RollingWindowTickerParams, + ): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - Trading endpoints + * + **/ +⋮---- +submitNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >(params: NewSpotOrderParams): Promise> +⋮---- +testNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >(params: NewSpotOrderParams): Promise +⋮---- +getOrder(params: GetOrderParams): Promise +⋮---- +cancelOrder(params: CancelOrderParams): Promise +⋮---- +cancelAllSymbolOrders(params: { + symbol: string; + }): Promise +⋮---- +replaceOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >( + params: ReplaceSpotOrderParams, + ): Promise> +⋮---- +/** + * Reduce the quantity of an existing open order while keeping its priority in the order book. + * The new quantity must be less than the current quantity. + * https://binance-docs.github.io/apidocs/futures/en/#order-amend-keep-priority-trade + */ +amendOrderKeepPriority( + params: AmendKeepPriorityParams, + ): Promise +⋮---- +getOpenOrders(params?: { symbol?: string }): Promise +⋮---- +getAllOrders(params: GetAllOrdersParams): Promise +⋮---- +/** + * @deprecated + */ +submitNewOCO(params: NewOCOParams): Promise +⋮---- +submitNewOrderList( + params: NewOrderListParams, + ): Promise> +⋮---- +submitNewOrderListOTO( + params: NewOrderListOTOParams, + ): Promise +⋮---- +submitNewOrderListOTOCO( + params: NewOrderListOTOCOParams, + ): Promise +⋮---- +submitNewOrderListOPO( + params: NewOrderListOPOParams, + ): Promise +⋮---- +submitNewOrderListOPOCO( + params: NewOrderListOPOCOParams, + ): Promise +⋮---- +cancelOCO(params: CancelOCOParams): Promise +⋮---- +getOCO(params?: GetOCOParams): Promise +⋮---- +getAllOCO(params?: BasicFromPaginatedParams): Promise +⋮---- +/** + * Query open OCO + */ +getAllOpenOCO(): Promise +⋮---- +/** + * Places an order using smart order routing (SOR). + */ +submitNewSOROrder( + params: NewSpotSOROrderParams, + ): Promise +⋮---- +/** + * Test new order creation and signature/recvWindow using smart order routing (SOR). + * Creates and validates a new order but does not send it into the matching engine. + */ +testNewSOROrder( + params: NewSpotSOROrderParams & { computeCommissionRates?: boolean }, + ): Promise +⋮---- +/** + * + * SPOT TRADING Endpoints - Account endpoints + * + **/ +⋮---- +/** + * Get current account information + */ +getAccountInformation(params?: { + omitZeroBalances?: boolean; + }): Promise +⋮---- +getAccountTradeList( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, + ): Promise +⋮---- +getOrderRateLimit(): Promise +⋮---- +getPreventedMatches( + params: PreventedMatchesParams, + ): Promise +⋮---- +getAllocations(params: AllocationsParams): Promise +⋮---- +getCommissionRates(params: { symbol: string }): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Market Data endpoints + * + **/ +⋮---- +/** + * Get cross margin collateral ratios. + * The additional ratio sets are undocumented in the endpoint reference but confirmed by Binance staff. + * @see https://dev.binance.vision/t/39429 + */ +getCrossMarginCollateralRatio(): Promise< + { + /** Liquidation collateral ratios. */ + collaterals: Collateral[]; + /** Transfer-out collateral ratios (undocumented, confirmed by Binance staff). */ + withdrawCollaterals?: Collateral[]; + /** Borrow collateral ratios (undocumented, confirmed by Binance staff). */ + borrowCollaterals?: Collateral[]; + assetNames: string[]; + }[] + > +⋮---- +/** Liquidation collateral ratios. */ +⋮---- +/** Transfer-out collateral ratios (undocumented, confirmed by Binance staff). */ +⋮---- +/** Borrow collateral ratios (undocumented, confirmed by Binance staff). */ +⋮---- +getAllCrossMarginPairs(): Promise +⋮---- +getIsolatedMarginAllSymbols(params?: { + symbol?: string; + }): Promise +⋮---- +getAllMarginAssets(): Promise +⋮---- +getMarginDelistSchedule(): Promise +⋮---- +getIsolatedMarginTierData( + params: QueryIsolatedMarginTierDataParams, + ): Promise +⋮---- +queryMarginPriceIndex( + params: BasicSymbolParam, + ): Promise +⋮---- +getMarginAvailableInventory(params: { + type: string; + }): Promise +⋮---- +getLeverageBracket(): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Borrow and Repay endpoints + * + **/ +⋮---- +getNextHourlyInterestRate( + params: GetNextHourlyInterestRateParams, + ): Promise +⋮---- +getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise<{ + rows: MarginInterestHistory[]; + total: number; + }> +⋮---- +submitMarginAccountBorrowRepay( + params: MarginAccountLoanParams, + ): Promise +⋮---- +getMarginAccountBorrowRepayRecords( + params: GetMarginAccountBorrowRepayRecordsParams, + ): Promise<{ rows: MarginAccountRecord[]; total: number }> +⋮---- +getMarginInterestRateHistory( + params: QueryMarginInterestRateHistoryParams, + ): Promise +⋮---- +queryMaxBorrow( + params: BasicMarginAssetParams, + ): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Trade endpoints + * + **/ +⋮---- +getMarginForceLiquidationRecord( + params: GetForceLiquidationRecordParams, + ): Promise<{ + rows: ForceLiquidationRecord[]; + total: number; + }> +⋮---- +getSmallLiabilityExchangeCoins(): Promise +⋮---- +getSmallLiabilityExchangeHistory( + params: GetSmallLiabilityExchangeHistoryParams, + ): Promise<{ + total: number; + rows: SmallLiabilityExchangeHistory[]; + }> +⋮---- +marginAccountCancelOpenOrders( + params: BasicSymbolParam, + ): Promise +⋮---- +marginAccountCancelOCO(params: CancelOCOParams): Promise +⋮---- +marginAccountCancelOrder( + params: CancelOrderParams, + ): Promise +⋮---- +marginAccountNewOCO(params: NewOCOParams): Promise +⋮---- +marginAccountNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >(params: NewSpotOrderParams): Promise> +⋮---- +getMarginOrderCountUsage( + params: GetMarginOrderCountUsageParams, + ): Promise +⋮---- +queryMarginAccountAllOCO( + params: QueryMarginAccountAllOCOParams, + ): Promise +⋮---- +queryMarginAccountAllOrders( + params: GetAllOrdersParams, + ): Promise +⋮---- +queryMarginAccountOCO(params: GetOCOParams): Promise +⋮---- +queryMarginAccountOpenOCO(params: { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; + }): Promise +⋮---- +queryMarginAccountOpenOTOOrderLists( + params: QueryMarginOpenOTOOrderListsParams, + ): Promise +⋮---- +queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise +⋮---- +queryMarginAccountOrder(params: GetOrderParams): Promise +⋮---- +queryMarginAccountTradeList( + params: QueryMarginAccountTradeListParams, + ): Promise +⋮---- +submitSmallLiabilityExchange(params: { assetNames: string[] }): Promise<{ + success: boolean; + message: string; + }> +⋮---- +submitManualLiquidation( + params: ManualLiquidationParams, + ): Promise +⋮---- +/** + * Post a new OTO order for margin account + */ +submitMarginOTOOrder( + params: SubmitMarginOTOOrderParams, + ): Promise +⋮---- +/** + * Submit a new OTOCO order for margin account + */ +submitMarginOTOCOOrder( + params: SubmitMarginOTOCOOrderParams, + ): Promise +⋮---- +/** + * Create a special key for low-latency trading (VIP 4+ only) + */ +createMarginSpecialLowLatencyKey( + params: CreateSpecialLowLatencyKeyParams, + ): Promise +⋮---- +deleteMarginSpecialLowLatencyKey(params?: { + apiKey?: string; + apiName?: string; + symbol?: string; + }): Promise +⋮---- +updateMarginIPForSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; + ip: string; + }): Promise +⋮---- +/** + * Query the list of special keys for low-latency trading + */ +getMarginSpecialLowLatencyKeys(params: { + symbol?: string; + }): Promise +⋮---- +/** + * Query information for a specific special key used in low-latency trading + */ +getMarginSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; + }): Promise +⋮---- +/** + * Query the current cross-margin liquidation loan status (bankruptcy deficit). + */ +getMarginLiquidationLoan(): Promise +⋮---- +/** + * Repay an outstanding cross-margin liquidation loan from the spot wallet. + */ +repayMarginLiquidationLoan( + params: RepayMarginLiquidationLoanParams, + ): Promise +⋮---- +/** + * Query cross-margin liquidation loan repayment history. + */ +getMarginLiquidationLoanRepayHistory( + params?: GetMarginLiquidationLoanRepayHistoryParams, + ): Promise +⋮---- +/** + * Exit Margin Special Key mode for Cross Margin Classic accounts. + */ +exitMarginSpecialKeyMode(): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Transfer endpoints + * + **/ +⋮---- +getCrossMarginTransferHistory( + params: GetCrossMarginTransferHistoryParams, + ): Promise> +⋮---- +queryMaxTransferOutAmount( + params: BasicMarginAssetParams, + ): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Account endpoints + * + **/ +⋮---- +updateCrossMarginMaxLeverage(params: { maxLeverage: number }): Promise<{ + success: boolean; + }> +⋮---- +disableIsolatedMarginAccount(params: { symbol: string }): Promise<{ + success: boolean; + symbol: string; + }> +⋮---- +enableIsolatedMarginAccount(params: { symbols: string }): Promise<{ + success: boolean; + symbol: string; + }> +⋮---- +getBNBBurn(): Promise +⋮---- +getMarginSummary(): Promise +⋮---- +queryCrossMarginAccountDetails(): Promise +⋮---- +getCrossMarginFeeData( + params: QueryCrossMarginFeeDataParams, + ): Promise +⋮---- +getIsolatedMarginAccountLimit(): Promise<{ + enabledAccount: number; + maxAccount: number; + }> +⋮---- +getIsolatedMarginAccountInfo(params?: { + symbols?: string; + }): Promise +⋮---- +getIsolatedMarginFeeData( + params: QueryCrossMarginFeeDataParams, + ): Promise +⋮---- +toggleBNBBurn(params: ToggleBNBBurnParams): Promise +⋮---- +/** + * Possibly @deprecated + * Only existing in old documentation, not in new documentation + */ +getMarginCapitalFlow( + params: GetMarginCapitalFlowParams, + ): Promise +⋮---- +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryLoanRecord( + params: QueryMarginRecordParams, + ): Promise<{ rows: MarginAccountRecord[]; total: number }> +⋮---- +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryRepayRecord( + params: QueryMarginRecordParams, + ): Promise<{ rows: MarginAccountRecord[]; total: number }> +⋮---- +/** + * @deprecated on 2024-01-09, use submitUniversalTransfer() instead + */ +isolatedMarginAccountTransfer( + params: IsolatedMarginAccountTransferParams, + ): Promise +⋮---- +/** + * + * WALLET Endpoints - Capital endpoints + * + **/ +⋮---- +getBalances(): Promise +⋮---- +withdraw(params: WithdrawParams): Promise<{ id: string }> +⋮---- +getWithdrawHistory( + params?: WithdrawHistoryParams, + ): Promise +⋮---- +getWithdrawAddresses(): Promise +⋮---- +getWithdrawQuota(): Promise<{ + wdQuota: string; + usedWdQuota: string; + }> +⋮---- +getDepositHistory(params?: DepositHistoryParams): Promise +⋮---- +getDepositAddress( + params: DepositAddressParams, + ): Promise +⋮---- +getDepositAddresses( + params: DepositAddressListParams, + ): Promise +⋮---- +submitDepositCredit( + params: SubmitDepositCreditParams, + ): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + */ +getAutoConvertStablecoins(): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + */ +setConvertibleCoins(params: ConvertibleCoinsParams): Promise +⋮---- +/** + * + * WALLET Endpoints - Asset endpoints + * + **/ +⋮---- +getAssetDetail( + params?: Partial, + ): Promise> +⋮---- +getWalletBalances(params?: { + quoteAsset?: string; + }): Promise +⋮---- +getUserAsset(params: GetAssetParams): Promise +⋮---- +getSpotAssetTags(params?: SpotAssetTagsParams): Promise +⋮---- +submitUniversalTransfer( + params: UniversalTransferParams, + ): Promise<{ tranId: number }> +⋮---- +getUniversalTransferHistory( + params: UniversalTransferHistoryParams, + ): Promise +⋮---- +getDust(params: { accountType?: 'SPOT' | 'MARGIN' }): Promise +⋮---- +convertDustToBnb(params: ConvertDustParams): Promise +⋮---- +/** + * Convert dust assets to a target asset (e.g. BNB, USDT). + */ +convertDustAssets(params: DustConvertParams): Promise +⋮---- +/** + * Query assets eligible for dust conversion. + */ +queryDustConvertibleAssets( + params: DustConvertibleAssetsParams, + ): Promise +⋮---- +getDustLog(params?: BasicTimeRangeParam): Promise +⋮---- +getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise +⋮---- +getTradeFee(params?: { symbol?: string }): Promise +⋮---- +getFundingAsset(params: GetAssetParams): Promise +⋮---- +getCloudMiningHistory(params: CloudMiningHistoryParams): Promise<{ + total: number; + rows: CloudMining[]; + }> +⋮---- +getDelegationHistory( + params: DelegationHistoryParams, + ): Promise> +⋮---- +/** + * + * Futures Management Endpoints: + * https://binance-docs.github.io/apidocs/spot/en/#futures + * + * Note: to trade futures use the usdm-client or coinm-client. + * MainClient only has the futures endpoints listed in the "spot" docs category, primarily used for transfers. + * + **/ +⋮---- +/** + * Execute transfer between spot account and futures account. + * + * Type: + * - 1: transfer from spot account to USDT-Ⓜ futures account. + * - 2: transfer from USDT-Ⓜ futures account to spot account. + * - 3: transfer from spot account to COIN-Ⓜ futures account. + * - 4: transfer from COIN-Ⓜ futures account to spot account. + */ +⋮---- +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +submitNewFutureAccountTransfer( + params: NewFutureAccountTransferParams, + ): Promise<{ tranId: number }> +⋮---- +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +getFutureAccountTransferHistory( + params: GetFutureAccountTransferHistoryParams, + ): Promise> +⋮---- +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise +⋮---- +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise +⋮---- +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralWalletV2(): Promise +⋮---- +/** + * @deprecated as of 2023-09-25 + */ +getAdjustCrossCollateralLTVHistory( + params?: GetLoanCoinPaginatedHistoryParams, + ): Promise +⋮---- +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralLiquidationHistory( + params?: GetLoanCoinPaginatedHistoryParams, + ): Promise +⋮---- +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralInterestHistory( + params?: GetLoanCoinPaginatedHistoryParams, + ): Promise +⋮---- +/** + * + * WALLET Endpoints - Account endpoints + * + **/ +⋮---- +getAccountInfo(): Promise +⋮---- +getDailyAccountSnapshot( + params: DailyAccountSnapshotParams, + ): Promise +⋮---- +disableFastWithdrawSwitch(): Promise +⋮---- +enableFastWithdrawSwitch(): Promise +⋮---- +getAccountStatus(): Promise<{ data: string }> +⋮---- +getApiTradingStatus(): Promise +⋮---- +getApiKeyPermissions(): Promise +⋮---- +/** + * + * WALLET Endpoints - Travel Rule endpoints + * + **/ +⋮---- +/** + * Submit a withdrawal request for local entities that require travel rule + * + * For questionaire format, please refer to the docs: + * https://developers.binance.com/docs/wallet/travel-rule/withdraw-questionnaire + */ +withdrawTravelRule(params: WithdrawTravelRuleParams): Promise<{ + trId: number; + accpted: boolean; + info: string; + }> +⋮---- +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistory( + params?: GetTravelRuleWithdrawHistoryParams, + ): Promise +⋮---- +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistoryV2( + params?: GetTravelRuleWithdrawHistoryV2Params, + ): Promise +⋮---- +/** + * Submit questionnaire for local entities that require travel rule + * + * for questionaire format, please refer to the docs: + * https://developers.binance.com/docs/wallet/travel-rule/deposit-questionnaire + */ +submitTravelRuleDepositQuestionnaire( + params: SubmitTravelRuleDepositQuestionnaireParams, + ): Promise +⋮---- +/** + * Fetch deposit history for local entities that require travel rule + */ +getTravelRuleDepositHistory( + params?: GetTravelRuleDepositHistoryParams, + ): Promise +⋮---- +/** + * Fetch the onboarded VASP list for local entities that require travel rule. + * Use the `identifier` field (not vaspCode) for the `vasp` param in deposit/withdrawal questionnaires. + * Both vaspCode and identifier accepted until 28 May 2026. + */ +getOnboardedVASPList(): Promise +⋮---- +getTravelRuleCountryList(): Promise +⋮---- +getTravelRuleRegionList( + params: GetTravelRuleRegionListParams, + ): Promise +⋮---- +/** + * + * WALLET Endpoints - Other endpoints + * + **/ +⋮---- +getSystemStatus(): Promise +⋮---- +getDelistSchedule(): Promise +⋮---- +/** + * + * SUB ACCOUNT Endpoints - Account management + * + **/ +⋮---- +createVirtualSubAccount( + params: CreateSubAccountParams, + ): Promise +⋮---- +getSubAccountList( + params?: SubAccountListParams, + ): Promise +⋮---- +subAccountEnableFutures(email: string): Promise +⋮---- +/** + * @deprecated as of 2025-06-03 + * User now should make the initial transfer in the Margin account to enable it. + */ +subAccountEnableMargin(email: string): Promise +⋮---- +enableOptionsForSubAccount(params: { + email: string; + }): Promise +⋮---- +/** + * @deprecated as of 2025-06-03 + * User now should make the initial transfer in the Margin account to enable it. + */ +subAccountEnableLeverageToken( + params: SubAccountEnableLeverageToken, + ): Promise +⋮---- +getSubAccountStatusOnMarginOrFutures(params?: { + email?: string; + }): Promise +⋮---- +getSubAccountFuturesPositionRisk( + email: string, + ): Promise +⋮---- +getSubAccountFuturesPositionRiskV2( + params: BasicFuturesSubAccountParams, + ): Promise +⋮---- +getSubAccountTransactionStatistics(params: { + email: string; + }): Promise +⋮---- +/** + * + * SUB ACCOUNT Endpoints - API management + * + **/ +⋮---- +/** + * Query a sub-account's API keys (for master account). + */ +getSubAccountApiKeys( + params: GetSubAccountApiKeysParams, + ): Promise> +⋮---- +/** + * Create a sub-account API key (for master account). + * Permission flags default to false. FIX permissions require an Ed25519 key. + */ +createSubAccountApiKey( + params: CreateSubAccountApiKeyParams, + ): Promise +⋮---- +/** + * Delete a sub-account API key (for master account). + */ +deleteSubAccountApiKey( + params: DeleteSubAccountApiKeyParams, + ): Promise +⋮---- +/** + * Modify a sub-account API key's permissions (for master account). + * FIX permissions require an Ed25519 key and remain unchanged when omitted. + */ +modifySubAccountApiKeyPermission( + params: ModifySubAccountApiKeyPermissionParams, + ): Promise +⋮---- +getSubAccountIPRestriction( + params: BasicSubAccount, + ): Promise +⋮---- +subAccountDeleteIPList( + params: SubAccountAddOrDeleteIPList, + ): Promise +⋮---- +subAccountAddIPRestriction( + params: AddIpRestriction, + ): Promise +⋮---- +/** + * @deprecated + * Use subAccountAddIPRestriction instead + **/ +subAccountAddIPList( + params: SubAccountEnableOrDisableIPRestriction, + ): Promise +⋮---- +/** + * @deprecated + * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList + **/ +subAccountEnableOrDisableIPRestriction( + params: EnableOrDisableIPRestrictionForSubAccountParams, + ): Promise +⋮---- +/** + * + * SUB ACCOUNT Endpoints - Asset management + * + **/ +⋮---- +subAccountFuturesTransfer( + params: SubAccountTransferParams, + ): Promise +⋮---- +getSubAccountFuturesAccountDetail( + email: string, + ): Promise +⋮---- +getSubAccountDetailOnFuturesAccountV2( + params: BasicFuturesSubAccountParams, + ): Promise +⋮---- +getSubAccountDetailOnMarginAccount( + email: string, + ): Promise +⋮---- +getSubAccountDepositAddress( + params: SubAccountDepositAddressParams, + ): Promise +⋮---- +getSubAccountDepositHistory( + params: SubAccountDepositHistoryParams, + ): Promise +⋮---- +getSubAccountFuturesAccountSummary(): Promise +⋮---- +getSubAccountSummaryOnFuturesAccountV2( + params: SubAccountSummaryOnFuturesAccountV2Params, + ): Promise +⋮---- +getSubAccountsSummaryOfMarginAccount(): Promise +⋮---- +subAccountMarginTransfer( + params: SubAccountTransferParams, + ): Promise +⋮---- +getSubAccountAssets( + params: SubAccountAssetsParams, + ): Promise +⋮---- +getSubAccountAssetsMaster(params: { email: string }): Promise<{ + balances: SubaccountBalances[]; + }> +⋮---- +getSubAccountFuturesAssetTransferHistory( + params: SubAccountFuturesAssetTransferHistoryParams, + ): Promise +⋮---- +getSubAccountSpotAssetTransferHistory( + params?: SubAccountSpotAssetTransferHistoryParams, + ): Promise +⋮---- +getSubAccountSpotAssetsSummary( + params?: SubAccountSpotAssetsSummaryParams, + ): Promise +⋮---- +getSubAccountUniversalTransferHistory( + params?: SubAccountUniversalTransferHistoryParams, + ): Promise +⋮---- +subAccountFuturesAssetTransfer( + params: SubAccountFuturesAssetTransferParams, + ): Promise +⋮---- +subAccountTransferHistory( + params?: SubAccountTransferHistoryParams, + ): Promise +⋮---- +subAccountTransferToMaster( + params: SubAccountTransferToMasterParams, + ): Promise +⋮---- +subAccountTransferToSameMaster( + params: SubAccountTransferToSameMasterParams, + ): Promise +⋮---- +subAccountUniversalTransfer( + params: SubAccountUniversalTransferParams, + ): Promise +⋮---- +subAccountMovePosition( + params: SubAccountMovePositionParams, + ): Promise<{ movePositionOrders: SubAccountMovePosition[] }> +⋮---- +getSubAccountFuturesPositionMoveHistory( + params: SubAccountMovePositionHistoryParams, + ): Promise<{ + total: number; + futureMovePositionOrderVoList: SubAccountMovePositionHistory[]; + }> +⋮---- +/** + * + * SUB ACCOUNT Endpoints - Managed Sub Account + * + **/ +⋮---- +depositAssetsIntoManagedSubAccount( + params: SubAccountTransferToSameMasterParams, + ): Promise +⋮---- +getManagedSubAccountDepositAddress( + params: ManagedSubAccountDepositAddressParams, + ): Promise +⋮---- +withdrawAssetsFromManagedSubAccount( + params: WithdrawAssetsFromManagedSubAccountParams, + ): Promise +⋮---- +getManagedSubAccountTransfersParent( + params: ManagedSubAccountTransferLogParams, + ): Promise<{ + managerSubTransferHistoryVos: ManagerSubTransferHistoryVos[]; + count: number; + }> +⋮---- +getManagedSubAccountTransferLog( + params: ManagedSubAccountTransferTTLogParams, + ): Promise<{ + managerSubTransferHistoryVos: ManagerSubTransferHistoryVos[]; + count: number; + }> +⋮---- +getManagedSubAccountTransfersInvestor( + params: ManagedSubAccountTransferLogParams, + ): Promise<{ + managerSubTransferHistoryVos: ManagerSubTransferHistoryVos[]; + count: number; + }> +⋮---- +getManagedSubAccounts(params: ManagedSubAccountListParams): Promise<{ + total: number; + managerSubUserInfoVoList: ManagerSubUserInfoVo[]; + }> +⋮---- +getManagedSubAccountSnapshot( + params: ManagedSubAccountSnapshotParams, + ): Promise +⋮---- +getManagedSubAccountAssetDetails( + email: string, + ): Promise +⋮---- +getManagedSubAccountMarginAssets(params: { + email: string; + accountType?: string; + }): Promise +⋮---- +getManagedSubAccountFuturesAssets(params: { + email: string; + accountType?: string; + }): Promise +⋮---- +/** + * + * AUTO INVEST Endpoints - Market data + * + **/ +⋮---- +getAutoInvestAssets(): Promise<{ + targetAssets: string[]; + sourceAssets: string[]; + }> +⋮---- +getAutoInvestSourceAssets( + params: GetSourceAssetListParams, + ): Promise +⋮---- +getAutoInvestTargetAssets( + params: GetTargetAssetListParams, + ): Promise +⋮---- +getAutoInvestTargetAssetsROI( + params: GetTargetAssetROIParams, + ): Promise +⋮---- +getAutoInvestIndex(params: { + indexId: number; + }): Promise +⋮---- +getAutoInvestPlans(params: { + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; + }): Promise +⋮---- +/** + * + * AUTO INVEST Endpoints - Trade + * + **/ +⋮---- +/** + * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction + * + * @param params + * @returns + */ +submitAutoInvestOneTimeTransaction( + params: SubmitOneTimeTransactionParams, + ): Promise +⋮---- +updateAutoInvestPlanStatus( + params: ChangePlanStatusParams, + ): Promise +⋮---- +updateAutoInvestmentPlan( + params: EditInvestmentPlanParams, + ): Promise +⋮---- +submitAutoInvestRedemption( + params: SubmitIndexLinkedPlanRedemptionParams, + ): Promise<{ + redemptionId: number; + }> +⋮---- +getAutoInvestSubscriptionTransactions( + params: GetSubscriptionTransactionHistoryParams, + ): Promise +⋮---- +getOneTimeTransactionStatus( + params: GetOneTimeTransactionStatusParams, + ): Promise +⋮---- +submitAutoInvestmentPlan( + params: CreateInvestmentPlanParams, + ): Promise +⋮---- +getAutoInvestRedemptionHistory( + params: GetIndexLinkedPlanRedemptionHistoryParams, + ): Promise +⋮---- +getAutoInvestPlan(params: GetPlanDetailsParams): Promise +⋮---- +getAutoInvestUserIndex(params: { + indexId: number; + }): Promise +⋮---- +getAutoInvestRebalanceHistory( + params: GetIndexLinkedPlanRebalanceHistoryParams, + ): Promise +⋮---- +/** + * + * CONVERT Endpoints - Market Data + * + **/ +⋮---- +getConvertPairs(params: GetAllConvertPairsParams): Promise +⋮---- +getConvertAssetInfo(): Promise +⋮---- +/** + * + * CONVERT Endpoints - Trade + * + **/ +⋮---- +convertQuoteRequest(params: ConvertQuoteRequestParams): Promise +⋮---- +acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise +⋮---- +getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise +⋮---- +getOrderStatus(params: GetOrderStatusParams): Promise +⋮---- +submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise +⋮---- +cancelConvertLimitOrder(params: { orderId: number }): Promise +⋮---- +getConvertLimitOpenOrders(): Promise<{ + list: ConvertLimitOpenOrder[]; + }> +⋮---- +/** + * + * STAKING Endpoints - ETH Staking - Account + * + **/ +⋮---- +/** + * @deprecated use getEthStakingAccountV2 instead + **/ +getEthStakingAccount(): Promise +⋮---- +getEthStakingAccountV2(): Promise +⋮---- +getEthStakingQuota(): Promise +⋮---- +/** + * + * STAKING Endpoints - ETH Staking- Staking + * + **/ +⋮---- +/** + * @deprecated use subscribeEthStakingV2 instead + **/ +subscribeEthStakingV1(params: { amount: number }): Promise<{ + success: boolean; + }> +⋮---- +subscribeEthStakingV2(params: { + amount: number; + }): Promise +⋮---- +redeemEth(params: RedeemEthParams): Promise +⋮---- +wrapBeth(params: { amount: number }): Promise +⋮---- +/** + * + * STAKING Endpoints - ETH Staking - History + * + **/ +⋮---- +getEthStakingHistory(params: GetEthStakingHistoryParams): Promise<{ + rows: EthStakingHistory[]; + total: number; + }> +⋮---- +getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise<{ + rows: EthRedemptionHistory[]; + total: number; + }> +⋮---- +getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise<{ + rows: BethRewardsHistory[]; + total: number; + }> +⋮---- +getWbethRewardsHistory( + params: GetWrapHistoryParams, + ): Promise +⋮---- +getEthRateHistory(params: GetETHRateHistoryParams): Promise<{ + rows: ETHRateHistory[]; + total: string; + }> +⋮---- +getBethWrapHistory(params: GetWrapHistoryParams): Promise<{ + rows: WrapHistory[]; + total: number; + }> +⋮---- +getBethUnwrapHistory(params: GetWrapHistoryParams): Promise<{ + rows: WrapHistory[]; + total: number; + }> +⋮---- +/** + * + * BFUSD (sapi/v1/bfusd) + * + **/ +⋮---- +getBfusdAccount(): Promise +⋮---- +getBfusdQuota(): Promise +⋮---- +subscribeBfusd( + params: BfusdSubscribeParams, + ): Promise +⋮---- +redeemBfusd(params: BfusdRedeemParams): Promise +⋮---- +getBfusdSubscriptionHistory( + params: GetBfusdSubscriptionHistoryParams, + ): Promise<{ rows: BfusdSubscriptionHistoryRow[]; total: number }> +⋮---- +getBfusdRedemptionHistory( + params: GetBfusdRedemptionHistoryParams, + ): Promise<{ rows: BfusdRedemptionHistoryRow[]; total: number }> +⋮---- +getBfusdRewardsHistory( + params: GetBfusdRewardsHistoryParams, + ): Promise<{ rows: BfusdRewardsHistoryRow[]; total: number }> +⋮---- +getBfusdRateHistory( + params: GetBfusdRateHistoryParams, + ): Promise<{ rows: BfusdRateHistoryRow[]; total: string }> +⋮---- +/** + * + * RWUSD (sapi/v1/rwusd) + * + **/ +⋮---- +getRwusdAccount(): Promise +⋮---- +getRwusdQuota(): Promise +⋮---- +subscribeRwusd( + params: RwusdSubscribeParams, + ): Promise +⋮---- +redeemRwusd(params: RwusdRedeemParams): Promise +⋮---- +getRwusdSubscriptionHistory( + params: GetRwusdSubscriptionHistoryParams, + ): Promise<{ rows: RwusdSubscriptionHistoryRow[]; total: number }> +⋮---- +getRwusdRedemptionHistory( + params: GetRwusdRedemptionHistoryParams, + ): Promise<{ rows: RwusdRedemptionHistoryRow[]; total: number }> +⋮---- +getRwusdRewardsHistory( + params: GetRwusdRewardsHistoryParams, + ): Promise<{ rows: RwusdRewardsHistoryRow[]; total: number }> +⋮---- +getRwusdRateHistory( + params: GetRwusdRateHistoryParams, + ): Promise<{ rows: RwusdRateHistoryRow[]; total: string }> +⋮---- +/** + * @deprecated as of 2024-01-19 + */ +getStakingProducts( + params: StakingBasicParams & { + asset?: string; + }, + ): Promise +⋮---- +/** + * @deprecated as of 2024-01-19 + */ +getStakingProductPosition( + params: StakingBasicParams & { + productId?: string; + asset?: string; + }, + ): Promise +⋮---- +/** + * @deprecated as of 2024-01-19 + */ +getStakingHistory(params: StakingHistoryParams): Promise +⋮---- +/** + * @deprecated as of 2024-01-19 + */ +getPersonalLeftQuotaOfStakingProduct(params: { + product: StakingProductType; + productId: string; + }): Promise +⋮---- +/** + * + * STAKING Endpoints - SOL Staking- Account + * + **/ +⋮---- +getSolStakingAccount(): Promise +⋮---- +getSolStakingQuota(): Promise +⋮---- +/** + * + * STAKING Endpoints - SOL Staking - Staking + * + **/ +⋮---- +subscribeSolStaking(params: { + amount: number; + }): Promise +⋮---- +redeemSol(params: { amount: number }): Promise +⋮---- +claimSolBoostRewards(): Promise<{ + success: boolean; + }> +⋮---- +/** + * + * STAKING Endpoints - SOL Staking- History + * + **/ +⋮---- +getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise<{ + rows: SolStakingHistoryRecord[]; + total: number; + }> +⋮---- +getSolRedemptionHistory(params?: { + rows: SolRedemptionHistoryRecord[]; + total: number; + }): Promise +⋮---- +getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise<{ + estRewardsInSOL: string; + rows: BnsolRewardHistoryRecord[]; + total: number; + }> +⋮---- +getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise<{ + rows: BnsolRateHistoryRecord[]; + total: string; + }> +⋮---- +getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise<{ + rows: SolBoostRewardsHistoryRecord[]; + total: number; + }> +⋮---- +getSolUnclaimedRewards(): Promise< + { + amount: string; + rewardsAsset: string; + }[] + > +⋮---- +/** + * + * STAKING - Onchain Yields - Account + * + **/ +⋮---- +getOnchainYieldsLockedProducts( + params?: OnchainYieldsLockedProductListParams, + ): Promise +⋮---- +getOnchainYieldsLockedPersonalLeftQuota( + params: OnchainYieldsLockedPersonalLeftQuotaParams, + ): Promise +⋮---- +getOnchainYieldsLockedPosition( + params?: OnchainYieldsLockedPositionParams, + ): Promise +⋮---- +getOnchainYieldsAccount(): Promise +⋮---- +/** + * + * STAKING - Onchain Yields - Earn + * + **/ +⋮---- +getOnchainYieldsLockedSubscriptionPreview( + params: OnchainYieldsLockedSubscriptionPreviewParams, + ): Promise +⋮---- +subscribeOnchainYieldsLockedProduct( + params: OnchainYieldsLockedSubscribeParams, + ): Promise +⋮---- +setOnchainYieldsLockedAutoSubscribe( + params: OnchainYieldsLockedSetAutoSubscribeParams, + ): Promise +⋮---- +setOnchainYieldsLockedRedeemOption( + params: OnchainYieldsLockedSetRedeemOptionParams, + ): Promise +⋮---- +redeemOnchainYieldsLockedProduct( + params: OnchainYieldsLockedRedeemParams, + ): Promise +⋮---- +/** + * + * STAKING - Onchain Yields - History + * + **/ +⋮---- +getOnchainYieldsLockedSubscriptionRecord( + params?: OnchainYieldsLockedSubscriptionRecordParams, + ): Promise +⋮---- +getOnchainYieldsLockedRewardsHistory( + params?: OnchainYieldsLockedRewardsHistoryParams, + ): Promise +⋮---- +getOnchainYieldsLockedRedemptionRecord( + params?: OnchainYieldsLockedRedemptionRecordParams, + ): Promise +⋮---- +/** + * + * STAKING - Soft staking + * + **/ +⋮---- +getSoftStakingProductList( + params?: GetSoftStakingProductListParams, + ): Promise +⋮---- +setSoftStaking( + params: SetSoftStakingParams, + ): Promise +⋮---- +getSoftStakingRewardsHistory( + params?: GetSoftStakingRewardsHistoryParams, + ): Promise +⋮---- +/** + * + * COPY TRADING Endpoints - Future copy trading + * + **/ +⋮---- +getFuturesLeadTraderStatus(): Promise +⋮---- +getFuturesLeadTradingSymbolWhitelist(): Promise< + GetFuturesLeadTradingSymbolWhitelistResponse[] + > +⋮---- +/** + * + * MINING Endpoints - rest api + * + **/ +⋮---- +getMiningAlgos(): Promise +⋮---- +getMiningCoins(): Promise +⋮---- +getHashrateResales( + params: GetHashrateResaleListParams, + ): Promise +⋮---- +getMiners(params: GetMinerListParams): Promise +⋮---- +getMinerDetails( + params: GetMinerDetailsParams, + ): Promise +⋮---- +getExtraBonuses( + params: GetExtraBonusListParams, + ): Promise +⋮---- +getMiningEarnings( + params: GetEarningsListParams, + ): Promise +⋮---- +cancelHashrateResaleConfig( + params: CancelHashrateResaleConfigParams, + ): Promise +⋮---- +getHashrateResale( + params: GetHashrateResaleDetailParams, + ): Promise +⋮---- +getMiningAccountEarnings( + params: GetMiningAccountEarningParams, + ): Promise +⋮---- +getMiningStatistics( + params: GetStatisticListParams, + ): Promise +⋮---- +submitHashrateResale(params: SubmitHashrateResaleParams): Promise +⋮---- +getMiningAccounts( + params: getMiningAccountsListParams, + ): Promise +⋮---- +/** + * + * ALGO TRADING Endpoints - Future algo + * + **/ +⋮---- +submitVpNewOrder( + params: SubmitVpNewOrderParams, + ): Promise +⋮---- +submitTwapNewOrder( + params: SubmitTwapNewOrderParams, + ): Promise +⋮---- +cancelAlgoOrder( + params: + | { algoId: number; clientAlgoId?: string } + | { clientAlgoId: string; algoId?: number }, + ): Promise +⋮---- +getAlgoSubOrders( + params: GetAlgoSubOrdersParams, + ): Promise +⋮---- +getAlgoOpenOrders(): Promise<{ + total: number; + orders: AlgoOrder[]; + }> +⋮---- +getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise<{ + total: number; + orders: HistoricalAlgoOrder[]; + }> +⋮---- +/** + * + * ALGO TRADING Endpoints - Spot algo + * + **/ +⋮---- +submitSpotAlgoTwapOrder( + params: SubmitSpotTwapNewOrderParams, + ): Promise +⋮---- +cancelSpotAlgoOrder( + params: + | { algoId: number; clientAlgoId?: string } + | { clientAlgoId: string; algoId?: number }, + ): Promise +⋮---- +getSpotAlgoSubOrders( + params: GetSpotAlgoSubOrdersParams, + ): Promise +⋮---- +getSpotAlgoOpenOrders(): Promise<{ + total: number; + orders: SpotAlgoOrder[]; + }> +⋮---- +getSpotAlgoHistoricalOrders( + params: GetSpotAlgoHistoricalOrdersParams, + ): Promise<{ + total: number; + orders: HistoricalSpotAlgoOrder[]; + }> +⋮---- +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - Market data + * + **/ +⋮---- +getCryptoLoanFlexibleCollateralAssets(params: { + collateralCoin?: string; + }): Promise<{ + rows: FlexibleLoanCollateralAssetData[]; + total: number; + }> +⋮---- +getCryptoLoanFlexibleAssets(params: { loanCoin?: string }): Promise<{ + rows: FlexibleLoanAssetData[]; + total: number; + }> +⋮---- +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - Trade + * + **/ +⋮---- +borrowCryptoLoanFlexible( + params: BorrowFlexibleLoanParams, + ): Promise +⋮---- +repayCryptoLoanFlexible( + params: RepayCryptoFlexibleLoanParams, + ): Promise +⋮---- +repayCryptoLoanFlexibleWithCollateral( + params: RepayCryptoLoanFlexibleWithCollateralParams, + ): Promise +⋮---- +adjustCryptoLoanFlexibleLTV( + params: AdjustFlexibleCryptoLoanLTVParams, + ): Promise +⋮---- +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - User info + * + **/ +⋮---- +getCryptoLoanFlexibleLTVAdjustmentHistory( + params: GetFlexibleLoanLTVAdjustmentHistoryParams, + ): Promise<{ + rows: FlexibleLoanLTVAdjustmentHistory[]; + total: number; + }> +⋮---- +getFlexibleLoanCollateralRepayRate(params: { + loanCoin: string; + collateralCoin: string; + }): Promise<{ + loanCoin: string; + collateralCoin: string; + rate: string; + }> +⋮---- +getLoanFlexibleBorrowHistory( + params: GetFlexibleCryptoLoanBorrowHistoryParams, + ): Promise<{ + rows: FlexibleCryptoLoanBorrowHistory[]; + total: number; + }> +⋮---- +getCryptoLoanFlexibleOngoingOrders( + params: GetFlexibleLoanOngoingOrdersParams, + ): Promise<{ + rows: FlexibleLoanOngoingOrder[]; + total: number; + }> +⋮---- +getFlexibleLoanLiquidationHistory( + params?: GetFlexibleLoanLiquidationHistoryParams, + ): Promise<{ + rows: FlexibleLoanLiquidationHistoryRecord[]; + total: number; + }> +⋮---- +getLoanFlexibleRepaymentHistory( + params: GetLoanRepaymentHistoryParams, + ): Promise<{ + rows: LoanRepaymentHistory[]; + total: number; + }> +⋮---- +/** + * + * CRYPTO LOAN Endpoints - Stable rate - Market data + * + **/ +⋮---- +/** + * @deprecated + */ +getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise<{ + rows: LoanableAssetData[]; + total: number; + }> +⋮---- +getCryptoLoanCollateralRepayRate( + params: CheckCollateralRepayRateParams, + ): Promise +⋮---- +/** + * @deprecated + */ +getCryptoLoanCollateralAssetsData( + params: GetCollateralAssetDataParams, + ): Promise<{ + rows: CollateralAssetData[]; + total: number; + }> +⋮---- +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/income` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoansIncomeHistory( + params: GetCryptoLoansIncomeHistoryParams, + ): Promise +⋮---- +/** + * + * CRYPTO LOAN Endpoints - Stable rate - Trade + * + **/ +⋮---- +/** + * @deprecated + */ +borrowCryptoLoan( + params: BorrowCryptoLoanParams, + ): Promise +⋮---- +/** + * @deprecated + */ +repayCryptoLoan( + params: RepayCryptoLoanParams, + ): Promise +⋮---- +/** + * @deprecated + */ +adjustCryptoLoanLTV( + params: AdjustCryptoLoanLTVParams, + ): Promise +⋮---- +/** + * @deprecated + */ +customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise<{ + rows: CustomizeMarginCall[]; + total: number; + }> +⋮---- +/** + * + * CRYPTO LOAN Endpoints - Stable rate - User info + * + **/ +⋮---- +/** + * @deprecated + */ +getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise<{ + rows: LoanOngoingOrder[]; + total: number; + }> +⋮---- +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/borrow/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise<{ + rows: LoanBorrowHistory[]; + total: number; + }> +⋮---- +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/ltv/adjustment/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoanLTVAdjustmentHistory( + params: GetLoanLTVAdjustmentHistoryParams, + ): Promise<{ + rows: LoanLTVAdjustmentHistory[]; + total: number; + }> +⋮---- +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/repay/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoanRepaymentHistory( + params: GetLoanRepaymentHistoryParams, + ): Promise +⋮---- +/** + * + * SIMPLE EARN Endpoints - Account + * + **/ +⋮---- +getSimpleEarnAccount(): Promise +⋮---- +getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise<{ + rows: SimpleEarnFlexibleProduct[]; + total: number; + }> +⋮---- +getSimpleEarnLockedProductList( + params?: SimpleEarnProductListParams, + ): Promise<{ + rows: SimpleEarnLockedProduct[]; + total: number; + }> +⋮---- +getFlexibleProductPosition( + params?: SimpleEarnFlexibleProductPositionParams, + ): Promise<{ + rows: any[]; + total: number; + }> +⋮---- +getLockedProductPosition( + params?: SimpleEarnLockedProductPositionParams, + ): Promise<{ + rows: SimpleEarnLockedProductPosition[]; + total: number; + }> +⋮---- +getFlexiblePersonalLeftQuota(params: { productId: string }): Promise<{ + leftPersonalQuota: string; + }> +⋮---- +getLockedPersonalLeftQuota(params: { projectId: string }): Promise<{ + leftPersonalQuota: string; + }> +⋮---- +/** + * + * SIMPLE EARN Endpoints - Earn + * + **/ +⋮---- +purchaseFlexibleProduct( + params: SimpleEarnSubscribeProductParams, + ): Promise +⋮---- +subscribeSimpleEarnLockedProduct( + params: SimpleEarnSubscribeProductParams, + ): Promise +⋮---- +redeemFlexibleProduct( + params: SimpleEarnRedeemFlexibleProductParams, + ): Promise +⋮---- +redeemLockedProduct(params: { + positionId: string; + }): Promise +⋮---- +setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise<{ + success: boolean; + }> +⋮---- +setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise<{ + success: boolean; + }> +⋮---- +getFlexibleSubscriptionPreview( + params: GetFlexibleSubscriptionPreviewParams, + ): Promise +⋮---- +getLockedSubscriptionPreview( + params: GetLockedSubscriptionPreviewParams, + ): Promise +⋮---- +setLockedProductRedeemOption(params: { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; + }): Promise<{ + success: boolean; + }> +⋮---- +/** + * + * SIMPLE EARN Endpoints - History + * + **/ +⋮---- +getFlexibleSubscriptionRecord( + params: GetFlexibleSubscriptionRecordParams, + ): Promise<{ + rows: GetFlexibleSubscriptionRecordResponse[]; + total: number; + }> +⋮---- +getLockedSubscriptionRecord( + params: GetLockedSubscriptionRecordParams, + ): Promise<{ + rows: LockedSubscriptionRecord[]; + total: number; + }> +⋮---- +getFlexibleRedemptionRecord( + params: GetFlexibleRedemptionRecordParams, + ): Promise<{ + rows: FlexibleRedemptionRecord[]; + total: number; + }> +⋮---- +getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise<{ + rows: LockedRedemptionRecord[]; + total: number; + }> +⋮---- +getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise<{ + rows: FlexibleRewardsHistory[]; + total: number; + }> +⋮---- +getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise<{ + rows: GetLockedRewardsHistory[]; + total: number; + }> +⋮---- +getCollateralRecord(params: GetCollateralRecordParams): Promise<{ + rows: CollateralRecord[]; + total: string; + }> +⋮---- +getRateHistory(params: GetRateHistoryParams): Promise<{ + rows: GetRateHistory[]; + total: string; + }> +⋮---- +/** + * + * VIP LOAN Endpoints - Market Data + * + **/ +⋮---- +getVipBorrowInterestRate(params: { + loanCoin: string; + }): Promise +⋮---- +getVipLoanInterestRateHistory( + params: VipLoanInterestRateHistoryParams, + ): Promise<{ + rows: VipLoanInterestRateRecord[]; + total: number; + }> +⋮---- +getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise<{ + rows: LoanableAssetData[]; + total: number; + }> +⋮---- +getVipCollateralAssets(params: { collateralCoin?: string }): Promise<{ + rows: CollateralAssetData[]; + total: number; + }> +⋮---- +/** + * + * VIP LOAN Endpoints - User Info + * + **/ +⋮---- +getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise<{ + rows: VipOngoingOrder[]; + total: number; + }> +⋮---- +getVipLoanRepaymentHistory( + params: GetVipLoanRepaymentHistoryParams, + ): Promise<{ + rows: VipLoanRepaymentHistory[]; + total: number; + }> +⋮---- +checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise<{ + rows: VipCollateralAccount[]; + total: number; + }> +⋮---- +getVipApplicationStatus(params: GetApplicationStatusParams): Promise<{ + rows: ApplicationStatus[]; + total: number; + }> +⋮---- +/** + * + * VIP LOAN Endpoints - Trade + * + **/ +⋮---- +renewVipLoan(params: VipLoanRenewParams): Promise +⋮---- +repayVipLoan(params: VipLoanRepayParams): Promise +⋮---- +borrowVipLoan(params: VipLoanBorrowParams): Promise +⋮---- +getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise<{ + total: number; + rows: VipLoanFixedRateMarketRecord[]; + }> +⋮---- +borrowVipLoanFixedRate( + params: VipLoanFixedRateBorrowParams, + ): Promise +⋮---- +/** + * + * DUAL INVESTMENT Endpoints - Market Data + * + **/ +⋮---- +getDualInvestmentProducts( + params: GetDualInvestmentProductListParams, + ): Promise<{ + total: number; + list: DualInvestmentProduct[]; + }> +⋮---- +/** + * + * DUAL INVESTMENT Endpoints - Trade + * + **/ +⋮---- +subscribeDualInvestmentProduct( + params: SubscribeDualInvestmentProductParams, + ): Promise +⋮---- +getDualInvestmentPositions( + params: GetDualInvestmentPositionsParams, + ): Promise<{ + total: number; + list: DualInvestmentPosition[]; + }> +⋮---- +getDualInvestmentAccounts(): Promise +⋮---- +getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise<{ + rows: VipLoanAccruedInterestRecord[]; + total: number; + }> +⋮---- +/** + * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. + * Calls to this method will fail. Configure auto-compound for Dual Investment positions + * in the Binance web UI. This method will be removed in a future major version. + * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published + * binance-api-swagger spec still lists the endpoint, so this method stays deprecated. + */ +updateAutoCompoundStatus( + params: ChangeAutoCompoundStatusParams, + ): Promise +⋮---- +/** + * + * GIFT CARD Endpoints - Market Data + * + **/ +⋮---- +createGiftCard(params: CreateGiftCardParams): Promise +⋮---- +createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise +⋮---- +redeemGiftCard(params: RedeemGiftCardParams): Promise +⋮---- +verifyGiftCard(params: { referenceNo: string }): Promise +⋮---- +getTokenLimit(params: { baseToken: string }): Promise +⋮---- +getRsaPublicKey(): Promise +⋮---- +/** + * + * NFT Endpoints - REST api + * + **/ +⋮---- +getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise<{ + total: number; + list: NftTransaction[]; + }> +⋮---- +getNftDepositHistory(params: GetNftDepositHistoryParams): Promise<{ + total: number; + list: NftDeposit[]; + }> +⋮---- +getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise<{ + total: number; + list: NftWithdraw[]; + }> +⋮---- +getNftAsset(params: GetNftAssetParams): Promise<{ + total: number; + list: NftAsset[]; + }> +⋮---- +/** + * + * C2C Endpoints + * + **/ +⋮---- +getC2CTradeHistory( + params: GetC2CTradeHistoryParams, + ): Promise +⋮---- +/** + * + * FIAT Endpoints - REST api + * + **/ +⋮---- +getFiatOrderHistory( + params: GetFiatOrderHistoryParams, + ): Promise +⋮---- +getFiatPaymentsHistory( + params: GetFiatOrderHistoryParams, + ): Promise +⋮---- +fiatWithdraw(params: WithdrawFiatParams): Promise<{ id: string }> +⋮---- +fiatDeposit(params: FiatDepositParams): Promise +⋮---- +getFiatOrderDetail( + params: GetFiatOrderDetailParams, + ): Promise +⋮---- +/** + * + * Rebate Endpoints + * + **/ +⋮---- +getSpotRebateHistoryRecords( + params: GetSpotRebateHistoryRecordsParams, + ): Promise +⋮---- +/** + * + * DERIVATIVES - Portfolio Margin Pro - Market Data + * This is in mainclient because it shares the same base url + * + **/ +⋮---- +getPortfolioMarginIndexPrice(params?: { + asset?: string; + }): Promise +⋮---- +getPortfolioMarginAssetLeverage(): Promise< + GetPortfolioMarginAssetLeverageResponse[] + > +⋮---- +getPortfolioMarginProCollateralRate(): Promise< + GetPortfolioMarginProCollateralRateResponse[] + > +⋮---- +getPortfolioMarginProTieredCollateralRate(): Promise +⋮---- +/** + * + * DERIVATIVES - Portfolio Margin Pro - Account + * This is in mainclient because it shares the same base url + * + **/ +⋮---- +getPortfolioMarginProAccountInfo(): Promise +⋮---- +getPortfolioDeltaMode(): Promise +⋮---- +switchPortfolioDeltaMode( + params: SwitchPortfolioDeltaModeParams, + ): Promise<{ msg: string }> +⋮---- +setPortfolioMarginMarginCallLevel( + params: SetPortfolioMarginMarginCallLevelParams, + ): Promise +⋮---- +getPortfolioMarginMarginCallLevel(): Promise +⋮---- +deletePortfolioMarginMarginCallLevel(): Promise +⋮---- +bnbTransfer(params: BnbTransferParams): Promise<{ + tranId: number; + }> +⋮---- +submitPortfolioMarginProFullTransfer(): Promise<{ + msg: string; + }> +⋮---- +/** + * Fund collection by asset (`POST /sapi/v1/portfolio/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. + */ +submitPortfolioMarginProSpecificTransfer(params: { + asset: string; + amount?: number; + futureType?: 'UM' | 'CM' | 'OPTION'; + }): Promise<{ + msg: string; + }> +⋮---- +repayPortfolioMarginProBankruptcyLoan(params: { + from?: 'SPOT' | 'MARGIN'; + }): Promise<{ + tranId: number; + }> +⋮---- +getPortfolioMarginProBankruptcyLoanAmount(): Promise +⋮---- +repayFuturesNegativeBalance(): Promise<{ + msg: string; + }> +⋮---- +updateAutoRepayFuturesStatus(params: { autoRepay: string }): Promise<{ + msg: string; + }> +⋮---- +getAutoRepayFuturesStatus(): Promise<{ + autoRepay: boolean; + }> +⋮---- +getPortfolioMarginProInterestHistory( + params: GetPortfolioMarginProInterestHistoryParams, + ): Promise +⋮---- +getPortfolioMarginProSpanAccountInfo(): Promise +⋮---- +getPortfolioMarginProAccountBalance(params?: { + asset?: string; + }): Promise +⋮---- +/** + * @deprecated + * Check Simple Earn endpoints for new way of doing it + */ +mintPortfolioMarginBFUSD( + params: PMProMintBFUSDParams, + ): Promise +⋮---- +/** + * @deprecated + * Check Simple Earn endpointsfor new way of doing it + */ +redeemPortfolioMarginBFUSD(params: { + fromAsset: string; // BFUSD only + targetAsset: string; // USDT only + amount: number; + }): Promise +⋮---- +fromAsset: string; // BFUSD only +targetAsset: string; // USDT only +⋮---- +getPortfolioMarginBankruptcyLoanRepayHistory(params?: { + startTime?: number; + endTime?: number; + current?: number; + size?: number; + }): Promise<{ + total: number; + rows: PMProBankruptcyLoanRepaymentHistory[]; + }> +⋮---- +/** + * Transfer LDUSDT as collateral for all types of Portfolio Margin account + */ +transferLDUSDTPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; + amount: number; + }): Promise<{ + msg: string; + }> +⋮---- +/** + * Get transferable earn asset balance for all types of Portfolio Margin account + */ +getTransferableEarnAssetBalanceForPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; + }): Promise<{ + asset: string; + amount: string; + }> +⋮---- +/** + * + * DERIVATIVES - Futures Data - Market + * This is in mainclient because it shares the same base url + * + **/ +⋮---- +getFuturesTickLevelOrderbookDataLink( + params: GetFutureTickLevelOrderbookDataLinkParams, + ): Promise<{ + data: HistoricalDataLink[]; + }> +⋮---- +/** + * + * BLVT Endpoints + * BLVT category is possibly @deprecated, found only in old docs + **/ +⋮---- +getBlvtInfo(params?: { tokenName?: string }): Promise +⋮---- +subscribeBlvt(params: SubscribeBlvtParams): Promise +⋮---- +getBlvtSubscriptionRecord( + params: GetBlvtSubscriptionRecordParams, + ): Promise +⋮---- +redeemBlvt(params: RedeemBlvtParams): Promise +⋮---- +getBlvtRedemptionRecord( + params: GetBlvtRedemptionRecordParams, + ): Promise +⋮---- +getBlvtUserLimitInfo(params: { + tokenName?: string; + }): Promise +⋮---- +/** + * + * Pay endpoints + * Found only in old docs, possibly @deprecated + **/ +getPayTransactions(params: GetPayTradeHistoryParams): Promise +⋮---- +/** + * + * INSTITUTIONAL LOAN - Account Endpoints + * + **/ +⋮---- +getInstLoanRiskUnit( + params?: GetInstitutionalLoanRiskUnitDetailsParams, + ): Promise +⋮---- +closeInstLoanRiskUnit(): Promise +⋮---- +addInstLoanCollateralAccount( + params: AddInstitutionalLoanCollateralAccountParams, + ): Promise +⋮---- +getActiveInstLoanRiskUnits(): Promise +⋮---- +getClosedInstLoanRiskUnits( + params?: GetClosedInstitutionalLoanRiskUnitsParams, + ): Promise +⋮---- +/** + * + * INSTITUTIONAL LOAN - Trade Endpoints + * + **/ +⋮---- +getInstLoanForceLiquidationRecord( + params: GetInstitutionalLoanForceLiquidationParams, + ): Promise +/** + * + * INSTITUTIONAL LOAN - TransferEndpoints + * + **/ +⋮---- +transferInstLoanRiskUnit( + params: InstitutionalLoanRiskUnitTransferParams, + ): Promise +⋮---- +/** + * + * INSTITUTIONAL LOAN - Borrow/Repay Endpoints + * + **/ +⋮---- +getInstitutionalLoanMaxBorrowable( + params: GetInstitutionalLoanMaxBorrowableParams, + ): Promise +⋮---- +borrowInstitutionalLoan( + params: InstitutionalLoanBorrowParams, + ): Promise +⋮---- +getInstLoanInterestHistory( + params?: GetInstitutionalLoanInterestHistoryParams, + ): Promise +⋮---- +repayInstitutionalLoan( + params: InstitutionalLoanRepayParams, + ): Promise +⋮---- +getInstLoanBorrowRepayRecords( + params: GetInstitutionalLoanBorrowRepayRecordsParams, + ): Promise +⋮---- +getMarginInterestRebateBalance(): Promise +⋮---- +getMarginInterestRebateBalanceRecords( + params?: GetMarginInterestRebateBalanceRecordsParams, + ): Promise +⋮---- +/** + * + * ALPHA TRADING - Market Data + * https://developers.binance.com/docs/alpha + */ +⋮---- +getAlphaTokenList(): Promise +⋮---- +getAlphaExchangeInfo(): Promise +⋮---- +getAlphaAggTrades(params: AlphaAggTradesParams): Promise +⋮---- +getAlphaKlines(params: AlphaKlinesParams): Promise +⋮---- +getAlphaTicker(params: { symbol: string }): Promise +⋮---- +getAlphaFullDepth( + params: AlphaFullDepthParams, + ): Promise +⋮---- +/** + * + * EXCHANGE LINK - Account Endpoints + * https://developers.binance.com/docs/binance_link + */ +⋮---- +createBrokerSubAccount( + params: CreateBrokerSubAccountParams, + ): Promise +⋮---- +getBrokerSubAccount( + params: GetBrokerSubAccountParams, + ): Promise +⋮---- +enableMarginBrokerSubAccount( + params: EnableMarginBrokerSubAccountParams, + ): Promise +⋮---- +createApiKeyBrokerSubAccount( + params: CreateApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +changePermissionApiKeyBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +changeComissionBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +enableUniversalTransferApiKeyBrokerSubAccount( + params: EnableUniversalTransferApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +updateIpRestrictionForSubAccountApiKey( + params: UpdateIpRestrictionForSubApiKey, + ): Promise<{ + status: string; + ipList?: string[]; + updateTime: number; + apiKey: string; + }> +⋮---- +deleteIPRestrictionForSubAccountApiKey(params: { + subAccountId: string; + subAccountApiKey: string; + ipAddress?: string; + }): Promise<{ + subaccountId: string; + apikey: string; + ipList: string[]; + updateTime: number; + }> +⋮---- +deleteApiKeyBrokerSubAccount( + params: DeleteApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +getSubAccountBrokerIpRestriction(params: { + subAccountId: string; + subAccountApiKey: string; + }): Promise<{ + subaccountId: string; + ipRestrict: boolean; + apikey: string; + ipList: string[]; + updateTime: number; + }> +⋮---- +getApiKeyBrokerSubAccount( + params: GetApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +getBrokerInfo(): Promise +⋮---- +updateSubAccountBNBBurn(params: { + subAccountId: string; + spotBNBBurn: 'true' | 'false'; + }): Promise<{ + subAccountId: string; + spotBNBBurn: boolean; + }> +⋮---- +updateSubAccountMarginInterestBNBBurn(params: { + subAccountId: string; + interestBNBBurn: 'true' | 'false'; + }): Promise<{ + subAccountId: string; + interestBNBBurn: boolean; + }> +⋮---- +getSubAccountBNBBurnStatus(params: { subAccountId: string }): Promise<{ + subAccountId: string; + spotBNBBurn: boolean; + interestBNBBurn: boolean; + }> +⋮---- +/** + * Caution: + * The operation will delete a sub account under your brokerage master account. + * Please transfer out all funds from the sub account and delete API key of the sub account before deleting it. + * The deleted sub account CANNOT be reverted. + * The daily deletion limit for a broker Master is 20 sub accounts. + * You need to enable "trade" option for the api key which requests this endpoint. + */ +deleteBrokerSubAccount(params: { subAccountId: string }): Promise +⋮---- +/** + * + * EXCHANGE LINK - Asset Endpoints + * https://developers.binance.com/docs/binance_link + */ +⋮---- +transferBrokerSubAccount( + params: TransferBrokerSubAccountParams, + ): Promise +⋮---- +getBrokerSubAccountHistory( + params: GetBrokerSubAccountHistoryParams, + ): Promise +⋮---- +submitBrokerSubFuturesTransfer(params: { + fromId?: string; + toId?: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + asset: string; + amount: number; + clientTranId?: string; // The max length is 32 characters + }): Promise<{ + success: boolean; + txnId: string; + clientTranId?: string; + }> +⋮---- +futuresType: number; // 1: USDT Futures, 2: COIN Futures +⋮---- +clientTranId?: string; // The max length is 32 characters +⋮---- +getSubAccountFuturesTransferHistory(params: { + subAccountId: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + }): Promise +⋮---- +futuresType: number; // 1: USDT Futures, 2: COIN Futures +⋮---- +getBrokerSubDepositHistory( + params: GetSubAccountDepositHistoryParams, + ): Promise +⋮---- +getBrokerSubAccountSpotAssets( + params: QuerySubAccountSpotMarginAssetInfoParams, + ): Promise<{ + data: SubaccountBrokerSpotAsset[]; + timestamp: number; + }> +⋮---- +getSubAccountMarginAssetInfo( + params: QuerySubAccountSpotMarginAssetInfoParams, + ): Promise<{ + data: SubAccountBrokerMarginAsset[]; + timestamp: number; + }> +⋮---- +querySubAccountFuturesAssetInfo( + params: QuerySubAccountFuturesAssetInfoParams, + ): Promise<{ + data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; + timestamp: number; + }> +⋮---- +universalTransferBroker(params: UniversalTransferBrokerParams): Promise<{ + txnId: number; + clientTranId: string; + }> +⋮---- +getUniversalTransferBroker( + params: GetUniversalTransferBrokerParams, + ): Promise +⋮---- +/** + * + * EXCHANGE LINK - Fee Endpoints + * https://developers.binance.com/docs/binance_link + */ +⋮---- +updateBrokerSubAccountCommission( + params: ChangeSubAccountCommissionParams, + ): Promise +⋮---- +updateBrokerSubAccountFuturesCommission( + params: ChangeSubAccountFuturesCommissionParams, + ): Promise +⋮---- +getBrokerSubAccountFuturesCommission( + params: QuerySubAccountFuturesCommissionParams, + ): Promise +⋮---- +updateBrokerSubAccountCoinFuturesCommission( + params: ChangeSubAccountCoinFuturesCommissionParams, + ): Promise +⋮---- +getBrokerSubAccountCoinFuturesCommission( + params: QuerySubAccountCoinFuturesCommissionParams, + ): Promise +⋮---- +getBrokerSpotCommissionRebate( + params: QueryBrokerSpotCommissionRebateParams, + ): Promise +⋮---- +getBrokerFuturesCommissionRebate( + params: QueryBrokerFuturesCommissionRebateParams, + ): Promise +⋮---- +/** + * + * @deprecated + */ +// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) +getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) +⋮---- +/** + * Broker Endpoints - only on old docs + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link + */ +⋮---- +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerIfNewSpotUser(): Promise<{ + rebateWorking: boolean; + ifNewUser: boolean; + }> +⋮---- +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerSubAccountDepositHistory( + params?: GetBrokerSubAccountDepositHistoryParams, + ): Promise +⋮---- +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerUserCustomisedId(market: 'spot' | 'futures') +⋮---- +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableFuturesBrokerSubAccount( + params: EnableFuturesBrokerSubAccountParams, + ): Promise +⋮---- +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableMarginApiKeyBrokerSubAccount( + params: EnableMarginApiKeyBrokerSubAccountParams, + ): Promise +⋮---- +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewSpotOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams + | NewOrderListParams, + orderIdProperty: OrderIdProperty, + ): void +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +⋮---- +// spot +getSpotUserDataListenKey(): Promise<{ listenKey: string }> +⋮---- +keepAliveSpotUserDataListenKey(listenKey: string): Promise +⋮---- +closeSpotUserDataListenKey(listenKey: string): Promise +⋮---- +/** + * Get a cross margin user data listen key + */ +getMarginUserDataListenKey(): Promise<{ listenKey: string }> +⋮---- +keepAliveMarginUserDataListenKey(listenKey: string): Promise +⋮---- +closeMarginUserDataListenKey(listenKey: string): Promise +⋮---- +// isolated margin +getIsolatedMarginUserDataListenKey(params: { + symbol: string; + }): Promise<{ listenKey: string }> +⋮---- +keepAliveIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; + }): Promise +⋮---- +closeIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; + }): Promise +⋮---- +/** + * Get a cross margin risk data listen key + */ +getMarginRiskUserDataListenKey(): Promise<{ listenKey: string }> +⋮---- +keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise +⋮---- +closeMarginRiskUserDataListenKey(): Promise +⋮---- +/** + * Start a Margin user data stream (`POST /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. + * + * New and migrated accounts receive -3086 from + * `POST /sapi/v1/margin/listen-key` and `POST /sapi/v1/userListenToken`. + * Connect with `wss://fstream.binance.com/private/ws/`. + */ +getMarginUserDataListenKeyV2(): Promise<{ listenKey: string }> +⋮---- +/** + * Keepalive a Margin user data stream (`PUT /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. `listenKey` is a query parameter. + */ +keepAliveMarginUserDataListenKeyV2(listenKey: string): Promise +⋮---- +/** + * Close a Margin user data stream (`DELETE /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. The listen key is not a parameter. + */ +closeMarginUserDataListenKeyV2(): Promise +⋮---- +getMarginUtaUserDataListenKey(): Promise<{ listenKey: string }> +⋮---- +keepAliveMarginUtaUserDataListenKey(listenKey: string): Promise +⋮---- +closeMarginUtaUserDataListenKey(): Promise +⋮---- +/** + * Get/create margin account listenToken for the user data stream + * https://developers.binance.com/docs/margin_trading/trade-data-stream + */ +getMarginListenToken(params?: { + symbol?: string; + isIsolated?: boolean; + validity?: number; + }): Promise<{ token: string; expirationTime: number }> +⋮---- +/** + * + * DEPRECATED ENDPOINTS + * + **/ +/** + * + * BSwap Endpoints + * @deprecated as of 2024-01-19 + **/ +⋮---- +/** + * @deprecated as of 2024-01-19 + **/ +getBSwapLiquidity(params?: { poolId: number }): Promise +⋮---- +/** + * @deprecated as of 2024-01-19 + **/ +addBSwapLiquidity(params: AddBSwapLiquidityParams): Promise<{ + operationId: number; + }> +⋮---- +/** + * @deprecated as of 2024-01-19 + **/ +removeBSwapLiquidity(params: RemoveBSwapLiquidityParams): Promise<{ + operationId: number; + }> +⋮---- +/** + * @deprecated as of 2024-01-19 + **/ +getBSwapOperations( + params?: BSwapOperationsParams, + ): Promise +⋮---- +/** + * + * Savings Endpoints + * @deprecated as of 2023-06-22, now Simple Earn + **/ +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyPurchaseQuotaFlexibleProduct(params: { + productId: string; + }): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyRedemptionQuotaFlexibleProduct(params: { + productId: string; + }): Promise< + LeftDailyPurchaseQuotaFlexibleProductResponse & { + dailyQuota: string; + minRedemptionAmount: string; + } + > +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +purchaseFixedAndActivityProject(params: { + projectId: string; + lot: number; + }): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProjects( + params: FixedAndActivityProjectParams, + ): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProductPosition( + params: FixedAndActivityProjectPositionParams, + ): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLendingAccount(): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getPurchaseRecord(params: PurchaseRecordParams): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getRedemptionRecord(params: PurchaseRecordParams): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getInterestHistory(params: PurchaseRecordParams): Promise +⋮---- +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +changeFixedAndActivityPositionToDailyPosition(params: { + projectId: string; + lot: number; + positionId?: number; + }): Promise +⋮---- +/** + * + * Wallet Endpoints + * @deprecated + **/ +⋮---- +/** + * @deprecated + */ +enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + * + */ +convertBUSD(params: ConvertTransfer): Promise +⋮---- +/** + * @deprecated + */ +getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise<{ + total: number; + rows: BUSDConversionRecord[]; + }> ================ File: package.json