This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter), security check has been disabled. ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter - Security check has been disabled - content may contain sensitive information - Files are sorted by Git change count (files with more changes are at the bottom) ================================================================ Directory Structure ================================================================ .circleci/ config.yml examples/ auth/ rest-private-ed25519.md rest-private-ed25519.ts rest-private-rsa.md rest-private-rsa.ts misc/ README.md rest-spot-exchange-info.ts tracking-candles.ts REST/ rest-future-bracket-order.ts rest-portfoliomargin-private.ts rest-portfoliomargin-public.ts rest-spot-private-autoinvest.ts rest-spot-private-misc.ts rest-spot-private-trade.ts rest-spot-public.ts rest-usdm-order-sl.ts rest-usdm-order.ts rest-usdm-private-get.ts rest-usdm-public.ts rest-usdm-testnet.ts WebSockets/ deprecated-ws-public.ts ws-api-client.ts ws-api-raw-promises.ts ws-close.ts ws-proxy-socks.ts ws-public-spot-orderbook.ts ws-public-spot-trades.ts ws-public-usdm-funding.ts ws-public.ts ws-unsubscribe.ts ws-userdata-connection-safety.ts ws-userdata-listenKey-testnet.ts ws-userdata-listenkey.ts ws-userdata-README.MD ws-userdata-wsapi.ts README.md src/ types/ websockets/ ws-api-requests.ts ws-api-responses.ts ws-api.ts ws-events-formatted.ts ws-events-raw.ts ws-general.ts coin.ts futures.ts portfolio-margin.ts shared.ts spot.ts coinm-client.ts index.ts main-client.ts portfolio-client.ts usdm-client.ts websocket-api-client.ts websocket-client-legacy.ts websocket-client.ts webpack/ webpack.config.js .eslintrc.cjs .gitignore .jshintrc .npmignore .nvmrc .prettierrc CHANGELOG.md index.js jest.config.ts jsconfig.json LICENSE.md package.json README.md tea.yaml tsconfig.build.json tsconfig.json tsconfig.linting.json ================================================================ Files ================================================================ ================ File: .circleci/config.yml ================ version: 2.1 jobs: test: docker: - image: cimg/node:15.1 # resource_class: tiagosiebler/localcirunner # The resource_class feature allows configuring CPU and RAM resources for each job. Different resource classes are available for different executors. https://circleci.com/docs/2.0/configuration-reference/#resourceclass resource_class: large steps: - checkout - restore_cache: # See the configuration reference documentation for more details on using restore_cache and save_cache steps # https://circleci.com/docs/2.0/configuration-reference/?section=reference#save_cache keys: - node-deps-v1-{{ .Branch }}-{{checksum "package-lock.json"}} - run: name: install packages command: npm ci --ignore-scripts - save_cache: key: node-deps-v1-{{ .Branch }}-{{checksum "package-lock.json"}} paths: - ~/.npm - run: name: Run Build command: npm run build - run: name: Run Tests command: npm run test workflows: integrationtests: jobs: - test ================ File: examples/auth/rest-private-ed25519.ts ================ import { MainClient } from '../../src/index'; ⋮---- // or // import { MainClient } from 'binance'; ⋮---- // Received after creating a new API key with a self-generated RSA public key on binance ⋮---- // The self-generated RSA private key, this is never directly given to binance, but used to generate a signature // Note: this MUST include the "BEGIN PRIVATE KEY" header so the SDK understands this is RSA auth ================ File: examples/auth/rest-private-rsa.md ================ # RSA Authentication with Binance APIs in Node.js ## Creating RSA Keys Officially, binance recommends downloading and running a key generator from their repo. Guidance for this can be found on the binance website when trying to add a new RSA API key. However, openssl can be used to create the public & private key files using the following steps: ```bash # Generate a private key with either 2048 or 4096 bit length openssl genrsa -out rsa-private-key.pem 4096 # Generate a corresponding public key openssl rsa -in rsa-private-key.pem -pubout -out rsa-public-key.pem ``` ## Using the RSA public key to get an API key from Binance Once created, keep your **private key** completely secret! The **public** key needs to be provided to binance when creating new API credentials with the "Self-generated" option. Your public key should look something like this: ```pem -----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1uWxxOXZUaX6AeZszf4x rBsU6axA5ipwxG7VPihVgssphDrrSOD0hZqnBmtF2bvT9ee1U0XOfMn+H+J5SH+1 jgUpfioqH0L+KXl6wmLoPsadgfJz0SiQlFnKTkDXvMmecr6cdMHi2qNEx4CMc68C obvQ4Voz5qqpDwbohGtJh0p10PB//0Ejcoz0UwrTDq8BGeFmWa9pL/7h2vHtw+QU UxlnGmt98M8KkKqqvVicMK+IVtng/QlDw9ofG2kQcbBkPRaTjNI+8ULtCDH0sOkZ nT8PtGm4sEwmWH/dRWtUTWkMnUwCzuo/rWPb7WMprW2pKDTrLjUAr9M161t3Xa6W JO03K3NOxupy7ilululLY8d/WKWYDOZMvS5bPiPRUoZqlJneC0CT/2q1W6GfWzsT DCDTpgq/Ao7jTtnME9iadpwvFn0nMtNgJSrFDWPq8vKY9pRcEp/Na5qvIEOQIFnp /kIDPuMf+LZwO8lGFO3jnndY+62835rm7t6ZNM3NLoNCarvUCEasobgDJHw7x7c1 fW/OxYtLrWGdMpsP0MewgGJZXcT7mvlBjQ+JWLoyIc5rYMIDw9RLWUPnrlRCxvPp sD9kDX7eaipdoik5yLyMaRvd16Vt9Bck/9pbSHazm41m/nd4KCZeGdsvrAA2beww zFWQQV9EX6/VLBgbnGTsMe0CAwEAAQ== -----END PUBLIC KEY----- ``` Submit this in the "Upload public key" form, shown when creating a new API key on binance and choosing the "self-generated" option. Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. After using the public key to create a new API key, you will be given an API Key such as the following: ``` SIHqWcDeRoj6gkOjLjQh1dnV1CD7IgwQTfL4LVa8wu04zNTYVSmJBIHsjQjgwWqt ``` This is the first piece, used as the "apiKey" in the [rest-private-rsa.ts](./rest-private-rsa.ts) example. ## Using the RSA private key for RSA authentication with binance APIs in Node.js Your private key, if generated with the above steps, should look something like this (but with much more text): ```pem -----BEGIN RSA PRIVATE KEY----- uayyi6wFTaNeG1/WCqhrowj2kCx8eB6NDZYl+OS9ZI9WC q/44iFERNuP0TXvQx8tgvSZXyu4/G618QzKh0Ii1uAATt2upa8dp1uGl2U7EqBE8 p5y4pPzJuwvB3j6LQON20u2Wpbg8PQZACMfKym7lYDO+9MloK/gAQpyeYJzbw92C YE/ymq4JVjCMCQKCAQEA4/X0I9TO8vT0D0l83o693QA3C09uSZ6j9Obx5UrtDnA9 sMkkRoe+R/vvIpVDzukMEEOmCuxbcdPoniVUKlTooK0Llo6JJ1l8CdFzQsOR97Pe csB6pxkLLH2qHx05xPBy4PyoB -----END RSA PRIVATE KEY----- ``` This is your secret, you should never share this with anyone, not even binance! Treat this like a password. As part of this authentication process, your private key is used to generate a signature (using `RSA-SHA256`). This SDK handles this process automatically for you. RSA authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. Note: Binance also supports Ed25519 authentication. If your "secret" matches the following condition, the SDK will revert to to Ed25519 authentication: - Contains "PRIVATE KEY" as a header - Does NOT contain "RSA PRIVATE KEY" as a header. From here, simply use the key provided by binance as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. Based on the above example, the following would prepare the main REST client using the above credentials: ```typescript const api_key = `SIHqWcDeRoj6gkOjLjQh1dnV1CD7IgwQTfL4LVa8wu04zNTYVSmJBIHsjQjgwWqt`; const rsaPrivateKey = ` -----BEGIN RSA PRIVATE KEY----- uayyi6wFTaNeG1/WCqhrowj2kCx8eB6NDZYl+OS9ZI9WC q/44iFERNuP0TXvQx8tgvSZXyu4/G618QzKh0Ii1uAATt2upa8dp1uGl2U7EqBE8 p5y4pPzJuwvB3j6LQON20u2Wpbg8PQZACMfKym7lYDO+9MloK/gAQpyeYJzbw92C YE/ymq4JVjCMCQKCAQEA4/X0I9TO8vT0D0l83o693QA3C09uSZ6j9Obx5UrtDnA9 sMkkRoe+R/vvIpVDzukMEEOmCuxbcdPoniVUKlTooK0Llo6JJ1l8CdFzQsOR97Pe csB6pxkLLH2qHx05xPBy4PyoB -----END RSA PRIVATE KEY----- `; const client = new MainClient({ api_key: api_key, api_secret: rsaPrivateKey, beautifyResponses: true, }); ``` For a complete example, refer to the [rest-private-rsa.ts](./rest-private-rsa.ts) file on GitHub. ================ File: examples/misc/README.md ================ # Utilities These are miscellaneous utilities used by some of the examples in this repo. These do not represent best practices and are merely for easier demonstrations. ================ File: examples/misc/rest-spot-exchange-info.ts ================ import { ExchangeInfo, MainClient, numberInString, roundToStepSize, roundToTickSize, } from '../../src'; // from 'binance'; ⋮---- } from '../../src'; // from 'binance'; ⋮---- // or // import { MainClient } from 'binance'; ⋮---- // Optional (default: false) - when true, response strings are parsed to floats (only for known keys). // beautifyResponses: true, ⋮---- interface SymbolInfo { tickSize: numberInString; qtyStepSize: numberInString; minOrderQty: numberInString; maxOrderQty: numberInString; maxMarketQty: numberInString; maxNumOfOrders: number; minNotional: numberInString; maxNotional: numberInString; maxBasePrecisionDecimals: number; maxQuotePrecisionDecimals: number; } ⋮---- // Get full exchange info so we can cache it and use it for other functions without making request every time async function fetchExchangeInfo() ⋮---- async function getSymbolInfo( exchangeInfo: ExchangeInfo, symbol: string, ): Promise ⋮---- // Find the symbol information once ⋮---- // console.log(symbolInfo); ⋮---- // Extract filters from the symbol info ⋮---- /** * Validates and formats an order based on symbol constraints */ function formatOrderParams( symbol: string, price: number, quantity: number, symbolInfo: any, ): ⋮---- // Check if price is within allowed range ⋮---- // Check if quantity is within allowed range ⋮---- // Check notional value (price * quantity) ⋮---- // Format price and quantity according to exchange requirements ⋮---- // Example usage async function testSymbolUtils() ⋮---- // Test price formatting ⋮---- // Test quantity formatting ⋮---- // Test full order formatting ⋮---- // example how to use the order params ================ File: examples/misc/tracking-candles.ts ================ import { EventEmitter } from 'events'; ⋮---- import { DefaultLogger, isWsFormattedKline, KlineInterval, USDMClient, WebsocketClient, } from '../../src'; ⋮---- // or, with the npm package /* import { WebsocketClient, isWsFormattedKline, USDMClient, KlineInterval, } from 'binance'; */ ⋮---- /** * This elaborate example serves the following key functions: * - Connect to various candle websockets to receive realtime candle events (update open candle & append closed candle) * - Backfill some candles using the REST API * - Once backfilled, start processing candle events (update & append in-memory, depending if candle closed or not) * - Keep the candle stores trimmed, so we never store more than `maxStoredCandles` candles per symbol * - When a connection opens or reconnects, the backfill is executed again to ensure there are no gaps * * The "onCandleClosed()" function is where you would run custom logic with a dataset of candles (e.g. run some indicator calculations) */ ⋮---- /** * Configuration logic */ ⋮---- /** * Data stores */ ⋮---- interface EngineCandle { open: number; close: number; high: number; low: number; volume: number; openTime: number; openDt: Date; closeTime: number; closeDt: Date; } ⋮---- /** * The shape of the events produced by the candle store. * All the info needed to query the candle store for all candles, after receiving a candle closed event */ interface CandleStoreEvent { symbol: string; interval: string; } ⋮---- /** These are the events produced by the candle store, which can be used to implement this abstraction layer */ export declare interface CandleEmitter extends EventEmitter { on(event: 'candleClose', listener: (event: CandleStoreEvent) => void): this; on(event: 'candleUpdate', listener: (event: CandleStoreEvent) => void): this; } ⋮---- on(event: 'candleClose', listener: (event: CandleStoreEvent) on(event: 'candleUpdate', listener: (event: CandleStoreEvent) ⋮---- /** Some options to configure the behaviour of the candle store */ interface CandleStoreOptions { /** Keep a ceiling on how many candles are stored, before old ones are discarded (prevent the store from growing forever into infinity) */ maxStoredCandles?: number; eventEmitter: EventEmitter; } ⋮---- /** Keep a ceiling on how many candles are stored, before old ones are discarded (prevent the store from growing forever into infinity) */ ⋮---- /** /** * A general store for symbol/interval candles, including handling the currently open candle, with some utility methods */ export class CandleStore ⋮---- // Closed candles are stored as an array of candles per interval in this store. // This is essentially an object acting as a key/value store (key: interval, value: candle array) ⋮---- // Open candles are kept separate from the closed candles, also in a key/value store (key: interval, value: current open candle) ⋮---- constructor(symbol: string, options: CandleStoreOptions) ⋮---- // super(); ⋮---- /** * Overwrite the current candle store, e.g. after backfilling. Candles are sorted automatically before overwriting the store */ public setCandles(candles: EngineCandle[], interval: string): void ⋮---- public setOpenCandle(candle: EngineCandle | null, interval: string): void ⋮---- /** * Provide a candle event to the store for processing (e.g candle closed vs open candle updated). * - Closed candles are appended to the array. * - Open candles are tracked separately and only (optionally) used during the getCandles(true) query. */ public processCandleEvent( candle: EngineCandle, interval: string, isCandleClosed: boolean, ): void ⋮---- // console.log(this.symbol, `Open candle update`); ⋮---- // console.log(`Emit candle closed evt`, evt); ⋮---- private initCandleStores(interval: string) ⋮---- /** * Execute a store-trim. This is called automatically during candle-closed events, but * can be called manually (e.g. after backfilling) to ensure the store only keeps the most recent `maxStoredCandles`. */ public trimExcessCandles(interval: string): void ⋮---- // This mutates the closed candle store to remove the first x elements ⋮---- /** * Query all candles in the store for an interval. * Optionally append the currently open candle to the end of the array. */ public getCandles( interval: string, includeOpenCandle?: boolean, ): EngineCandle[] ⋮---- // check last candle has same open time as open candle, just in case ⋮---- // Include open candle at end of array ⋮---- /** * A key value store for all symbols & intervals * * // All CandleStores for that symbol (one per symbol, supports many intervals in one store) * const symbolCandles = allCandleStores[symbol]; * */ ⋮---- /** * Get a candle store for a symbol. * Since a missing candle store is automatically initialised, you can assume this will always return a candle store. */ function getCandleStore(symbol: string): CandleStore ⋮---- // Hook up event consumers on the shared event emitter ⋮---- // eventEmitter.on('candleUpdate', (e) => { // console.log('candle updated', { // dt: new Date(), // symbol: e.symbol, // interval: e.interval, // }); // }); ⋮---- /** Ensure a candle store exists for this symbol & attach consumers to the store */ function initCandleStoreIfMissing(symbol: string): void ⋮---- // Inject your own event emitter and initialise one candle store per symbol (it supports multiple intervals) ⋮---- /** * Websocket Listeners */ ⋮---- // console.log('kline received ', { candle, isCandleClosed }); ⋮---- // const candleStore: CandleStore = allIntervalCandleStores[symbol][interval]; ⋮---- // response to command sent via WS stream (e.g. subscription confirmation) // this will automatically trigger a backfill for that symbol. ⋮---- // empty response result === success ⋮---- // btcusdt@kline_1m -> btcusdt, kline_1m ⋮---- // kline_1m -> kline, 1m // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- /** * Execute a 1-page backfill (1000 candles). Called automatically when a connection opens OR reconnects. */ async function backfillCandles( symbol: string, interval: KlineInterval, ): Promise ⋮---- // Map to a standard candle structure ⋮---- // Last candle might not be closed, so filter that out (ignore any candles with close time in the future) ⋮---- // const candleStore: CandleStore = allIntervalCandleStores[symbol][interval]; ⋮---- // Overwrite the current candles in the store and remove excess candles ⋮---- /** * Bootstrap a connection per symbol & timeframe. Backfill will automatically trigger when the connection opens successfully. * Note: this will spawn one websocket connection per symbol per timeframe. For complex cases, this may create too many connections. */ ⋮---- // Open a websocket to start consuming candle events ⋮---- function onCandleClosed(symbol: string, interval: string): void ⋮---- // When a candle closes, fetch all closed candles from the store for that symbol, e.g. to calculate some indicators ================ File: examples/REST/rest-future-bracket-order.ts ================ import { NewFuturesOrderParams, USDMClient } from '../../src/index'; ⋮---- // submit a 1:1 bracket market buy order with market entry order ⋮---- // TODO: check balance and do other validations ⋮---- // create three orders // 1. entry order (GTC), // 2. take profit order (GTE_GTC), // 3. stop loss order (GTE_GTC) ================ File: examples/REST/rest-portfoliomargin-private.ts ================ import { PortfolioClient } from '../../src/index'; ⋮---- // or // import { PortfolioClient } from 'binance'; ⋮---- // const newOrderRes = await client.submitNewUMOrder({ // symbol: 'BTCUSDT', // side: 'BUY', // type: 'MARKET', // quantity: '10', // }); ⋮---- // console.log('new order res: ', newOrderRes); ================ File: examples/REST/rest-portfoliomargin-public.ts ================ import { PortfolioClient } from '../../src/index'; ⋮---- // or // import { PortfolioClient } from 'binance'; ⋮---- // const serverTime = await client.getServerTime(); // console.log('serverTime: ', serverTime); ================ File: examples/REST/rest-spot-private-autoinvest.ts ================ import { MainClient } from '../../src/index'; ⋮---- // or // import { MainClient } from 'binance'; ================ File: examples/REST/rest-spot-private-misc.ts ================ import { MainClient } from '../../src/index'; ⋮---- // or // import { MainClient } from 'binance'; ================ File: examples/REST/rest-spot-private-trade.ts ================ import { MainClient, NewSpotOrderParams, OrderResponseFull, SymbolPrice, } from '../../src/index'; ⋮---- // or // import { MainClient } from 'binance'; ⋮---- const entryAmountPercent = 50; // trigger trade with 50% ⋮---- const assetDecimalPlaces = 4; // get this from exchange info, it varies per asset ⋮---- // method to trim down to decimal. function trimToDecimalPlaces(number: number, precision: number): number ⋮---- /** * This is a very silly demonstration on placing market orders using various parts of the module. * By default it will use 50% of your available USDT balance to buy BTC and sell it again. */ ⋮---- /** * Get available balance */ ⋮---- // console.log('USDT balance object: ', usdtBal); ⋮---- /** * Get last asset price */ ⋮---- /** * Calculate and submit buy amount */ ⋮---- /** * ACK = confirmation of order acceptance (no placement/fill information) -> OrderResponseACK * RESULT = fill state -> OrderResponseResult * FULL = fill state + detail on fills and other detail -> OrderResponseFull */ ⋮---- /** * Process bought fills and submit sell amount */ ================ File: examples/REST/rest-spot-public.ts ================ import { MainClient } from '../../src/index'; ⋮---- // or // import { MainClient } from 'binance'; ⋮---- // Optional (default: false) - when true, response strings are parsed to floats (only for known keys). // beautifyResponses: true, ⋮---- // console.log( // 'getAvgPrice: ', // await client.getAvgPrice({ symbol: 'BTCUSDT' }), // ); // console.log( // 'getExchangeInfo: ', // JSON.stringify(await client.getExchangeInfo(), null, 2), // ); ================ File: examples/REST/rest-usdm-order-sl.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { USDMClient } from '../../src/index'; ⋮---- // or // import { USDMClient } from 'binance'; ⋮---- async function start() ⋮---- // ### This is for Hedge Mode Only ### // assuming you currently have a open position, and you want to modify the SL order. ⋮---- /** * first we get all long and short positions status * the result of this method in hedge mode is array of two objects * first index for LONG and second index for SHORT */ ⋮---- // if longAmount is bigger than 0 means we have open long position and if shortAmount is below 0 means we have open short position ⋮---- // if we have any open position then we continue ⋮---- // we get ourstop loss here ⋮---- // we want to modify our long position SL here ⋮---- // we get the StopLoss order which is realted to long ⋮---- // if it exists, cancel it. ⋮---- // creating SL order ⋮---- side: 'SELL', // the action of order, means this order will sell which is sl for long position positionSide: 'LONG', // based on the headge mode we either LONG or SHORT, here we are doing it for our long pos ⋮---- closePosition: 'true', // this is here because we don't have the position quantity value, and it means closee all quantity stopPrice: parseFloat((markPrice * 0.99).toFixed(3)), // set sl price 1% below current price ================ File: examples/REST/rest-usdm-order.ts ================ import { USDMClient } from '../../src/index'; ⋮---- // or // import { USDMClient } from 'binance'; ⋮---- async function start() ⋮---- // To open a short position - if you don't have a position yet, and your account is set to one-way mode, just place a sell order to open a short position ⋮---- // newOrderRespType: 'FULL', ================ File: examples/REST/rest-usdm-private-get.ts ================ import { USDMClient } from '../../src/index'; // import axios from 'axios'; ⋮---- // or // import { USDMClient } from 'binance'; ================ File: examples/REST/rest-usdm-public.ts ================ import { USDMClient } from '../../src'; ⋮---- // keepAlive: true, // ... any other params, ================ File: examples/REST/rest-usdm-testnet.ts ================ import { USDMClient } from '../../src/index'; ⋮---- // or // import { USDMClient } from 'binance'; ⋮---- /** * Note: testnet is NOT a good place to test strategy performance. * * For more information and guidance, refer to: * https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets */ ⋮---- async function start() ⋮---- // To open a short position - if you don't have a position yet, and your account is set to one-way mode, just place a sell order to open a short position ⋮---- // newOrderRespType: 'FULL', ================ File: examples/WebSockets/deprecated-ws-public.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { DefaultLogger, isWsFormatted24hrTicker, isWsFormatted24hrTickerArray, isWsFormattedKline, isWsFormattedRollingWindowTickerArray, WebsocketClientV1, } from '../../src/index'; ⋮---- // or, with the npm package /* import { WebsocketClientV1, DefaultLogger, isWsFormatted24hrTicker, isWsFormattedKline, } from 'binance'; */ ⋮---- /** * * This example demonstrates basic usage of the previous WebsocketClientV1, which should be considered deprecated. * */ ⋮---- // api_key: key, // api_secret: secret, ⋮---- // manually handle events and narrow down to desired types ⋮---- // or use a supplied type guard (if available - not all type guards have been written yet) ⋮---- // console.log('log formattedMessage: ', JSON.stringify(data[0], null, 2)); ⋮---- // response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- // wsClient.subscribeCoinIndexPrice(coinMSymbol); // wsClient.subscribeSpotAllBookTickers(); ⋮---- // wsClient.subscribeSpotKline(market, '1m'); // wsClient.subscribeKlines(market, '1m', 'usdm'); // wsClient.subscribeMarkPrice(market, 'usdm'); // wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); // wsClient.subscribeAllMarketMarkPrice('usdm'); // wsClient.subscribeAllMarketMarkPrice('coinm'); // wsClient.subscribeKlines(market, '1m', 'usdm'); // wsClient.subscribeContinuousContractKlines(market, 'perpetual', '1m', 'usdm'); // wsClient.subscribeIndexKlines(coinMSymbol, '1m'); // wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); // wsClient.subscribeSymbolMini24hrTicker(market, 'usdm'); // wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); // wsClient.subscribeSymbolMini24hrTicker(market, 'spot'); // wsClient.subscribeSymbol24hrTicker(market, 'usdm'); // wsClient.subscribeSymbol24hrTicker(market, 'coinm'); // wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'spot'); // wsClient.subscribeAllMini24hrTickers('usdm'); // wsClient.subscribeAllMini24hrTickers('coinm'); // wsClient.subscribeAllMini24hrTickers('spot'); // wsClient.subscribeAll24hrTickers('usdm'); // wsClient.subscribeAll24hrTickers('coinm'); // wsClient.subscribeAll24hrTickers('spot'); // wsClient.subscribeAllLiquidationOrders('usdm'); // wsClient.subscribeAllLiquidationOrders('coinm'); // wsClient.subscribeSpotSymbol24hrTicker(market); // wsClient.subscribeAggregateTrades(market, 'usdm'); // wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); ⋮---- // wsClient.subscribeAllRollingWindowTickers('spot', '1d'); ================ File: examples/WebSockets/ws-proxy-socks.ts ================ /** * Minimal example for using a socks proxy with the ws client, extracted from https://github.com/tiagosiebler/binance/pull/319 */ import { WebsocketClient } from '../../src/index'; ⋮---- // or // import { WebsocketClient } from 'binance'; ================ File: examples/WebSockets/ws-public-spot-orderbook.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-unused-vars */ import { DefaultLogger, isWsPartialBookDepthEventFormatted, WebsocketClient, WsMessagePartialBookDepthEventFormatted, } from '../../src/index'; ⋮---- // or, with the npm package /* import { WebsocketClient, DefaultLogger, isWsFormattedTrade, } from 'binance'; */ ⋮---- // trace: () => {}, ⋮---- /** * Simple example for receiving depth snapshots from spot orderbooks */ ⋮---- // Request subscription to the following symbol events: ⋮---- // const symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT']; ⋮---- // Loop through symbols ⋮---- // The old way, convenient but unnecessary: // wsClient.subscribePartialBookDepths(symbol, levels, 1000, 'spot'); ⋮---- // Manually build a topic matching the structure expected by binance: // btcusdt@depth20@1000ms ⋮---- // Request subscribe for these topics in the main product group (spot markets are under "main") ================ File: examples/WebSockets/ws-public-spot-trades.ts ================ import { DefaultLogger, isWsFormattedTrade, WebsocketClient, } from '../../src/index'; ⋮---- // or, with the npm package /* import { WebsocketClient, DefaultLogger, isWsFormattedTrade, } from 'binance'; */ ⋮---- // trace: () => {}, ⋮---- // Request subscription to the following symbol trade events: ⋮---- // Loop through symbols ================ File: examples/WebSockets/ws-public-usdm-funding.ts ================ import { DefaultLogger, isWsFormattedMarkPriceUpdateArray, WebsocketClient, } from '../../src/index'; ⋮---- // or, with the npm package /* import { WebsocketClient, DefaultLogger, isWsFormattedMarkPriceUpdateArray, } from 'binance'; */ ⋮---- // trace: () => {}, ⋮---- // api_key: key, // api_secret: secret, ⋮---- // value is in decimal, multiply by 100 to get percent value ⋮---- // log table sorted alphabetically by symbol ⋮---- // response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ================ File: examples/WebSockets/ws-unsubscribe.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { WebsocketClient } from '../../src/index'; ⋮---- // or, with the npm package /* import { WebsocketClient, DefaultLogger, isWsFormatted24hrTicker, isWsFormattedKline, } from 'binance'; */ ⋮---- /** * * A simple demonstration on how to unsubscribe from one or more topics. * */ ⋮---- // Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- /** * The Websocket Client will automatically manage connectivity and active topics/subscriptions for you. * * Simply call wsClient.subscribe(topic, wsKey) as many times as you want, with or without an array. */ ⋮---- // Aggregate Trade Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#aggregate-trade-streams ⋮---- // Kline/Candlestick Streams for UTC // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc ⋮---- // Individual Symbol Mini Ticker Stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream ⋮---- // Individual Symbol Ticker Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-ticker-streams ⋮---- // Individual Symbol Rolling Window Statistics Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-rolling-window-statistics-streams ⋮---- // Average Price // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price ⋮---- /** * Subscribe to each available type of spot market topic, the new way */ ⋮---- // 5 seconds later, unsubscribe from almost all topics except avg price ================ File: examples/WebSockets/ws-userdata-connection-safety.ts ================ import { DefaultLogger, isWsFormattedFuturesUserDataEvent, isWsFormattedSpotUserDataEvent, isWsFormattedSpotUserDataExecutionReport, isWsFormattedUserDataEvent, WebsocketClient, WsUserDataEvents, } from '../../src/index'; ⋮---- // or // import { DefaultLogger, WebsocketClient } from 'binance'; ⋮---- /** * This extended example for using the user data stream demonstrates one way to handle failures in the first connection attempt of the user data stream. * In most cases this is overkill! */ ⋮---- // optionally block some silly logs from showing in the logger ⋮---- // Optional, hook and customise logging behavior ⋮---- // wsClient.on('message', (data) => { // console.log('raw message received ', JSON.stringify(data, null, 2)); // }); ⋮---- function onUserDataEvent(data: WsUserDataEvents) ⋮---- // the market denotes which API category it came from // if (data.wsMarket.includes('spot')) { ⋮---- // or use a type guard, if one exists (PRs welcome) ⋮---- // The wsKey can be parsed to determine the type of message (what websocket it came from) // if (!Array.isArray(data) && data.wsKey.includes('userData')) { // return onUserDataEvent(data); // } ⋮---- // or use a type guard if available ⋮---- // response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- // Note: manually re-subscribing like this may only be needed if the FIRST user data connection attempt failed // Capture exceptions using the error event, and handle this. ⋮---- // wsClient.subscribeMarginUserDataStream(); // wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); ================ File: src/types/websockets/ws-general.ts ================ import { AxiosRequestConfig } from 'axios'; 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'; ⋮---- export interface WsSharedBase { wsMarket: WsMarket; wsKey: WsKey; streamName: string; } ⋮---- export interface WsResponse { type: 'message'; data: { result: boolean | string[] | null; id: number; isWSAPIResponse: boolean; wsKey: WsKey; }; } ⋮---- // Same as inverse futures export type WsPublicInverseTopic = | 'orderBookL2_25' | 'orderBookL2_200' | 'trade' | 'insurance' | 'instrument_info' | 'klineV2'; ⋮---- export type WsPublicUSDTPerpTopic = | 'orderBookL2_25' | 'orderBookL2_200' | 'trade' | 'insurance' | 'instrument_info' | 'kline'; ⋮---- export type WsPublicSpotV1Topic = | 'trade' | 'realtimes' | 'kline' | 'depth' | 'mergedDepth' | 'diffDepth'; ⋮---- export type WsPublicSpotV2Topic = | 'depth' | 'kline' | 'trade' | 'bookTicker' | 'realtimes'; ⋮---- export type WsPublicTopics = | WsPublicInverseTopic | WsPublicUSDTPerpTopic | WsPublicSpotV1Topic | WsPublicSpotV2Topic | string; ⋮---- // Same as inverse futures export type WsPrivateInverseTopic = | 'position' | 'execution' | 'order' | 'stop_order'; ⋮---- export type WsPrivateUSDTPerpTopic = | 'position' | 'execution' | 'order' | 'stop_order' | 'wallet'; ⋮---- export type WsPrivateSpotTopic = | 'outboundAccountInfo' | 'executionReport' | 'ticketInfo'; ⋮---- export type WsPrivateTopic = | WsPrivateInverseTopic | WsPrivateUSDTPerpTopic | WsPrivateSpotTopic | string; ⋮---- export type WsTopic = WsPublicTopics | WsPrivateTopic; ⋮---- export interface WSClientConfigurableOptions { /** Your API key */ api_key?: string; /** Your API secret */ api_secret?: string; beautify?: boolean; /** * If true, log a warning if the beautifier is missing anything for an event */ beautifyWarnIfMissing?: boolean; /** * Set to `true` to connect to Binance's testnet environment. * * Notes: * - Not all WebSocket categories support testnet. * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets */ testnet?: boolean; /** 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[]; agent?: any; }; wsUrl?: string; /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ customSignMessageFn?: (message: string, secret: string) => Promise; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** * If true, log a warning if the beautifier is missing anything for an event */ ⋮---- /** * Set to `true` to connect to Binance's testnet environment. * * Notes: * - Not all WebSocket categories support testnet. * - If testing a strategy, this is not recommended. Testnet market data is very different from real market conditions. More guidance here: https://github.com/tiagosiebler/awesome-crypto-examples/wiki/CEX-Testnets */ ⋮---- /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- // Disable ping/pong ws heartbeat mechanism (not recommended) ⋮---- /** How often to check if the connection is alive */ ⋮---- /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- /** Delay in milliseconds before respawning the connection */ ⋮---- /** * 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. */ ⋮---- /** * 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; authPrivateRequests: 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; } ⋮---- export interface FundingRate { symbol: string; adjustedFundingRateCap: string; adjustedFundingRateFloor: string; fundingIntervalHours: number; disclaimer: boolean; } ⋮---- export interface GetClassicPortfolioMarginNotionalLimitParams { symbol?: string; pair?: string; } ⋮---- export interface ClassicPortfolioMarginNotionalLimit { symbol: string; pair: string; notionalLimit: string; } ⋮---- export interface ClassicPortfolioMarginAccount { maxWithdrawAmountUSD: string; asset: string; maxWithdrawAmount: string; } ⋮---- export interface FuturesTransactionHistoryDownloadLink { downloadId: string; status: string; url: string; notified: boolean; expirationTimestamp: number; isExpired: boolean | null; } ================ File: src/types/portfolio-margin.ts ================ // Enums export type PMStrategyType = | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET' | 'TRAILING_STOP_MARKET'; ⋮---- export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- export type PMPriceMatch = | 'NONE' | 'OPPONENT' | 'OPPONENT_5' | 'OPPONENT_10' | 'OPPONENT_20' | 'QUEUE' | 'QUEUE_5' | 'QUEUE_10' | 'QUEUE_20'; ⋮---- export type PMSelfTradePreventionMode = | 'NONE' | 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH'; ⋮---- export type PMMarginOrderType = | 'LIMIT' | 'MARKET' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT'; ⋮---- export type PMMarginSideEffectType = | 'NO_SIDE_EFFECT' | 'MARGIN_BUY' | 'AUTO_REPAY' | 'AUTO_BORROW_REPAY'; ⋮---- export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; ⋮---- export interface NewPortfolioUMOrderReq { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode type: 'LIMIT' | 'MARKET'; timeInForce?: string; quantity?: string; reduceOnly?: boolean; // Cannot be sent in Hedge Mode price?: string; newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders selfTradePreventionMode?: PMSelfTradePreventionMode; goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode ⋮---- reduceOnly?: boolean; // Cannot be sent in Hedge Mode ⋮---- newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders ⋮---- goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- export interface NewPortfolioUMOrderResponse { clientOrderId: string; cumQty: string; cumQuote: string; executedQty: string; orderId: number; avgPrice: string; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; status: string; symbol: string; timeInForce: string; type: 'LIMIT' | 'MARKET'; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate?: number; updateTime: number; priceMatch: PMPriceMatch; } ⋮---- export interface NewPortfolioUMConditionalOrderReq { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; strategyType: PMStrategyType; timeInForce?: string; quantity?: string; reduceOnly?: boolean; price?: string; workingType?: PMWorkingType; priceProtect?: boolean; newClientStrategyId?: string; stopPrice?: string; activationPrice?: string; callbackRate?: string; priceMatch?: PMPriceMatch; selfTradePreventionMode?: PMSelfTradePreventionMode; goodTillDate?: number; } ⋮---- export interface NewPortfolioConditionalOrderResponse { newClientStrategyId: string; strategyId: number; strategyStatus: string; strategyType: PMStrategyType; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; stopPrice?: string; symbol: string; timeInForce: string; activatePrice?: string; priceRate?: string; bookTime: number; updateTime: number; workingType: PMWorkingType; priceProtect: boolean; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate?: number; priceMatch: PMPriceMatch; } ⋮---- export interface NewPortfolioCMOrderReq { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; type: 'LIMIT' | 'MARKET'; timeInForce?: string; quantity?: string; reduceOnly?: boolean; price?: string; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT'; } ⋮---- export interface NewPortfolioCMOrderResponse { clientOrderId: string; cumQty: string; cumBase: string; executedQty: string; orderId: number; avgPrice: string; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; status: string; symbol: string; pair: string; timeInForce: string; type: 'LIMIT' | 'MARKET'; updateTime: number; } ⋮---- export interface NewPortfolioCMConditionalOrderReq { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; strategyType: PMStrategyType; timeInForce?: string; quantity?: string; reduceOnly?: boolean; price?: string; workingType?: PMWorkingType; priceProtect?: boolean; newClientStrategyId?: string; stopPrice?: string; activationPrice?: string; callbackRate?: string; } ⋮---- export interface NewPortfolioCMConditionalOrderResponse { newClientStrategyId: string; strategyId: number; strategyStatus: string; strategyType: PMStrategyType; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; stopPrice?: string; symbol: string; pair: string; timeInForce: string; activatePrice?: string; priceRate?: string; bookTime: number; updateTime: number; workingType: PMWorkingType; priceProtect: boolean; } ⋮---- export interface MarginOrderFill { price: string; qty: string; commission: string; commissionAsset: string; } ⋮---- export interface NewPortfolioMarginOrderReq { symbol: string; side: 'BUY' | 'SELL'; type: PMMarginOrderType; quantity?: string; quoteOrderQty?: string; price?: string; stopPrice?: string; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; icebergQty?: string; sideEffectType?: PMMarginSideEffectType; timeInForce?: string; selfTradePreventionMode?: PMSelfTradePreventionMode; autoRepayAtCancel?: boolean; } ⋮---- export interface NewPortfolioMarginOrderResponse { symbol: string; orderId: number; clientOrderId: string; transactTime: number; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: PMMarginOrderType; side: 'BUY' | 'SELL'; marginBuyBorrowAmount?: string; marginBuyBorrowAsset?: string; fills: MarginOrderFill[]; } ⋮---- export interface PortfolioMarginOCOOrder { symbol: string; orderId: number; clientOrderId: string; } ⋮---- export interface PortfolioMarginOCOOrderReport { symbol: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: string; side: 'BUY' | 'SELL'; stopPrice?: string; } ⋮---- export interface NewPortfolioMarginOCOReq { symbol: string; listClientOrderId?: string; side: 'BUY' | 'SELL'; quantity: string; limitClientOrderId?: string; price: string; limitIcebergQty?: string; stopClientOrderId?: string; stopPrice: string; stopLimitPrice?: string; stopIcebergQty?: string; stopLimitTimeInForce?: 'GTC' | 'FOK' | 'IOC'; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; sideEffectType?: PMMarginSideEffectType; } ⋮---- export interface NewPortfolioMarginOCOResponse { orderListId: number; contingencyType: 'OCO'; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; marginBuyBorrowAmount?: string; marginBuyBorrowAsset?: string; orders: PortfolioMarginOCOOrder[]; orderReports: PortfolioMarginOCOOrderReport[]; } ⋮---- // Add new interfaces for canceling UM orders export interface CancelPortfolioUMOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface PortfolioUMCancelOrderResponse { avgPrice: string; clientOrderId: string; cumQty: string; cumQuote: string; executedQty: string; orderId: number; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; status: string; symbol: string; timeInForce: string; type: 'LIMIT' | 'MARKET'; updateTime: number; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate: number; priceMatch: PMPriceMatch; } ⋮---- export interface CancelPortfolioUMConditionalOrderReq { symbol: string; strategyId?: number; newClientStrategyId?: string; } ⋮---- export interface PortfolioUMCancelConditionalOrderResponse { newClientStrategyId: string; strategyId: number; strategyStatus: string; strategyType: PMStrategyType; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; stopPrice?: string; symbol: string; timeInForce: string; activatePrice?: string; priceRate?: string; bookTime: number; updateTime: number; workingType: PMWorkingType; priceProtect: boolean; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate: number; priceMatch: PMPriceMatch; } ⋮---- export interface CancelPortfolioCMOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface PortfolioCMCancelOrderResponse { avgPrice: string; clientOrderId: string; cumQty: string; cumBase: string; executedQty: string; orderId: number; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; status: string; symbol: string; pair: string; timeInForce: string; type: 'LIMIT' | 'MARKET'; updateTime: number; } ⋮---- export interface CancelPortfolioCMConditionalOrderReq { symbol: string; strategyId?: number; newClientStrategyId?: string; } ⋮---- export interface PortfolioCMCancelConditionalOrderResponse { newClientStrategyId: string; strategyId: number; strategyStatus: string; strategyType: PMStrategyType; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; stopPrice?: string; symbol: string; timeInForce: string; activatePrice?: string; priceRate?: string; bookTime: number; updateTime: number; workingType: PMWorkingType; priceProtect: boolean; } ⋮---- export interface CancelPortfolioMarginOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; newClientOrderId?: string; } ⋮---- export interface PortfolioMarginCancelOrderResponse { symbol: string; orderId: number; origClientOrderId: string; clientOrderId: string; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: PMMarginOrderType; side: 'BUY' | 'SELL'; } ⋮---- export interface CancelPortfolioMarginOCOReq { symbol: string; orderListId?: number; listClientOrderId?: string; newClientOrderId?: string; } ⋮---- export interface PortfolioMarginOCOCancelOrder { symbol: string; orderId: number; clientOrderId: string; } ⋮---- export interface PortfolioMarginOCOCancelOrderReport { symbol: string; origClientOrderId: string; orderId: number; orderListId: number; clientOrderId: string; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: 'STOP_LOSS_LIMIT' | 'LIMIT_MAKER'; side: 'BUY' | 'SELL'; stopPrice?: string; } ⋮---- export interface PortfolioMarginOCOCancelResponse { orderListId: number; contingencyType: 'OCO'; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: PortfolioMarginOCOCancelOrder[]; orderReports: PortfolioMarginOCOCancelOrderReport[]; } ⋮---- export interface PortfolioMarginCancelAllOrdersOrderReport { symbol: string; origClientOrderId: string; orderId: number; orderListId: number; clientOrderId: string; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: PMMarginOrderType; side: 'BUY' | 'SELL'; stopPrice?: string; icebergQty?: string; } ⋮---- export interface PortfolioMarginCancelAllOrdersOCOReport { orderListId: number; contingencyType: 'OCO'; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: PortfolioMarginOCOCancelOrder[]; orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; } ⋮---- export type PortfolioMarginCancelAllOrdersResponse = | PortfolioMarginCancelAllOrdersOrderReport | PortfolioMarginCancelAllOrdersOCOReport; ⋮---- export interface ModifyPortfolioUMOrderReq { symbol: string; side: 'BUY' | 'SELL'; quantity: string; price: string; orderId?: number; origClientOrderId?: string; priceMatch?: PMPriceMatch; } ⋮---- export interface PortfolioUMModifyOrderResponse { orderId: number; symbol: string; status: string; clientOrderId: string; price: string; avgPrice: string; origQty: string; executedQty: string; cumQty: string; cumQuote: string; timeInForce: string; type: 'LIMIT'; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'LONG' | 'SHORT' | 'BOTH'; origType: 'LIMIT'; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate: number; updateTime: number; priceMatch: PMPriceMatch; } ⋮---- export interface ModifyPortfolioCMOrderReq { symbol: string; side: 'BUY' | 'SELL'; quantity: string; price: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface PortfolioCMModifyOrderResponse { orderId: number; symbol: string; pair: string; status: string; clientOrderId: string; price: string; avgPrice: string; origQty: string; executedQty: string; cumQty: string; cumBase: string; timeInForce: string; type: 'LIMIT'; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'LONG' | 'SHORT' | 'BOTH'; origType: 'LIMIT'; updateTime: number; } ⋮---- export interface QueryPortfolioUMOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface PortfolioUMOrder { avgPrice: string; clientOrderId: string; cumQuote: string; executedQty: string; orderId: number; origQty: string; origType: 'LIMIT' | 'MARKET'; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'LONG' | 'SHORT' | 'BOTH'; status: string; symbol: string; time: number; timeInForce: string; type: 'LIMIT' | 'MARKET'; updateTime: number; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate: number; priceMatch: PMPriceMatch; } ⋮---- export interface QueryPortfolioAllUMOrdersReq { symbol: string; orderId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface QueryPortfolioUMOpenOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface QueryPortfolioAllUMConditionalOrdersReq { symbol?: string; strategyId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface PortfolioUMConditionalOrder { newClientStrategyId: string; strategyId: number; strategyStatus: string; strategyType: PMStrategyType; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'LONG' | 'SHORT' | 'BOTH'; stopPrice?: string; symbol: string; orderId?: number; status?: string; bookTime: number; updateTime: number; triggerTime?: number; timeInForce: string; type?: 'MARKET' | 'LIMIT'; activatePrice?: string; priceRate?: string; selfTradePreventionMode: PMSelfTradePreventionMode; goodTillDate: number; priceMatch: PMPriceMatch; } ⋮---- export interface QueryPortfolioUMOpenConditionalOrderReq { symbol: string; strategyId?: number; newClientStrategyId?: string; } ⋮---- export interface QueryPortfolioUMConditionalOrderHistoryReq { symbol: string; strategyId?: number; newClientStrategyId?: string; } ⋮---- export interface QueryPortfolioCMOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface PortfolioCMOrder { avgPrice: string; clientOrderId: string; cumBase: string; executedQty: string; orderId: number; origQty: string; origType: 'LIMIT' | 'MARKET'; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; status: string; symbol: string; pair: string; positionSide: 'BOTH' | 'LONG' | 'SHORT'; time: number; timeInForce: string; type: 'LIMIT' | 'MARKET'; updateTime: number; } ⋮---- export interface QueryPortfolioAllCMOrdersReq { symbol: string; pair?: string; orderId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface QueryPortfolioCMOpenOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface QueryPortfolioAllCMConditionalOrdersReq { symbol?: string; strategyId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface PortfolioCMConditionalOrder { newClientStrategyId: string; strategyId: number; strategyStatus: string; strategyType: PMStrategyType; origQty: string; price: string; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; stopPrice?: string; symbol: string; orderId?: number; status?: string; bookTime: number; updateTime: number; triggerTime?: number; timeInForce: string; type?: 'MARKET' | 'LIMIT'; activatePrice?: string; priceRate?: string; workingType: PMWorkingType; priceProtect: boolean; } ⋮---- export interface QueryPortfolioCMConditionalOrderHistoryReq { symbol: string; strategyId?: number; newClientStrategyId?: string; } ⋮---- export interface PortfolioCMConditionalHistoryOrder extends PortfolioCMConditionalOrder { priceMatch: PMPriceMatch; } ⋮---- export interface QueryPortfolioUMForceOrdersReq { symbol?: string; autoCloseType?: PMAutoCloseType; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface PortfolioUMForceOrder { orderId: number; symbol: string; status: string; clientOrderId: string; price: string; avgPrice: string; origQty: string; executedQty: string; cumQuote: string; timeInForce: string; type: 'LIMIT'; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; origType: 'LIMIT'; time: number; updateTime: number; } ⋮---- export interface QueryPortfolioCMForceOrdersReq { symbol?: string; autoCloseType?: PMAutoCloseType; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface PortfolioCMForceOrder { orderId: number; symbol: string; pair: string; status: string; clientOrderId: string; price: string; avgPrice: string; origQty: string; executedQty: string; cumBase: string; timeInForce: string; type: 'LIMIT'; reduceOnly: boolean; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; origType: 'LIMIT'; time: number; updateTime: number; } ⋮---- export interface QueryPortfolioUMOrderAmendmentReq { symbol: string; orderId?: number; origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface PortfolioUMOrderAmendment { price: { before: string; after: string; }; origQty: { before: string; after: string; }; count: number; } ⋮---- export interface PortfolioUMOrderModificationHistory { amendmentId: number; symbol: string; pair: string; orderId: number; clientOrderId: string; time: number; amendment: PortfolioUMOrderAmendment; priceMatch: PMPriceMatch; } ⋮---- export interface QueryPortfolioCMOrderAmendmentReq { symbol: string; orderId?: number; origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface PortfolioCMOrderAmendment { price: { before: string; after: string; }; origQty: { before: string; after: string; }; count: number; } ⋮---- export interface PortfolioCMOrderModificationHistory { amendmentId: number; symbol: string; pair: string; orderId: number; clientOrderId: string; time: number; amendment: PortfolioCMOrderAmendment; } ⋮---- export interface QueryPortfolioMarginForceOrdersReq { startTime?: number; endTime?: number; current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 } ⋮---- current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 ⋮---- export interface PortfolioMarginForceOrder { avgPrice: string; executedQty: string; orderId: number; price: string; qty: string; side: 'BUY' | 'SELL'; symbol: string; timeInForce: string; updatedTime: number; } ⋮---- export interface QueryPortfolioUMTradesReq { symbol: string; startTime?: number; endTime?: number; fromId?: number; // Trade id to fetch from. Default gets most recent trades limit?: number; // Default 500; max 1000 } ⋮---- fromId?: number; // Trade id to fetch from. Default gets most recent trades limit?: number; // Default 500; max 1000 ⋮---- export interface PortfolioUMTrade { symbol: string; id: number; orderId: number; side: 'BUY' | 'SELL'; price: string; qty: string; realizedPnl: string; quoteQty: string; commission: string; commissionAsset: string; time: number; buyer: boolean; maker: boolean; positionSide: 'BOTH' | 'LONG' | 'SHORT'; } ⋮---- export interface QueryPortfolioCMTradesReq { symbol?: string; pair?: string; startTime?: number; endTime?: number; fromId?: number; // Trade id to fetch from. Default gets most recent trades limit?: number; // Default 50; max 1000 } ⋮---- fromId?: number; // Trade id to fetch from. Default gets most recent trades limit?: number; // Default 50; max 1000 ⋮---- export interface PortfolioCMTrade { symbol: string; id: number; orderId: number; pair: string; side: 'BUY' | 'SELL'; price: string; qty: string; realizedPnl: string; marginAsset: string; baseQty: string; commission: string; commissionAsset: string; time: number; positionSide: 'BOTH' | 'LONG' | 'SHORT'; buyer: boolean; maker: boolean; } ⋮---- export interface PortfolioADLQuantile { LONG: number; SHORT: number; BOTH?: number; // For one-way mode or isolated margin in hedge mode HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) } ⋮---- BOTH?: number; // For one-way mode or isolated margin in hedge mode HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) ⋮---- export interface QueryPortfolioMarginOrderReq { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface PortfolioMarginOrder { clientOrderId: string; cummulativeQuoteQty: string; executedQty: string; icebergQty: string; isWorking: boolean; orderId: number; origQty: string; price: string; side: 'BUY' | 'SELL'; status: string; stopPrice: string; symbol: string; time: number; timeInForce: string; type: PMMarginOrderType; updateTime: number; accountId: number; selfTradePreventionMode: PMSelfTradePreventionMode; preventedMatchId: number | null; preventedQuantity: string | null; } ⋮---- export interface QueryPortfolioMarginAllOrdersReq { symbol: string; orderId?: number; startTime?: number; endTime?: number; limit?: number; // Default 500; max 500 } ⋮---- limit?: number; // Default 500; max 500 ⋮---- export interface QueryPortfolioMarginOCOReq { orderListId?: number; // Either orderListId or origClientOrderId must be provided origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided } ⋮---- orderListId?: number; // Either orderListId or origClientOrderId must be provided origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided ⋮---- export interface PortfolioMarginOCOQueryOrder { symbol: string; orderId: number; clientOrderId: string; } ⋮---- export interface PortfolioMarginOCO { orderListId: number; contingencyType: 'OCO'; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: PortfolioMarginOCOQueryOrder[]; } ⋮---- export interface QueryPortfolioMarginAllOCOReq { fromId?: number; // If supplied, neither startTime or endTime can be provided startTime?: number; endTime?: number; limit?: number; // Default 500; max 500 } ⋮---- fromId?: number; // If supplied, neither startTime or endTime can be provided ⋮---- limit?: number; // Default 500; max 500 ⋮---- export interface QueryPortfolioMarginTradesReq { symbol: string; orderId?: number; startTime?: number; endTime?: number; fromId?: number; // TradeId to fetch from. Default gets most recent trades limit?: number; // Default 500; max 1000 } ⋮---- fromId?: number; // TradeId to fetch from. Default gets most recent trades limit?: number; // Default 500; max 1000 ⋮---- export interface PortfolioMarginTrade { commission: string; commissionAsset: string; id: number; isBestMatch: boolean; isBuyer: boolean; isMaker: boolean; orderId: number; price: string; qty: string; symbol: string; time: number; } ⋮---- export interface PortfolioMarginRepayDebtReq { asset: string; amount?: string; specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas } ⋮---- specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas ⋮---- export interface PortfolioMarginRepayDebtResponse { amount: string; asset: string; specifyRepayAssets: string[]; updateTime: number; success: boolean; } ⋮---- /** * * DERIVATIVES - ACCOUNT endpoints * **/ ⋮---- export type PMAccountStatus = | 'NORMAL' | 'MARGIN_CALL' | 'SUPPLY_MARGIN' | 'REDUCE_ONLY' | 'ACTIVE_LIQUIDATION' | 'FORCE_LIQUIDATION' | 'BANKRUPTED'; ⋮---- export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- export interface PortfolioTotalBalance { asset: string; totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked crossMarginBorrowed: string; // principal of cross margin crossMarginFree: string; // free asset of cross margin crossMarginInterest: string; // interest of cross margin crossMarginLocked: string; // lock asset of cross margin umWalletBalance: string; // wallet balance of um umUnrealizedPNL: string; // unrealized profit of um cmWalletBalance: string; // wallet balance of cm cmUnrealizedPNL: string; // unrealized profit of cm updateTime: number; negativeBalance: string; } ⋮---- totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked crossMarginBorrowed: string; // principal of cross margin crossMarginFree: string; // free asset of cross margin crossMarginInterest: string; // interest of cross margin crossMarginLocked: string; // lock asset of cross margin umWalletBalance: string; // wallet balance of um umUnrealizedPNL: string; // unrealized profit of um cmWalletBalance: string; // wallet balance of cm cmUnrealizedPNL: string; // unrealized profit of cm ⋮---- export interface PortfolioSingleBalance { asset: string; totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance crossMarginBorrowed: string; // principal of cross margin crossMarginFree: string; // free asset of cross margin crossMarginInterest: string; // interest of cross margin crossMarginLocked: string; // lock asset of cross margin umWalletBalance: string; // wallet balance of um umUnrealizedPNL: string; // unrealized profit of um cmWalletBalance: string; // wallet balance of cm cmUnrealizedPNL: string; // unrealized profit of cm updateTime: number; negativeBalance: string; } ⋮---- totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance crossMarginBorrowed: string; // principal of cross margin crossMarginFree: string; // free asset of cross margin crossMarginInterest: string; // interest of cross margin crossMarginLocked: string; // lock asset of cross margin umWalletBalance: string; // wallet balance of um umUnrealizedPNL: string; // unrealized profit of um cmWalletBalance: string; // wallet balance of cm cmUnrealizedPNL: string; // unrealized profit of cm ⋮---- export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; ⋮---- export interface PortfolioAccountInformation { uniMMR: string; // Portfolio margin account maintenance margin rate accountEquity: string; // Account equity, in USD value actualEquity: string; // Account equity without collateral rate, in USD value accountInitialMargin: string; accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD accountStatus: PMAccountStatus; virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD totalAvailableBalance: string; totalMarginOpenLoss: string; // in USD margin open order updateTime: number; // last update time } ⋮---- uniMMR: string; // Portfolio margin account maintenance margin rate accountEquity: string; // Account equity, in USD value actualEquity: string; // Account equity without collateral rate, in USD value ⋮---- accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD ⋮---- virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD ⋮---- totalMarginOpenLoss: string; // in USD margin open order updateTime: number; // last update time ⋮---- export interface PortfolioUMPosition { symbol: string; positionAmt: string; entryPrice: string; markPrice: string; unRealizedProfit: string; liquidationPrice: string; leverage: string; maxNotionalValue: string; positionSide: 'BOTH' | 'LONG' | 'SHORT'; notional: string; updateTime: number; } ⋮---- export interface PortfolioCMPosition { symbol: string; positionAmt: string; entryPrice: string; markPrice: string; unRealizedProfit: string; liquidationPrice: string; leverage: string; positionSide: 'BOTH' | 'LONG' | 'SHORT'; updateTime: number; maxQty: string; notionalValue: string; } ⋮---- export interface PortfolioUMLeverageBracket { bracket: number; // Notional bracket initialLeverage: number; // Max initial leverage for this bracket notionalCap: number; // Cap notional of this bracket notionalFloor: number; // Notional threshold of this bracket maintMarginRatio: number; // Maintenance ratio for this bracket cum: number; // Auxiliary number for quick calculation } ⋮---- bracket: number; // Notional bracket initialLeverage: number; // Max initial leverage for this bracket notionalCap: number; // Cap notional of this bracket notionalFloor: number; // Notional threshold of this bracket maintMarginRatio: number; // Maintenance ratio for this bracket cum: number; // Auxiliary number for quick calculation ⋮---- export interface PortfolioCMLeverageBracket { bracket: number; // bracket level initialLeverage: number; // the maximum leverage qtyCap: number; // upper edge of base asset quantity qtyFloor: number; // lower edge of base asset quantity maintMarginRatio: number; // maintenance margin rate cum: number; // Auxiliary number for quick calculation } ⋮---- bracket: number; // bracket level initialLeverage: number; // the maximum leverage qtyCap: number; // upper edge of base asset quantity qtyFloor: number; // lower edge of base asset quantity maintMarginRatio: number; // maintenance margin rate cum: number; // Auxiliary number for quick calculation ⋮---- export interface PortfolioTradingIndicator { isLocked: boolean; plannedRecoverTime: number; indicator: PMIndicatorType; value: number; triggerValue: number; } ⋮---- export interface PortfolioTradingStatus { indicators: { [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" }; updateTime: number; } ⋮---- [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" ⋮---- export interface PortfolioMarginLoanRecord { txId: number; asset: string; principal: string; timestamp: number; status: PMMarginLoanStatus; } ⋮---- export interface GetMarginLoanRecordsReq { asset: string; txId?: number; startTime?: number; endTime?: number; current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 archived?: boolean; // Default: false. Set to true for archived data from 6 months ago } ⋮---- current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 archived?: boolean; // Default: false. Set to true for archived data from 6 months ago ⋮---- export interface GetMarginRepayRecordsReq { asset: string; txId?: number; startTime?: number; endTime?: number; current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 archived?: boolean; // Default: false. Set to true for archived data from 6 months ago } ⋮---- current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 archived?: boolean; // Default: false. Set to true for archived data from 6 months ago ⋮---- export interface PortfolioMarginRepayRecord { amount: string; // Total amount repaid asset: string; interest: string; // Interest repaid principal: string; // Principal repaid status: PMMarginLoanStatus; txId: number; } ⋮---- amount: string; // Total amount repaid ⋮---- interest: string; // Interest repaid principal: string; // Principal repaid ⋮---- export interface GetMarginInterestHistoryReq { asset?: string; startTime?: number; endTime?: number; current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 archived?: boolean; // Default: false. Set to true for archived data from 6 months ago } ⋮---- current?: number; // Currently querying page. Start from 1. Default: 1 size?: number; // Default: 10, Max: 100 archived?: boolean; // Default: false. Set to true for archived data from 6 months ago ⋮---- export type PMInterestType = | 'PERIODIC' // interest charged per hour | 'ON_BORROW' // first interest charged on borrow | 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB | 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB | 'PORTFOLIO'; // Portfolio Margin negative balance daily interest ⋮---- | 'PERIODIC' // interest charged per hour | 'ON_BORROW' // first interest charged on borrow | 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB | 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB | 'PORTFOLIO'; // Portfolio Margin negative balance daily interest ⋮---- export interface PortfolioMarginInterestRecord { txId: number; interestAccuredTime: number; asset: string; rawAsset: string; principal: string; interest: string; interestRate: string; type: PMInterestType; } ⋮---- export interface GetPortfolioInterestHistoryReq { asset?: string; startTime?: number; endTime?: number; size?: number; // Default: 10, Max: 100 } ⋮---- size?: number; // Default: 10, Max: 100 ⋮---- export interface PortfolioNegativeBalanceInterestRecord { asset: string; interest: string; // interest amount interestAccuredTime: number; interestRate: string; // daily interest rate principal: string; } ⋮---- interest: string; // interest amount ⋮---- interestRate: string; // daily interest rate ⋮---- export type UMIncomeType = | 'TRANSFER' | 'WELCOME_BONUS' | 'REALIZED_PNL' | 'FUNDING_FEE' | 'COMMISSION' | 'INSURANCE_CLEAR' | 'REFERRAL_KICKBACK' | 'COMMISSION_REBATE' | 'API_REBATE' | 'CONTEST_REWARD' | 'CROSS_COLLATERAL_TRANSFER' | 'OPTIONS_PREMIUM_FEE' | 'OPTIONS_SETTLE_PROFIT' | 'INTERNAL_TRANSFER' | 'AUTO_EXCHANGE' | 'DELIVERED_SETTELMENT' | 'COIN_SWAP_DEPOSIT' | 'COIN_SWAP_WITHDRAW' | 'POSITION_LIMIT_INCREASE_FEE'; ⋮---- export interface QueryPortfolioUMIncomeReq { symbol?: string; incomeType?: UMIncomeType; startTime?: number; endTime?: number; page?: number; limit?: number; // Default 100; max 1000 } ⋮---- limit?: number; // Default 100; max 1000 ⋮---- export interface PortfolioUMIncome { symbol: string; // trade symbol, if existing incomeType: UMIncomeType; income: string; // income amount asset: string; // income asset info: string; // extra information time: number; tranId: string; // transaction id tradeId: string; // trade id, if existing } ⋮---- symbol: string; // trade symbol, if existing ⋮---- income: string; // income amount asset: string; // income asset info: string; // extra information ⋮---- tranId: string; // transaction id tradeId: string; // trade id, if existing ⋮---- export type CMIncomeType = | 'TRANSFER' | 'WELCOME_BONUS' | 'FUNDING_FEE' | 'REALIZED_PNL' | 'COMMISSION' | 'INSURANCE_CLEAR' | 'DELIVERED_SETTELMENT'; ⋮---- export interface QueryPortfolioCMIncomeReq { symbol?: string; incomeType?: CMIncomeType; startTime?: number; endTime?: number; page?: number; limit?: number; // Default 100; max 1000 } ⋮---- limit?: number; // Default 100; max 1000 ⋮---- export interface PortfolioCMIncome { symbol: string; // trade symbol, if existing incomeType: CMIncomeType; income: string; // income amount asset: string; // income asset info: string; // extra information time: number; tranId: string; // transaction id tradeId: string; // trade id, if existing } ⋮---- symbol: string; // trade symbol, if existing ⋮---- income: string; // income amount asset: string; // income asset info: string; // extra information ⋮---- tranId: string; // transaction id tradeId: string; // trade id, if existing ⋮---- export interface PortfolioUMAccountAsset { asset: string; // asset name crossWalletBalance: string; // wallet balance crossUnPnl: string; // unrealized profit maintMargin: string; // maintenance margin required initialMargin: string; // total initial margin required with current mark price positionInitialMargin: string; // initial margin required for positions with current mark price openOrderInitialMargin: string; // initial margin required for open orders with current mark price updateTime: number; // last update time } ⋮---- asset: string; // asset name crossWalletBalance: string; // wallet balance crossUnPnl: string; // unrealized profit maintMargin: string; // maintenance margin required initialMargin: string; // total initial margin required with current mark price positionInitialMargin: string; // initial margin required for positions with current mark price openOrderInitialMargin: string; // initial margin required for open orders with current mark price updateTime: number; // last update time ⋮---- export interface PortfolioUMAccountPosition { symbol: string; // symbol name initialMargin: string; // initial margin required with current mark price maintMargin: string; // maintenance margin required unrealizedProfit: string; // unrealized profit positionInitialMargin: string; // initial margin required for positions with current mark price openOrderInitialMargin: string; // initial margin required for open orders with current mark price leverage: string; // current initial leverage entryPrice: string; // average entry price maxNotional: string; // maximum available notional with current leverage bidNotional: string; // bids notional askNotional: string; // ask notional positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side positionAmt: string; // position amount updateTime: number; // last update time } ⋮---- symbol: string; // symbol name initialMargin: string; // initial margin required with current mark price maintMargin: string; // maintenance margin required unrealizedProfit: string; // unrealized profit positionInitialMargin: string; // initial margin required for positions with current mark price openOrderInitialMargin: string; // initial margin required for open orders with current mark price leverage: string; // current initial leverage entryPrice: string; // average entry price maxNotional: string; // maximum available notional with current leverage bidNotional: string; // bids notional askNotional: string; // ask notional positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side positionAmt: string; // position amount updateTime: number; // last update time ⋮---- export interface PortfolioCMAccountAsset { asset: string; // asset name crossWalletBalance: string; // total wallet balance crossUnPnl: string; // unrealized profit or loss maintMargin: string; // maintenance margin initialMargin: string; // total initial margin required with the latest mark price positionInitialMargin: string; // positions' margin required with the latest mark price openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price updateTime: number; // last update time } ⋮---- asset: string; // asset name crossWalletBalance: string; // total wallet balance crossUnPnl: string; // unrealized profit or loss maintMargin: string; // maintenance margin initialMargin: string; // total initial margin required with the latest mark price positionInitialMargin: string; // positions' margin required with the latest mark price openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price updateTime: number; // last update time ⋮---- export interface PortfolioCMAccountPosition { symbol: string; // symbol name positionAmt: string; // position amount initialMargin: string; maintMargin: string; unrealizedProfit: string; positionInitialMargin: string; openOrderInitialMargin: string; leverage: string; positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode entryPrice: string; maxQty: string; // maximum quantity of base asset updateTime: number; } ⋮---- symbol: string; // symbol name positionAmt: string; // position amount ⋮---- positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode ⋮---- maxQty: string; // maximum quantity of base asset ⋮---- export interface PortfolioUMAccountConfig { feeTier: number; // account commission tier canTrade: boolean; // if can trade canDeposit: boolean; // if can transfer in asset canWithdraw: boolean; // if can transfer out asset dualSidePosition: boolean; updateTime: number; // reserved property multiAssetsMargin: boolean; tradeGroupId: number; } ⋮---- feeTier: number; // account commission tier canTrade: boolean; // if can trade canDeposit: boolean; // if can transfer in asset canWithdraw: boolean; // if can transfer out asset ⋮---- updateTime: number; // reserved property ⋮---- export interface PortfolioUMSymbolConfig { symbol: string; marginType: 'CROSSED' | 'ISOLATED'; isAutoAddMargin: string; // "true" or "false" as string leverage: number; maxNotionalValue: string; } ⋮---- isAutoAddMargin: string; // "true" or "false" as string ⋮---- export interface PortfolioUMAccountAssetV2 { asset: string; // asset name crossWalletBalance: string; // wallet balance crossUnPnl: string; // unrealized profit maintMargin: string; // maintenance margin required initialMargin: string; // total initial margin required with current mark price positionInitialMargin: string; // initial margin required for positions with current mark price openOrderInitialMargin: string; // initial margin required for open orders with current mark price updateTime: number; // last update time } ⋮---- asset: string; // asset name crossWalletBalance: string; // wallet balance crossUnPnl: string; // unrealized profit maintMargin: string; // maintenance margin required initialMargin: string; // total initial margin required with current mark price positionInitialMargin: string; // initial margin required for positions with current mark price openOrderInitialMargin: string; // initial margin required for open orders with current mark price updateTime: number; // last update time ⋮---- export interface PortfolioUMAccountPositionV2 { symbol: string; // symbol name initialMargin: string; // initial margin required with current mark price maintMargin: string; // maintenance margin required unrealizedProfit: string; // unrealized profit positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side positionAmt: string; // position amount updateTime: number; // last update time notional: string; // position notional value } ⋮---- symbol: string; // symbol name initialMargin: string; // initial margin required with current mark price maintMargin: string; // maintenance margin required unrealizedProfit: string; // unrealized profit positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side positionAmt: string; // position amount updateTime: number; // last update time notional: string; // position notional value ⋮---- export interface DownloadLinkResponse { downloadId: string; status: 'completed' | 'processing'; // Enum: completed, processing url: string; // The link is mapped to download id s3Link: string | null; notified: boolean; // ignore expirationTimestamp: number; // The link would expire after this timestamp isExpired: boolean | null; } ⋮---- status: 'completed' | 'processing'; // Enum: completed, processing url: string; // The link is mapped to download id ⋮---- notified: boolean; // ignore expirationTimestamp: number; // The link would expire after this timestamp ================ File: src/coinm-client.ts ================ import { AxiosRequestConfig } from 'axios'; ⋮---- import { ClassicPortfolioMarginAccount, ClassicPortfolioMarginNotionalLimit, CoinMAccountTradeParams, CoinMOpenInterest, CoinMPositionTrade, CoinMSymbolOrderBookTicker, FundingRate, FuturesTransactionHistoryDownloadLink, GetClassicPortfolioMarginNotionalLimitParams, PositionRisk, } from './types/coin'; import { AggregateFuturesTrade, CancelAllOpenOrdersResult, CancelFuturesOrderResult, CancelMultipleOrdersParams, CancelOrdersTimeoutParams, ChangeStats24hr, ContinuousContractKlinesParams, ForceOrderResult, FundingRateHistory, FuturesCoinMAccountBalance, FuturesCoinMAccountInformation, FuturesCoinMBasisParams, FuturesCoinMTakerBuySellVolumeParams, FuturesDataPaginatedParams, FuturesExchangeInfo, FuturesOrderBook, GetForceOrdersParams, GetIncomeHistoryParams, GetPositionMarginChangeHistoryParams, IncomeHistory, IndexPriceConstituents, IndexPriceKlinesParams, MarkPrice, ModeChangeResult, ModifyFuturesOrderParams, ModifyFuturesOrderResult, NewFuturesOrderParams, NewOrderError, NewOrderResult, OrderAmendment, OrderResult, PositionModeParams, PositionModeResponse, QuarterlyContractSettlementPrice, RawFuturesTrade, RebateDataOverview, SetCancelTimeoutResult, SetIsolatedMarginParams, SetIsolatedMarginResult, SetLeverageParams, SetLeverageResult, SetMarginTypeParams, SymbolKlinePaginatedParams, SymbolLeverageBracketsResult, UserCommissionRate, } from './types/futures'; import { BasicSymbolPaginatedParams, BinanceBaseUrlKey, CancelOCOParams, CancelOrderParams, GenericCodeMsgError, GetAllOrdersParams, GetOrderModifyHistoryParams, GetOrderParams, HistoricalTradesParams, Kline, KlinesParams, NewOCOParams, OrderBookParams, OrderIdProperty, RecentTradesParams, SymbolFromPaginatedRequestFromId, SymbolPrice, } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { asArray, generateNewOrderId, getOrderIdPrefix, getServerTimeEndpoint, logInvalidOrderId, RestClientOptions, } from './util/requestUtils'; ⋮---- export class CoinMClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- /** * Abstraction required by each client to aid with time sync / drift handling */ async getServerTime(): Promise ⋮---- /** * * Market Data Endpoints * **/ ⋮---- testConnectivity(): Promise ⋮---- getExchangeInfo(): Promise ⋮---- getOrderBook(params: OrderBookParams): Promise ⋮---- getRecentTrades(params: RecentTradesParams): Promise ⋮---- getHistoricalTrades( params: HistoricalTradesParams, ): Promise ⋮---- getAggregateTrades( params: SymbolFromPaginatedRequestFromId, ): Promise ⋮---- /** * Index Price and Mark Price */ getMarkPrice(params?: ⋮---- getFundingRateHistory( params?: Partial, ): Promise ⋮---- getFundingRate(params?: ⋮---- getKlines(params: KlinesParams): Promise ⋮---- getContinuousContractKlines( params: ContinuousContractKlinesParams, ): Promise ⋮---- getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- getPremiumIndexKlines(params: KlinesParams): Promise ⋮---- get24hrChangeStatistics(params?: { symbol?: string; pair?: string; }): Promise ⋮---- getSymbolPriceTicker(params?: { symbol?: string; pair?: string; }): Promise ⋮---- getSymbolOrderBookTicker(params?: { symbol?: string; pair?: string; }): Promise ⋮---- getOpenInterest(params: ⋮---- getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise ⋮---- getTopTradersLongShortAccountRatio( params: FuturesDataPaginatedParams, ): Promise ⋮---- getTopTradersLongShortPositionRatio( params: FuturesDataPaginatedParams & { pair?: string }, ): Promise ⋮---- getGlobalLongShortAccountRatio( params: FuturesDataPaginatedParams, ): Promise ⋮---- getTakerBuySellVolume( params: FuturesCoinMTakerBuySellVolumeParams, ): Promise ⋮---- getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise ⋮---- /** * possibly @deprecated * Only in old documentation, not in new one **/ getIndexPriceConstituents(params: { symbol: string; }): Promise ⋮---- /** * possibly @deprecated * Only in old documentation, not in new one **/ getQuarterlyContractSettlementPrices(params: { pair: string; }): Promise ⋮---- /** * * Trade Endpoints * **/ ⋮---- submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- /** * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. * * Known issue: `quantity` and `price` should be sent as strings */ submitMultipleOrders( orders: NewFuturesOrderParams[], ): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- /** * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue */ modifyOrder( params: ModifyFuturesOrderParams, ): Promise ⋮---- /** * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. */ modifyMultipleOrders( orders: ModifyFuturesOrderParams[], ): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> ⋮---- getOrderModifyHistory( params: GetOrderModifyHistoryParams, ): Promise ⋮---- cancelOrder(params: CancelOrderParams): Promise ⋮---- cancelMultipleOrders( params: CancelMultipleOrdersParams, ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- cancelAllOpenOrders(params: { symbol?: string; }): Promise ⋮---- // Auto-cancel all open orders setCancelOrdersOnTimeout( params: CancelOrdersTimeoutParams, ): Promise ⋮---- getOrder(params: GetOrderParams): Promise ⋮---- getAllOrders(params: GetAllOrdersParams): Promise ⋮---- getAllOpenOrders(params?: ⋮---- getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- getAccountTrades( params: CoinMAccountTradeParams & { orderId?: number }, ): Promise ⋮---- getPositions(params?: { marginAsset?: string; pair?: string; }): Promise ⋮---- setPositionMode(params: PositionModeParams): Promise ⋮---- setMarginType(params: SetMarginTypeParams): Promise ⋮---- setLeverage(params: SetLeverageParams): Promise ⋮---- getADLQuantileEstimation(params?: ⋮---- setIsolatedPositionMargin( params: SetIsolatedMarginParams, ): Promise ⋮---- getPositionMarginChangeHistory( params: GetPositionMarginChangeHistoryParams, ): Promise /** * * Account Endpoints * **/ ⋮---- getBalance(): Promise ⋮---- getAccountCommissionRate(params: { symbol?: string; }): Promise ⋮---- getAccountInformation(): Promise ⋮---- /** * Notional Bracket for Symbol (NOT "pair") */ getNotionalAndLeverageBrackets(params?: { symbol?: string; }): Promise ⋮---- // TO ADD: dapi/v1/leverageBracket // can use dapi/v2/leverageBracket ⋮---- getCurrentPositionMode(): Promise ⋮---- getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- getDownloadIdForFuturesTransactionHistory(params: { startTime: number; endTime: number; }): Promise< ⋮---- getFuturesTransactionHistoryDownloadLink(params: { downloadId: string; }): Promise ⋮---- getDownloadIdForFuturesOrderHistory(params: { startTime: number; endTime: number; }): Promise< ⋮---- getFuturesOrderHistoryDownloadLink(params: { downloadId: string; }): Promise ⋮---- getDownloadIdForFuturesTradeHistory(params: { startTime: number; endTime: number; }): Promise< ⋮---- getFuturesTradeHistoryDownloadLink(params: { downloadId: string; }): Promise ⋮---- /** * * Portfolio Margin Endpoints * **/ ⋮---- getClassicPortfolioMarginAccount(params: { asset: string; }): Promise ⋮---- /** * @deprecated at 6th August, 2024 **/ getClassicPortfolioMarginNotionalLimits( params?: GetClassicPortfolioMarginNotionalLimitParams, ): Promise< ⋮---- /** * * Broker Futures Endpoints * Possibly @deprecated, found only in old docs * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker * **/ ⋮---- /** * @deprecated **/ getBrokerIfNewFuturesUser( brokerId: string, type: 1 | 2 = 1, ): Promise< ⋮---- /** * @deprecated **/ setBrokerCustomIdForClient( customerId: string, email: string, ): Promise< ⋮---- /** * @deprecated **/ getBrokerClientCustomIds( customerId: string, email: string, page?: number, limit?: number, ): Promise ⋮---- /** * @deprecated **/ getBrokerUserCustomId(brokerId: string): Promise ⋮---- /** * @deprecated **/ getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- /** * @deprecated **/ getBrokerUserTradeVolume( type: 1 | 2 = 1, startTime?: number, endTime?: number, limit?: number, ): Promise ⋮---- /** * @deprecated **/ getBrokerRebateVolume( type: 1 | 2 = 1, startTime?: number, endTime?: number, limit?: number, ): Promise ⋮---- /** * @deprecated **/ getBrokerTradeDetail( type: 1 | 2 = 1, startTime?: number, endTime?: number, limit?: number, ): Promise ⋮---- /** * * User Data Stream Endpoints * **/ ⋮---- getFuturesUserDataListenKey(): Promise< ⋮---- keepAliveFuturesUserDataListenKey(): Promise ⋮---- closeFuturesUserDataListenKey(): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: | NewFuturesOrderParams | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void ================ File: src/index.ts ================ ================ File: src/portfolio-client.ts ================ import { AxiosRequestConfig } from 'axios'; ⋮---- import { CancelPortfolioCMConditionalOrderReq, CancelPortfolioCMOrderReq, CancelPortfolioMarginOCOReq, CancelPortfolioMarginOrderReq, CancelPortfolioUMConditionalOrderReq, CancelPortfolioUMOrderReq, DownloadLinkResponse, GetMarginInterestHistoryReq, GetMarginLoanRecordsReq, GetMarginRepayRecordsReq, GetPortfolioInterestHistoryReq, ModifyPortfolioCMOrderReq, ModifyPortfolioUMOrderReq, NewPortfolioCMConditionalOrderReq, NewPortfolioCMConditionalOrderResponse, NewPortfolioCMOrderReq, NewPortfolioCMOrderResponse, NewPortfolioConditionalOrderResponse, NewPortfolioMarginOCOReq, NewPortfolioMarginOCOResponse, NewPortfolioMarginOrderReq, NewPortfolioMarginOrderResponse, NewPortfolioUMConditionalOrderReq, NewPortfolioUMOrderReq, NewPortfolioUMOrderResponse, PortfolioAccountInformation, PortfolioADLQuantile, PortfolioBalance, PortfolioCMAccountAsset, PortfolioCMAccountPosition, PortfolioCMCancelConditionalOrderResponse, PortfolioCMCancelOrderResponse, PortfolioCMConditionalHistoryOrder, PortfolioCMConditionalOrder, PortfolioCMForceOrder, PortfolioCMIncome, PortfolioCMLeverageBracket, PortfolioCMModifyOrderResponse, PortfolioCMOrder, PortfolioCMOrderModificationHistory, PortfolioCMPosition, PortfolioCMTrade, PortfolioMarginCancelAllOrdersResponse, PortfolioMarginCancelOrderResponse, PortfolioMarginForceOrder, PortfolioMarginInterestRecord, PortfolioMarginLoanRecord, PortfolioMarginOCO, PortfolioMarginOCOCancelResponse, PortfolioMarginOrder, PortfolioMarginRepayDebtReq, PortfolioMarginRepayDebtResponse, PortfolioMarginRepayRecord, PortfolioMarginTrade, PortfolioNegativeBalanceInterestRecord, PortfolioTradingStatus, PortfolioUMAccountAsset, PortfolioUMAccountAssetV2, PortfolioUMAccountConfig, PortfolioUMAccountPosition, PortfolioUMAccountPositionV2, PortfolioUMCancelConditionalOrderResponse, PortfolioUMCancelOrderResponse, PortfolioUMConditionalOrder, PortfolioUMForceOrder, PortfolioUMIncome, PortfolioUMLeverageBracket, PortfolioUMModifyOrderResponse, PortfolioUMOrder, PortfolioUMOrderModificationHistory, PortfolioUMPosition, PortfolioUMSymbolConfig, PortfolioUMTrade, QueryPortfolioAllCMConditionalOrdersReq, QueryPortfolioAllCMOrdersReq, QueryPortfolioAllUMConditionalOrdersReq, QueryPortfolioAllUMOrdersReq, QueryPortfolioCMConditionalOrderHistoryReq, QueryPortfolioCMForceOrdersReq, QueryPortfolioCMIncomeReq, QueryPortfolioCMOpenOrderReq, QueryPortfolioCMOrderAmendmentReq, QueryPortfolioCMOrderReq, QueryPortfolioCMTradesReq, QueryPortfolioMarginAllOCOReq, QueryPortfolioMarginAllOrdersReq, QueryPortfolioMarginForceOrdersReq, QueryPortfolioMarginOCOReq, QueryPortfolioMarginOrderReq, QueryPortfolioMarginTradesReq, QueryPortfolioUMConditionalOrderHistoryReq, QueryPortfolioUMForceOrdersReq, QueryPortfolioUMIncomeReq, QueryPortfolioUMOpenConditionalOrderReq, QueryPortfolioUMOpenOrderReq, QueryPortfolioUMOrderAmendmentReq, QueryPortfolioUMOrderReq, QueryPortfolioUMTradesReq, } from './types/portfolio-margin'; import { BinanceBaseUrlKey, CancelOCOParams, CancelOrderParams, NewOCOParams, OrderIdProperty, } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { generateNewOrderId, getOrderIdPrefix, getServerTimeEndpoint, logInvalidOrderId, RestClientOptions, } from './util/requestUtils'; ⋮---- /** * REST client for Portfolio Margin APIs (papi) * * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info */ export class PortfolioClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- getClientId(): BinanceBaseUrlKey ⋮---- /** * Abstraction required by each client to aid with time sync / drift handling */ async getServerTime(): Promise ⋮---- /** * * Misc Endpoints * **/ ⋮---- testConnectivity(): Promise ⋮---- /** * * DERIVATIVES -TRADE endpoints * **/ ⋮---- submitNewUMOrder( params: NewPortfolioUMOrderReq, ): Promise ⋮---- submitNewUMConditionalOrder( params: NewPortfolioUMConditionalOrderReq, ): Promise ⋮---- submitNewCMOrder( params: NewPortfolioCMOrderReq, ): Promise ⋮---- submitNewCMConditionalOrder( params: NewPortfolioCMConditionalOrderReq, ): Promise ⋮---- submitNewMarginOrder( params: NewPortfolioMarginOrderReq, ): Promise ⋮---- submitMarginLoan(params: ⋮---- submitMarginRepay(params: ⋮---- submitNewMarginOCO( params: NewPortfolioMarginOCOReq, ): Promise ⋮---- cancelUMOrder( params: CancelPortfolioUMOrderReq, ): Promise ⋮---- cancelAllUMOrders(params: ⋮---- cancelUMConditionalOrder( params: CancelPortfolioUMConditionalOrderReq, ): Promise ⋮---- cancelAllUMConditionalOrders(params: ⋮---- cancelCMOrder( params: CancelPortfolioCMOrderReq, ): Promise ⋮---- cancelAllCMOrders(params: ⋮---- cancelCMConditionalOrder( params: CancelPortfolioCMConditionalOrderReq, ): Promise ⋮---- cancelAllCMConditionalOrders(params: ⋮---- cancelMarginOrder( params: CancelPortfolioMarginOrderReq, ): Promise ⋮---- cancelMarginOCO( params: CancelPortfolioMarginOCOReq, ): Promise ⋮---- cancelAllMarginOrders(params: { symbol: string; }): Promise ⋮---- modifyUMOrder( params: ModifyPortfolioUMOrderReq, ): Promise ⋮---- modifyCMOrder( params: ModifyPortfolioCMOrderReq, ): Promise ⋮---- getUMOrder(params: QueryPortfolioUMOrderReq): Promise ⋮---- getAllUMOrders( params: QueryPortfolioAllUMOrdersReq, ): Promise ⋮---- getUMOpenOrder( params: QueryPortfolioUMOpenOrderReq, ): Promise ⋮---- getAllUMOpenOrders(params: ⋮---- getAllUMConditionalOrders( params: QueryPortfolioAllUMConditionalOrdersReq, ): Promise ⋮---- getUMOpenConditionalOrders(params: { symbol?: string; }): Promise ⋮---- getUMOpenConditionalOrder( params: QueryPortfolioUMOpenConditionalOrderReq, ): Promise ⋮---- getUMConditionalOrderHistory( params: QueryPortfolioUMConditionalOrderHistoryReq, ): Promise ⋮---- getCMOrder(params: QueryPortfolioCMOrderReq): Promise ⋮---- getAllCMOrders( params: QueryPortfolioAllCMOrdersReq, ): Promise ⋮---- getCMOpenOrder( params: QueryPortfolioCMOpenOrderReq, ): Promise ⋮---- getAllCMOpenOrders(params: { symbol?: string; pair?: string; }): Promise ⋮---- getCMOpenConditionalOrders(params: { symbol?: string; }): Promise ⋮---- getCMOpenConditionalOrder(params: { symbol: string; strategyId?: number; newClientStrategyId?: string; }): Promise ⋮---- getAllCMConditionalOrders( params: QueryPortfolioAllCMConditionalOrdersReq, ): Promise ⋮---- getCMConditionalOrderHistory( params: QueryPortfolioCMConditionalOrderHistoryReq, ): Promise ⋮---- getUMForceOrders( params: QueryPortfolioUMForceOrdersReq, ): Promise ⋮---- getCMForceOrders( params: QueryPortfolioCMForceOrdersReq, ): Promise ⋮---- getUMOrderModificationHistory( params: QueryPortfolioUMOrderAmendmentReq, ): Promise ⋮---- getCMOrderModificationHistory( params: QueryPortfolioCMOrderAmendmentReq, ): Promise ⋮---- getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< ⋮---- getUMTrades(params: QueryPortfolioUMTradesReq): Promise ⋮---- getCMTrades(params: QueryPortfolioCMTradesReq): Promise ⋮---- getUMADLQuantile(params: { symbol?: string }): Promise< { symbol: string; adlQuantile: PortfolioADLQuantile; }[] > { return this.getPrivate('papi/v1/um/adlQuantile', params); ⋮---- getCMADLQuantile(params: { symbol?: string }): Promise< { symbol: string; adlQuantile: PortfolioADLQuantile; }[] > { return this.getPrivate('papi/v1/cm/adlQuantile', params); ⋮---- toggleUMFeeBurn(params: { feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off }): Promise< ⋮---- feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off ⋮---- getUMFeeBurnStatus(): Promise< ⋮---- getMarginOrder( params: QueryPortfolioMarginOrderReq, ): Promise ⋮---- getMarginOpenOrders(params: { symbol: string; }): Promise ⋮---- getAllMarginOrders( params: QueryPortfolioMarginAllOrdersReq, ): Promise ⋮---- getMarginOCO( params: QueryPortfolioMarginOCOReq, ): Promise ⋮---- getAllMarginOCO( params: QueryPortfolioMarginAllOCOReq, ): Promise ⋮---- getMarginOpenOCO(): Promise ⋮---- getMarginTrades( params: QueryPortfolioMarginTradesReq, ): Promise ⋮---- repayMarginDebt( params: PortfolioMarginRepayDebtReq, ): Promise ⋮---- /** * * DERIVATIVES - ACCOUNT endpoints * **/ ⋮---- getBalance(params?: ⋮---- getAccountInfo(): Promise ⋮---- getMarginMaxBorrow(params: ⋮---- amount: string; // account's currently max borrowable amount with sufficient system availability borrowLimit: string; // max borrowable amount limited by the account level ⋮---- getMarginMaxWithdraw(params: ⋮---- amount: string; // max withdrawable amount ⋮---- getUMPosition(params?: ⋮---- getCMPosition(params?: { marginAsset?: string; pair?: string; }): Promise ⋮---- updateUMLeverage(params: ⋮---- updateCMLeverage(params: ⋮---- updateUMPositionMode(params: { dualSidePosition: 'true' | 'false'; }): Promise< ⋮---- updateCMPositionMode(params: { dualSidePosition: 'true' | 'false'; }): Promise< ⋮---- getUMPositionMode(): Promise< ⋮---- dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- getCMPositionMode(): Promise< ⋮---- dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- getUMLeverageBrackets(params?: { symbol?: string }): Promise< { symbol: string; notionalCoef: string; brackets: PortfolioUMLeverageBracket[]; }[] > { return this.getPrivate('papi/v1/um/leverageBracket', params); ⋮---- getCMLeverageBrackets(params?: { symbol?: string }): Promise< { symbol: string; brackets: PortfolioCMLeverageBracket[]; }[] > { return this.getPrivate('papi/v1/cm/leverageBracket', params); ⋮---- getUMTradingStatus(params?: { symbol?: string; }): Promise ⋮---- getUMCommissionRate(params: ⋮---- makerCommissionRate: string; // e.g., "0.0002" for 0.02% takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- getCMCommissionRate(params: ⋮---- makerCommissionRate: string; // e.g., "0.0002" for 0.02% takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise< ⋮---- getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< ⋮---- getAutoRepayFuturesStatus(): Promise< ⋮---- autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off ⋮---- updateAutoRepayFuturesStatus(params: { autoRepay: 'true' | 'false'; }): Promise< ⋮---- getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< ⋮---- repayFuturesNegativeBalance(): Promise< ⋮---- getPortfolioNegativeBalanceInterestHistory( params?: GetPortfolioInterestHistoryReq, ): Promise ⋮---- autoCollectFunds(): Promise< ⋮---- transferAssetFuturesMargin(params: ⋮---- transferBNB(params: { amount: string; transferSide: 'TO_UM' | 'FROM_UM'; }): Promise< ⋮---- tranId: number; // transaction id ⋮---- getUMIncomeHistory( params?: QueryPortfolioUMIncomeReq, ): Promise ⋮---- getCMIncomeHistory( params?: QueryPortfolioCMIncomeReq, ): Promise ⋮---- getUMAccount(): Promise< ⋮---- positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market ⋮---- getCMAccount(): Promise< ⋮---- getUMAccountConfig(): Promise ⋮---- getUMSymbolConfig(params?: { symbol?: string; }): Promise ⋮---- getUMAccountV2(): Promise< ⋮---- positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market ⋮---- getUMTradeHistoryDownloadId(params: { startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms }): Promise< ⋮---- startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms ⋮---- avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days ⋮---- getUMTradeDownloadLink(params: { downloadId: string; }): Promise ⋮---- getUMOrderHistoryDownloadId(params: { startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms }): Promise< ⋮---- startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms ⋮---- avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days ⋮---- getUMOrderDownloadLink(params: { downloadId: string; }): Promise ⋮---- getUMTransactionHistoryDownloadId(params: { startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms }): Promise< ⋮---- startTime: number; // Timestamp in ms endTime: number; // Timestamp in ms ⋮---- avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days ⋮---- getUMTransactionDownloadLink(params: { downloadId: string; }): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: | NewPortfolioUMOrderReq | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void ⋮---- /** * * User Data Stream Endpoints * **/ getPMUserDataListenKey(): Promise< ⋮---- keepAlivePMUserDataListenKey(): Promise ⋮---- closePMUserDataListenKey(): Promise ================ File: src/usdm-client.ts ================ import { AxiosRequestConfig } from 'axios'; ⋮---- import { FundingRate } from './types/coin'; import { AggregateFuturesTrade, Basis, BasisParams, CancelAllOpenOrdersResult, CancelFuturesOrderResult, CancelMultipleOrdersParams, CancelOrdersTimeoutParams, ChangeStats24hr, ContinuousContractKlinesParams, ForceOrderResult, FundingRateHistory, FuturesAccountBalance, FuturesAccountConfig, FuturesAccountInformation, FuturesConvertOrderStatus, FuturesConvertPair, FuturesConvertQuote, FuturesConvertQuoteRequest, FuturesDataPaginatedParams, FuturesExchangeInfo, FuturesOrderBook, FuturesPosition, FuturesPositionTrade, FuturesPositionV3, FuturesSymbolOrderBookTicker, FuturesTradeHistoryDownloadId, FuturesTransactionDownloadLink, GetForceOrdersParams, GetFuturesOrderModifyHistoryParams, GetIncomeHistoryParams, GetPositionMarginChangeHistoryParams, HistoricOpenInterest, IncomeHistory, IndexPriceConstituents, IndexPriceKlinesParams, InsuranceFundBalance, MarkPrice, ModeChangeResult, ModifyFuturesOrderParams, ModifyFuturesOrderResult, ModifyOrderParams, MultiAssetModeResponse, MultiAssetsMode, NewFuturesOrderParams, NewOrderError, NewOrderResult, OpenInterest, OrderResult, PortfolioMarginProAccountInfo, PositionModeParams, PositionModeResponse, QuarterlyContractSettlementPrice, RawFuturesTrade, RebateDataOverview, SetCancelTimeoutResult, SetIsolatedMarginParams, SetIsolatedMarginResult, SetLeverageParams, SetLeverageResult, SetMarginTypeParams, SymbolConfig, SymbolKlinePaginatedParams, SymbolLeverageBracketsResult, UserCommissionRate, UserForceOrder, } from './types/futures'; import { BasicSymbolPaginatedParams, BasicSymbolParam, BinanceBaseUrlKey, CancelOCOParams, CancelOrderParams, GenericCodeMsgError, GetAllOrdersParams, GetOrderParams, HistoricalTradesParams, Kline, KlinesParams, NewOCOParams, numberInString, OrderBookParams, OrderIdProperty, RecentTradesParams, SymbolFromPaginatedRequestFromId, SymbolPrice, } from './types/shared'; import BaseRestClient from './util/BaseRestClient'; import { generateNewOrderId, getOrderIdPrefix, getServerTimeEndpoint, logInvalidOrderId, RestClientOptions, } from './util/requestUtils'; ⋮---- export class USDMClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- /** * Abstraction required by each client to aid with time sync / drift handling */ async getServerTime(): Promise ⋮---- /** * * MARKET DATA endpoints - Rest API * **/ ⋮---- testConnectivity(): Promise ⋮---- getExchangeInfo(): Promise ⋮---- getOrderBook(params: OrderBookParams): Promise ⋮---- getRecentTrades(params: RecentTradesParams): Promise ⋮---- getHistoricalTrades( params: HistoricalTradesParams, ): Promise ⋮---- getAggregateTrades( params: SymbolFromPaginatedRequestFromId, ): Promise ⋮---- getKlines(params: KlinesParams): Promise ⋮---- getContinuousContractKlines( params: ContinuousContractKlinesParams, ): Promise ⋮---- getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- getMarkPrice(params: ⋮---- getMarkPrice(): Promise; ⋮---- getMarkPrice(params?: ⋮---- getFundingRateHistory( params?: Partial, ): Promise ⋮---- getFundingRates(): Promise ⋮---- get24hrChangeStatistics(params: ⋮---- get24hrChangeStatistics(): Promise; ⋮---- get24hrChangeStatistics(params?: { symbol?: string; }): Promise ⋮---- getSymbolPriceTicker(params: ⋮---- getSymbolPriceTicker(): Promise; ⋮---- getSymbolPriceTicker(params?: { symbol?: string; }): Promise ⋮---- getSymbolPriceTickerV2(params: ⋮---- getSymbolPriceTickerV2(): Promise; ⋮---- getSymbolPriceTickerV2(params?: { symbol?: string; }): Promise ⋮---- getSymbolOrderBookTicker(params: { symbol: string; }): Promise; ⋮---- getSymbolOrderBookTicker(): Promise; ⋮---- getSymbolOrderBookTicker(params?: { symbol?: string; }): Promise ⋮---- getQuarterlyContractSettlementPrices(params: { pair: string; }): Promise ⋮---- getOpenInterest(params: ⋮---- getOpenInterestStatistics( params: FuturesDataPaginatedParams, ): Promise ⋮---- getTopTradersLongShortPositionRatio( params: FuturesDataPaginatedParams, ): Promise ⋮---- getTopTradersLongShortAccountRatio( params: FuturesDataPaginatedParams, ): Promise ⋮---- getGlobalLongShortAccountRatio( params: FuturesDataPaginatedParams, ): Promise ⋮---- getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise ⋮---- getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- getCompositeSymbolIndex(params?: ⋮---- getMultiAssetsModeAssetIndex(params?: ⋮---- /** * Possibly @deprecated, found only in old docs **/ getBasis(params: BasisParams): Promise ⋮---- getIndexPriceConstituents(params: { symbol: string; }): Promise ⋮---- getInsuranceFundBalance(params?: { symbol?: string; }): Promise ⋮---- /** * * TRADE endpoints - Rest API * **/ ⋮---- submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- /** * Warning: max 5 orders at a time! This method does not throw, instead it returns * individual errors in the response array if any orders were rejected. * * Note: this method will automatically ensure "price" and "quantity" are sent as a * string, if present in the request. See #523 & #526 for more details. */ submitMultipleOrders( orders: NewFuturesOrderParams[], ): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- // Known issue: `quantity` and `price` should be sent as strings, see #523, #526 ⋮---- /** * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue */ modifyOrder( params: ModifyFuturesOrderParams, ): Promise ⋮---- modifyMultipleOrders(orders: ModifyOrderParams[]): Promise ⋮---- getOrderModifyHistory( params: GetFuturesOrderModifyHistoryParams, ): Promise ⋮---- cancelOrder(params: CancelOrderParams): Promise ⋮---- cancelMultipleOrders( params: CancelMultipleOrdersParams, ): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- cancelAllOpenOrders(params: { symbol: string; }): Promise ⋮---- // Auto-cancel all open orders setCancelOrdersOnTimeout( params: CancelOrdersTimeoutParams, ): Promise ⋮---- getOrder(params: GetOrderParams): Promise ⋮---- getAllOrders(params: GetAllOrdersParams): Promise ⋮---- getAllOpenOrders(params?: ⋮---- getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- getAccountTrades( params: SymbolFromPaginatedRequestFromId & { orderId?: number }, ): Promise ⋮---- setMarginType(params: SetMarginTypeParams): Promise ⋮---- setPositionMode(params: PositionModeParams): Promise ⋮---- setLeverage(params: SetLeverageParams): Promise ⋮---- setMultiAssetsMode(params: { multiAssetsMargin: MultiAssetsMode; }): Promise ⋮---- setIsolatedPositionMargin( params: SetIsolatedMarginParams, ): Promise ⋮---- /** * @deprecated * Use getPositionsV3() instead **/ getPositions(params?: Partial): Promise ⋮---- getPositionsV3(params?: ⋮---- getADLQuantileEstimation(params?: ⋮---- getPositionMarginChangeHistory( params: GetPositionMarginChangeHistoryParams, ): Promise ⋮---- /** * * ACCOUNT endpoints - Rest API * **/ ⋮---- getBalanceV3(): Promise ⋮---- /** * @deprecated * Use getBalanceV3() instead **/ getBalance(): Promise ⋮---- getAccountInformationV3(): Promise ⋮---- /** * @deprecated * Use getAccountInformationV3() instead **/ getAccountInformation(): Promise ⋮---- getAccountCommissionRate(params: { symbol: string; }): Promise ⋮---- getFuturesAccountConfig(): Promise ⋮---- getFuturesSymbolConfig(params: ⋮---- getUserForceOrders(): Promise ⋮---- /** * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) */ getNotionalAndLeverageBrackets(params?: { symbol?: string; }): Promise ⋮---- getMultiAssetsMode(): Promise ⋮---- getCurrentPositionMode(): Promise ⋮---- getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- getApiQuantitativeRulesIndicators(params?: { symbol?: string; }): Promise ⋮---- getFuturesTransactionHistoryDownloadId(params: { startTime: number; endTime: number; }): Promise ⋮---- getFuturesTransactionHistoryDownloadLink(params: { downloadId: string; }): Promise ⋮---- getFuturesOrderHistoryDownloadId(params: { startTime: number; endTime: number; }): Promise ⋮---- getFuturesOrderHistoryDownloadLink(params: { downloadId: string; }): Promise ⋮---- getFuturesTradeHistoryDownloadId(params: { startTime: number; endTime: number; }): Promise ⋮---- getFuturesTradeDownloadLink(params: { downloadId: string; }): Promise ⋮---- setBNBBurnEnabled(params: { feeBurn: 'true' | 'false'; }): Promise< ⋮---- getBNBBurnStatus(): Promise< ⋮---- testOrder(params: NewFuturesOrderParams): Promise ⋮---- /** * * Convert Endpoints * **/ ⋮---- getAllConvertPairs(params?: { fromAsset?: string; toAsset?: string; }): Promise ⋮---- submitConvertQuoteRequest( params: FuturesConvertQuoteRequest, ): Promise ⋮---- acceptConvertQuote(params: ⋮---- getConvertOrderStatus(params: { orderId?: string; quoteId?: string; }): Promise ⋮---- /** * * Portfolio Margin Pro Endpoints * **/ ⋮---- getPortfolioMarginProAccountInfo(params: { asset: string; }): Promise ⋮---- /** * * Broker Futures Endpoints * Possibly @deprecated, found only in old docs * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker * **/ ⋮---- /** * @deprecated **/ getBrokerIfNewFuturesUser( brokerId: string, type: 1 | 2 = 1, ): Promise< ⋮---- /** * @deprecated **/ setBrokerCustomIdForClient( customerId: string, email: string, ): Promise< ⋮---- /** * @deprecated **/ getBrokerClientCustomIds( customerId: string, email: string, page?: number, limit?: number, ): Promise ⋮---- /** * @deprecated **/ getBrokerUserCustomId(brokerId: string): Promise ⋮---- /** * @deprecated **/ getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- /** * @deprecated **/ getBrokerUserTradeVolume( type: 1 | 2 = 1, startTime?: number, endTime?: number, limit?: number, ): Promise ⋮---- /** * @deprecated **/ getBrokerRebateVolume( type: 1 | 2 = 1, startTime?: number, endTime?: number, limit?: number, ): Promise ⋮---- /** * @deprecated **/ getBrokerTradeDetail( type: 1 | 2 = 1, startTime?: number, endTime?: number, limit?: number, ): Promise ⋮---- /** * * User Data Stream Endpoints * **/ ⋮---- // USD-M Futures ⋮---- getFuturesUserDataListenKey(): Promise< ⋮---- keepAliveFuturesUserDataListenKey(): Promise ⋮---- closeFuturesUserDataListenKey(): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: | NewFuturesOrderParams | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void ================ 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: .nvmrc ================ v22.11.0 ================ 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: index.js ================ ================ File: jest.config.ts ================ /** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */ ⋮---- import type { Config } from 'jest'; ⋮---- // All imported modules in your tests should be mocked automatically // automock: false, ⋮---- // Stop running tests after `n` failures // bail: 0, bail: false, // enable to stop test when an error occur, ⋮---- // The directory where Jest should store its cached dependency information // cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- // Automatically clear mock calls, instances, contexts and results before every test ⋮---- // Indicates whether the coverage information should be collected while executing the test ⋮---- // An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- // The directory where Jest should output its coverage files ⋮---- // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // Indicates which provider should be used to instrument code for coverage ⋮---- // A list of reporter names that Jest uses when writing coverage reports // coverageReporters: [ // "json", // "text", // "lcov", // "clover" // ], ⋮---- // An object that configures minimum threshold enforcement for coverage results // coverageThreshold: undefined, ⋮---- // A path to a custom dependency extractor // dependencyExtractor: undefined, ⋮---- // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, ⋮---- // The default configuration for fake timers // fakeTimers: { // "enableGlobally": false // }, ⋮---- // Force coverage collection from ignored files using an array of glob patterns // forceCoverageMatch: [], ⋮---- // A path to a module which exports an async function that is triggered once before all test suites // globalSetup: undefined, ⋮---- // A path to a module which exports an async function that is triggered once after all test suites // globalTeardown: undefined, ⋮---- // A set of global variables that need to be available in all test environments // globals: {}, ⋮---- // 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%", ⋮---- // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ // "node_modules" // ], ⋮---- // An array of file extensions your modules use // moduleFileExtensions: [ // "js", // "mjs", // "cjs", // "jsx", // "ts", // "tsx", // "json", // "node" // ], ⋮---- // 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: {}, ⋮---- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], ⋮---- // Activates notifications for test results // notify: false, ⋮---- // An enum that specifies notification mode. Requires { notify: true } // notifyMode: "failure-change", ⋮---- // A preset that is used as a base for Jest's configuration // preset: undefined, ⋮---- // Run tests from one or more projects // projects: undefined, ⋮---- // Use this configuration option to add custom reporters to Jest // reporters: undefined, ⋮---- // Automatically reset mock state before every test // resetMocks: false, ⋮---- // Reset the module registry before running each individual test // resetModules: false, ⋮---- // A path to a custom resolver // resolver: undefined, ⋮---- // Automatically restore mock state and implementation before every test // restoreMocks: false, ⋮---- // The root directory that Jest should scan for tests and modules within // rootDir: undefined, ⋮---- // A list of paths to directories that Jest should use to search for files in // roots: [ // "" // ], ⋮---- // Allows you to use a custom runner instead of Jest's default test runner // runner: "jest-runner", ⋮---- // The paths to modules that run some code to configure or set up the testing environment before each test // setupFiles: [], ⋮---- // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], ⋮---- // The number of seconds after which a test is considered as slow and reported as such in the results. // slowTestThreshold: 5, ⋮---- // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], ⋮---- // The test environment that will be used for testing // testEnvironment: "jest-environment-node", ⋮---- // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, ⋮---- // Adds a location field to test results // testLocationInResults: false, ⋮---- // The glob patterns Jest uses to detect test files ⋮---- // "**/__tests__/**/*.[jt]s?(x)", ⋮---- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped // testPathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // The regexp pattern or array of patterns that Jest uses to detect test files // testRegex: [], ⋮---- // This option allows the use of a custom results processor // testResultsProcessor: undefined, ⋮---- // This option allows use of a custom test runner // testRunner: "jest-circus/runner", ⋮---- // A map from regular expressions to paths to transformers // transform: undefined, ⋮---- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ // "/node_modules/", // "\\.pnp\\.[^\\/]+$" // ], ⋮---- // Prevents import esm module error from v1 axios release, issue #5026 ⋮---- // 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, ⋮---- // Indicates whether each individual test should be reported during the run // verbose: undefined, verbose: true, // report individual test ⋮---- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode // watchPathIgnorePatterns: [], ⋮---- // 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 2021 Tiago Siebler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================ File: tsconfig.build.json ================ { "extends": "./tsconfig.json", "exclude": [ "node_modules", "test", "dist", "**/*spec.ts", "**/*test.ts", "jest.config.ts" ] } ================ File: tsconfig.json ================ { "compileOnSave": true, "compilerOptions": { "allowJs": true, "target": "es6", "module": "commonjs", "moduleResolution": "node", "declaration": true, "removeComments": false, "noEmitOnError": true, "noImplicitAny": false, "strictNullChecks": true, "skipLibCheck": true, "sourceMap": true, "esModuleInterop": true, "lib": ["es2017", "dom"], "baseUrl": ".", "outDir": "lib" }, "include": ["src/**/*"], "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"] } ================ File: tsconfig.linting.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "outDir": "dist/cjs", "target": "esnext", "rootDir": "../", "allowJs": true }, "include": [ "src/**/*.*", "test/**/*.*", "examples/**/*.*", ".eslintrc.cjs", "jest.config.ts", "webpack/webpack.config.ts" ] } ================ File: examples/auth/rest-private-ed25519.md ================ # Ed25519 Authentication with Binance APIs in Node.js ## Creating Ed25519 Keys Officially, binance recommends downloading and running a key generator from their repo. Guidance for this can be found on the [binance website](https://www.binance.com/en/support/faq/detail/6b9a63f1e3384cf48a2eedb82767a69a) when trying to add a new Ed25519 API key, or in their GitHub repository: https://github.com/binance/asymmetric-key-generator ## Using the Ed25519 public key to get an API key from Binance Once created, keep your **private key** completely secret! The **public** key needs to be provided to binance when creating new API credentials with the "Self-generated" option. Your public key should look something like this: ```pem -----BEGIN PUBLIC KEY----- lkn123bx123x+7lkmlkn123bx123xAMDO/lkm123x= -----END PUBLIC KEY----- ``` Submit this in the "Upload public key" form, shown when creating a new API key on binance and choosing the "self-generated" option. Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. After using the public key to create a new API key, you will be given an API Key such as the following: ``` mlk2mx3l12m3lxk1m3lxk1m3l1k2mx3l12km3xl1km23x1l2k3mx1l2km3x ``` This is the first piece, used as the "apiKey" in the [rest-private-ed25519.ts](./rest-private-ed25519.ts) example. ## Using the Ed25519 private key for Ed25519 authentication with binance APIs in Node.js Your private key, if generated with the above steps, should look something like this (but with much more text): ```pem -----BEGIN PRIVATE KEY----- lx1k2m3xl12lkm2l1kmx312312l3mx1lk23m -----END PRIVATE KEY----- ``` This is your secret, you should **never** share this with anyone, not even binance! Treat this like a password. As part of this authentication process, your private key is used to generate a signature. This SDK handles this process automatically for you. Ed25519 authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. From here, simply use the key provided by binance as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. Based on the above example, the following would prepare the main REST client using the above credentials: ```typescript const ed25519PrivateKey = ` -----BEGIN PRIVATE KEY----- lkmlkm123lkms1s12s+lkmlkm123lkms1s12s -----END PRIVATE KEY----- `; const ed25519APIKey = 'lkmlkm123lkms1s12slkmlkm123lkms1s12slkmlkm123lkms1s12s'; const client = new MainClient({ api_key: ed25519APIKey, api_secret: ed25519PrivateKey, beautifyResponses: true, }); ``` The rest is automatic - just continue using the SDK as you would normally. It will automatically handle signing requests using Ed25519 for you. For a complete example, refer to the [rest-private-ed25519.ts](./rest-private-ed25519.ts) file on GitHub. ================ File: examples/auth/rest-private-rsa.ts ================ import { MainClient } from '../../src/index'; ⋮---- // or // import { MainClient } from 'binance'; ⋮---- // Received after creating a new API key with a self-generated RSA public key on binance ⋮---- // The self-generated RSA private key, this is never directly given to binance, but used to generate a signature // Note: this MUST include the "BEGIN PRIVATE KEY" header so the SDK understands this is RSA auth ================ File: examples/WebSockets/ws-close.ts ================ import { DefaultLogger, WebsocketClient } from '../../src/index'; ⋮---- // or // import { DefaultLogger, WebsocketClient } from 'binance'; ⋮---- // unsubscribe from user data stream (for usd futures) ⋮---- // unsubscribe from individual topics on a connection, one at a time: // wsClient.unsubscribe('!miniTicker@arr', 'main'); ⋮---- // arrays also supported: ================ File: examples/WebSockets/ws-public.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { DefaultLogger, isWsAggTradeFormatted, isWsFormatted24hrTicker, isWsFormatted24hrTickerArray, isWsFormattedForceOrder, isWsFormattedKline, isWsFormattedMarkPriceUpdateArray, isWsFormattedMarkPriceUpdateEvent, isWsFormattedRollingWindowTickerArray, isWsFormattedTrade, isWsPartialBookDepthEventFormatted, WebsocketClient, } from '../../src'; ⋮---- // or, with the npm package /* import { WebsocketClient, DefaultLogger, isWsFormatted24hrTicker, isWsFormattedKline, } from 'binance'; */ ⋮---- // Without typescript: // const logger = { ⋮---- // A simple way to suppress heartbeats but receive all other traces // if (params[0].includes('ping') || params[0].includes('pong')) { // return; // } ⋮---- // Optional: when enabled, the SDK will try to format incoming data into more readable objects. // Beautified data is emitted via the "formattedMessage" event ⋮---- logger, // Optional: customise logging behaviour by extending or overwriting the default logger implementation ⋮---- // Raw unprocessed incoming data, e.g. if you have the beautifier disabled ⋮---- // console.log('raw message received ', JSON.stringify(data, null, 2)); // console.log('raw message received ', JSON.stringify(data)); ⋮---- // Formatted data that has gone through the beautifier ⋮---- /** * Optional: we've included type-guards for many formatted websocket topics. * * These can be used within `if` blocks to narrow down specific event types (even for non-typescript users). */ // if (isWsAggTradeFormatted(data)) { // console.log('log agg trade: ', data); // return; // } ⋮---- // // For one symbol // if (isWsFormattedMarkPriceUpdateEvent(data)) { // console.log('log mark price: ', data); // return; // } ⋮---- // // for many symbols // if (isWsFormattedMarkPriceUpdateArray(data)) { // console.log('log mark prices: ', data); // return; // } ⋮---- // if (isWsFormattedKline(data)) { // console.log('log kline: ', data); // return; // } ⋮---- // if (isWsFormattedTrade(data)) { // return console.log('log trade: ', data); // } ⋮---- // if (isWsFormattedForceOrder(data)) { // return console.log('log force order: ', data); // } ⋮---- // if (isWsFormatted24hrTickerArray(data)) { // return console.log('log 24hr ticker array: ', data); // } ⋮---- // if (isWsFormattedRollingWindowTickerArray(data)) { // return console.log('log rolling window ticker array: ', data); // } ⋮---- // if (isWsFormatted24hrTicker(data)) { // return console.log('log 24hr ticker: ', data); // } ⋮---- // if (isWsPartialBookDepthEventFormatted(data)) { // return console.log('log partial book depth event: ', 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. */ ⋮---- // // 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', // '!ticker@arr', // '!miniTicker@arr', // ], // 'usdm', // ); ⋮---- /** * Subscribe to each available type of spot market topic, the new way */ ⋮---- // Aggregate Trade Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#aggregate-trade-streams ⋮---- // Trade Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#trade-streams ⋮---- // Kline/Candlestick Streams for UTC // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc ⋮---- // Kline/Candlestick Streams with timezone offset // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-with-timezone-offset ⋮---- // Individual Symbol Mini Ticker Stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-mini-ticker-stream ⋮---- // All Market Mini Tickers Stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-mini-tickers-stream ⋮---- // Individual Symbol Ticker Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-ticker-streams ⋮---- // All Market Tickers Stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-tickers-stream ⋮---- // Individual Symbol Rolling Window Statistics Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-rolling-window-statistics-streams ⋮---- // All Market Rolling Window Statistics Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams ⋮---- // Individual Symbol Book Ticker Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams ⋮---- // Average Price // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price ⋮---- // Partial Book Depth Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams ⋮---- // Diff. Depth Stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream ⋮---- // Look at the `WS_KEY_URL_MAP` for a list of values here: // https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts // "main" connects to wss://stream.binance.com:9443/stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams ⋮---- // Aggregate Trade Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams ⋮---- // Mark Price Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream ⋮---- // Mark Price Stream for All market // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Mark-Price-Stream-for-All-market ⋮---- // Kline/Candlestick Streams // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Kline-Candlestick-Streams // 'btcusdt@kline_1m', // Continuous Contract Kline/Candlestick Streams // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Continuous-Contract-Kline-Candlestick-Streams // 'btcusdt_perpetual@continuousKline_1m', // DOESNT EXIST AS TYPE GUARD, ONLY IN BEAUTIFIER // Individual Symbol Mini Ticker Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Mini-Ticker-Stream // 'btcusdt@miniTicker', // DOESNT EXIST AS TYPE GUARD, ONLY FOR RAW MESSAGE // All Market Mini Tickers Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Mini-Tickers-Stream // '!miniTicker@arr', // DOESNT EXIST AS TYPE GUARD // Individual Symbol Ticker Streams // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Ticker-Streams //'btcusdt@ticker', // All Market Tickers Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Tickers-Stream // '!ticker@arr', // DOESNT EXIST AS TYPE GUARD // Individual Symbol Book Ticker Streams // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Individual-Symbol-Book-Ticker-Streams //'btcusdt@bookTicker', // DOESNT EXIST AS TYPE GUARD // All Book Tickers Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Book-Tickers-Stream // '!bookTicker', // DOESNT EXIST AS TYPE GUARD // Liquidation Order Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams // 'btcusdt@forceOrder', // Liquidation Order Stream for All market // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/All-Market-Liquidation-Order-Streams //'!forceOrder@arr', // Partial Book Depth Streams // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams //'btcusdt@depth5', // 'btcusdt@depth10@100ms' // Diff. Book Depth Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Diff-Book-Depth-Streams // 'btcusdt@depth', // 'btcusdt@depth@100ms', // 'btcusdt@depth@500ms', // 'btcusdt@depth@1000ms' // Composite Index Symbol Information Streams // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Composite-Index-Symbol-Information-Streams // 'btcusdt@compositeIndex' // DOESNT EXIST AS TYPE GUARD // Contract Info Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Contract-Info-Stream // '!contractInfo' // DOESNT EXIST AS TYPE GUARD // Multi-Assets Mode Asset Index Stream // https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Multi-Assets-Mode-Asset-Index // '!assetIndex@arr' // DOESNT EXIST AS TYPE GUARD // 'btcusdt@assetIndex' ⋮---- /** * Subscribe to each available european options market data websocket topic, the new way: * * https://developers.binance.com/docs/derivatives/option/websocket-market-streams/New-Symbol-Info * * https://eapi.binance.com/eapi/v1/exchangeInfo */ ⋮---- // /** // * // * For those that used the Node.js Binance SDK before the v3 release, you can // * still subscribe to available market topics the "old" way, for convenience // * when migrating from the old WebsocketClient to the new multiplex client): // * // */ ⋮---- // wsClient.subscribeAggregateTrades(symbol, 'usdm'); // wsClient.subscribeTrades(symbol, 'spot'); // wsClient.subscribeTrades(symbol, 'usdm'); // wsClient.subscribeTrades(coinMSymbol, 'coinm'); // wsClient.subscribeCoinIndexPrice(coinMSymbol2); // wsClient.subscribeAllBookTickers('usdm'); // wsClient.subscribeSpotKline(symbol, '1m'); // wsClient.subscribeMarkPrice(symbol, 'usdm'); // wsClient.subscribeMarkPrice(coinMSymbol, 'coinm'); // wsClient.subscribeAllMarketMarkPrice('usdm'); // wsClient.subscribeAllMarketMarkPrice('coinm'); // wsClient.subscribeKlines(symbol, '1m', 'usdm'); // wsClient.subscribeContinuousContractKlines( // symbol, // 'perpetual', // '1m', // 'usdm', // ); // wsClient.subscribeIndexKlines(coinMSymbol2, '1m'); // wsClient.subscribeMarkPriceKlines(coinMSymbol, '1m'); // wsClient.subscribeSymbolMini24hrTicker(symbol, 'spot'); // 0116 265 5309, opt 1 // wsClient.subscribeSymbolMini24hrTicker(symbol, 'usdm'); // wsClient.subscribeSymbolMini24hrTicker(coinMSymbol, 'coinm'); // wsClient.subscribeSymbol24hrTicker(symbol, 'spot'); // wsClient.subscribeSymbol24hrTicker(symbol, 'usdm'); // wsClient.subscribeSymbol24hrTicker(coinMSymbol, 'coinm'); // wsClient.subscribeAllMini24hrTickers('spot'); // wsClient.subscribeAllMini24hrTickers('usdm'); // wsClient.subscribeAllMini24hrTickers('coinm'); // wsClient.subscribeAll24hrTickers('spot'); // wsClient.subscribeAll24hrTickers('usdm'); // wsClient.subscribeAll24hrTickers('coinm'); // wsClient.subscribeSymbolLiquidationOrders(symbol, 'usdm'); // wsClient.subscribeAllLiquidationOrders('usdm'); // wsClient.subscribeAllLiquidationOrders('coinm'); // wsClient.subscribeSpotSymbol24hrTicker(symbol); // wsClient.subscribeSpotPartialBookDepth('ETHBTC', 5, 1000); // wsClient.subscribeAllRollingWindowTickers('spot', '1d'); // wsClient.subscribeSymbolBookTicker(symbol, 'spot'); // wsClient.subscribePartialBookDepths(symbol, 5, 100, 'spot'); // wsClient.subscribeDiffBookDepth(symbol, 100, 'spot'); // wsClient.subscribeContractInfoStream('usdm'); // wsClient.subscribeContractInfoStream('coinm'); ================ File: examples/WebSockets/ws-userdata-listenKey-testnet.ts ================ import { DefaultLogger, isWsFormattedFuturesUserDataEvent, isWsFormattedSpotUserDataEvent, isWsFormattedSpotUserDataExecutionReport, isWsFormattedUserDataEvent, WebsocketClient, WsUserDataEvents, } from '../../src/index'; ⋮---- // or // import { DefaultLogger, WebsocketClient } from 'binance'; ⋮---- // console.log('using api credentials: ', { key, secret }); ⋮---- // Optional, hook and customise logging behavior ⋮---- // If you prefer, you can receive raw unprocessed data without the "beautifier": // wsClient.on('message', (data) => { // console.log('raw message received ', JSON.stringify(data, null, 2)); // }); ⋮---- function onUserDataEvent(data: WsUserDataEvents) ⋮---- // the market denotes which API category it came from // if (data.wsMarket.includes('spot')) { ⋮---- // or use a type guard, if one exists (PRs welcome) ⋮---- // Beautified/formatted events from binance: ⋮---- // The wsKey can be parsed to determine the type of message (what websocket it came from) // if (!Array.isArray(data) && data.wsKey.includes('userData')) { // return onUserDataEvent(data); // } ⋮---- // or use a type guard if available ⋮---- // response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) ⋮---- // This is a good place to check your own state is still in sync with the account state on the exchange, in case any events were missed while the library was reconnecting: // - fetch balances // - fetch positions // - fetch orders ⋮---- // wsClient.subscribeMarginUserDataStream(); // wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); // wsClient.subscribeUsdFuturesUserDataStream(); ⋮---- // setTimeout(() => { // console.log('killing all connections'); // wsClient.closeAll(); // }, 1000 * 15); ================ File: src/types/websockets/ws-events-formatted.ts ================ import { FuturesContractType, FuturesOrderType, MarginType, PositionSide, WorkingType, } from '../futures'; import { KlineInterval, numberInString, OCOOrderStatus, OCOStatus, OrderBookRowFormatted, OrderExecutionType, OrderSide, OrderStatus, OrderTimeInForce, OrderType, SelfTradePreventionMode, } from '../shared'; import { AccountUpdateEventType } from './ws-events-raw'; import { WsSharedBase } from './ws-general'; ⋮---- export interface WsMessageKlineFormatted extends WsSharedBase { eventType: 'kline' | 'indexPrice_kline'; eventTime: number; symbol: string; kline: { startTime: number; endTime: number; symbol: string; interval: KlineInterval; firstTradeId: number; lastTradeId: number; open: number; close: number; high: number; low: number; volume: number; trades: number; final: false; quoteVolume: number; volumeActive: number; quoteVolumeActive: number; ignored: number; }; } ⋮---- export interface WsMessageContinuousKlineFormatted extends WsSharedBase { eventType: 'continuous_kline'; eventTime: number; symbol: string; contractType: FuturesContractType; kline: { startTime: number; endTime: number; symbol: string; interval: KlineInterval; firstTradeId: number; lastTradeId: number; open: number; close: number; high: number; low: number; volume: number; trades: number; final: false; quoteVolume: number; volumeActive: number; quoteVolumeActive: number; ignored: number; }; } ⋮---- export interface WsMessageAggTradeFormatted extends WsSharedBase { eventType: 'aggTrade'; eventTime: number; symbol: string; tradeId: number; price: number; quantity: number; firstTradeId: number; lastTradeId: number; time: number; maker: boolean; ignored: boolean; } ⋮---- export interface WsMessageTradeFormatted extends WsSharedBase { eventType: 'trade'; eventTime: number; symbol: string; tradeId: number; price: number; quantity: number; buyerOrderId: number; sellerOrderId: number; time: number; maker: boolean; ignored: boolean; } ⋮---- export interface WsMessage24hrMiniTickerFormatted extends WsSharedBase { eventType: '24hrMiniTicker'; eventTime: number; symbol: string; contractSymbol?: string; //coinm only close: number; open: number; high: number; low: number; baseAssetVolume: number; quoteAssetVolume: number; } ⋮---- contractSymbol?: string; //coinm only ⋮---- export interface WsMessage24hrTickerFormatted extends WsSharedBase { eventType: '24hrTicker' | '!ticker@arr'; eventTime: number; symbol: string; priceChange: number; priceChangePercent: number; weightedAveragePrice: number; previousClose: number; currentClose: number; closeQuantity: number; bestBid: number; bestBidQuantity: number; bestAskPrice: number; bestAskQuantity: number; open: number; high: number; low: number; baseAssetVolume: number; quoteAssetVolume: number; openTime: number; closeTime: number; firstTradeId: number; lastTradeId: number; trades: number; } ⋮---- export interface WsMessageRollingWindowTickerFormatted extends WsSharedBase { eventType: 'ticker'; eventTime: number; symbol: string; priceChange: number; priceChangePercent: number; weightedAveragePrice: number; open: number; high: number; low: number; currentClose: number; baseAssetVolume: number; quoteAssetVolume: number; openTime: number; closeTime: number; firstTradeId: number; lastTradeId: number; trades: number; streamName: string; isWSAPIResponse: false; } ⋮---- export interface WsMessageBookTickerEventFormatted extends WsSharedBase { eventType: 'bookTicker'; updateId: number; eventTime: number; transactionTime: number; symbol: string; bidPrice: number; bidQty: number; askPrice: number; askQty: number; } ⋮---- export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { eventType: 'partialBookDepth' | 'string'; lastUpdateId: number; bids: OrderBookRowFormatted[]; asks: OrderBookRowFormatted[]; } ⋮---- /** * USER DATA WS EVENTS **/ ⋮---- interface SpotBalanceFormatted { asset: string; availableBalance: number; onOrderBalance: number; } ⋮---- export interface WsMessageSpotOutboundAccountPositionFormatted extends WsSharedBase { eventType: 'outboundAccountPosition'; eventTime: number; lastAccountUpdateTime: number; balances: SpotBalanceFormatted[]; } ⋮---- export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { eventType: 'balanceUpdate'; eventTime: number; asset: string; balanceDelta: number; clearTime: number; } ⋮---- export interface WsMessageSpotUserDataExecutionReportEventFormatted extends WsSharedBase { eventType: 'executionReport'; eventTime: number; symbol: string; newClientOrderId: string; side: OrderSide; orderType: OrderType; cancelType: OrderTimeInForce; quantity: number; price: number; stopPrice: number; icebergQuantity: number; orderListId: number; originalClientOrderId: string; executionType: OrderExecutionType; orderStatus: OrderStatus; rejectReason: string; orderId: number; lastTradeQuantity: number; accumulatedQuantity: number; lastTradePrice: number; commission: number; commissionAsset: string | null; tradeTime: number; tradeId: number; ignoreThis1: number; isOrderOnBook: false; isMaker: false; ignoreThis2: true; orderCreationTime: number; cummulativeQuoteAssetTransactedQty: number; lastQuoteAssetTransactedQty: number; orderQuoteQty: number; workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; } ⋮---- export interface OrderObjectFormatted { symbol: string; orderId: number; clientOrderId: string; } ⋮---- export interface WsMessageSpotUserDataListStatusEventFormatted extends WsSharedBase { eventType: 'listStatus'; eventTime: number; symbol: string; orderListId: number; contingencyType: 'OCO'; listStatusType: OCOStatus; listOrderStatus: OCOOrderStatus; listRejectReason: string; listClientOrderId: string; transactionTime: number; orders: OrderObjectFormatted[]; } ⋮---- export interface WsAccountUpdatedBalance { asset: string; balanceChange: number; // this is except for pnl and commission crossWalletBalance: number; walletBalance: number; } ⋮---- balanceChange: number; // this is except for pnl and commission ⋮---- export interface WsUpdatedPosition { symbol: string; marginAsset: string; positionAmount: number; entryPrice: number; accumulatedRealisedPreFee: number; unrealisedPnl: number; marginType: 'cross' | 'isolated'; isolatedWalletAmount: number; positionSide: PositionSide; } ⋮---- export interface WsMessageFuturesUserDataListenKeyExpiredFormatted extends WsSharedBase { eventType: 'listenKeyExpired'; eventTime: number; } ⋮---- export interface WsMessageFuturesMarginCalledPositionFormatted { symbol: string; positionSide: PositionSide; positionAmount: number; marginType: Uppercase; isolatedWalletAmount: number; markPrice: number; unrealisedPnl: number; maintenanceMarginRequired: number; } ⋮---- export interface WsMessageFuturesUserDataMarginCallFormatted extends WsSharedBase { eventType: 'MARGIN_CALL'; eventTime: number; crossWalletBalance: number; positions: WsMessageFuturesMarginCalledPositionFormatted[]; } ⋮---- export interface WsMessageFuturesUserDataAccountUpdateFormatted extends WsSharedBase { eventType: 'ACCOUNT_UPDATE'; eventTime: number; transactionTime: number; updateData: { updateEventType: AccountUpdateEventType; updatedBalances: WsAccountUpdatedBalance[]; updatedPositions: WsUpdatedPosition[]; }; } ⋮---- export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted extends WsSharedBase { eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; eventTime: number; transactionTime: number; order: { symbol: string; orderId: number; reason: string; }; } ⋮---- export interface WsMessageFuturesUserDataTradeLiteEventFormatted extends WsSharedBase { eventType: 'TRADE_LITE'; eventTime: number; transactionTime: number; symbol: string; originalQuantity: number; originalPrice: number; isMakerSide: boolean; clientOrderId: string; side: 'BUY' | 'SELL'; lastFilledPrice: number; lastFilledQuantity: number; tradeId: number; orderId: number; } ⋮---- export interface WsMessageFuturesUserDataTradeUpdateEventFormatted extends WsSharedBase { eventType: 'ORDER_TRADE_UPDATE'; eventTime: number; transactionTime: number; order: { symbol: string; clientOrderId: string; orderSide: OrderSide; orderType: FuturesOrderType; timeInForce: OrderTimeInForce; originalQuantity: number; originalPrice: number; averagePrice: number; stopPrice: number; executionType: OrderExecutionType; orderStatus: OrderStatus; orderId: number; lastFilledQuantity: number; orderFilledAccumulatedQuantity: number; lastFilledPrice: number; commissionAsset: string; commissionAmount: number; orderTradeTime: number; tradeId: number; bidsNotional: number; asksNotional: number; isMakerTrade: boolean; isReduceOnly: boolean; stopPriceWorkingType: WorkingType; originalOrderType: FuturesOrderType; positionSide: PositionSide; isCloseAll: boolean; realisedProfit: number; trailingStopActivationPrice?: number; trailingStopCallbackRate?: number; pP?: boolean; // ignore si?: number; // ignore ss?: number; // ignore }; } ⋮---- pP?: boolean; // ignore si?: number; // ignore ss?: number; // ignore ⋮---- export interface WsMessageFuturesUserDataAccountConfigUpdateEventFormatted extends WsSharedBase { eventType: 'ACCOUNT_CONFIG_UPDATE'; eventTime: number; transactionTime: number; assetConfiguration?: { symbol: string; leverage: number; }; accountConfiguration?: { isMultiAssetsMode: boolean; }; } ⋮---- export interface WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { eventType: 'indexPriceUpdate'; eventTime: number; symbol: string; indexPrice: number; } ⋮---- export interface WsMessageMarkPriceUpdateEventFormatted extends WsSharedBase { eventType: 'markPriceUpdate'; eventTime: number; symbol: string; markPrice: number; settlePriceEstimate: number; indexPrice?: number; // undefined for coinm /** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ fundingRate: number | ''; nextFundingTime: number; } ⋮---- indexPrice?: number; // undefined for coinm /** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ ⋮---- export interface WsLiquidationOrderFormatted { symbol: string; side: OrderSide; orderType: FuturesOrderType; timeInForce: OrderTimeInForce; quantity: number; price: number; averagePrice: number; orderStatus: OrderStatus; lastFilledQuantity: number; orderFilledAccumulatedQuantity: number; orderTradeTime: number; } ⋮---- export interface WsMessageForceOrderFormatted extends WsSharedBase { eventType: 'forceOrder'; eventTime: number; liquidationOrder: WsLiquidationOrderFormatted; } ⋮---- export interface WsMessageFuturesUserDataStrategyUpdateFormatted extends WsSharedBase { eventType: 'STRATEGY_UPDATE'; transactionTime: number; eventTime: number; strategy: { strategyId: number; strategyType: string; strategyStatus: string; symbol: string; updateTime: number; opCode: number; }; } ⋮---- export interface WsMessageFuturesUserDataGridUpdateFormatted extends WsSharedBase { eventType: 'GRID_UPDATE'; transactionTime: number; eventTime: number; grid: { strategyId: number; strategyType: string; strategyStatus: string; symbol: string; realizedPnl: numberInString; unmatchedAveragePrice: numberInString; unmatchedQuantity: numberInString; unmatchedFee: numberInString; matchedPnl: numberInString; updateTime: number; }; } ⋮---- export interface WsMessageFuturesUserDataContractInfoFormatted extends WsSharedBase { eventType: 'contractInfo'; eventTime: number; symbol: string; pair: string; contractType: string; deliveryDateTime: number; onboardDateTime: number; contractStatus: string; notionalBrackets: { notionalBracket: number; floorNotional: number; capNotional: number; maintenanceRatio: number; auxiliaryNumber: number; minLeverage: number; maxLeverage: number; }[]; } ⋮---- export type WsMessageSpotUserDataEventFormatted = | WsMessageSpotUserDataExecutionReportEventFormatted | WsMessageSpotOutboundAccountPositionFormatted | WsMessageSpotBalanceUpdateFormatted | WsMessageSpotUserDataListStatusEventFormatted; ⋮---- export type WsMessageFuturesUserDataEventFormatted = | WsMessageFuturesUserDataAccountUpdateFormatted | WsMessageFuturesUserDataListenKeyExpiredFormatted | WsMessageFuturesUserDataMarginCallFormatted | WsMessageFuturesUserDataTradeUpdateEventFormatted | WsMessageFuturesUserDataAccountConfigUpdateEventFormatted | WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted | WsMessageFuturesUserDataTradeLiteEventFormatted | WsMessageFuturesUserDataStrategyUpdateFormatted | WsMessageFuturesUserDataGridUpdateFormatted | WsMessageFuturesUserDataContractInfoFormatted; ⋮---- export type WsUserDataEvents = | WsMessageSpotUserDataEventFormatted | WsMessageFuturesUserDataEventFormatted; ⋮---- export type WsFormattedMessage = | WsUserDataEvents | WsMessageKlineFormatted | WsMessageAggTradeFormatted | WsMessageTradeFormatted | WsMessage24hrMiniTickerFormatted | WsMessage24hrTickerFormatted | WsMessageBookTickerEventFormatted | WsMessagePartialBookDepthEventFormatted | WsMessageIndexPriceUpdateEventFormatted | WsMessageMarkPriceUpdateEventFormatted | WsMessageForceOrderFormatted | WsMessage24hrMiniTickerFormatted[] | WsMessage24hrTickerFormatted[] | WsMessageRollingWindowTickerFormatted[] | WsMessageMarkPriceUpdateEventFormatted[]; ================ File: src/types/websockets/ws-events-raw.ts ================ import { FuturesOrderType, MarginType, PositionSide, WorkingType, } from '../futures'; import { KlineInterval, numberInString, OCOOrderStatus, OCOStatus, OrderBookRow, OrderExecutionType, OrderSide, OrderStatus, OrderTimeInForce, OrderType, SelfTradePreventionMode, } from '../shared'; import { WsSharedBase } from './ws-general'; ⋮---- export interface WsMessageKlineRaw extends WsSharedBase { e: 'kline'; E: number; s: string; k: { t: number; T: number; s: string; i: KlineInterval; f: number; L: number; o: numberInString; c: numberInString; h: numberInString; l: numberInString; v: numberInString; n: number; x: boolean; q: numberInString; V: numberInString; Q: numberInString; B: numberInString; }; } export interface WsMessageAggTradeRaw extends WsSharedBase { e: 'aggTrade'; E: number; s: string; a: number; p: numberInString; q: numberInString; f: number; l: number; T: number; m: boolean; M: boolean; } ⋮---- export interface WsMessageTradeRaw extends WsSharedBase { e: 'trade'; E: number; s: string; t: number; p: numberInString; q: numberInString; b: number; a: number; T: number; m: boolean; M: boolean; } ⋮---- export interface WsMessage24hrMiniTickerRaw extends WsSharedBase { e: '24hrMiniTicker'; E: number; s: string; c: numberInString; o: numberInString; h: numberInString; l: numberInString; v: numberInString; q: numberInString; } ⋮---- export interface WsMessage24hrTickerRaw extends WsSharedBase { e: '24hrTicker'; E: number; s: string; p: numberInString; P: numberInString; w: numberInString; x: numberInString; c: numberInString; Q: numberInString; b: numberInString; B: numberInString; a: numberInString; A: numberInString; o: numberInString; h: numberInString; l: numberInString; v: numberInString; q: numberInString; O: numberInString; C: numberInString; F: number; L: number; n: number; } ⋮---- export interface WsMessageRollingWindowTickerRaw extends WsSharedBase { e: '1hTicker' | '4hTicker' | '1dTicker'; E: number; s: string; p: string; P: string; w: string; o: string; h: string; l: string; c: string; v: string; q: string; O: number; C: number; F: number; L: number; n: number; } ⋮---- export interface WsMessageBookTickerEventRaw extends WsSharedBase { e: 'bookTicker'; u: number; E: number; // futures only - event time T: number; // futures only - transaction time s: string; b: numberInString; B: numberInString; a: numberInString; A: numberInString; } ⋮---- E: number; // futures only - event time T: number; // futures only - transaction time ⋮---- export interface WsMessagePartialBookDepthEventRaw extends WsSharedBase { e: 'partialBookDepth'; lastUpdateId: number; bids: OrderBookRow[]; asks: OrderBookRow[]; } ⋮---- /** * USER DATA WS EVENTS **/ ⋮---- interface SpotBalanceRaw { a: string; f: numberInString; l: numberInString; } ⋮---- export interface WsMessageSpotOutboundAccountPositionRaw extends WsSharedBase { e: 'outboundAccountPosition'; E: number; u: number; B: SpotBalanceRaw[]; } ⋮---- export interface WsMessageSpotBalanceUpdateRaw extends WsSharedBase { e: 'balanceUpdate'; E: number; a: string; d: numberInString; T: number; } ⋮---- export interface WsMessageSpotUserDataExecutionReportEventRaw extends WsSharedBase { e: 'executionReport'; E: number; s: string; c: string; S: OrderSide; o: OrderType; f: OrderTimeInForce; q: numberInString; p: numberInString; P: numberInString; F: numberInString; g: number; C: string; x: OrderExecutionType; X: OrderStatus; r: string; i: number; l: numberInString; z: numberInString; L: numberInString; n: numberInString; N: string | null; T: number; t: number; I: number; w: boolean; m: boolean; M: boolean; O: number; Z: numberInString; Y: numberInString; Q: numberInString; W: number; V: SelfTradePreventionMode; } ⋮---- export interface OrderObjectRaw { s: string; i: number; c: string; } ⋮---- export interface WsMessageSpotUserDataListStatusEventRaw extends WsSharedBase { e: 'listStatus'; E: number; s: string; g: number; c: 'OCO'; l: OCOStatus; L: OCOOrderStatus; r: string; C: string; T: number; O: OrderObjectRaw[]; } ⋮---- export type AccountUpdateEventType = | 'DEPOSIT' | 'WITHDRAW' | 'ORDER' | 'FUNDING_FEE' | 'WITHDRAW_REJECT' | 'ADJUSTMENT' | 'INSURANCE_CLEAR' | 'ADMIN_DEPOSIT' | 'ADMIN_WITHDRAW' | 'MARGIN_TRANSFER' | 'MARGIN_TYPE_CHANGE' | 'ASSET_TRANSFER' | 'OPTIONS_PREMIUM_FEE' | 'OPTIONS_SETTLE_PROFIT' | 'AUTO_EXCHANGE'; ⋮---- export interface WsMessageFuturesUserDataListenKeyExpiredRaw extends WsSharedBase { e: 'listenKeyExpired'; E: number; } ⋮---- export interface WsMessageFuturesMarginCalledPositionRaw { s: string; ps: PositionSide; pa: numberInString; mt: Uppercase; iw: numberInString; mp: numberInString; up: numberInString; mm: numberInString; } ⋮---- export interface WsMessageFuturesUserDataMarginCallRaw extends WsSharedBase { e: 'MARGIN_CALL'; E: number; cw: numberInString; p: WsMessageFuturesMarginCalledPositionRaw[]; } ⋮---- export interface WsMessageFuturesAccountUpdatePositionRaw { s: string; pa: numberInString; ep: numberInString; cr: numberInString; up: numberInString; mt: 'cross' | 'isolated'; iw: numberInString; ps: PositionSide; } ⋮---- export interface WsMessageFuturesAccountUpdateBalanceRaw { a: string; wb: numberInString; cw: numberInString; bc: numberInString; } ⋮---- export interface WsMessageFuturesUserDataAccountUpdateRaw extends WsSharedBase { e: 'ACCOUNT_UPDATE'; E: number; T: number; a: { m: AccountUpdateEventType; B: WsMessageFuturesAccountUpdateBalanceRaw[]; P: WsMessageFuturesAccountUpdatePositionRaw[]; }; } ⋮---- export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw extends WsSharedBase { e: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; E: number; T: number; or: { s: string; i: number; r: string; }; } ⋮---- export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw extends WsSharedBase { e: 'ORDER_TRADE_UPDATE'; E: number; T: number; o: { s: string; c: string; S: OrderSide; o: FuturesOrderType; f: OrderTimeInForce; q: numberInString; p: numberInString; ap: numberInString; sp: numberInString; x: OrderExecutionType; X: OrderStatus; i: number; l: numberInString; z: numberInString; L: numberInString; N: string; n: numberInString; T: numberInString; t: number; b: numberInString; a: numberInString; m: boolean; R: boolean; wt: WorkingType; ot: FuturesOrderType; ps: PositionSide; cp: boolean; AP: numberInString; cr: numberInString; rp: numberInString; pP: boolean; // ignore si: numberInString; // ignore ss: numberInString; // ignore V: string; pm: string; gtd: number; }; } ⋮---- pP: boolean; // ignore si: numberInString; // ignore ss: numberInString; // ignore ⋮---- export interface WsMessageFuturesUserDataTradeLiteEventRaw extends WsSharedBase { e: 'TRADE_LITE'; // Event Type E: number; // Event Time T: number; // Transaction Time s: string; // Symbol q: string; // Original Quantity p: string; // Original Price m: boolean; // Is this trade the maker side? c: string; // Client Order Id S: 'BUY' | 'SELL'; // Side L: string; // Last Filled Price l: string; // Order Last Filled Quantity t: number; // Trade Id i: number; // Order Id } ⋮---- e: 'TRADE_LITE'; // Event Type E: number; // Event Time T: number; // Transaction Time s: string; // Symbol q: string; // Original Quantity p: string; // Original Price m: boolean; // Is this trade the maker side? c: string; // Client Order Id S: 'BUY' | 'SELL'; // Side L: string; // Last Filled Price l: string; // Order Last Filled Quantity t: number; // Trade Id i: number; // Order Id ⋮---- export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw extends WsSharedBase { e: 'ACCOUNT_CONFIG_UPDATE'; E: number; T: number; ac?: { s: string; l: number; }; ai?: { j: boolean; }; } ⋮---- export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { e: 'indexPriceUpdate'; E: number; i: string; p: numberInString; } ⋮---- export interface WsMessageMarkPriceUpdateEventRaw extends WsSharedBase { e: 'markPriceUpdate'; E: number; s: string; p: string; P: string; i: string; r: string; T: number; } ⋮---- export interface WsMessageForceOrderRaw extends WsSharedBase { e: 'forceOrder'; E: number; o: { s: string; S: string; o: string; f: string; q: string; p: string; ap: string; X: string; l: string; z: string; T: number; }; } ⋮---- export interface WsMessageFuturesUserDataStrategyUpdateRaw extends WsSharedBase { e: 'STRATEGY_UPDATE'; // Event Type T: number; // Transaction Time E: number; // Event Time su: { si: number; // Strategy ID st: string; // Strategy Type ss: string; // Strategy Status s: string; // Symbol ut: number; // Update Time c: number; // opCode }; } ⋮---- e: 'STRATEGY_UPDATE'; // Event Type T: number; // Transaction Time E: number; // Event Time ⋮---- si: number; // Strategy ID st: string; // Strategy Type ss: string; // Strategy Status s: string; // Symbol ut: number; // Update Time c: number; // opCode ⋮---- export interface WsMessageFuturesUserDataGridUpdateRaw extends WsSharedBase { e: 'GRID_UPDATE'; // Event Type T: number; // Transaction Time E: number; // Event Time gu: { si: number; // Strategy ID st: string; // Strategy Type ss: string; // Strategy Status s: string; // Symbol r: numberInString; // Realized PNL up: numberInString; // Unmatched Average Price uq: numberInString; // Unmatched Qty uf: numberInString; // Unmatched Fee mp: numberInString; // Matched PNL ut: number; // Update Time }; } ⋮---- e: 'GRID_UPDATE'; // Event Type T: number; // Transaction Time E: number; // Event Time ⋮---- si: number; // Strategy ID st: string; // Strategy Type ss: string; // Strategy Status s: string; // Symbol r: numberInString; // Realized PNL up: numberInString; // Unmatched Average Price uq: numberInString; // Unmatched Qty uf: numberInString; // Unmatched Fee mp: numberInString; // Matched PNL ut: number; // Update Time ⋮---- export interface WsMessageFuturesUserDataContractInfoRaw extends WsSharedBase { e: 'contractInfo'; // Event Type E: number; // Event Time s: string; // Symbol ps: string; // Pair ct: string; // Contract type dt: number; // Delivery date time ot: number; // onboard date time cs: string; // Contract status bks: { bs: number; // Notional bracket bnf: number; // Floor notional of this bracket bnc: number; // Cap notional of this bracket mmr: number; // Maintenance ratio for this bracket cf: number; // Auxiliary number for quick calculation mi: number; // Min leverage for this bracket ma: number; // Max leverage for this bracket }[]; } ⋮---- e: 'contractInfo'; // Event Type E: number; // Event Time s: string; // Symbol ps: string; // Pair ct: string; // Contract type dt: number; // Delivery date time ot: number; // onboard date time cs: string; // Contract status ⋮---- bs: number; // Notional bracket bnf: number; // Floor notional of this bracket bnc: number; // Cap notional of this bracket mmr: number; // Maintenance ratio for this bracket cf: number; // Auxiliary number for quick calculation mi: number; // Min leverage for this bracket ma: number; // Max leverage for this bracket ⋮---- export type WsRawSpotUserDataEventRaw = | WsMessageSpotUserDataExecutionReportEventRaw | WsMessageSpotOutboundAccountPositionRaw | WsMessageSpotBalanceUpdateRaw | WsMessageSpotUserDataListStatusEventRaw; ⋮---- export type WsMessageFuturesUserDataEventRaw = | WsMessageFuturesUserDataAccountUpdateRaw | WsMessageFuturesUserDataListenKeyExpiredRaw | WsMessageFuturesUserDataMarginCallRaw | WsMessageFuturesUserDataOrderTradeUpdateEventRaw | WsMessageFuturesUserDataAccountConfigUpdateEventRaw | WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw | WsMessageFuturesUserDataTradeLiteEventRaw | WsMessageFuturesUserDataStrategyUpdateRaw | WsMessageFuturesUserDataGridUpdateRaw | WsMessageFuturesUserDataContractInfoRaw; ⋮---- export type WsRawMessage = | WsMessageKlineRaw | WsMessageAggTradeRaw | WsMessageTradeRaw | WsMessage24hrMiniTickerRaw | WsMessage24hrMiniTickerRaw[] | WsMessage24hrTickerRaw | WsMessage24hrTickerRaw[] | WsMessageRollingWindowTickerRaw[] | WsMessageBookTickerEventRaw | WsMessagePartialBookDepthEventRaw | WsMessageForceOrderRaw | WsRawSpotUserDataEventRaw | WsMessageIndexPriceUpdateEventRaw | WsMessageFuturesUserDataAccountUpdateRaw | WsMessageFuturesUserDataListenKeyExpiredRaw | WsMessageFuturesUserDataMarginCallRaw | WsMessageFuturesUserDataOrderTradeUpdateEventRaw | WsMessageFuturesUserDataAccountConfigUpdateEventRaw | WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw; ================ File: src/types/futures.ts ================ import { BooleanString, BooleanStringCapitalised, ExchangeFilter, KlineInterval, numberInString, OrderBookRow, OrderSide, OrderStatus, OrderTimeInForce, OrderType, RateLimiter, SelfTradePreventionMode, SymbolIcebergPartsFilter, SymbolLotSizeFilter, SymbolMarketLotSizeFilter, SymbolMaxIcebergOrdersFilter, SymbolMaxPositionFilter, SymbolPriceFilter, } from './shared'; ⋮---- export type FuturesContractType = | 'PERPETUAL' | 'CURRENT_MONTH' | 'NEXT_MONTH' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; ⋮---- export interface ContinuousContractKlinesParams { pair: string; contractType: FuturesContractType; interval: KlineInterval; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface IndexPriceKlinesParams { pair: string; interval: KlineInterval; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface SymbolKlinePaginatedParams { symbol: string; interval: KlineInterval; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface FuturesDataPaginatedParams { symbol: string; contractType?: string; period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit?: number; startTime?: number; endTime?: number; } ⋮---- export interface FuturesCoinMTakerBuySellVolumeParams { pair: string; contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit?: number; startTime?: number; endTime?: number; } ⋮---- export interface FuturesCoinMBasisParams { pair: string; contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit?: number; startTime?: number; endTime?: number; } ⋮---- export enum EnumDualSideMode { HedgeMode = 'true', OneWayMode = 'false', } ⋮---- export type DualSideMode = `${EnumDualSideMode}`; ⋮---- export enum EnumMultiAssetMode { MultiAssetsMode = 'true', SingleAssetsMode = 'false', } ⋮---- export type MultiAssetsMode = `${EnumMultiAssetMode}`; ⋮---- export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; ⋮---- export type MarginType = 'ISOLATED' | 'CROSSED'; ⋮---- export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- export type FuturesOrderType = | 'LIMIT' | 'MARKET' | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET' | 'TRAILING_STOP_MARKET'; ⋮---- export type PriceMatchMode = | 'NONE' | 'OPPONENT' | 'OPPONENT_5' | 'OPPONENT_10' | 'OPPONENT_20' | 'QUEUE' | 'QUEUE_5' | 'QUEUE_10' | 'QUEUE_20'; ⋮---- // When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. export interface NewFuturesOrderParams { symbol: string; side: OrderSide; positionSide?: PositionSide; type: FuturesOrderType; timeInForce?: OrderTimeInForce; quantity?: numberType; reduceOnly?: BooleanString; price?: numberType; newClientOrderId?: string; stopPrice?: numberType; closePosition?: BooleanString; activationPrice?: numberType; callbackRate?: numberType; workingType?: WorkingType; priceProtect?: BooleanStringCapitalised; newOrderRespType?: 'ACK' | 'RESULT'; selfTradePreventionMode?: SelfTradePreventionMode; priceMatch?: PriceMatchMode; goodTillDate?: number; // Mandatory when timeInForce is GTD } ⋮---- goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- export interface ModifyFuturesOrderParams { orderId?: number; origClientOrderId?: string; symbol: string; side: OrderSide; quantity?: numberType; price?: numberType; priceMatch?: PriceMatchMode; } ⋮---- export enum EnumPositionMarginChangeType { AddPositionMargin = 1, ReducePositionMargin = 0, } ⋮---- export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; ⋮---- export type IncomeType = | 'TRANSFER' | 'WELCOME_BONUS' | 'REALIZED_PNL' | 'FUNDING_FEE' | 'COMMISSION' | 'INSURANCE_CLEAR'; ⋮---- export interface CancelMultipleOrdersParams { symbol: string; orderIdList?: number[]; origClientOrderIdList?: string[]; } ⋮---- export interface CancelOrdersTimeoutParams { symbol: string; countdownTime?: 0 | number; } ⋮---- export interface SetLeverageParams { symbol: string; leverage: number; } ⋮---- export interface SetLeverageResult { leverage: number; maxNotionalValue: numberInString; symbol: string; } ⋮---- export interface SetMarginTypeParams { symbol: string; marginType: MarginType; } ⋮---- export interface SetIsolatedMarginParams { symbol: string; positionSide?: PositionSide; amount: number; type: PositionMarginChangeType; } ⋮---- export interface SetIsolatedMarginResult { amount: numberInString; code: 200 | number; msg: string; type: 1 | 2; } ⋮---- export interface GetPositionMarginChangeHistoryParams { symbol: string; type?: PositionMarginChangeType; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface GetIncomeHistoryParams { symbol?: string; incomeType?: IncomeType; startTime?: number; endTime?: number; limit?: number; page?: number; } ⋮---- export interface IncomeHistory { symbol?: string; incomeType: IncomeType; income: string; asset: string; time: number; info: string; tranId: number; tradeId: string; } ⋮---- export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; ⋮---- export interface GetForceOrdersParams { symbol?: string; autoCloseType?: ForceOrderCloseType; startTime?: number; endTime?: number; limit?: number; } ⋮---- export type ContactType = | 'PERPETUAL' | 'CURRENT_MONTH' | 'NEXT_MONTH' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; ⋮---- export type ContractStatus = | 'PENDING_TRADING' | 'TRADING' | 'PRE_DELIVERING' | 'DELIVERING' | 'DELIVERED' | 'CANCELLED' | 'PRE_SETTLE' | 'SETTLING' | 'CLOSE'; ⋮---- export interface FuturesSymbolPercentPriceFilter { filterType: 'PERCENT_PRICE'; multiplierUp: numberInString; multiplierDown: numberInString; multiplierDecimal: numberInString; } ⋮---- export interface FuturesSymbolMaxOrdersFilter { filterType: 'MAX_NUM_ORDERS'; limit: number; } ⋮---- export interface FuturesSymbolMaxAlgoOrdersFilter { filterType: 'MAX_NUM_ALGO_ORDERS'; limit: number; } ⋮---- export interface FuturesSymbolMinNotionalFilter { filterType: 'MIN_NOTIONAL'; notional: numberInString; } ⋮---- export type FuturesSymbolFilter = | SymbolPriceFilter | FuturesSymbolPercentPriceFilter | SymbolLotSizeFilter | FuturesSymbolMinNotionalFilter | SymbolIcebergPartsFilter | SymbolMarketLotSizeFilter | FuturesSymbolMaxOrdersFilter | FuturesSymbolMaxAlgoOrdersFilter | SymbolMaxIcebergOrdersFilter | SymbolMaxPositionFilter; ⋮---- export interface FuturesSymbolExchangeInfo { symbol: string; pair: string; contractType: ContactType; deliveryDate: number; onboardDate: number; status: ContractStatus; maintMarginPercent: numberInString; requiredMarginPercent: numberInString; baseAsset: string; quoteAsset: string; marginAsset: string; pricePrecision: number; quantityPrecision: number; baseAssetPrecision: number; quotePrecision: number; underlyingType: 'COIN' | 'INDEX'; // No other known values underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc settlePlan: number; triggerProtect: numberInString; filters: FuturesSymbolFilter[]; OrderType: OrderType[]; timeInForce: OrderTimeInForce[]; liquidationFee: numberInString; marketTakeBound: numberInString; contractSize?: number; } ⋮---- underlyingType: 'COIN' | 'INDEX'; // No other known values underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc ⋮---- export interface FuturesExchangeInfo { exchangeFilters: ExchangeFilter[]; rateLimits: RateLimiter[]; serverTime: number; assets: any[]; symbols: FuturesSymbolExchangeInfo[]; timezone: string; } ⋮---- export interface FuturesOrderBook { lastUpdateId: number; E: number; T: number; bids: OrderBookRow[]; asks: OrderBookRow[]; } ⋮---- export interface RawFuturesTrade { id: number; price: numberInString; qty: numberInString; quoteQty: numberInString; time: number; isBuyerMaker: boolean; } ⋮---- export interface AggregateFuturesTrade { a: number; p: numberInString; q: numberInString; f: number; l: number; T: number; m: boolean; } ⋮---- export interface MarkPrice { symbol: string; markPrice: numberInString; indexPrice: numberInString; estimatedSettlePrice: numberInString; lastFundingRate: numberInString; interestRate: numberInString; nextFundingTime: number; time: number; } ⋮---- export interface FundingRateHistory { symbol: string; fundingRate: numberInString; fundingTime: number; markPrice: numberInString; } ⋮---- export interface FuturesSymbolOrderBookTicker { symbol: string; bidPrice: numberInString; bidQty: numberInString; askPrice: numberInString; askQty: numberInString; time: number; } ⋮---- export interface OpenInterest { openInterest: numberInString; symbol: string; time: number; } ⋮---- export interface HistoricOpenInterest { symbol: string; sumOpenInterest: string; sumOpenInterestValue: string; CMCCirculatingSupply: string; timestamp: number; } ⋮---- export interface PositionModeParams { dualSidePosition: DualSideMode; } ⋮---- export interface ModeChangeResult { code: 200 | number; msg: 'success' | string; } ⋮---- export interface PositionModeResponse { dualSidePosition: boolean; } ⋮---- export interface MultiAssetModeResponse { multiAssetsMargin: boolean; } ⋮---- export interface NewOrderResult { clientOrderId: string; cumQty: numberInString; cumQuote: numberInString; executedQty: numberInString; orderId: number; avgPrice: numberInString; origQty: numberInString; price: numberInString; reduceOnly: boolean; side: OrderSide; positionSide: PositionSide; status: OrderStatus; stopPrice: numberInString; closePosition: boolean; symbol: string; timeInForce: OrderTimeInForce; type: FuturesOrderType; origType: FuturesOrderType; activatePrice: numberInString; priceRate: numberInString; updateTime: number; workingType: WorkingType; priceProtect: boolean; selfTradePreventionMode: SelfTradePreventionMode; priceMatch: PriceMatchMode; } ⋮---- export interface NewOrderError { code: number; msg: string; } ⋮---- export interface OrderResult { avgPrice: numberInString; clientOrderId: string; cumQuote: numberInString; executedQty: numberInString; orderId: number; origQty: numberInString; origType: FuturesOrderType; price: numberInString; reduceOnly: boolean; side: OrderSide; positionSide: PositionSide; status: OrderStatus; stopPrice: numberInString; closePosition: boolean; symbol: string; time: number; timeInForce: OrderTimeInForce; type: FuturesOrderType; activatePrice: numberInString; priceRate: numberInString; updateTime: number; workingType: WorkingType; priceProtect: boolean; selfTradePreventionMode: SelfTradePreventionMode; priceMatch: PriceMatchMode; goodTillDate: number; } ⋮---- export interface ModifyFuturesOrderResult { orderId: number; symbol: string; pair: string; status: OrderStatus; clientOrderId: string; price: numberInString; avgPrice: numberInString; origQty: numberInString; executedQty: numberInString; cumQty: numberInString; cumBase: numberInString; timeInForce: OrderTimeInForce; type: FuturesOrderType; reduceOnly: boolean; closePosition: boolean; side: OrderSide; positionSide: PositionSide; stopPrice: numberInString; workingType: WorkingType; priceProtect: boolean; origType: FuturesOrderType; updateTime: number; selfTradePreventionMode: SelfTradePreventionMode; priceMatch: PriceMatchMode; } ⋮---- export interface CancelFuturesOrderResult { clientOrderId: string; cumQty: numberInString; cumQuote: numberInString; executedQty: numberInString; orderId: number; origQty: numberInString; origType: FuturesOrderType; price: numberInString; reduceOnly: boolean; side: OrderSide; positionSide: PositionSide; status: OrderStatus; stopPrice: numberInString; closePosition: boolean; symbol: string; timeInForce: OrderTimeInForce; type: FuturesOrderType; activatePrice: numberInString; priceRate: numberInString; updateTime: number; workingType: WorkingType; priceProtect: boolean; selfTradePreventionMode: SelfTradePreventionMode; priceMatch: PriceMatchMode; } ⋮---- export interface CancelAllOpenOrdersResult { code: 200 | numberInString; msg: string; } ⋮---- export interface FuturesAccountBalance { accountAlias: string; asset: string; balance: numberInString; crossWalletBalance: numberInString; crossUnPnl: numberInString; availableBalance: numberInString; maxWithdrawAmount: numberInString; marginAvailable: boolean; updateTime: numberInString; } ⋮---- export interface FuturesCoinMAccountBalance { accountAlias: string; asset: string; balance: numberInString; withdrawAvailable: numberInString; crossWalletBalance: numberInString; crossUnPnl: numberInString; availableBalance: numberInString; updateTime: number; } ⋮---- export interface FuturesAccountAsset { asset: string; walletBalance: numberInString; unrealizedProfit: numberInString; marginBalance: numberInString; maintMargin: numberInString; initialMargin: numberInString; positionInitialMargin: numberInString; openOrderInitialMargin: numberInString; maxWithdrawAmount: numberInString; crossWalletBalance: numberInString; crossUnPnl: numberInString; availableBalance: numberInString; marginAvailable: boolean; updateTime: number; } ⋮---- export interface FuturesAccountPosition { symbol: string; initialMargin: numberInString; maintMargin: numberInString; unrealizedProfit: numberInString; positionInitialMargin: numberInString; openOrderInitialMargin: numberInString; leverage: numberInString; isolated: boolean; entryPrice: numberInString; maxNotional: numberInString; positionSide: PositionSide; positionAmt: numberInString; notional: numberInString; isolatedWallet: numberInString; updateTime: number; bidNotional: numberInString; askNotional: numberInString; } ⋮---- export interface FuturesCoinMAccountPosition { symbol: string; positionAmt: numberInString; initialMargin: numberInString; maintMargin: numberInString; unrealizedProfit: numberInString; positionInitialMargin: numberInString; openOrderInitialMargin: numberInString; leverage: numberInString; isolated: boolean; positionSide: PositionSide; entryPrice: numberInString; maxQty: numberInString; updateTime: number; } ⋮---- export interface FuturesAccountInformation { feeTier: numberInString; canTrade: boolean; canDeposit: boolean; canWithdraw: boolean; updateTime: numberInString; multiAssetsMargin: boolean; totalInitialMargin: numberInString; totalMaintMargin: numberInString; totalWalletBalance: numberInString; totalUnrealizedProfit: numberInString; totalMarginBalance: numberInString; totalPositionInitialMargin: numberInString; totalOpenOrderInitialMargin: numberInString; totalCrossWalletBalance: numberInString; totalCrossUnPnl: numberInString; availableBalance: numberInString; maxWithdrawAmount: numberInString; assets: FuturesAccountAsset[]; positions: FuturesAccountPosition[]; } ⋮---- export interface FuturesCoinMAccountInformation { assets: Omit[]; positions: FuturesCoinMAccountPosition[]; canTrade: boolean; canDeposit: boolean; canWithdraw: boolean; feeTier: number; updateTime: number; } ⋮---- export interface FuturesPosition { entryPrice: numberInString; marginType: 'isolated' | 'cross'; isAutoAddMargin: 'false' | 'true'; isolatedMargin: numberInString; leverage: numberInString; liquidationPrice: numberInString; markPrice: numberInString; maxNotionalValue: numberInString; positionAmt: numberInString; notional: numberInString; isolatedWallet: numberInString; symbol: string; unRealizedProfit: numberInString; positionSide: PositionSide; updateTime: number; } ⋮---- export interface FuturesPositionV3 { symbol: string; positionSide: PositionSide; positionAmt: numberInString; entryPrice: numberInString; breakEvenPrice: numberInString; markPrice: numberInString; unRealizedProfit: numberInString; liquidationPrice: numberInString; isolatedMargin: numberInString; notional: numberInString; marginAsset: string; isolatedWallet: numberInString; initialMargin: numberInString; maintMargin: numberInString; positionInitialMargin: numberInString; openOrderInitialMargin: numberInString; adl: number; bidNotional: numberInString; askNotional: numberInString; updateTime: number; } ⋮---- export interface FuturesPositionTrade { buyer: boolean; commission: numberInString; commissionAsset: string; id: number; maker: boolean; orderId: number; price: numberInString; qty: numberInString; quoteQty: numberInString; realizedPnl: numberInString; side: OrderSide; positionSide: PositionSide; symbol: string; time: number; } ⋮---- export interface ForceOrderResult { orderId: number; symbol: string; status: OrderStatus; clientOrderId: string; price: numberInString; avgPrice: numberInString; origQty: numberInString; executedQty: numberInString; cumQuote: numberInString; timeInForce: OrderTimeInForce; type: FuturesOrderType; reduceOnly: boolean; closePosition: boolean; side: OrderSide; stopPrice: numberInString; workingType: WorkingType; origType: FuturesOrderType; time: number; updateTime: number; } ⋮---- export interface SymbolLeverageBracket { bracket: number; initialLeverage: number; notionalCap: number; notionalFloor: number; maintMarginRatio: number; cum: number; } ⋮---- export interface SymbolLeverageBracketsResult { symbol: string; brackets: SymbolLeverageBracket[]; } ⋮---- export interface UserCommissionRate { symbol: string; makerCommissionRate: numberInString; takerCommissionRate: numberInString; } ⋮---- export interface FuturesAccountConfig { feeTier: number; canTrade: boolean; canDeposit: boolean; canWithdraw: boolean; dualSidePosition: boolean; updateTime: number; multiAssetsMargin: boolean; tradeGroupId: number; } ⋮---- export interface SymbolConfig { symbol: string; marginType: string; isAutoAddMargin: string; leverage: number; maxNotionalValue: string; } ⋮---- export interface UserForceOrder { rateLimitType: string; interval: string; intervalNum: number; limit: number; } ⋮---- export interface RebateDataOverview { brokerId: string; newTraderRebateCommission: numberInString; oldTraderRebateCommission: numberInString; totalTradeUser: number; unit: string; totalTradeVol: numberInString; totalRebateVol: numberInString; time: number; } ⋮---- export interface SetCancelTimeoutResult { symbol: string; countdownTime: numberInString; } ⋮---- export interface ChangeStats24hr { symbol: string; priceChange: numberInString; priceChangePercent: numberInString; weightedAvgPrice: numberInString; lastPrice: numberInString; lastQty: numberInString; openPrice: numberInString; highPrice: numberInString; lowPrice: numberInString; volume: numberInString; quoteVolume: numberInString; openTime: number; closeTime: number; firstId: number; // First tradeId lastId: number; // Last tradeId count: number; } ⋮---- firstId: number; // First tradeId lastId: number; // Last tradeId ⋮---- export interface OrderAmendmentDetailPrice { before: numberInString; after: numberInString; } ⋮---- export interface OrderAmendmentDetailQty { before: numberInString; after: numberInString; } ⋮---- export interface OrderAmendmentDetail { price: OrderAmendmentDetailPrice; origQty: OrderAmendmentDetailQty; count: number; } ⋮---- export interface OrderAmendment { amendmentId: number; symbol: string; pair: string; orderId: number; clientOrderId: string; time: number; amendment: OrderAmendmentDetail; } ⋮---- export interface QuarterlyContractSettlementPrice { deliveryTime: number; deliveryPrice: number; } ⋮---- export interface BasisParams { pair: string; contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; limit: number; startTime?: number; endTime?: number; } ⋮---- export interface Basis { indexPrice: string; contractType: string; basisRate: string; futuresPrice: string; annualizedBasisRate: string; basis: string; pair: string; timestamp: number; } ⋮---- export interface IndexPriceConstituent { exchange: string; symbol: string; price: numberInString; weight: numberInString; } ⋮---- export interface IndexPriceConstituents { symbol: string; time: number; constituents: IndexPriceConstituent[]; } ⋮---- export interface InsuranceFundBalance { symbols: string[]; assets: { asset: string; marginBalance: string; updateTime: number; }[]; } ⋮---- export interface ModifyOrderParams { orderId?: number; origClientOrderId?: string; symbol: string; side: 'SELL' | 'BUY'; quantity: string; price: string; priceMatch?: | 'OPPONENT' | 'OPPONENT_5' | 'OPPONENT_10' | 'OPPONENT_20' | 'QUEUE' | 'QUEUE_5' | 'QUEUE_10' | 'QUEUE_20'; recvWindow?: number; timestamp: number; } ⋮---- export interface GetFuturesOrderModifyHistoryParams { symbol: string; orderId?: number; origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface FuturesTradeHistoryDownloadId { avgCostTimestampOfLast30d: number; downloadId: string; } ⋮---- export interface FuturesTransactionDownloadLink { downloadId: string; status: 'completed' | 'processing'; url: string; expirationTimestamp: number; isExpired: boolean | null; } ⋮---- export interface PortfolioMarginProAccountInfo { maxWithdrawAmountUSD: string; asset: string; maxWithdrawAmount: string; // This field will be ignored in the response } ⋮---- maxWithdrawAmount: string; // This field will be ignored in the response ⋮---- export interface FuturesConvertPair { fromAsset: string; toAsset: string; fromAssetMinAmount: string; fromAssetMaxAmount: string; toAssetMinAmount: string; toAssetMaxAmount: string; } ⋮---- export interface FuturesConvertQuoteRequest { fromAsset: string; toAsset: string; fromAmount?: number; toAmount?: number; validTime?: '10s' | '30s' | '1m' | '2m'; } ⋮---- export interface FuturesConvertQuote { quoteId: string; ratio: string; inverseRatio: string; validTimestamp: number; toAmount: string; fromAmount: string; } ⋮---- export interface FuturesConvertOrderStatus { orderId: string; orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; fromAsset: string; fromAmount: string; toAsset: string; toAmount: string; ratio: string; inverseRatio: string; createTime: number; } ================ File: src/websocket-client-legacy.ts ================ /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ import { EventEmitter } from 'events'; import WebSocket from 'isomorphic-ws'; ⋮---- import { KlineInterval } from './types/shared'; import { WsFormattedMessage, WsUserDataEvents, } from './types/websockets/ws-events-formatted'; import { WsRawMessage } from './types/websockets/ws-events-raw'; import { WebsocketClientOptions, WSClientConfigurableOptions, WsMarket, WsResponse, } from './types/websockets/ws-general'; import Beautifier from './util/beautifier'; import { DefaultLogger } from './util/logger'; import { appendEventIfMissing, RestClientOptions } from './util/requestUtils'; import { neverGuard } from './util/typeGuards'; import { ListenKeyStateCache } from './util/websockets/listen-key-state-cache'; import { RestClientCache } from './util/websockets/rest-client-cache'; import { appendEventMarket, getContextFromWsKey, getLegacyWsStoreKeyWithContext, parseEventTypeFromMessage, parseRawWsMessageLegacy, safeTerminateWs, WS_LOGGER_CATEGORY, WsKey, } from './util/websockets/websocket-util'; import { WsStore } from './util/websockets/WsStore'; import { WsConnectionStateEnum } from './util/websockets/WsStore.types'; ⋮---- type WsEventInternalSrc = 'event' | 'function'; ⋮---- export declare interface WebsocketClientV1 { on(event: 'reply', listener: (event: WsResponse) => void): this; on(event: 'message', listener: (event: WsRawMessage) => void): this; on( event: 'formattedMessage', listener: (event: WsFormattedMessage) => void, ): this; on( event: 'formattedUserDataMessage', listener: (event: WsUserDataEvents) => void, ): this; on( event: 'error', listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, ): this; on( event: 'open' | 'reconnected' | 'reconnecting' | 'close', listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, ): this; } ⋮---- on(event: 'reply', listener: (event: WsResponse) ⋮---- on(event: 'message', listener: (event: WsRawMessage) ⋮---- on( event: 'formattedMessage', listener: (event: WsFormattedMessage) => void, ): this; ⋮---- on( event: 'formattedUserDataMessage', listener: (event: WsUserDataEvents) => void, ): this; ⋮---- on( event: 'error', listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, ): this; ⋮---- on( event: 'open' | 'reconnected' | 'reconnecting' | 'close', listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, ): this; ⋮---- /** * @deprecated This legacy websocket client creates one websocket connection per topic. * * If subscribing to a lot of topics, consider using the new multiplex `WebsocketClient`. * * To split your topics into smaller groups (one connection per group), simply make multiple multiplex WebsocketClient instances. */ export class WebsocketClientV1 extends EventEmitter ⋮---- constructor( options: WSClientConfigurableOptions, logger?: typeof DefaultLogger, ) ⋮---- // Some defaults: ⋮---- // Automatically send an authentication op/request after a connection opens, for private connections. ⋮---- // Individual requests require a signature ⋮---- // add default error handling so this doesn't crash node (if the user didn't set a handler) ⋮---- private getRestClientOptions(): RestClientOptions ⋮---- public connectToWsUrl( url: string, wsKey?: WsKey | string, forceNewConnection?: boolean, ): WebSocket ⋮---- // Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node ⋮---- // Add ws connection with key to store ⋮---- public tryWsSend(wsKey: WsKey | string, wsMessage: string) ⋮---- public tryWsPing(wsKey: WsKey | string) ⋮---- // this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- // Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- private onWsOpen(ws: WebSocket, wsKey: WsKey | string, wsUrl: string) ⋮---- private onWsClose( event: any, wsKey: WsKey | string, ws: WebSocket, wsUrl: string, ) ⋮---- // Clear any timers before we initiate revival ⋮---- // User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states ⋮---- private onWsMessage( event: MessageEvent, wsKey: WsKey | string, source: WsEventInternalSrc, ) ⋮---- // Edge case where raw event does not include event type, detect using wsKey and mutate msg.e ⋮---- // Just closing the connection (with the last parameter as true) will handle cleanup and respawn ⋮---- // emit a separate event for user data messages ⋮---- private sendPing(wsKey: WsKey | string, wsUrl: string) ⋮---- private onWsPing( event: any, wsKey: WsKey | string, ws: WebSocket, source: WsEventInternalSrc, ) ⋮---- private onWsPong( event: any, wsKey: WsKey | string, source: WsEventInternalSrc, ) ⋮---- /** * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. * If closed, trigger a reconnect immediately */ private executeReconnectableClose( wsKey: WsKey | string, reason: string, wsUrl: string, ) ⋮---- public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) ⋮---- public closeAll(shouldReconnectAfterClose?: boolean) ⋮---- public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) ⋮---- private parseWsError( context: string, error: any, wsKey: WsKey | string, wsUrl: string, ) ⋮---- private reconnectWithDelay( wsKey: WsKey | string, connectionDelayMs: number, wsUrl: string, ) ⋮---- // We'll set a new one once the new stream respawns, with a diff listenKey in the key ⋮---- private clearTimers(wsKey: WsKey | string) ⋮---- // Send a ping at intervals private clearPingTimer(wsKey: WsKey | string) ⋮---- // Expect a pong within a time limit private clearPongTimer(wsKey: WsKey | string) ⋮---- // Timer tracking that a reconnect is about to happen / in progress private clearReconnectTimer(wsKey: WsKey | string) ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string ⋮---- public getWs(wsKey: WsKey | string): WebSocket | undefined ⋮---- private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) ⋮---- /** * Send WS message to subscribe to topics. Use subscribe() to call this. */ private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) ⋮---- /** * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. */ private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) ⋮---- /** * Send WS message to unsubscribe from topics. */ public requestListSubscriptions(wsKey: WsKey, requestId: number) ⋮---- /** * Send WS message to set property state */ public requestSetProperty( wsKey: WsKey, property: 'combined' | string, value: any, requestId: number, ) ⋮---- /** * Send WS message to get property state */ public requestGetProperty( wsKey: WsKey, property: 'combined' | string, requestId: number, ) ⋮---- /** * -------------------------- * User data listen key tracking & persistence * -------------------------- **/ ⋮---- private setKeepAliveListenKeyTimer( listenKey: string, market: WsMarket, ws: WebSocket, wsKey: WsKey, symbol?: string, isTestnet?: boolean, ) ⋮---- // Set timer to keep WS alive every 50 minutes ⋮---- // 1000 * 60 ⋮---- private sendKeepAliveForMarket( listenKey: string, market: WsMarket, ws: WebSocket, wsKey: WsKey, symbol?: string, isTestnet?: boolean, ) ⋮---- private async checkKeepAliveListenKey( listenKey: string, market: WsMarket, ws: WebSocket, wsKey: WsKey, symbol?: string, isTestnet?: boolean, ) ⋮---- // Simple way to test keep alive failure handling: // throw new Error(`Fake keep alive failure`); ⋮---- // code: -1125, // message: 'This listenKey does not exist.', ⋮---- // If max failurees reached, tear down and respawn if allowed ⋮---- // reconnect follows a less automatic workflow since this is tied to a listen key (which may need a new one). // Kill connection first, with instruction NOT to reconnect automatically ⋮---- // Then respawn a connection with a potentially new listen key (since the old one may be invalid now) ⋮---- private teardownUserDataListenKey(listenKey: string, ws: WebSocket) ⋮---- private async respawnUserDataStream( market: WsMarket, symbol?: string, isTestnet?: boolean, respawnAttempt?: number, ): Promise ⋮---- // If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key ⋮---- // This timer should probably be tracked/singleton ⋮---- /** * -------------------------- * Universal market websocket streams (may apply to one or more API markets) * -------------------------- **/ ⋮---- /** * Subscribe to a universal market websocket stream */ ⋮---- public subscribeEndpoint( endpoint: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to aggregate trades for a symbol in a market category */ public subscribeAggregateTrades( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to trades for a symbol in a market category * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning */ public subscribeTrades( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to coin index for a symbol in COINM Futures markets */ public subscribeCoinIndexPrice( symbol: string, updateSpeedMs: 1000 | 3000 = 3000, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to mark price for a symbol in a market category */ public subscribeMarkPrice( symbol: string, market: 'usdm' | 'coinm', updateSpeedMs: 1000 | 3000 = 3000, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to mark price for all symbols in a market category */ public subscribeAllMarketMarkPrice( market: 'usdm' | 'coinm', updateSpeedMs: 1000 | 3000 = 3000, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to klines(candles) for a symbol in a market category */ public subscribeKlines( symbol: string, interval: KlineInterval, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to continuous contract klines(candles) for a symbol futures */ public subscribeContinuousContractKlines( symbol: string, contractType: 'perpetual' | 'current_quarter' | 'next_quarter', interval: KlineInterval, market: 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to index klines(candles) for a symbol in a coinm futures */ public subscribeIndexKlines( symbol: string, interval: KlineInterval, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to index klines(candles) for a symbol in a coinm futures */ public subscribeMarkPriceKlines( symbol: string, interval: KlineInterval, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to mini 24hr ticker for a symbol in market category. */ public subscribeSymbolMini24hrTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to mini 24hr mini ticker in market category. */ public subscribeAllMini24hrTickers( market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to 24hr ticker for a symbol in any market. */ public subscribeSymbol24hrTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to 24hr ticker in any market. */ public subscribeAll24hrTickers( market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to rolling window ticker statistics for all market symbols, * computed over multiple windows. Note that only tickers that have * changed will be present in the array. * * Notes: * - Supported window sizes: 1h,4h,1d. * - Supported markets: spot */ public subscribeAllRollingWindowTickers( market: 'spot', windowSize: '1h' | '4h' | '1d', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. */ public subscribeSymbolBookTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeAllBookTickers( market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. */ public subscribeSymbolLiquidationOrders( symbol: string, market: 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeAllLiquidationOrders( market: 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to partial book depths (snapshots). * * Note: * - spot only supports 1000ms or 100ms for updateMs * - futures only support 100, 250 or 500ms for updateMs * * Use getContextFromWsKey(data.wsKey) to extract symbol from events */ public subscribePartialBookDepths( symbol: string, levels: 5 | 10 | 20, updateMs: 100 | 250 | 500 | 1000, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to orderbook depth updates to locally manage an order book. * * Note that the updatems parameter depends on which market you're trading * * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams * * Use getContextFromWsKey(data.wsKey) to extract symbol from events */ public subscribeDiffBookDepth( symbol: string, updateMs: 100 | 250 | 500 | 1000 = 100, market: 'spot' | 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeContractInfoStream( market: 'usdm' | 'coinm', forceNewConnection?: boolean, ): WebSocket ⋮---- /** * -------------------------- * SPOT market websocket streams * -------------------------- **/ ⋮---- /** * Subscribe to aggregate trades for a symbol in spot markets. */ public subscribeSpotAggregateTrades( symbol: string, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to trades for a symbol in spot markets. */ public subscribeSpotTrades( symbol: string, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to candles for a symbol in spot markets. */ public subscribeSpotKline( symbol: string, interval: KlineInterval, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to mini 24hr ticker for a symbol in spot markets. */ public subscribeSpotSymbolMini24hrTicker( symbol: string, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to mini 24hr mini ticker in spot markets. */ public subscribeSpotAllMini24hrTickers( forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to 24hr ticker for a symbol in spot markets. */ public subscribeSpotSymbol24hrTicker( symbol: string, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to 24hr ticker in spot markets. */ public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. */ public subscribeSpotSymbolBookTicker( symbol: string, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** * Subscribe to top bid/ask levels for symbol in spot markets. */ public subscribeSpotPartialBookDepth( symbol: string, levels: 5 | 10 | 20, updateMs: 1000 | 100 = 1000, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to spot orderbook depth updates to locally manage an order book. */ public subscribeSpotDiffBookDepth( symbol: string, updateMs: 1000 | 100 = 1000, forceNewConnection?: boolean, ): WebSocket ⋮---- /** * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. * Supports spot, margin & isolated margin listen keys. */ public subscribeSpotUserDataStreamWithListenKey( listenKey: string, forceNewConnection?: boolean, isReconnecting?: boolean, ): WebSocket | undefined ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** * Subscribe to spot user data stream - listen key is automaticallyr generated. Calling multiple times only opens one connection. */ public async subscribeSpotUserDataStream( forceNewConnection?: boolean, isReconnecting?: boolean, ): Promise ⋮---- /** * Subscribe to margin user data stream - listen key is automatically generated. */ public async subscribeMarginUserDataStream( forceNewConnection?: boolean, isReconnecting?: boolean, ): Promise ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** * Subscribe to isolated margin user data stream - listen key is automatically generated. */ public async subscribeIsolatedMarginUserDataStream( symbol: string, forceNewConnection?: boolean, isReconnecting?: boolean, ): Promise ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** * -------------------------- * End of SPOT market websocket streams * -------------------------- **/ ⋮---- /** * Subscribe to USD-M Futures user data stream - listen key is automatically generated. */ public async subscribeUsdFuturesUserDataStream( isTestnet?: boolean, forceNewConnection?: boolean, isReconnecting?: boolean, ): Promise ⋮---- // Necessary so client knows this is a reconnect ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. */ public async subscribeCoinFuturesUserDataStream( isTestnet?: boolean, forceNewConnection?: boolean, isReconnecting?: boolean, ): Promise ⋮---- // Necessary so client knows this is a reconnect ⋮---- // Start & store timer to keep alive listen key (and handle expiration) ================ File: webpack/webpack.config.js ================ function generateConfig(name) { ⋮---- path: path.resolve(__dirname, '../dist'), ⋮---- // Add '.ts' and '.tsx' as resolvable extensions. ⋮---- [path.resolve(__dirname, "../lib/util/node-support.js")]: path.resolve(__dirname, "../lib/util/browser-support.js"), ⋮---- // 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'. ⋮---- // new webpack.DefinePlugin({ // 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) // }), // new BundleAnalyzerPlugin({ // defaultSizes: 'stat', // analyzerMode: 'static', // reportFilename: '../doc/bundleReport.html', // openAnalyzer: false, // }) ⋮---- module.exports = generateConfig('binanceapi'); ================ File: .eslintrc.cjs ================ // 'require-extensions', // only once moved to ESM ⋮---- // 'plugin:require-extensions/recommended', // only once moved to ESM ⋮---- // 'no-unused-vars': ['warn'], ================ 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 ================ File: tea.yaml ================ # https://tea.xyz/what-is-this-file # # DO NOT REMOVE OR EDIT THIS WARNING: # # This file is auto-generated by the TEA app. It is intended to validate ownership of your repository. # DO NOT commit this file or accept any PR if you don't know what this is. # We are aware that spammers will try to use this file to try to profit off others' work. # We take this very seriously and will take action against any malicious actors. # # If you are not the owner of this repository, and someone maliciously opens a commit with this file # please report it to us at support@tea.xyz. # # A constitution without this header is invalid. --- version: 2.0.0 codeOwners: - '0x6C226c3214ed2Cc2530Efd89F3EA403D28288B2F' quorum: 1 ================ File: examples/WebSockets/ws-userdata-wsapi.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ // or // import { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } from 'binance'; // or // const { WebsocketAPIClient, WebsocketClient, WS_KEY_MAP } = require('binance'); ⋮---- import { isWsFormattedFuturesUserDataEvent, isWsFormattedSpotBalanceUpdate, isWsFormattedSpotOutboundAccountPosition, isWsFormattedSpotUserDataEvent, isWsFormattedUserDataEvent, WebsocketAPIClient, WebsocketClient, WS_KEY_MAP, } from '../../src'; ⋮---- /** * The WS API only works with an Ed25519 API key. * * Check the rest-private-ed25519.md in this folder for more guidance * on preparing this Ed25519 API key. */ ⋮---- // returned by binance, generated using the publicKey (above) // const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; // Your Ed25519 private key is passed as the "secret" // const secret = privateKey; ⋮---- function attachEventHandlers( wsClient: TWSClient, ): void ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- // Raw events received from binance, as is: ⋮---- // console.log('raw message received ', JSON.stringify(data)); ⋮---- // Formatted events from the built-in beautifier, with fully readable property names and parsed floats: ⋮---- // We've included type guards for many events, especially on the user data stream, to help easily // identify events using simple `if` checks. // // Use `if` checks to narrow down specific events from the user data stream ⋮---- //// More general handlers, if you prefer: ⋮---- // Any user data event in spot: ⋮---- // Any user data event in futures: ⋮---- // Any user data event on any market (spot + futures) ⋮---- // Formatted user data events also have a dedicated event handler, but that's optional and no different to the above // wsClient.on('formattedUserDataMessage', (data) => { // if (isWsFormattedSpotOutboundAccountPosition(data)) { // return; // // console.log( // // 'formattedUserDataMessage->isWsFormattedSpotOutboundAccountPosition: ', // // data, // // ); // } // if (isWsFormattedSpotBalanceUpdate(data)) { // return console.log( // 'formattedUserDataMessage->isWsFormattedSpotBalanceUpdate: ', // data, // ); // } // console.log('formattedUserDataMessage: ', data); // }); ⋮---- // console.log('ws response: ', JSON.stringify(data)); ⋮---- async function main() ⋮---- // Enforce testnet ws connections, regardless of supplied wsKey: ⋮---- // Note: unless you set this to false, the SDK will automatically call // the `subscribeUserDataStream()` method again if reconnected (if you called it before): // resubscribeUserDataStreamAfterReconnect: true, ⋮---- // If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: ⋮---- // Attach your own event handlers to process incoming events // You may want to disable the default ones to avoid unnecessary logs (via attachEventListeners:false, above) ⋮---- // Optional, if you see RECV Window errors, you can use this to manage time issues. // ! However, make sure you sync your system clock first! // https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow // wsClient.setTimeOffsetMs(-5000); ⋮---- // Note: unless you set resubscribeUserDataStreamAfterReconnect to false, the SDK will // automatically call this method again if reconnected, ⋮---- WS_KEY_MAP.mainWSAPI, // The `mainWSAPI` wsKey will connect to the "spot" Websocket API on Binance. ⋮---- // Start executing the example workflow ================ File: examples/README.md ================ # Binance API - Examples This folder contains ready to go examples demonstrating various aspects of this API implementation, written in TypeScript (but they are compatible with pure JavaScript projects). Found something difficult to implement? Contribute to these examples and help others! ## Getting started - Clone the project (or download it as a zip, or install the module in your own project `npm install binance`). - Edit the sample as needed (some samples require edits, e.g API keys or import statements to import from npm, not src). - Execute the sample using tsx: `tsx examples/REST/rest-spot-public.ts`. Samples that refer to API credentials using `process.env.API_KEY_COM` can be spawned with environment variables. Unix/macOS example: ``` APIKEY='apikeypastedhere' APISECRET='apisecretpastedhere' tsx examples/WebSockets/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 three order, entry, TP, SL and submit them all at once using `submitMultipleOrders` - `rest-usdm-order.ts` Creates single entry, using `submitNewOrder` - `rest-usdm-order-sl.ts` Modify current Stop Loss order(HedgeMode only) ================ File: src/types/websockets/ws-api-responses.ts ================ import { numberInString } from '../shared'; import { OrderResponse } from '../spot'; ⋮---- /** * Error response type */ export interface ErrorResponse { code: number; msg: string; } ⋮---- export interface WSAPISessionStatus { apiKey: string; authorizedSince: number; connectedSince: number; returnRateLimits: boolean; serverTime: number; userDataStream: boolean; } ⋮---- /** * General response types */ export interface WSAPIServerTime { serverTime: number; } ⋮---- /** * Market data response types */ export interface WSAPIOrderBook { lastUpdateId: number; // [price, quantity] bids: [numberInString, numberInString][]; asks: [numberInString, numberInString][]; } ⋮---- // [price, quantity] ⋮---- export interface WSAPITrade { id: number; price: numberInString; qty: numberInString; quoteQty: numberInString; time: number; isBuyerMaker: boolean; isBestMatch: boolean; } ⋮---- export interface WSAPIAggregateTrade { a: number; // Aggregate trade ID p: numberInString; // Price q: numberInString; // Quantity f: number; // First trade ID l: number; // Last trade ID T: number; // Timestamp m: boolean; // Was the buyer the maker? M: boolean; // Was the trade the best price match? } ⋮---- a: number; // Aggregate trade ID p: numberInString; // Price q: numberInString; // Quantity f: number; // First trade ID l: number; // Last trade ID T: number; // Timestamp m: boolean; // Was the buyer the maker? M: boolean; // Was the trade the best price match? ⋮---- export type WSAPIKline = [ number, // Kline open time numberInString, // Open price numberInString, // High price numberInString, // Low price numberInString, // Close price numberInString, // Volume number, // Kline close time numberInString, // Quote asset volume number, // Number of trades numberInString, // Taker buy base asset volume numberInString, // Taker buy quote asset volume numberInString, // Unused field ]; ⋮---- number, // Kline open time numberInString, // Open price numberInString, // High price numberInString, // Low price numberInString, // Close price numberInString, // Volume number, // Kline close time numberInString, // Quote asset volume number, // Number of trades numberInString, // Taker buy base asset volume numberInString, // Taker buy quote asset volume numberInString, // Unused field ⋮---- export interface WSAPIAvgPrice { mins: number; // Average price interval (in minutes) price: numberInString; // Average price closeTime: number; // Last trade time } ⋮---- mins: number; // Average price interval (in minutes) price: numberInString; // Average price closeTime: number; // Last trade time ⋮---- export interface WSAPIFullTicker { symbol: string; priceChange: numberInString; priceChangePercent: numberInString; weightedAvgPrice: numberInString; prevClosePrice: numberInString; lastPrice: numberInString; lastQty: numberInString; bidPrice: numberInString; bidQty: numberInString; askPrice: numberInString; askQty: numberInString; openPrice: numberInString; highPrice: numberInString; lowPrice: numberInString; volume: numberInString; quoteVolume: numberInString; openTime: number; closeTime: number; firstId: number; // First trade ID lastId: number; // Last trade ID count: number; // Number of trades } ⋮---- firstId: number; // First trade ID lastId: number; // Last trade ID count: number; // Number of trades ⋮---- export interface WSAPIMiniTicker { symbol: string; openPrice: numberInString; highPrice: numberInString; lowPrice: numberInString; lastPrice: numberInString; volume: numberInString; quoteVolume: numberInString; openTime: number; closeTime: number; firstId: number; // First trade ID lastId: number; // Last trade ID count: number; // Number of trades } ⋮---- firstId: number; // First trade ID lastId: number; // Last trade ID count: number; // Number of trades ⋮---- export interface WSAPIPriceTicker { symbol: string; price: numberInString; } ⋮---- export interface WSAPIBookTicker { symbol: string; bidPrice: numberInString; bidQty: numberInString; askPrice: numberInString; askQty: numberInString; } ⋮---- /** * Futures market data response types */ export interface WSAPIFuturesOrderBook { lastUpdateId: number; E: number; // Message output time T: number; // Transaction time // [price, quantity] bids: [numberInString, numberInString][]; asks: [numberInString, numberInString][]; } ⋮---- E: number; // Message output time T: number; // Transaction time // [price, quantity] ⋮---- export interface WSAPIFuturesPriceTicker { symbol: string; price: numberInString; time: number; // Transaction time } ⋮---- time: number; // Transaction time ⋮---- export interface WSAPIFuturesBookTicker { lastUpdateId: number; symbol: string; bidPrice: numberInString; bidQty: numberInString; askPrice: numberInString; askQty: numberInString; time: number; // Transaction time } ⋮---- time: number; // Transaction time ⋮---- /** * Account response types */ export interface WSAPIAccountInformation { makerCommission: number; takerCommission: number; buyerCommission: number; sellerCommission: number; canTrade: boolean; canWithdraw: boolean; canDeposit: boolean; commissionRates: { maker: numberInString; taker: numberInString; buyer: numberInString; seller: numberInString; }; brokered: boolean; requireSelfTradePrevention: boolean; preventSor: boolean; updateTime: number; accountType: string; balances: { asset: string; free: numberInString; locked: numberInString; }[]; permissions: string[]; uid: number; } ⋮---- export interface WSAPIAccountCommission { symbol: string; standardCommission: { maker: numberInString; taker: numberInString; buyer: numberInString; seller: numberInString; }; taxCommission: { maker: numberInString; taker: numberInString; buyer: numberInString; seller: numberInString; }; discount: { enabledForAccount: boolean; enabledForSymbol: boolean; discountAsset: string; discount: numberInString; }; } ⋮---- export interface WSAPIRateLimit { rateLimitType: string; interval: string; intervalNum: number; limit: number; count: number; } ⋮---- export interface WSAPIOrder { symbol: string; orderId: number; orderListId: number; clientOrderId: string; price: numberInString; origQty: numberInString; executedQty: numberInString; cummulativeQuoteQty: numberInString; status: string; timeInForce: string; type: string; side: string; stopPrice: numberInString; icebergQty: numberInString; time: number; updateTime: number; isWorking: boolean; workingTime: number; origQuoteOrderQty: numberInString; selfTradePreventionMode: string; preventedMatchId?: number; preventedQuantity?: numberInString; } ⋮---- export interface WSAPIOrderList { orderListId: number; contingencyType: string; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; } ⋮---- export interface WSAPITrade { symbol: string; id: number; orderId: number; orderListId: number; price: numberInString; qty: numberInString; quoteQty: numberInString; commission: numberInString; commissionAsset: string; time: number; isBuyer: boolean; isMaker: boolean; isBestMatch: boolean; } ⋮---- export interface WSAPIPreventedMatch { symbol: string; preventedMatchId: number; takerOrderId: number; makerSymbol: string; makerOrderId: number; tradeGroupId: number; selfTradePreventionMode: string; price: numberInString; makerPreventedQuantity: numberInString; transactTime: number; } ⋮---- export interface WSAPIAllocation { symbol: string; allocationId: number; allocationType: string; orderId: number; orderListId: number; price: numberInString; qty: numberInString; quoteQty: numberInString; commission: numberInString; commissionAsset: string; time: number; isBuyer: boolean; isMaker: boolean; isAllocator: boolean; } ⋮---- /** * Trading response types */ export interface WSAPIOrderTestResponse { // Empty response object [key: string]: never; } ⋮---- // Empty response object ⋮---- export interface WSAPIOrderTestWithCommission { standardCommissionForOrder: { maker: numberInString; taker: numberInString; }; taxCommissionForOrder: { maker: numberInString; taker: numberInString; }; discount: { enabledForAccount: boolean; enabledForSymbol: boolean; discountAsset: string; discount: numberInString; }; } ⋮---- export interface WSAPIOrderCancel { symbol: string; origClientOrderId: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: numberInString; origQty: numberInString; executedQty: numberInString; origQuoteOrderQty: numberInString; cummulativeQuoteQty: numberInString; status: string; timeInForce: string; type: string; side: string; stopPrice?: numberInString; trailingDelta?: number; trailingTime?: number; icebergQty?: numberInString; strategyId?: number; strategyType?: number; selfTradePreventionMode: string; } ⋮---- export interface WSAPIOrderCancelReplaceResponse { cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; cancelResponse: WSAPIOrderCancel | ErrorResponse; newOrderResponse: OrderResponse | ErrorResponse | null; } ⋮---- export interface WSAPIOrderListCancelResponse { orderListId: number; contingencyType: string; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; orderReports: WSAPIOrderCancel[]; } ⋮---- /** * Order list response types */ export interface WSAPIOrderListPlaceResponse { orderListId: number; contingencyType: string; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; orderReports: OrderResponse[]; } ⋮---- export interface WSAPIOrderListStatusResponse { orderListId: number; contingencyType: string; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; } ⋮---- /** * SOR response types */ export interface WSAPISOROrderPlaceResponse { symbol: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: string; origQty: string; executedQty: string; origQuoteOrderQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: string; side: string; workingTime: number; fills: { matchType: string; price: string; qty: string; commission: string; commissionAsset: string; tradeId: number; allocId: number; }[]; workingFloor: string; selfTradePreventionMode: string; usedSor: boolean; } ⋮---- export interface WSAPISOROrderTestResponse { // Empty response object [key: string]: never; } ⋮---- // Empty response object ⋮---- export interface WSAPISOROrderTestResponseWithCommission { standardCommissionForOrder: { maker: numberInString; taker: numberInString; }; taxCommissionForOrder: { maker: numberInString; taker: numberInString; }; discount: { enabledForAccount: boolean; enabledForSymbol: boolean; discountAsset: string; discount: numberInString; }; } ⋮---- /** * Futures trading response types */ export interface WSAPIFuturesOrder { orderId: number; symbol: string; status: string; clientOrderId: string; price: string; avgPrice: string; origQty: string; executedQty: string; cumQty: string; cumQuote: string; timeInForce: string; type: string; reduceOnly: boolean; closePosition: boolean; side: string; positionSide: string; stopPrice: string; workingType: string; priceProtect: boolean; origType: string; priceMatch: string; selfTradePreventionMode: string; goodTillDate: number; updateTime: number; time?: number; activatePrice?: string; priceRate?: string; } ⋮---- export interface WSAPIFuturesPosition { entryPrice: string; breakEvenPrice: string; marginType: string; isAutoAddMargin: string; isolatedMargin: string; leverage: string; liquidationPrice: string; markPrice: string; maxNotionalValue: string; positionAmt: string; notional: string; isolatedWallet: string; symbol: string; unRealizedProfit: string; positionSide: string; updateTime: number; } ⋮---- export interface WSAPIFuturesPositionV2 { symbol: string; positionSide: string; positionAmt: string; entryPrice: string; breakEvenPrice: string; markPrice: string; unrealizedProfit: string; liquidationPrice: string; isolatedMargin: string; notional: string; marginAsset: string; isolatedWallet: string; initialMargin: string; maintMargin: string; positionInitialMargin: string; openOrderInitialMargin: string; adl: number; bidNotional: string; askNotional: string; updateTime: number; } ⋮---- /** * Futures account response types */ export interface WSAPIFuturesAccountBalanceItem { accountAlias: string; asset: string; balance: string; crossWalletBalance: string; crossUnPnl: string; availableBalance: string; maxWithdrawAmount: string; marginAvailable: boolean; updateTime: number; } ⋮---- export interface WSAPIFuturesAccountAsset { asset: string; walletBalance: string; unrealizedProfit: string; marginBalance: string; maintMargin: string; initialMargin: string; positionInitialMargin: string; openOrderInitialMargin: string; crossWalletBalance: string; crossUnPnl: string; availableBalance: string; maxWithdrawAmount: string; marginAvailable?: boolean; updateTime: number; } ⋮---- export interface WSAPIFuturesAccountPosition { symbol: string; initialMargin?: string; maintMargin?: string; unrealizedProfit: string; positionInitialMargin?: string; openOrderInitialMargin?: string; leverage?: string; isolated?: boolean; entryPrice?: string; breakEvenPrice?: string; maxNotional?: string; bidNotional?: string; askNotional?: string; positionSide: string; positionAmt: string; updateTime: number; } ⋮---- export interface WSAPIFuturesAccountStatus { feeTier?: number; canTrade?: boolean; canDeposit?: boolean; canWithdraw?: boolean; updateTime: number; multiAssetsMargin: boolean; tradeGroupId?: number; totalInitialMargin: string; totalMaintMargin: string; totalWalletBalance: string; totalUnrealizedProfit: string; totalMarginBalance: string; totalPositionInitialMargin: string; totalOpenOrderInitialMargin: string; totalCrossWalletBalance: string; totalCrossUnPnl: string; availableBalance: string; maxWithdrawAmount: string; assets: WSAPIFuturesAccountAsset[]; positions: WSAPIFuturesAccountPosition[]; } ⋮---- /** * Spot Order response types based on newOrderRespType parameter */ export interface WSAPISpotOrderACK { symbol: string; orderId: number; orderListId: number; // always -1 for singular orders clientOrderId: string; transactTime: number; } ⋮---- orderListId: number; // always -1 for singular orders ⋮---- export interface WSAPISpotOrderRESULT extends WSAPISpotOrderACK { price: numberInString; origQty: numberInString; executedQty: numberInString; origQuoteOrderQty: numberInString; cummulativeQuoteQty: numberInString; status: string; timeInForce: string; type: string; side: string; workingTime: number; selfTradePreventionMode: string; } ⋮---- export interface WSAPISpotOrderFill { price: numberInString; qty: numberInString; commission: numberInString; commissionAsset: string; tradeId: number; } ⋮---- export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { fills: WSAPISpotOrderFill[]; } ⋮---- export type WSAPISpotOrderResponse = | WSAPISpotOrderACK | WSAPISpotOrderRESULT | WSAPISpotOrderFULL; ================ File: examples/WebSockets/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'); ⋮---- import { DefaultLogger, WebsocketAPIClient } from '../../src'; ⋮---- /** * The WS API only works with an Ed25519 API key. * * Check the rest-private-ed25519.md in this folder for more guidance * on preparing this Ed25519 API key. */ ⋮---- // returned by binance, generated using the publicKey (above) // const key = 'BVv39ATnIme5TTZRcC3I04C3FqLVM7vCw3Hf7mMT7uu61nEZK8xV1V5dmhf9kifm'; // Your Ed25519 private key is passed as the "secret" // const secret = privateKey; ⋮---- // function attachEventHandlers( // wsClient: TWSClient, // ): void { // /** // * General event handlers for monitoring the WebsocketClient // */ // 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)); // }); // } ⋮---- async function main() ⋮---- // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: // trace: (...params) => console.log(new Date(), 'trace', ...params), ⋮---- // Enforce testnet ws connections, regardless of supplied wsKey // testnet: true, ⋮---- // Note: unless you set this to false, the SDK will automatically call // the `subscribeUserDataStream()` method again if reconnected (if you called it before): // resubscribeUserDataStreamAfterReconnect: true, ⋮---- // If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below: // attachEventListeners: false ⋮---- // Optional, attach basic event handlers, so nothing is left unhandled // attachEventHandlers(wsClient.getWSClient()); ⋮---- // Optional, if you see RECV Window errors, you can use this to manage time issues. // ! However, make sure you sync your system clock first! // https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow // wsClient.setTimeOffsetMs(-5000); ⋮---- // Optional. Can be used to prepare a connection before sending commands. // Can be done as part of a bootstrapping workflow, to reduce initial latency when sending the first command // await wsClient.getWSClient().connectWSAPI(WS_KEY_MAP.mainWSAPI); ⋮---- // SPOT - Market data requests ⋮---- // SPOT - Trading requests ⋮---- // SPOT - Account requests ⋮---- // FUTURES - Market data requests ⋮---- // FUTURES - Trading requests ⋮---- // FUTURES - Account requests ⋮---- // Start executing the example workflow ================ File: examples/WebSockets/ws-api-raw-promises.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { DefaultLogger, WebsocketClient, WS_KEY_MAP, WSAPIWsKey, } from '../../src/index'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient, WSAPIWsKey } from 'binance'; ⋮---- // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: ⋮---- // testnet: true, ⋮---- logger, // Optional: inject a custom logger ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- // WS API responses can be processed here too, but that is optional // console.log('ws response: ', JSON.stringify(data)); ⋮---- async function main() ⋮---- /** * * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send * your first command. That connection will then be reused for every command you send, unless the connection drops - then * it will automatically be replaced with a healthy connection. * * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands (using the connectWSAPI() method shown below). This is optional. * */ ⋮---- /** * Websockets (with their unique URLs) are tracked using the concept of a "WsKey". * * This WsKey identifies the "main" WS API connection URL (e.g. for spot & margin markets): * wss://ws-api.binance.com:443/ws-api/v3 * * Other notable keys: * - mainWSAPI2: alternative for "main" * - mainWSAPITestnet: "main" testnet * - usdmWSAPI: usdm futures * - usdmWSAPITestnet: usdm futures testnet * - coinmWSAPI: coinm futures * - coinmWSAPITestnet: coinm futures testnet */ ⋮---- // Note: if you set "testnet: true" in the config, this will automatically resolve to WS_KEY_MAP.mainWSAPITestnet (you can keep using mainWSAPI). ⋮---- // Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! // https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow // wsClient.setTimeOffsetMs(-5000); ⋮---- // Optional, see above. Can be used to prepare a connection before sending commands. This is not required and will happen automatically // await wsClient.connectWSAPI(WS_API_WS_KEY); ⋮---- // rateLimits: wsAPIResponse.result.rateLimits, // symbols: wsAPIResponse.result.symbols, ⋮---- // Start executing the example workflow ================ File: examples/WebSockets/ws-userdata-listenkey.ts ================ // or // import { // DefaultLogger, // isWsFormattedFuturesUserDataEvent, // isWsFormattedSpotUserDataEvent, // isWsFormattedSpotUserDataExecutionReport, // isWsFormattedUserDataEvent, // WebsocketClient, // WsUserDataEvents, // } from 'binance'; ⋮---- import { DefaultLogger, isWsFormattedFuturesUserDataEvent, isWsFormattedSpotUserDataEvent, isWsFormattedSpotUserDataExecutionReport, isWsFormattedUserDataEvent, WebsocketClient, WsUserDataEvents, } from '../../src/index'; import { WsConnectionStateEnum } from '../../src/util/websockets/WsStore.types'; ⋮---- // 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. */ ⋮---- // Example 1: Spot, by default, routes to the "main" wss domain "wss://stream.binance.com:9443". // No parameters needed, just call the subscribe function. ⋮---- // // Example 2: Optional: subscribe to spot via other wss domains wsClient.subscribeSpotUserDataStream('main2'); // routed to "wss://stream.binance.com:443" ⋮---- // // Example 3: cross margin ⋮---- // Example 4: isolated margin ⋮---- /** * Futures */ ⋮---- // Example 5: usdm futures ⋮---- // Example 6: coinm futures ⋮---- // Example 7: portfolio margin // wsClient.subscribePortfolioMarginUserDataStream(); ⋮---- // Example 8: portfolio margin pro // wsClient.subscribePortfolioMarginUserDataStream('portfolioMarginProUserData'); ⋮---- // 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 1: ⋮---- // Example 2: use the wsKey to route to another domain ⋮---- // Example 3: cross margin ⋮---- // Example 4: isolated margin ⋮---- // 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/shared.ts ================ // Generic numeric value stored as a string. Can be parsed via parseInt or parseFloat. // Beautifier may convert these to number, if enabled. export type numberInString = string | number; ⋮---- export type ExchangeSymbol = string; ⋮---- export type BooleanString = 'true' | 'false'; export type BooleanStringCapitalised = 'TRUE' | 'FALSE'; ⋮---- export type BinanceBaseUrlKey = | 'spot' | 'spot1' | 'spot2' | 'spot3' | 'spot4' | 'spottest' | 'usdmtest' | 'usdm' | 'coinm' | 'coinmtest' | 'voptions' | 'voptionstest' | 'papi' | 'www'; ⋮---- /** * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. */ export type OrderTimeInForce = | 'GTC' | 'IOC' | 'FOK' | 'GTX' | 'GTE_GTC' | 'GTD'; ⋮---- export type StringBoolean = 'TRUE' | 'FALSE'; ⋮---- export type SideEffects = | 'MARGIN_BUY' | 'AUTO_REPAY' | 'NO_SIDE_EFFECT' | 'AUTO_BORROW_REPAY' | 'NO_SIDE_EFFECT'; ⋮---- /** * ACK = confirmation of order acceptance (no placement/fill information) * RESULT = fill state * FULL = fill state + detail on fills and other detail */ export type OrderResponseType = 'ACK' | 'RESULT' | 'FULL'; ⋮---- export type OrderIdProperty = | 'newClientOrderId' | 'newClientStrategyId' | 'listClientOrderId' | 'limitClientOrderId' | 'stopClientOrderId' | 'aboveClientOrderId' | 'belowClientOrderId' | 'workingClientOrderId' | 'pendingAboveClientOrderId' | 'pendingBelowClientOrderId' | 'pendingClientOrderId' | 'clientAlgoId'; ⋮---- export type OrderSide = 'BUY' | 'SELL'; ⋮---- export type OrderStatus = | 'NEW' | 'PARTIALLY_FILLED' | 'FILLED' | 'CANCELED' | 'PENDING_CANCEL' | 'REJECTED' | 'EXPIRED'; ⋮---- export type OrderExecutionType = | 'NEW' | 'CANCELED' | 'REJECTED' | 'TRADE' | 'EXPIRED'; ⋮---- // listStatusType export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; ⋮---- // listOrderStatus export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; ⋮---- export type OrderType = | 'LIMIT' | 'LIMIT_MAKER' | 'MARKET' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT'; ⋮---- export type OrderListOrderType = | 'STOP_LOSS_LIMIT' | 'STOP_LOSS' | 'LIMIT_MAKER' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT'; ⋮---- export type SelfTradePreventionMode = | 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; ⋮---- export interface BasicAssetParam { asset: string; } ⋮---- export interface BasicSymbolParam { symbol: string; isIsolated?: StringBoolean; } ⋮---- export interface SymbolArrayParam { symbols: string[]; } ⋮---- export interface BasicAssetPaginatedParams { asset?: string; startTime?: number; endTime?: number; limit?: number; } export interface BasicSymbolPaginatedParams { symbol?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface SymbolPrice { symbol: string; price: numberInString; time?: number; } ⋮---- // used by spot and usdm export interface OrderBookParams { symbol: string; limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; } ⋮---- export type KlineInterval = | '1s' | '1m' | '3m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '8h' | '12h' | '1d' | '3d' | '1w' | '1M'; ⋮---- export interface GetOrderParams { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface GetOrderModifyHistoryParams { symbol: string; orderId?: number; origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface HistoricalTradesParams { symbol: string; limit?: number; fromId?: number; } ⋮---- export interface KlinesParams { symbol: string; interval: KlineInterval; startTime?: number; endTime?: number; timeZone?: string; limit?: number; } ⋮---- export type Kline = [ number, // open time numberInString, // open numberInString, // high numberInString, // low numberInString, // close numberInString, // volume number, // close time numberInString, // quote asset volume number, // number of trades numberInString, // taker buy base asset vol numberInString, // taker buy quote asset vol numberInString, // ignore? ]; ⋮---- number, // open time numberInString, // open numberInString, // high numberInString, // low numberInString, // close numberInString, // volume number, // close time numberInString, // quote asset volume number, // number of trades numberInString, // taker buy base asset vol numberInString, // taker buy quote asset vol numberInString, // ignore? ⋮---- /** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ export type FuturesKline = Kline; export interface RecentTradesParams { symbol: string; limit?: number; } ⋮---- export interface CancelOrderParams { symbol: string; orderId?: number; origClientOrderId?: string; } ⋮---- export interface AmendKeepPriorityParams { symbol: string; orderId?: number; origClientOrderId?: string; newClientOrderId?: string; newQty: numberInString; } ⋮---- export interface CancelOCOParams { symbol: string; orderListId?: number; listClientOrderId?: string; newClientOrderId?: string; } ⋮---- export interface NewOCOParams { symbol: string; listClientOrderId?: string; side: OrderSide; quantity: number; limitClientOrderId?: string; limitStrategyId?: number; limitStrategyType?: number; price: number; limitIcebergQty?: number; trailingDelta?: number; stopClientOrderId?: string; stopPrice: number; stopStrategyId?: number; stopStrategyType?: number; stopLimitPrice?: number; stopIcebergQty?: number; stopLimitTimeInForce?: OrderTimeInForce; newOrderRespType?: OrderResponseType; /** For isolated margin trading only */ isIsolated?: StringBoolean; /** Define a side effect, only for margin trading */ sideEffectType?: SideEffects; } ⋮---- /** For isolated margin trading only */ ⋮---- /** Define a side effect, only for margin trading */ ⋮---- export interface NewOrderListParams< T extends OrderResponseType = OrderResponseType, > { symbol: string; listClientOrderId?: string; side: OrderSide; quantity: number; aboveType: OrderListOrderType; aboveClientOrderId?: string; aboveIcebergQty?: number; abovePrice?: number; aboveStopPrice?: number; aboveTrailingDelta?: number; aboveTimeInForce?: OrderTimeInForce; aboveStrategyId?: number; aboveStrategyType?: number; belowType: OrderListOrderType; belowClientOrderId?: string; belowIcebergQty?: number; belowPrice?: number; belowStopPrice?: number; belowTrailingDelta?: number; belowTimeInForce?: OrderTimeInForce; belowStrategyId?: number; belowStrategyType?: number; newOrderRespType?: T; selfTradePreventionMode?: SelfTradePreventionMode; } ⋮---- export interface SymbolFromPaginatedRequestFromId { symbol: string; fromId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface GetAllOrdersParams { symbol: string; orderId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface RateLimiter { rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; interval: 'SECOND' | 'MINUTE' | 'DAY'; intervalNum: number; limit: number; } ⋮---- export interface SymbolPriceFilter { filterType: 'PRICE_FILTER'; minPrice: numberInString; maxPrice: numberInString; tickSize: numberInString; } ⋮---- export interface SymbolPercentPriceFilter { filterType: 'PERCENT_PRICE'; multiplierUp: numberInString; multiplierDown: numberInString; avgPriceMins: number; } ⋮---- export interface SymbolLotSizeFilter { filterType: 'LOT_SIZE'; minQty: numberInString; maxQty: numberInString; stepSize: numberInString; } ⋮---- export interface SymbolMinNotionalFilter { filterType: 'NOTIONAL'; minNotional: numberInString; applyMinToMarket: boolean; maxNotional: numberInString; applyMaxToMarket: boolean; avgPriceMins: number; } ⋮---- export interface SymbolIcebergPartsFilter { filterType: 'ICEBERG_PARTS'; limit: number; } ⋮---- export interface SymbolMarketLotSizeFilter { filterType: 'MARKET_LOT_SIZE'; minQty: numberInString; maxQty: numberInString; stepSize: numberInString; } ⋮---- export interface SymbolMaxOrdersFilter { filterType: 'MAX_NUM_ORDERS'; maxNumOrders: number; } ⋮---- export interface SymbolMaxAlgoOrdersFilter { filterType: 'MAX_NUM_ALGO_ORDERS'; maxNumAlgoOrders: number; } ⋮---- export interface SymbolMaxIcebergOrdersFilter { filterType: 'MAX_NUM_ICEBERG_ORDERS'; maxNumIcebergOrders: number; } ⋮---- export interface SymbolMaxPositionFilter { filterType: 'MAX_POSITION'; maxPosition: numberInString; } ⋮---- export type SymbolFilter = | SymbolPriceFilter | SymbolPercentPriceFilter | SymbolLotSizeFilter | SymbolMinNotionalFilter | SymbolIcebergPartsFilter | SymbolMarketLotSizeFilter | SymbolMaxOrdersFilter | SymbolMaxAlgoOrdersFilter | SymbolMaxIcebergOrdersFilter | SymbolMaxPositionFilter; ⋮---- export interface ExchangeMaxNumOrdersFilter { filterType: 'EXCHANGE_MAX_NUM_ORDERS'; maxNumOrders: number; } ⋮---- export interface ExchangeMaxAlgoOrdersFilter { filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; maxNumAlgoOrders: number; } ⋮---- export type ExchangeFilter = | ExchangeMaxNumOrdersFilter | ExchangeMaxAlgoOrdersFilter; ⋮---- export type OrderBookPrice = numberInString; export type OrderBookAmount = numberInString; ⋮---- export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; ⋮---- export type OrderBookPriceFormatted = number; export type OrderBookAmountFormatted = number; export type OrderBookRowFormatted = [ OrderBookPriceFormatted, OrderBookAmountFormatted, ]; ⋮---- export interface GenericCodeMsgError { code: number; msg: string; } ⋮---- export interface RowsWithTotal { rows: T[]; total: number; } ⋮---- export interface CoinStartEndLimit { coin?: string; startTime?: number; endTime?: number; limit?: number; } ================ File: examples/WebSockets/ws-userdata-README.MD ================ # User Data Streams - Binance The user data streams are the WebSocket method for asynchronously receiving events when any changes happen on your account. Including but not limited to: - order events (filled/cancelled/updated/etc) - position events - balance events (deposit/withdraw/etc) - misc events (leverage changed, position mode changed, etc) ## Mechanisms There are currently two key mechanisms for subscribing to user data events ### Mechanisms - Listen Key The older and original mechanism involves a listen key. This is requested via the REST API and then used when opening a connection to the user data stream. The listen key can expire and needs a regular "ping" (a REST API call) to keep it alive. With the "binance" Node.js & JavaScript SDK, you can easily subscribe to the user data stream via the listen key workflow, through just one function call. The SDK will automatically: - fetch a listen key - perform regular keep alive requests on the listen key - handle listen key expiry/refresh - handle reconnects, if a connection is temporarily lost All you have to do is ask for the user data stream and process incoming events - the SDK will handle the rest! For a working example, refer to the [ws-userdata-listenkey](./ws-userdata-listenkey.ts) example. **Deprecation warning: As of April 2025, the listen key workflow is also deprecated for Spot markets (no known ETA for removal).** Refer to the changelog for details: https://developers.binance.com/docs/binance-spot-api-docs/CHANGELOG#2025-04-07 ### Mechanisms - WS API User Data Stream The newer mechanism for the user data stream is via an active WebSocket API connection. This is a simpler mechanism in that it does not require a listen key. You can easily use this new mechanism via the WebsocketClient (or WebsocketAPIClient) within this SDK. For a working example, refer to the [ws-userdata-wsapi](./ws-userdata-wsapi.ts) example. ================ File: src/types/websockets/ws-api.ts ================ import { WS_KEY_MAP, WsKey } from '../../util/websockets/websocket-util'; import { FuturesExchangeInfo } from '../futures'; import { ExchangeInfo } from '../spot'; import { WSAPIAccountCommissionWSAPIRequest, WSAPIAccountInformationRequest, WSAPIAllOrderListsRequest, WSAPIAllOrdersRequest, WSAPIAvgPriceRequest, WSAPIExchangeInfoRequest, WSAPIFuturesOrderBookRequest, WSAPIFuturesOrderCancelRequest, WSAPIFuturesOrderModifyRequest, WSAPIFuturesOrderStatusRequest, WSAPIFuturesTickerBookRequest, WSAPIFuturesTickerPriceRequest, WSAPIKlinesRequest, WSAPIMyAllocationsRequest, WSAPIMyPreventedMatchesRequest, WSAPIMyTradesRequest, WSAPINewFuturesOrderRequest, WSAPINewSpotOrderRequest, WSAPIOpenOrdersCancelAllRequest, WSAPIOpenOrdersStatusRequest, WSAPIOrderAmendKeepPriorityRequest, WSAPIOrderBookRequest, WSAPIOrderCancelReplaceRequest, WSAPIOrderCancelRequest, WSAPIOrderListCancelRequest, WSAPIOrderListPlaceOCORequest, WSAPIOrderListPlaceOTOCORequest, WSAPIOrderListPlaceOTORequest, WSAPIOrderListPlaceRequest, WSAPIOrderListStatusRequest, WSAPIOrderStatusRequest, WSAPIOrderTestRequest, WSAPIRecvWindowTimestamp, WSAPISessionLogonRequest, WSAPISOROrderPlaceRequest, WSAPISOROrderTestRequest, WSAPITicker24hrRequest, WSAPITickerBookRequest, WSAPITickerPriceRequest, WSAPITickerRequest, WSAPITickerTradingDayRequest, WSAPITradesAggregateRequest, WSAPITradesHistoricalRequest, WSAPITradesRecentRequest, } from './ws-api-requests'; import { WSAPIAccountCommission, WSAPIAccountInformation, WSAPIAggregateTrade, WSAPIAllocation, WSAPIAvgPrice, WSAPIBookTicker, WSAPIFullTicker, WSAPIFuturesAccountBalanceItem, WSAPIFuturesAccountStatus, WSAPIFuturesBookTicker, WSAPIFuturesOrder, WSAPIFuturesOrderBook, WSAPIFuturesPosition, WSAPIFuturesPositionV2, WSAPIFuturesPriceTicker, WSAPIKline, WSAPIMiniTicker, WSAPIOrder, WSAPIOrderBook, WSAPIOrderCancel, WSAPIOrderCancelReplaceResponse, WSAPIOrderListCancelResponse, WSAPIOrderListPlaceResponse, WSAPIOrderListStatusResponse, WSAPIOrderTestResponse, WSAPIOrderTestWithCommission, WSAPIPreventedMatch, WSAPIPriceTicker, WSAPIRateLimit, WSAPIServerTime, WSAPISessionStatus, WSAPISOROrderPlaceResponse, WSAPISOROrderTestResponse, WSAPISOROrderTestResponseWithCommission, WSAPISpotOrderResponse, WSAPITrade, } from './ws-api-responses'; ⋮---- /** * Standard WS commands (for consumers) */ export type WsOperation = | 'SUBSCRIBE' | 'UNSUBSCRIBE' | 'LIST_SUBSCRIPTIONS' | 'SET_PROPERTY' | 'GET_PROPERTY'; ⋮---- /** * WS API commands (for sending requests via WS) */ ⋮---- //// General commands ⋮---- //// Market data commands ⋮---- //// Account commands // Spot ⋮---- // Futures ⋮---- //// Trading commands ⋮---- // Order list commands ⋮---- // SOR commands ⋮---- // user data stream ⋮---- export interface WSAPIUserDataListenKeyRequest { apiKey: string; listenKey: string; } ⋮---- export type WsAPIOperation = (typeof WS_API_Operations)[number]; ⋮---- export interface WsRequestOperationBinance< TWSTopic extends string, TWSParams extends object = any, > { method: WsOperation | WsAPIOperation; params?: (TWSTopic | string | number)[] | TWSParams; id: number; } ⋮---- 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; request?: any; } ⋮---- /** Auto-generated */ ⋮---- export type Exact = { // This part says: if there's any key that's not in T, it's an error // This conflicts sometimes for some reason... // [K: string]: never; } & { [K in keyof T]: T[K]; }; ⋮---- // This part says: if there's any key that's not in T, it's an error // This conflicts sometimes for some reason... // [K: string]: never; ⋮---- /** * List of operations supported for this WsKey (connection) */ export interface WsAPIWsKeyTopicMap { [WS_KEY_MAP.main]: WsOperation; [WS_KEY_MAP.main2]: WsOperation; [WS_KEY_MAP.main3]: WsOperation; [WS_KEY_MAP.mainTestnetPublic]: WsOperation; [WS_KEY_MAP.mainTestnetUserData]: WsOperation; [WS_KEY_MAP.marginRiskUserData]: WsOperation; [WS_KEY_MAP.usdm]: WsOperation; [WS_KEY_MAP.usdmTestnet]: WsOperation; [WS_KEY_MAP.coinm]: WsOperation; [WS_KEY_MAP.coinm2]: WsOperation; [WS_KEY_MAP.coinmTestnet]: WsOperation; [WS_KEY_MAP.eoptions]: WsOperation; [WS_KEY_MAP.portfolioMarginUserData]: WsOperation; [WS_KEY_MAP.portfolioMarginProUserData]: WsOperation; [WS_KEY_MAP.mainWSAPI]: WsAPIOperation; [WS_KEY_MAP.mainWSAPI2]: WsAPIOperation; [WS_KEY_MAP.mainWSAPITestnet]: WsAPIOperation; [WS_KEY_MAP.usdmWSAPI]: WsAPIOperation; [WS_KEY_MAP.usdmWSAPITestnet]: WsAPIOperation; [WS_KEY_MAP.coinmWSAPI]: WsAPIOperation; [WS_KEY_MAP.coinmWSAPITestnet]: WsAPIOperation; } ⋮---- export type WsAPIFuturesWsKey = | typeof WS_KEY_MAP.usdmWSAPI | typeof WS_KEY_MAP.usdmWSAPITestnet; ⋮---- /** * Request parameters expected per operation. * * - Each "key" here is the name of the command/operation. * - Each "value" here has the parameters required for the command. * * Make sure to add new topics to WS_API_Operations and the response param map too. */ export interface WsAPITopicRequestParamMap { SUBSCRIBE: never; UNSUBSCRIBE: never; LIST_SUBSCRIPTIONS: never; SET_PROPERTY: never; GET_PROPERTY: never; /** * Authentication commands & parameters: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests */ 'session.logon': WSAPISessionLogonRequest; 'session.status': void; 'session.logout': void; /** * General requests & parameters: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests */ ping: void; time: void; exchangeInfo: void | WSAPIExchangeInfoRequest; /** * Market data requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api */ depth: TWSKey extends WsAPIFuturesWsKey ? WSAPIFuturesOrderBookRequest : WSAPIOrderBookRequest; 'trades.recent': WSAPITradesRecentRequest; 'trades.historical': WSAPITradesHistoricalRequest; 'trades.aggregate': WSAPITradesAggregateRequest; klines: WSAPIKlinesRequest; uiKlines: WSAPIKlinesRequest; avgPrice: WSAPIAvgPriceRequest; 'ticker.24hr': void | WSAPITicker24hrRequest; 'ticker.tradingDay': WSAPITickerTradingDayRequest; ticker: WSAPITickerRequest; 'ticker.price': void | TWSKey extends WsAPIFuturesWsKey ? WSAPIFuturesTickerPriceRequest | undefined : WSAPITickerPriceRequest | undefined; 'ticker.book': void | TWSKey extends WsAPIFuturesWsKey ? WSAPIFuturesTickerBookRequest | undefined : WSAPITickerBookRequest | undefined; /** * Account requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ 'account.status': | void | (TWSKey extends WsAPIFuturesWsKey ? WSAPIRecvWindowTimestamp : WSAPIAccountInformationRequest); 'account.rateLimits.orders': void | WSAPIRecvWindowTimestamp; allOrders: WSAPIAllOrdersRequest; allOrderLists: void | WSAPIAllOrderListsRequest; myTrades: WSAPIMyTradesRequest; myPreventedMatches: WSAPIMyPreventedMatchesRequest; myAllocations: WSAPIMyAllocationsRequest; 'account.commission': WSAPIAccountCommissionWSAPIRequest; /** * Futures account requests & parameters: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ 'account.position': WSAPIRecvWindowTimestamp; 'v2/account.position': WSAPIRecvWindowTimestamp; 'account.balance': WSAPIRecvWindowTimestamp; 'v2/account.balance': WSAPIRecvWindowTimestamp; 'v2/account.status': WSAPIRecvWindowTimestamp; /** * Trading requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api */ 'order.place': (TWSKey extends WsAPIFuturesWsKey ? WSAPINewFuturesOrderRequest : WSAPINewSpotOrderRequest) & { timestamp?: number; }; 'order.test': WSAPIOrderTestRequest; 'order.status': TWSKey extends WsAPIFuturesWsKey ? WSAPIFuturesOrderStatusRequest : WSAPIOrderStatusRequest; 'order.cancel': TWSKey extends WsAPIFuturesWsKey ? WSAPIFuturesOrderCancelRequest : WSAPIOrderCancelRequest; 'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures 'order.cancelReplace': WSAPIOrderCancelReplaceRequest; 'order.amend.keepPriority': WSAPIOrderAmendKeepPriorityRequest; 'openOrders.status': WSAPIOpenOrdersStatusRequest; 'openOrders.cancelAll': WSAPIOpenOrdersCancelAllRequest; /** * Order list requests & parameters: */ 'orderList.place': WSAPIOrderListPlaceRequest; 'orderList.place.oco': WSAPIOrderListPlaceOCORequest; 'orderList.place.oto': WSAPIOrderListPlaceOTORequest; 'orderList.place.otoco': WSAPIOrderListPlaceOTOCORequest; 'orderList.status': WSAPIOrderListStatusRequest; 'orderList.cancel': WSAPIOrderListCancelRequest; 'openOrderLists.status': WSAPIRecvWindowTimestamp; /** * SOR requests & parameters: */ 'sor.order.place': WSAPISOROrderPlaceRequest; 'sor.order.test': WSAPISOROrderTestRequest; /** * User data stream: * * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests * * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api * * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. */ 'userDataStream.start': { apiKey: string }; 'userDataStream.ping': WSAPIUserDataListenKeyRequest; 'userDataStream.stop': WSAPIUserDataListenKeyRequest; 'userDataStream.subscribe': void; 'userDataStream.unsubscribe': void; } ⋮---- /** * Authentication commands & parameters: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests */ ⋮---- /** * General requests & parameters: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests */ ⋮---- /** * Market data requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api */ ⋮---- /** * Account requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ ⋮---- /** * Futures account requests & parameters: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ ⋮---- /** * Trading requests & parameters: * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api */ ⋮---- 'order.modify': WSAPIFuturesOrderModifyRequest; // order.modify only futures ⋮---- /** * Order list requests & parameters: */ ⋮---- /** * SOR requests & parameters: */ ⋮---- /** * User data stream: * * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/user-data-stream-requests * * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api * * Note: for the user data stream, use the subscribe*UserDataStream() methods from the WS Client. */ ⋮---- /** * Response structure expected for each operation * * - Each "key" here is a command/request supported by the WS API * - Each "value" here is the response schema for that command. */ export interface WsAPIOperationResponseMap { [key: string]: unknown; SUBSCRIBE: never; UNSUBSCRIBE: never; LIST_SUBSCRIPTIONS: never; SET_PROPERTY: never; GET_PROPERTY: never; /** * Session authentication responses: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests */ 'session.login': WSAPIResponse; 'session.status': WSAPIResponse; 'session.logout': WSAPIResponse; /** * General responses: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests */ ping: unknown; time: WSAPIResponse; exchangeInfo: WSAPIResponse; /** * Market data responses * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api */ depth: WSAPIResponse; 'trades.recent': WSAPIResponse; 'trades.historical': WSAPIResponse; 'trades.aggregate': WSAPIResponse; klines: WSAPIResponse; uiKlines: WSAPIResponse; avgPrice: 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)[] >; /** * Order list responses */ 'orderList.place': WSAPIResponse; 'orderList.place.oco': WSAPIResponse; 'orderList.place.oto': WSAPIResponse; 'orderList.place.otoco': 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.unsubscribe': WSAPIResponse; } ⋮---- /** * Session authentication responses: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/session-authentication * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/authentication-requests */ ⋮---- /** * General responses: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-requests */ ⋮---- /** * Market data responses * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/market-data-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api */ ⋮---- /** * Account responses: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/account-requests */ ⋮---- /** * Futures account responses: * https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api */ ⋮---- /** * Trading responses * - Spot: * https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/trading-requests * - Futures: * https://developers.binance.com/docs/derivatives/usds-margined-futures/trading/websocket-api */ ⋮---- /** * Order list responses */ ⋮---- /** * SOR responses */ ================ File: src/types/websockets/ws-api-requests.ts ================ import { FuturesOrderType, PositionSide, PriceMatchMode, WorkingType, } from '../futures'; import { BooleanString, BooleanStringCapitalised, KlineInterval, numberInString, 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; } ⋮---- export interface WSAPITradesRecentRequest { symbol: string; limit?: number; } ⋮---- export interface WSAPITradesHistoricalRequest { 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; } ⋮---- /** * Symbol for single symbol, or symbols for multiple symbols */ export interface WSAPITicker24hrRequest { symbol?: string; symbols?: string[]; type?: 'FULL' | 'MINI'; } ⋮---- /** * Symbol for single symbol, or symbols for multiple symbols */ export interface WSAPITickerTradingDayRequest { symbol?: string; symbols?: string[]; timeZone?: string; type?: 'FULL' | 'MINI'; } ⋮---- /** * 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'; } ⋮---- 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[]; } ⋮---- /** * Symbol for single symbol, or symbols for multiple symbols */ export interface WSAPITickerBookRequest { symbol?: string; symbols?: string[]; } ⋮---- /** * * Account request types - Spot * */ ⋮---- export interface WSAPIAllOrdersRequest { symbol: string; orderId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface WSAPIAllOrderListsRequest { fromId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface WSAPIMyTradesRequest { symbol: string; orderId?: number; startTime?: number; endTime?: number; fromId?: number; limit?: number; } ⋮---- export interface WSAPIMyPreventedMatchesRequest { symbol: string; preventedMatchId?: number; orderId?: number; fromPreventedMatchId?: number; limit?: number; } ⋮---- export interface WSAPIMyAllocationsRequest { symbol: string; startTime?: number; endTime?: number; fromAllocationId?: number; limit?: number; orderId?: number; } ⋮---- /** * Trading request types */ ⋮---- export interface WSAPINewSpotOrderRequest { symbol: string; side: OrderSide; type: OrderType; timeInForce?: OrderTimeInForce; price?: numberInString; quantity?: numberInString; quoteOrderQty?: numberInString; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; stopPrice?: numberInString; trailingDelta?: number; icebergQty?: numberInString; strategyId?: number; strategyType?: number; selfTradePreventionMode?: string; } ⋮---- export interface WSAPIOrderTestRequest { symbol: string; side: 'BUY' | 'SELL'; type: string; timeInForce?: string; price?: numberInString; quantity?: numberInString; quoteOrderQty?: numberInString; newClientOrderId?: string; stopPrice?: numberInString; trailingDelta?: number; icebergQty?: numberInString; strategyId?: number; strategyType?: number; selfTradePreventionMode?: string; computeCommissionRates?: boolean; timestamp: number; recvWindow?: number; } ⋮---- export interface WSAPIOrderStatusRequest { symbol: string; orderId?: number; origClientOrderId?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderCancelRequest { symbol: string; orderId?: number; origClientOrderId?: string; newClientOrderId?: string; cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderCancelReplaceRequest { symbol: string; cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; cancelOrderId?: number; cancelOrigClientOrderId?: string; cancelNewClientOrderId?: string; side: 'BUY' | 'SELL'; type: string; timeInForce?: string; price?: numberInString; quantity?: numberInString; quoteOrderQty?: numberInString; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; stopPrice?: numberInString; trailingDelta?: number; icebergQty?: numberInString; strategyId?: number; strategyType?: number; selfTradePreventionMode?: string; cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderAmendKeepPriorityRequest { symbol: string; orderId?: number | string; origClientOrderId?: string; newClientOrderId?: string; newQty?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOpenOrdersStatusRequest { symbol?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOpenOrdersCancelAllRequest { symbol: string; recvWindow?: number; timestamp: number; } ⋮---- /** * Order list request types */ export interface WSAPIOrderListPlaceRequest { symbol: string; side: 'BUY' | 'SELL'; price: numberInString; quantity: numberInString; listClientOrderId?: string; limitClientOrderId?: string; limitIcebergQty?: numberInString; limitStrategyId?: number; limitStrategyType?: number; stopPrice?: numberInString; trailingDelta?: number; stopClientOrderId?: string; stopLimitPrice?: numberInString; stopLimitTimeInForce?: string; stopIcebergQty?: numberInString; stopStrategyId?: number; stopStrategyType?: number; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; selfTradePreventionMode?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderListPlaceOCORequest { symbol: string; side: 'BUY' | 'SELL'; quantity: numberInString; listClientOrderId?: string; aboveType: | 'STOP_LOSS_LIMIT' | 'STOP_LOSS' | 'LIMIT_MAKER' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT'; aboveClientOrderId?: string; aboveIcebergQty?: numberInString; abovePrice?: numberInString; aboveStopPrice?: numberInString; aboveTrailingDelta?: number; aboveTimeInForce?: string; aboveStrategyId?: number; aboveStrategyType?: number; belowType: | 'STOP_LOSS' | 'STOP_LOSS_LIMIT' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT' | 'LIMIT_MAKER'; belowClientOrderId?: string; belowIcebergQty?: numberInString; belowPrice?: numberInString; belowStopPrice?: numberInString; belowTrailingDelta?: number; belowTimeInForce?: string; belowStrategyId?: number; belowStrategyType?: number; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; selfTradePreventionMode?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderListPlaceOTORequest { symbol: string; listClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; selfTradePreventionMode?: string; workingType: 'LIMIT' | 'LIMIT_MAKER'; workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: numberInString; workingQuantity: numberInString; workingIcebergQty?: numberInString; workingTimeInForce?: string; workingStrategyId?: number; workingStrategyType?: number; pendingType: string; pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: numberInString; pendingStopPrice?: numberInString; pendingTrailingDelta?: numberInString; pendingQuantity: numberInString; pendingIcebergQty?: numberInString; pendingTimeInForce?: string; pendingStrategyId?: number; pendingStrategyType?: number; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderListPlaceOTOCORequest { symbol: string; listClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; selfTradePreventionMode?: string; workingType: 'LIMIT' | 'LIMIT_MAKER'; workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: numberInString; workingQuantity: numberInString; workingIcebergQty?: numberInString; workingTimeInForce?: string; workingStrategyId?: number; workingStrategyType?: number; pendingSide: 'BUY' | 'SELL'; pendingQuantity: number | string; pendingAboveType: | 'STOP_LOSS_LIMIT' | 'STOP_LOSS' | 'LIMIT_MAKER' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: numberInString; pendingAboveStopPrice?: numberInString; pendingAboveTrailingDelta?: numberInString; pendingAboveIcebergQty?: numberInString; pendingAboveTimeInForce?: string; pendingAboveStrategyId?: number; pendingAboveStrategyType?: number; pendingBelowType: | 'STOP_LOSS' | 'STOP_LOSS_LIMIT' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT' | 'LIMIT_MAKER'; pendingBelowClientOrderId?: string; pendingBelowPrice?: numberInString; pendingBelowStopPrice?: numberInString; pendingBelowTrailingDelta?: numberInString; pendingBelowIcebergQty?: numberInString; pendingBelowTimeInForce?: string; pendingBelowStrategyId?: number; pendingBelowStrategyType?: number; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderListStatusRequest { origClientOrderId?: string; orderListId?: number; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIOrderListCancelRequest { symbol: string; orderListId?: number; listClientOrderId?: string; newClientOrderId?: string; recvWindow?: number; timestamp: number; } ⋮---- /** * SOR request types */ export interface WSAPISOROrderPlaceRequest { symbol: string; side: 'BUY' | 'SELL'; type: 'LIMIT' | 'MARKET'; timeInForce?: string; price?: numberInString; quantity: numberInString; newClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; icebergQty?: numberInString; strategyId?: number; strategyType?: number; selfTradePreventionMode?: string; timestamp: number; recvWindow?: number; } ⋮---- export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { computeCommissionRates?: boolean; }; ⋮---- /** * Futures market data request types */ ⋮---- export interface WSAPIFuturesOrderBookRequest { symbol: string; limit?: number; } ⋮---- export interface WSAPIFuturesTickerPriceRequest { symbol?: string; } ⋮---- export interface WSAPIFuturesTickerBookRequest { symbol?: string; } ⋮---- /** * Futures trading request types */ ⋮---- export interface WSAPINewFuturesOrderRequest { symbol: string; side: OrderSide; positionSide?: PositionSide; type: FuturesOrderType; timeInForce?: OrderTimeInForce; quantity?: numberType; reduceOnly?: BooleanString; price?: numberType; newClientOrderId?: string; stopPrice?: numberType; closePosition?: BooleanString; activationPrice?: numberType; callbackRate?: numberType; workingType?: WorkingType; priceProtect?: BooleanStringCapitalised; newOrderRespType?: 'ACK' | 'RESULT'; selfTradePreventionMode?: SelfTradePreventionMode; priceMatch?: PriceMatchMode; goodTillDate?: number; // Mandatory when timeInForce is GTD recvWindow?: number; timestamp: number; } ⋮---- goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- export interface WSAPIFuturesOrderModifyRequest { symbol: string; orderId?: number; origClientOrderId?: string; side: 'BUY' | 'SELL'; quantity: numberInString; price: numberInString; priceMatch?: | 'NONE' | 'OPPONENT' | 'OPPONENT_5' | 'OPPONENT_10' | 'OPPONENT_20' | 'QUEUE' | 'QUEUE_5' | 'QUEUE_10' | 'QUEUE_20'; origType?: string; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIFuturesOrderCancelRequest { symbol: string; orderId?: number; origClientOrderId?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIFuturesOrderStatusRequest { symbol: string; orderId?: number; origClientOrderId?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIFuturesPositionRequest { symbol?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIFuturesPositionV2Request { symbol?: string; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIAccountInformationRequest { omitZeroBalances?: boolean; recvWindow?: number; timestamp: number; } ⋮---- export interface WSAPIAccountCommissionWSAPIRequest { symbol: string; } ================ File: src/main-client.ts ================ 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, AlphaKline, AlphaKlinesParams, AlphaTicker, AlphaToken, ApiKeyBrokerSubAccount, APIPermissions, APITradingStatus, ApplicationStatus, AssetDetail, BasicFromPaginatedParams, BasicFuturesSubAccountParams, BasicMarginAssetParams, BasicSubAccount, BasicTimeRangeParam, BethRewardsHistory, 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, DustInfo, DustLog, EditInvestmentPlanParams, EditInvestmentPlanResponse, EnableConvertSubAccountParams, EnableFuturesBrokerSubAccountParams, EnableFuturesBrokerSubAccountResponse, EnableMarginApiKeyBrokerSubAccountParams, EnableMarginBrokerSubAccountParams, EnableMarginBrokerSubAccountResponse, EnableOptionsForSubAccountResponse, EnableOrDisableIPRestrictionForSubAccountParams, EnableUniversalTransferApiKeyBrokerSubAccountParams, EnableUniversalTransferApiKeyBrokerSubAccountResponse, ETHRateHistory, EthRedemptionHistory, EthStakingHistory, ExchangeInfo, ExchangeInfoParams, FixedAndActivityProjectParams, FixedAndActivityProjectPositionParams, FlexibleCryptoLoanBorrowHistory, FlexibleLoanAssetData, FlexibleLoanCollateralAssetData, FlexibleLoanLiquidationHistoryRecord, FlexibleLoanLTVAdjustmentHistory, FlexibleLoanOngoingOrder, FlexibleRedemptionRecord, FlexibleRewardsHistory, FlexibleSubscriptionPreview, ForceLiquidationRecord, FundingAsset, FutureAccountTransfer, FuturesPositionRisk, GetAlgoHistoricalOrdersParams, GetAlgoSubOrdersParams, GetAlgoSubOrdersResponse, GetAllConvertPairsParams, GetApiKeyBrokerSubAccountParams, GetApplicationStatusParams, GetAssetParams, GetBethRewardsHistoryParams, 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, 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, GetInstitutionalLoanRiskUnitDetailsParams, GetLoanableAssetsDataParams, GetLoanBorrowHistoryParams, GetLoanCoinPaginatedHistoryParams, GetLoanLTVAdjustmentHistoryParams, GetLoanOngoingOrdersParams, GetLoanRepaymentHistoryParams, GetLockedRedemptionRecordParams, GetLockedRewardsHistory, GetLockedRewardsHistoryParams, GetLockedSubscriptionPreviewParams, GetLockedSubscriptionRecordParams, GetMarginAccountBorrowRepayRecordsParams, GetMarginCapitalFlowParams, GetMarginInterestHistoryParams, 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, GetSmallLiabilityExchangeHistoryParams, GetSolStakingHistoryReq, GetSourceAssetListParams, GetSourceAssetListResponse, GetSpotAlgoHistoricalOrdersParams, GetSpotAlgoSubOrdersParams, GetSpotAlgoSubOrdersResponse, GetSpotRebateHistoryRecordsParams, GetSpotRebateHistoryRecordsResponse, GetStatisticListParams, GetStatisticListResponse, GetSubAccountDepositHistoryParams, GetSubscriptionTransactionHistoryParams, GetTargetAssetListParams, GetTargetAssetListResponse, GetTargetAssetROIParams, GetTravelRuleDepositHistoryParams, GetTravelRuleWithdrawHistoryParams, GetTravelRuleWithdrawHistoryV2Params, GetUniversalTransferBrokerParams, GetVipLoanOngoingOrdersParams, GetVipLoanRepaymentHistoryParams, GetWbethRewardsHistoryResponse, GetWrapHistoryParams, HistoricalAlgoOrder, HistoricalDataLink, HistoricalSpotAlgoOrder, IndexLinkedPlanRedemptionRecord, InstitutionalLoanBorrowParams, InstitutionalLoanBorrowResponse, InstitutionalLoanInterestHistoryResponse, 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, MarginOrderCountUsageResponse, MarginOTOCOOrder, MarginOTOOrder, MarginTransactionResponse, NewFutureAccountTransferParams, 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, PortfolioMarginProAccountBalance, PortfolioMarginProSpanAccountInfo, PreventedMatch, PreventedMatchesParams, PurchaseFlexibleProductResponse, PurchaseRecordParams, QueryBrokerFuturesCommissionRebateParams, QueryBrokerSpotCommissionRebateParams, QueryCrossMarginAccountDetailsParams, QueryCrossMarginFeeDataParams, QueryCrossMarginPairResponse, QueryIsolatedMarginTierDataParams, QueryMarginAccountAllOCOParams, QueryMarginAccountTradeListParams, QueryMarginAssetResponse, QueryMarginInterestRateHistoryParams, QueryMarginPriceIndexResponse, QueryMarginRecordParams, QueryMaxBorrowResponse, QueryMaxTransferOutAmountResponse, QuerySubAccountCoinFuturesCommissionParams, QuerySubAccountFuturesAssetInfoParams, QuerySubAccountFuturesCommissionParams, QuerySubAccountSpotMarginAssetInfoParams, RawAccountTrade, RawTrade, RedeemBlvtParams, RedeemBlvtResponse, RedeemEthParams, RedeemEthResponse, RedeemGiftCardParams, RedeemSolResponse, RemoveBSwapLiquidityParams, RepayCryptoFlexibleLoanParams, RepayCryptoFlexibleLoanResponse, RepayCryptoLoanFlexibleWithCollateralParams, RepayCryptoLoanFlexibleWithCollateralResponse, RepayCryptoLoanParams, RepayCryptoLoanResponse, ReplaceSpotOrderParams, ReplaceSpotOrderResultSuccess, RollingWindowTickerParams, SetAutoSubscribeParams, 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, SpotOrder, StakingBasicParams, StakingHistory, StakingHistoryParams, StakingPersonalLeftQuota, StakingProduct, StakingProductPosition, StakingProductType, SubAccountAddOrDeleteIPList, SubAccountAssetDetails, SubAccountAssets, SubAccountAssetsParams, SubaccountBalances, SubAccountBrokerMarginAsset, SubaccountBrokerSpotAsset, SubAccountCOINMDetail, SubAccountCOINMPositionRisk, SubAccountCOINMSummary, SubAccountDeposit, SubAccountDepositAddress, SubAccountDepositAddressParams, SubAccountDepositHistoryList, SubAccountDepositHistoryParams, SubAccountEnableFutures, SubAccountEnableLeverageToken, SubAccountEnableMargin, SubAccountEnableOrDisableIPRestriction, SubAccountFuturesAccountDetail, SubAccountFuturesAccountSummary, SubAccountFuturesAssetTransfer, SubAccountFuturesAssetTransferHistory, SubAccountFuturesAssetTransferHistoryParams, SubAccountFuturesAssetTransferParams, SubAccountListParams, SubAccountListResponse, SubAccountMarginAccountDetail, SubAccountMovePosition, SubAccountMovePositionHistory, SubAccountMovePositionHistoryParams, SubAccountMovePositionParams, SubAccountsMarginAccountSummary, SubAccountSpotAssetsSummary, SubAccountSpotAssetsSummaryParams, SubAccountSpotAssetTransferHistory, SubAccountSpotAssetTransferHistoryParams, SubAccountStatus, SubAccountSummaryOnFuturesAccountV2Params, SubAccountTransactionStatistics, SubAccountTransfer, SubAccountTransferHistory, SubAccountTransferHistoryParams, SubAccountTransferParams, SubAccountTransferToMasterParams, SubAccountTransferToSameMasterParams, SubAccountUniversalTransfer, SubAccountUniversalTransferHistoryParams, SubAccountUniversalTransferHistoryResponse, SubAccountUniversalTransferParams, SubAccountUSDMDetail, SubAccountUSDMPositionRisk, SubAccountUSDMSummary, SubmitConvertLimitOrderParams, SubmitDepositCreditParams, SubmitDepositCreditResponse, SubmitHashrateResaleParams, SubmitIndexLinkedPlanRedemptionParams, SubmitMarginOTOCOOrderParams, SubmitMarginOTOOrderParams, SubmitOneTimeTransactionParams, SubmitOneTimeTransactionResponse, SubmitSpotTwapNewOrderParams, SubmitSpotTwapNewOrderResponse, SubmitTravelRuleDepositQuestionnaireParams, SubmitTravelRuleDepositQuestionnaireResponse, SubmitTwapNewOrderParams, SubmitTwapNewOrderResponse, SubmitVpNewOrderParams, SubmitVpNewOrderResponse, SubscribeBlvtParams, SubscribeBlvtResponse, SubscribeDualInvestmentProductParams, SubscribeDualInvestmentProductResponse, SubscribeEthStakingV2Response, SubscribeSolStakingResponse, SymbolOrderBookTicker, SymbolTradeFee, SystemStatusResponse, TargetAssetROI, Ticker24hrResponse, ToggleBNBBurnParams, TradingDayTickerArray, TradingDayTickerFull, TradingDayTickerMini, TradingDayTickerParams, TradingDayTickerSingle, TransferBrokerSubAccount, TransferBrokerSubAccountParams, TravelRuleDepositHistoryRecord, TravelRuleWithdrawHistoryRecord, UniversalTransferBrokerParams, UniversalTransferHistoryParams, UniversalTransferParams, UpdateIpRestrictionForSubApiKey, UsdtMarginedFuturesResponse, UserAsset, VASPInfo, VipCollateralAccount, VipLoanAccruedInterestParams, VipLoanAccruedInterestRecord, VipLoanBorrowParams, VipLoanBorrowResponse, VipLoanInterestRateHistoryParams, VipLoanInterestRateRecord, VipLoanRenewParams, VipLoanRenewResponse, VipLoanRepaymentHistory, VipLoanRepayParams, VipLoanRepayResponse, VipOngoingOrder, VirtualSubAccount, WalletBalance, WithdrawAddress, WithdrawAssetsFromManagedSubAccountParams, 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 ⋮---- getAggregateTrades( params: SymbolFromPaginatedRequestFromId, ): Promise ⋮---- getKlines(params: KlinesParams): Promise ⋮---- getUIKlines(params: KlinesParams): Promise ⋮---- getAvgPrice(params: ⋮---- get24hrChangeStatistics(params?: { symbols?: string[]; // use for multiple symbols type?: 'FULL' | 'MINI'; // default is FULL }): 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 }): 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 }): 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 }): 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 }): 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 ⋮---- 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 ⋮---- 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 ⋮---- /** * * 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 ⋮---- 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 ⋮---- submitUniversalTransfer( params: UniversalTransferParams, ): Promise< ⋮---- getUniversalTransferHistory( params: UniversalTransferHistoryParams, ): Promise ⋮---- getDust(params: ⋮---- convertDustToBnb(params: ConvertDustParams): 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 */ getOnboardedVASPList(): 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< ⋮---- /** * @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 ⋮---- /** * * 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; }): Promise ⋮---- getAlgoSubOrders( params: GetAlgoSubOrdersParams, ): Promise ⋮---- getAlgoOpenOrders(): Promise< ⋮---- getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< ⋮---- /** * * ALGO TRADING Endpoints - Spot algo * **/ ⋮---- submitSpotAlgoTwapOrder( params: SubmitSpotTwapNewOrderParams, ): Promise ⋮---- cancelSpotAlgoOrder(params: { 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< ⋮---- 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< ⋮---- getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< ⋮---- getCryptoLoanLTVAdjustmentHistory( params: GetLoanLTVAdjustmentHistoryParams, ): Promise< ⋮---- 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 ⋮---- /** * * 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< ⋮---- 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 ⋮---- /** * * 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 ⋮---- bnbTransfer(params: BnbTransferParams): Promise< ⋮---- submitPortfolioMarginProFullTransfer(): Promise< ⋮---- submitPortfolioMarginProSpecificTransfer(params: ⋮---- 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 ⋮---- mintPortfolioMarginBFUSD( params: PMProMintBFUSDParams, ): Promise ⋮---- 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 * **/ ⋮---- borrowInstitutionalLoan( params: InstitutionalLoanBorrowParams, ): Promise ⋮---- getInstLoanInterestHistory( params?: GetInstitutionalLoanInterestHistoryParams, ): Promise ⋮---- repayInstitutionalLoan( params: InstitutionalLoanRepayParams, ): Promise ⋮---- getInstLoanBorrowRepayRecords( params: GetInstitutionalLoanBorrowRepayRecordsParams, ): 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: ⋮---- /** * * 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 - Account 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 /** * * 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 ⋮---- /** * @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< ================ 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'; ⋮---- 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 interface DustInfoDetail { asset: string; assetFullName: string; amountFree: numberInString; toBTC: numberInString; toBNB: numberInString; toBNBOffExchange: numberInString; exchange: numberInString; } ⋮---- export interface DustInfo { details: DustInfoDetail[]; totalTransferBtc: numberInString; totalTransferBNB: numberInString; dribbletPercentage: numberInString; } ⋮---- export interface DustConversionResult { amount: numberInString; fromAsset: string; operateTime: number; serviceChargeAmount: numberInString; tranId: number; transferedAmount: numberInString; } ⋮---- export interface DustConversion { totalServiceCharge: numberInString; totalTransfered: numberInString; transferResult: DustConversionResult[]; } ⋮---- export interface UserAssetDribbletDetail { transId: number; serviceChargeAmount: numberInString; amount: numberInString; operateTime: number; transferedAmount: numberInString; fromAsset: string; } ⋮---- export interface UserAssetDribblet { operateTime: number; totalTransferedAmount: numberInString; totalServiceChargeAmount: numberInString; transId: number; userAssetDribbletDetails: UserAssetDribbletDetail[]; } ⋮---- export interface DustLog { total: number; userAssetDribblets: UserAssetDribblet[]; } ⋮---- export enum EnumUniversalTransferType { SpotToUSDM = 'MAIN_UMFUTURE', SpotToCOINM = 'MAIN_CMFUTURE', SpotToMargin = 'MAIN_MARGIN', SpotToFunding = 'MAIN_FUNDING', SpotToOptions = 'MAIN_OPTION', FundingToSpot = 'FUNDING_MAIN', FundingToUSDM = 'FUNDING_UMFUTURE', FundingToCOINM = 'FUNDING_CMFUTURE', FundingToMargin = 'FUNDING_MARGIN', FundingToOptions = 'FUNDING_OPTION', USDMToSpot = 'UMFUTURE_MAIN', USDMToFunding = 'UMFUTURE_FUNDING', USDMToMargin = 'UMFUTURE_MARGIN', USDMToOptions = 'UMFUTURE_OPTION', COINMToSpot = 'CMFUTURE_MAIN', COINMToFunding = 'CMFUTURE_FUNDING', COINMToMargin = 'CMFUTURE_MARGIN', MarginToSpot = 'MARGIN_MAIN', MarginToUSDM = 'MARGIN_UMFUTURE', MarginToCOINM = 'MARGIN_CMFUTURE', MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', MarginToFunding = 'MARGIN_FUNDING', MarginToOptions = 'MARGIN_OPTION', IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', OptionsToSpot = 'OPTION_MAIN', OptionsToUSDM = 'OPTION_UMFUTURE', OptionsToFunding = 'OPTION_FUNDING', OptionsToMargin = 'OPTION_MARGIN', } ⋮---- export type UniversalTransferType = `${EnumUniversalTransferType}`; ⋮---- export interface UniversalTransferParams { type: UniversalTransferType; asset: string; amount: number; fromSymbol: string; toSymbol: string; } ⋮---- export interface UniversalTransferHistoryParams { type: UniversalTransferType; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface ExchangeInfoParams { symbol?: string; symbols?: string[]; permissions?: string | string[]; showPermissionSets?: boolean; symbolStatus?: string; } ⋮---- export interface NewSpotOrderParams< T extends OrderType = OrderType, RT extends OrderResponseType | undefined = OrderResponseType, > { symbol: string; side: OrderSide; type: T; timeInForce?: OrderTimeInForce; quantity?: number; quoteOrderQty?: number; price?: number; newClientOrderId?: string; strategyId?: number; strategyType?: number; stopPrice?: number; trailingDelta?: number; icebergQty?: number; newOrderRespType?: RT; isIsolated?: StringBoolean; sideEffectType?: SideEffects; } ⋮---- 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; 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 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 enableReading: boolean; enableFutures: boolean; // API Key created before your futures account opened does not support futures API service enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed 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 } ⋮---- 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 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 ⋮---- enableFutures: boolean; // API Key created before your futures account opened does not support futures API service enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed 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; 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 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; } ⋮---- export interface DailyChangeStatistic { symbol: string; priceChange: numberInString; priceChangePercent: numberInString; weightedAvgPrice: numberInString; prevClosePrice: numberInString; lastPrice: numberInString; lastQty: numberInString; bidPrice: numberInString; bidQty: numberInString; askPrice: numberInString; askQty: numberInString; openPrice: numberInString; highPrice: numberInString; lowPrice: numberInString; volume: numberInString; quoteVolume: numberInString; openTime: number; closeTime: number; firstId: number; lastId: number; count: number; } ⋮---- export interface SymbolOrderBookTicker { symbol: string; bidPrice: numberInString; bidQty: numberInString; askPrice: numberInString; askQty: numberInString; } ⋮---- export interface OrderResponseACK { symbol: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; } ⋮---- export interface OrderResponseResult { symbol: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: numberInString; origQty: numberInString; executedQty: numberInString; cummulativeQuoteQty: numberInString; status: OrderStatus; timeInForce: OrderTimeInForce; type: OrderType; side: OrderSide; workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; } ⋮---- export interface OrderFill { price: numberInString; qty: numberInString; commission: numberInString; commissionAsset: string; } ⋮---- export interface OrderResponseFull { symbol: string; orderId: number; orderListId?: number; clientOrderId: string; transactTime: number; price: numberInString; origQty: numberInString; executedQty: numberInString; cummulativeQuoteQty: numberInString; status: OrderStatus; timeInForce: OrderTimeInForce; type: OrderType; side: OrderSide; marginBuyBorrowAmount?: number; marginBuyBorrowAsset?: string; isIsolated?: boolean; workingTime: number; selfTradePreventionMode: SelfTradePreventionMode; fills: OrderFill[]; } ⋮---- 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; } ⋮---- export interface OrderListResponse { orderListId: number; contingencyType: 'OCO'; listStatusType: OCOStatus; listOrderStatus: OCOOrderStatus; listClientOrderId: string; transactionTime: number; symbol: string; orders: [OrderListOrder, OrderListOrder]; orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; } ⋮---- export interface OrderList { orderListId: number; contingencyType: 'OCO'; listStatusType: OCOStatus; listOrderStatus: OCOOrderStatus; listClientOrderId: string; transactionTime: number; symbol: string; orders: [OrderListOrder, OrderListOrder]; } export interface SOROrderFill { matchType: string; price: numberInString; qty: numberInString; commission: numberInString; commissionAsset: string; tradeId: number; allocId: number; } ⋮---- export type SOROrderResponseFull = OrderResponseFull & { workingTime: number; fills: SOROrderFill[]; workingFloor: string; selfTradePreventionMode: string; usedSor: true; }; ⋮---- export interface SORTestOrderResponse { standardCommissionForOrder: { //Standard commission rates on trades from the order. maker: numberInString; taker: numberInString; }; taxCommissionForOrder: { //Tax commission rates for trades from the order. maker: numberInString; taker: numberInString; }; discount: { //Discount on standard commissions when paying in BNB. enabledForAccount: boolean; enabledForSymbol: boolean; discountAsset: string; discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. }; } ⋮---- //Standard commission rates on trades from the order. ⋮---- //Tax commission rates for trades from the order. ⋮---- //Discount on standard commissions when paying in BNB. ⋮---- discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. ⋮---- export interface CancelSpotOrderResult { symbol: string; origClientOrderId: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: numberInString; origQty: numberInString; executedQty: numberInString; cummulativeQuoteQty: numberInString; status: OrderStatus; timeInForce: OrderTimeInForce; type: OrderType; side: OrderSide; selfTradePreventionMode: SelfTradePreventionMode; } ⋮---- export interface CancelOrderListResult extends OrderList { orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; } ⋮---- export interface GenericReplaceSpotOrderResult { cancelResult: 'SUCCESS' | 'FAILURE'; newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; cancelResponse: C; newOrderResponse: N; } ⋮---- export interface ReplaceSpotOrderCancelStopFailure extends GenericReplaceSpotOrderResult { cancelResult: 'FAILURE'; newOrderResult: 'NOT_ATTEMPTED'; } ⋮---- export interface ReplaceSpotOrderNewFailure extends GenericReplaceSpotOrderResult< CancelSpotOrderResult, GenericCodeMsgError > { cancelResult: 'SUCCESS'; newOrderResult: 'FAILURE'; } ⋮---- export interface ReplaceSpotOrderCancelAllowFailure extends GenericReplaceSpotOrderResult { cancelResult: 'FAILURE'; newOrderResult: 'SUCCESS'; } ⋮---- export interface ReplaceSpotOrderCancelAllFailure extends GenericReplaceSpotOrderResult< GenericCodeMsgError, GenericCodeMsgError > { cancelResult: 'FAILURE'; newOrderResult: 'FAILURE'; } ⋮---- export interface ReplaceSpotOrderResultError { data: | ReplaceSpotOrderCancelStopFailure | ReplaceSpotOrderNewFailure | ReplaceSpotOrderCancelAllowFailure | ReplaceSpotOrderCancelAllFailure; } ⋮---- export interface ReplaceSpotOrderResultSuccess< T extends OrderType = OrderType, RT extends OrderResponseType | undefined = OrderResponseType, > extends GenericReplaceSpotOrderResult< CancelSpotOrderResult, OrderResponseTypeFor > { cancelResult: 'SUCCESS'; newOrderResult: 'SUCCESS'; } ⋮---- export interface SpotOrder { symbol: string; orderId: number; orderListId: number; clientOrderId: string; price: numberInString; origQty: numberInString; executedQty: numberInString; cummulativeQuoteQty: numberInString; status: OrderStatus; timeInForce: OrderTimeInForce; type: OrderType; side: OrderSide; stopPrice: numberInString; icebergQty: numberInString; time: number; updateTime: number; isWorking: boolean; origQuoteOrderQty: numberInString; selfTradePreventionMode: SelfTradePreventionMode; } ⋮---- export interface SpotAmendKeepPriorityResult { transactTime: number; executionId: number; amendedOrder: { symbol: string; orderId: number; orderListId: number; origClientOrderId: string; clientOrderId: string; price: string; qty: string; executedQty: string; preventedQty: string; quoteOrderQty: string; cumulativeQuoteQty: string; status: string; timeInForce: string; type: string; side: string; workingTime: number; selfTradePreventionMode: string; }; listStatus?: { orderListId: number; contingencyType: string; listOrderStatus: string; listClientOrderId: string; symbol: string; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; }; } ⋮---- export interface SpotAssetBalance { asset: string; free: numberInString; locked: numberInString; } ⋮---- export interface AccountInformation { makerCommission: number; takerCommission: number; buyerCommission: number; sellerCommission: number; commissionRates: { maker: string; taker: string; buyer: string; seller: string; }; canTrade: boolean; canWithdraw: boolean; canDeposit: boolean; brokered: boolean; requireSelfTradePrevention: boolean; preventSor: boolean; updateTime: number; accoountType: string; balances: SpotAssetBalance[]; permissions: string[]; uid: number; } ⋮---- export interface CrossMarginAccountTransferParams { asset: string; amount: number; type: 1 | 2; } ⋮---- export interface MarginTransactionResponse { tranId: number; } ⋮---- export interface MarginAccountLoanParams { asset: string; isIsolated: StringBoolean; symbol: string; amount: number; type: 'BORROW' | 'REPAY'; } ⋮---- export interface QueryMarginAssetParams { asset: string; } ⋮---- export interface QueryMarginAssetResponse { assetFullName: string; assetName: string; isBorrowable: boolean; isMortgageable: boolean; userMinBorrow: numberInString; userMinRepay: numberInString; } ⋮---- export interface QueryCrossMarginPairParams { symbol: string; } ⋮---- export interface QueryCrossMarginPairResponse { id: number; symbol: string; base: string; quote: string; isMarginTrade: boolean; isBuyAllowed: boolean; isSellAllowed: boolean; } ⋮---- export interface QueryMarginPriceIndexResponse { calcTime: number; price: numberInString; symbol: string; } ⋮---- export interface QueryMarginRecordParams { asset: string; isolatedSymbol?: string; txId?: number; startTime?: number; endTime?: number; current?: number; size?: number; archived?: boolean; } ⋮---- export interface GetMarginAccountBorrowRepayRecordsParams { asset?: string; isolatedSymbol?: string; txId?: number; startTime?: number; endTime?: number; current?: number; size?: number; type: 'BORROW' | 'REPAY'; } ⋮---- export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- export interface MarginAccountRecord { isolatedSymbol?: string; asset: string; principal: numberInString; status: LoanStatus; timestamp: number; txId: number; } ⋮---- export interface QueryCrossMarginAccountDetailsParams { created: boolean; borrowEnabled: boolean; marginLevel: numberInString; totalAssetOfBtc: numberInString; totalLiabilityOfBtc: numberInString; totalNetAssetOfBtc: numberInString; totalCollateralValueInUSDT: numberInString; totalOpenOrderLossInUSDT: numberInString; tradeEnabled: boolean; transferInEnabled: boolean; transferOutEnabled: boolean; accountType: string; userAssets: MarginBalance[]; } ⋮---- export interface BasicMarginAssetParams { asset: string; isolatedSymbol?: string; } ⋮---- export interface QueryMaxBorrowResponse { amount: numberInString; borrowLimit: numberInString; } ⋮---- export interface QueryMaxTransferOutAmountResponse { amount: numberInString; } ⋮---- export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; ⋮---- export interface IsolatedMarginAccountTransferParams { asset: string; symbol: string; transFrom: IsolatedMarginTransfer; transTo: IsolatedMarginTransfer; amount: number; } ⋮---- export interface IsolatedMarginAccountAsset { asset: string; borrowEnabled: boolean; borrowed: numberInString; free: numberInString; interest: numberInString; locked: numberInString; netAsset: numberInString; netAssetOfBtc: numberInString; repayEnabled: boolean; totalAsset: numberInString; } ⋮---- export type IsolatedMarginLevelStatus = | 'EXCESSIVE' | 'NORMAL' | 'MARGIN_CALL' | 'PRE_LIQUIDATION' | 'FORCE_LIQUIDATION'; ⋮---- export interface IsolatedMarginAccountAssets { baseAsset: IsolatedMarginAccountAsset; quoteAsset: IsolatedMarginAccountAsset; symbol: string; isolatedCreated: boolean; enabled: boolean; marginLevel: numberInString; marginLevelStatus: IsolatedMarginLevelStatus; marginRatio: numberInString; indexPrice: numberInString; liquidatePrice: numberInString; liquidateRate: numberInString; tradeEnabled: boolean; } ⋮---- export interface IsolatedMarginAccountInfo { assets: IsolatedMarginAccountAssets[]; totalAssetOfBtc?: numberInString; totalLiabilityOfBtc?: numberInString; totalNetAssetOfBtc?: numberInString; } ⋮---- export interface SpotSubUserAssetBtcList { email: string; totalAsset: numberInString; } ⋮---- export interface SubAccountList { email: string; isFreeze: boolean; createTime: number; isManagedSubAccount: boolean; isAssetManagementSubAccount: boolean; } ⋮---- export interface SubAccountDepositHistoryList { depositId: number; subAccountId: string; amount: string; coin: string; network: string; status: number; address: string; addressTag: string; txId: string; insertTime: number; sourceAddress: string; confirmTimes: string; } ⋮---- export interface SubAccountTransferHistoryList { fromId?: string; toId?: string; startTime?: number; endTime?: number; page?: number; limit?: number; } ⋮---- export interface SubAccountBasicTransfer { from: string; to: string; asset: string; qty: numberInString; tranId: number; time: number; } ⋮---- export interface MarginTradeCoeffVo { forceLiquidationBar: numberInString; marginCallBar: numberInString; normalBar: numberInString; } ⋮---- export interface SubAccountStatus { email: string; isSubUserEnabled: boolean; isUserActive: boolean; insertTime: number; isMarginEnabled: boolean; isFutureEnabled: boolean; mobile: number; } ⋮---- export interface BasicBtcTotals { totalAssetOfBtc: numberInString; totalLiabilityOfBtc: numberInString; totalNetAssetOfBtc: numberInString; } ⋮---- export interface FuturesSubAccountAssets { asset: string; initialMargin: numberInString; maintenanceMargin: numberInString; marginBalance: numberInString; maxWithdrawAmount: numberInString; openOrderInitialMargin: numberInString; positionInitialMargin: numberInString; unrealizedProfit: numberInString; walletBalance: numberInString; } ⋮---- export interface FuturesSubAccountList { totalInitialMargin: numberInString; totalMaintenanceMargin: numberInString; totalMarginBalance: numberInString; totalOpenOrderInitialMargin: numberInString; totalPositionInitialMargin: numberInString; totalUnrealizedProfit: numberInString; totalWalletBalance: numberInString; asset: string; email: string; } ⋮---- export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; ⋮---- export interface SubAccountTransferHistory { counterParty: string; email: string; type: number; asset: string; qty: numberInString; fromAccountType: AccountType; toAccountType: AccountType; status: string; tranId: number; time: number; } ⋮---- export interface SubAccountUniversalTransferHistory { tranId: number; fromEmail: string; toEmail: string; asset: string; amount: numberInString; createTimeStamp: number; fromAccountType: AccountType; toAccountType: AccountType; status: string; clientTranId?: string; } ⋮---- export interface BasicSubAccount { email: string; subAccountApiKey: string; } ⋮---- export interface CreateSubAccountParams { subAccountString: string; } ⋮---- export interface EnableOrDisableIPRestrictionForSubAccountParams extends BasicSubAccount { ipAddress?: string; } ⋮---- export interface GetBrokerSubAccountHistoryParams { fromId?: string; toId?: string; startTime?: number; endTime?: number; page?: number; limit?: number; showAllStatus?: boolean; } ⋮---- export interface CreateBrokerSubAccountParams { tag?: string; } ⋮---- export interface GetBrokerSubAccountParams { subAccountId?: string; page?: number; size?: number; } ⋮---- export interface GetApiKeyBrokerSubAccountParams { subAccountId: string; subAccountApiKey?: string; page?: number; size?: number; } ⋮---- export interface CreateApiKeyBrokerSubAccountParams { subAccountId: string; canTrade: boolean; marginTrade?: boolean; futuresTrade?: boolean; } export interface ApiKeyBrokerSubAccount { subAccountId: string; apiKey: string; canTrade: boolean; marginTrade: boolean; futuresTrade: boolean; } ⋮---- export interface UpdateIpRestrictionForSubApiKey { subAccountId: string; ipAddress?: string; subAccountApiKey: string; status: string; } ⋮---- export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { subAccountId: string; subAccountApiKey: string; canUniversalTransfer: boolean; } ⋮---- export interface EnableMarginBrokerSubAccountParams { subAccountId: string; margin: boolean; } ⋮---- export interface EnableMarginBrokerSubAccountResponse { subAccountId: string; enableMargin: boolean; updateTime: number; } ⋮---- export interface EnableFuturesBrokerSubAccountParams { subAccountId: string; futures: boolean; } ⋮---- export interface EnableFuturesBrokerSubAccountResponse { subAccountId: string; enableFutures: boolean; updateTime: number; } ⋮---- export interface EnableMarginApiKeyBrokerSubAccountParams { subAccountId: string; margin: boolean; } export interface UniversalTransferBrokerParams { fromId?: string; toId?: string; fromAccountType: string; toAccountType: string; asset: string; amount: number; } ⋮---- export interface GetUniversalTransferBrokerParams { fromId?: string; toId?: string; clientTranId?: string; startTime?: number; endTime?: number; page?: number; limit?: number; showAllStatus?: boolean; } ⋮---- export interface GetBrokerSubAccountDepositHistoryParams { subAccountId?: string; coin?: string; status?: number; startTime?: number; endTime?: number; limit?: number; offset?: number; } ⋮---- export interface DeleteApiKeyBrokerSubAccountParams { subAccountId: string; subAccountApiKey: string; } ⋮---- export interface ChangePermissionApiKeyBrokerSubAccountParams { subAccountId: string; subAccountApiKey: string; canTrade: boolean; marginTrade: boolean; futuresTrade: boolean; } ⋮---- export interface ChangePermissionApiKeyBrokerSubAccountResponse { subAccountId: string; apikey: string; canTrade: boolean; marginTrade: boolean; futuresTrade: boolean; } ⋮---- export interface VirtualSubAccount { email: string; } ⋮---- export interface BrokerSubAccountHistory { subAccountsHistory: SubAccountTransferHistoryList[]; } ⋮---- export interface BrokerSubAccount { subaccountId: string; email: string; makerCommission?: string; takerCommission?: string; marginMakerCommission?: string; marginTakerCommission?: string; createTime?: number; tag: string; } ⋮---- export interface CreateApiKeyBrokerSubAccountResponse { subaccountId: string; apiKey: string; secretKey: string; canTrade: boolean; marginTrade: boolean; futuresTrade: boolean; } ⋮---- export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { subAccountId: string; apikey: string; canUniversalTransfer: boolean; } ⋮---- export interface GetBrokerInfoResponse { maxMakerCommission: string; minMakerCommission: string; maxTakerCommission: string; minTakerCommission: string; subAccountQty: number; maxSubAccountQty: number; } export interface SubAccountListParams { email?: string; isFreeze?: StringBoolean; page?: number; limit?: number; } ⋮---- export interface SubAccountListResponse { subAccounts: SubAccountList[]; } ⋮---- export interface SubAccountSpotAssetTransferHistoryParams { fromEmail?: string; toEmail?: string; startTime?: number; endTime?: number; page?: number; limit?: number; } ⋮---- export interface SubAccountSpotAssetTransferHistory extends SubAccountBasicTransfer { status: string; } ⋮---- export interface SubAccountFuturesAssetTransferHistoryParams { email: string; futuresType: number; startTime?: number; endTime?: number; page?: number; limit?: number; } ⋮---- export interface SubAccountFuturesAssetTransferHistory { success: boolean; futuresType: number; transfers: SubAccountBasicTransfer[]; } ⋮---- export interface SubAccountFuturesAssetTransferParams { fromEmail: string; toEmail: string; futuresType: number; asset: string; amount: number; } ⋮---- export interface SubAccountFuturesAssetTransfer { success: boolean; txnId: numberInString; } ⋮---- export interface SubAccountAssetsParams { email: string; } ⋮---- export interface SubAccountAssets { balances: SpotBalance[]; } ⋮---- export interface SubAccountSpotAssetsSummaryParams { email?: string; page?: number; size?: number; } ⋮---- export interface SubAccountSpotAssetsSummary { totalCount: number; masterAccountTotalAsset: numberInString; spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; } ⋮---- export interface SubAccountDepositAddressParams { email: string; coin: string; network?: string; } ⋮---- export interface SubAccountDepositAddress { address: string; coin: string; tag: string; url: string; } ⋮---- export interface SubAccountDepositHistoryParams extends DepositHistoryParams { email: string; } ⋮---- export interface SubAccountEnableMargin { email: string; isMarginEnabled: boolean; } ⋮---- export interface SubAccountMarginAccountDetail extends BasicBtcTotals { email: string; marginLevel: numberInString; marginTradeCoeffVo: MarginTradeCoeffVo; marginUserAssetVoList: MarginBalance[]; } ⋮---- export interface SubAccountListBtc extends BasicBtcTotals { email: string; } ⋮---- export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { subAccountList: SubAccountListBtc; } ⋮---- export interface SubAccountEnableFutures { email: string; isFuturesEnabled: boolean; } ⋮---- export interface SubAccountFuturesAccountDetail { email: string; asset: string; assets: FuturesSubAccountAssets[]; canDeposit: boolean; canWithdraw: boolean; feeTier: number; maxWithdrawAmount: numberInString; totalInitialMargin: numberInString; totalMaintenanceMargin: numberInString; totalMarginBalance: numberInString; totalOpenOrderInitialMargin: numberInString; totalPositionInitialMargin: numberInString; totalUnrealizedProfit: numberInString; totalWalletBalance: numberInString; updateTime: number; } ⋮---- export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { subAccountList: FuturesSubAccountList[]; } ⋮---- export interface FuturesPositionRisk { entryPrice: numberInString; leverage: numberInString; maxNotional: numberInString; liquidationPrice: numberInString; markPrice: numberInString; positionAmount: numberInString; symbol: string; unrealizedProfit: numberInString; } ⋮---- export interface SubAccountTransferParams { email: string; asset: string; amount: number; type: number; } ⋮---- export interface SubAccountTransfer { txnId: numberInString; } ⋮---- export interface SubAccountTransferToSameMasterParams { toEmail: string; asset: string; amount: number; } ⋮---- export interface SubAccountTransferToMasterParams { asset: string; amount: number; } ⋮---- export interface SubAccountTransferHistoryParams { asset?: string; type?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface SubAccountUniversalTransferParams { fromEmail?: string; toEmail?: string; fromAccountType: AccountType; toAccountType: AccountType; clientTranId?: string; asset: string; amount: number; } ⋮---- export interface SubAccountMovePositionParams { fromUserEmail: string; toUserEmail: string; productType: string; orderArgs: { symbol: string; quantity: number; positionSide: 'BOTH' | 'LONG' | 'SHORT'; }[]; } export interface SubAccountUniversalTransfer extends SubAccountTransfer { clientTranId?: string; } ⋮---- export interface SubAccountMovePosition { fromUserEmail: string; toUserEmail: string; productType: string; symbol: string; priceType: string; price: string; quantity: string; positionSide: string; side: string; success: boolean; } ⋮---- export interface SubAccountMovePositionHistoryParams { symbol: string; startTime?: number; endTime?: number; page: number; row: number; } ⋮---- export interface SubAccountMovePositionHistory { fromUserEmail: string; toUserEmail: string; productType: string; symbol: string; price: string; quantity: string; positionSide: string; side: string; timeStamp: number; } ⋮---- export interface SubAccountUniversalTransferHistoryParams { fromEmail?: string; toEmail?: string; clientTranId?: string; startTime?: number; endTime?: number; page?: number; limit?: number; } ⋮---- export interface SubAccountUniversalTransferHistoryResponse { result: SubAccountUniversalTransferHistory[]; totalCount: number; } ⋮---- export interface SubAccountEnableLeverageToken { email: string; enableBlvt: boolean; } ⋮---- export interface AddIpRestriction extends BasicSubAccount { status: string; ipAddress: string; } ⋮---- export interface SubAccountEnableOrDisableIPRestriction { ipRestrict: boolean; ipList: string[]; updateTime: number; apiKey: string; } ⋮---- export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { ipAddress: string; } ⋮---- export interface AddIPListForSubAccountResponseParams { ip: string; updateTime: number; apiKey: string; } ⋮---- export interface SubAccountAssetDetails { coin: string; name: string; totalBalance: numberInString; availableBalance: numberInString; inOrder: numberInString; btcValue: numberInString; } ⋮---- export interface WithdrawAssetsFromManagedSubAccountParams { fromEmail: string; asset: string; amount: number; transferDate?: number; } ⋮---- export interface BasicFuturesSubAccountParams { email: string; futuresType: 1 | 2; } ⋮---- export interface SubAccountSummaryOnFuturesAccountV2Params { futuresType: 1 | 2; page?: number; limit?: number; } ⋮---- export interface SubAccountUSDMDetail { futureAccountResp: { email: string; assets: FuturesSubAccountAssets[]; canDeposit: boolean; canWithdraw: boolean; feeTier: number; maxWithdrawAmount: numberInString; totalInitialMargin: numberInString; totalMaintenanceMargin: numberInString; totalMarginBalance: numberInString; totalOpenOrderInitialMargin: numberInString; totalPositionInitialMargin: numberInString; totalUnrealizedProfit: numberInString; totalWalletBalance: numberInString; updateTime: number; }; } ⋮---- export interface COINMSubAccount { email: string; totalMarginBalance: numberInString; totalUnrealizedProfit: numberInString; totalWalletBalanceOfBTC: numberInString; asset: string; } ⋮---- export interface SubAccountCOINMDetail { deliveryAccountResp: { email: string; assets: FuturesSubAccountAssets[]; canDeposit: boolean; canWithdraw: boolean; feeTier: number; updateTime: number; }; } ⋮---- export interface SubAccountUSDMSummary { futureAccountSummaryResp: { totalInitialMargin: numberInString; totalMaintenanceMargin: numberInString; totalMarginBalance: numberInString; totalOpenOrderInitialMargin: numberInString; totalPositionInitialMargin: numberInString; totalUnrealizedProfit: numberInString; totalWalletBalance: numberInString; asset: string; subAccountList: FuturesSubAccountList[]; }; } ⋮---- export interface SubAccountCOINMSummary { deliveryAccountSummaryResp: { totalMarginBalanceOfBTC: numberInString; totalUnrealizedProfitOfBTC: numberInString; totalWalletBalanceOfBTC: numberInString; asset: string; subAccountList: COINMSubAccount[]; }; } ⋮---- export interface COINMPositionRisk { entryPrice: numberInString; markPrice: numberInString; leverage: numberInString; isolated: numberInString; isolatedWallet: numberInString; isolatedMargin: numberInString; isAutoAddMargin: numberInString; positionSide: string; positionAmount: numberInString; symbol: string; unrealizedProfit: numberInString; } ⋮---- export interface SubAccountUSDMPositionRisk { futurePositionRiskVos: FuturesPositionRisk[]; } ⋮---- export interface SubAccountCOINMPositionRisk { deliveryPositionRiskVos: COINMPositionRisk[]; } ⋮---- export interface StakingProductDetail { asset: string; rewardAsset: string; duration: number; renewable: boolean; apy: numberInString; } ⋮---- export interface StakingProductQuota { totalPersonalQuota: numberInString; minimum: numberInString; } ⋮---- export interface StakingProduct { projectId: string; detail: StakingProductDetail; quota: StakingProductQuota; } ⋮---- export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; export type StakingStatus = 'HOLDING' | 'REDEEMED'; export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; export type BSwapType = 'SINGLE' | 'COMBINATION'; export type BSwapOperationType = 'ADD' | 'REMOVE'; ⋮---- export interface StakingProductPosition { positionId: numberInString; projectId: string; asset: string; amount: numberInString; purchaseTime: numberInString; duration: numberInString; accrualDays: numberInString; rewardAsset: string; APY: numberInString; rewardAmt: numberInString; extraRewardAsset: string; extraRewardAPY: numberInString; estExtraRewardAmt: numberInString; nextInterestPay: numberInString; nextInterestPayDate: numberInString; payInterestPeriod: numberInString; redeemAmountEarly: numberInString; interestEndDate: numberInString; deliverDate: numberInString; redeemPeriod: numberInString; redeemingAmt: numberInString; partialAmtDeliverDate: numberInString; canRedeemEarly: boolean; renewable: boolean; type: string; status: StakingStatus; } export interface StakingBasicParams { product: StakingProductType; current?: number; size?: number; } ⋮---- export interface FlexibleSavingBasicParams { status?: string; featured?: number; current?: number; size?: number; asset?: string; } ⋮---- export interface FlexibleProductPositionParams { status?: string; featured?: number; current?: number; size?: number; } ⋮---- export interface PurchaseFlexibleProductParams { productId: string; amount: number; autoSubscribe: boolean; } ⋮---- export interface PurchaseFlexibleProductResponse { purchaseId: number; } ⋮---- export interface RedeemFlexibleProductParams { productId: string; amount: number; type: 'FAST' | 'NORMAL'; } ⋮---- export interface LeftDailyPurchaseQuotaFlexibleProductResponse { asset: string; leftQuota: string; } ⋮---- export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; export type ProjectSortBy = | 'START_TIME' | 'LOT_SIZE' | 'INTEREST_RATE' | 'DURATION'; ⋮---- export interface FixedAndActivityProjectParams { asset?: string; type: ProjectType; status?: ProjectStatus; isSortAsc?: boolean; sortBy?: ProjectSortBy; current?: number; size?: number; } export interface FixedAndActivityProjectPositionParams { asset?: string; projectId?: string; status?: StakingStatus; } ⋮---- export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; ⋮---- export interface PurchaseRecordParams { lendingType: LendingType; asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface NewFutureAccountTransferParams { asset: string; amount: number; type: 1 | 2 | 3 | 4; } ⋮---- export interface GetFutureAccountTransferHistoryParams { asset: string; startTime: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface FutureAccountTransfer { asset: string; tranId: number; amount: string; type: string; timestamp: number; status: 'PENDING' | 'CONFIRMED' | 'FAILED'; } ⋮---- export interface GetLoanCoinPaginatedHistoryParams { loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- /** * * STAKING * */ ⋮---- export interface StakingHistory { positionId: numberInString; time: number; asset: string; project?: string; amount: numberInString; lockPeriod?: numberInString; deliverDate?: numberInString; type?: string; status: string; } ⋮---- export interface StakingPersonalLeftQuota { leftPersonalQuota: numberInString; } ⋮---- export interface StakingHistoryParams extends StakingBasicParams { txnType: StakingTxnType; asset?: string; startTime?: number; endTime?: number; } export interface BSwapOperationsParams { operationId?: number; poolId?: number; operation: BSwapOperationType; startTime?: number; endTime?: number; limit: number; } ⋮---- export interface BSwapOperations { operationId: number; poolId: number; poolName: string; operation: BSwapOperationType; status: number; updateTime: number; shareAmount: numberInString; } export interface RemoveBSwapLiquidityParams { poolId: number; type: BSwapType; asset?: string; shareAmount: number; } ⋮---- export interface AddBSwapLiquidityParams { poolId: number; type?: BSwapType; asset: string; quantity: number; } ⋮---- export interface BSwapShare { shareAmount: number; sharePercentage: number; asset: { [k: string]: number }; } ⋮---- export interface BSwapLiquidity { poolId: number; poolNmae: string; updateTime: number; liquidity: { [k: string]: number }; share: BSwapShare; } ⋮---- export interface FundingAsset { asset: string; free: string; locked: string; freeze: string; withdrawing: string; btcValuation: string; } ⋮---- export interface GetAssetParams { asset?: string; needBtcValuation?: boolean; } ⋮---- export interface UserAsset { asset: string; free: string; locked: string; freeze: string; withdrawing: string; ipoable: string; btcValuation: string; } ⋮---- export interface ConvertTransfer { clientTranId: string; asset: string; amount: number; targetAsset: string; accountType?: string; } ⋮---- export interface ConvertTransferResponse { tranId: number; status: string; } ⋮---- export interface GetConvertBUSDHistoryParams { tranId?: number; clientTranId?: string; asset?: string; startTime: number; endTime: number; accountType?: string; current?: number; size?: number; } ⋮---- export interface BUSDConversionRecord { tranId: number; type: number; time: number; deductedAsset: string; deductedAmount: string; targetAsset: string; targetAmount: string; status: string; accountType: string; } ⋮---- export interface CloudMiningHistoryParams { tranId?: number; clientTranId?: string; asset?: string; startTime: number; endTime: number; current?: number; size?: number; } ⋮---- export interface CloudMining { createTime: number; tranId: number; type: number; asset: string; amount: string; status: string; } ⋮---- export interface ConvertibleCoinsResponse { convertEnabled: boolean; coins: string[]; exchangeRates: 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'; } ⋮---- 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'; } ⋮---- 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 OrderRateLimitUsage { rateLimitType: string; interval: string; intervalNum: number; limit: number; count: number; } ⋮---- export interface PreventedMatchesParams { symbol: string; preventedMatchId?: number; orderId?: number; fromPreventedMatchId?: number; limit?: number; } ⋮---- export interface PreventedMatch { symbol: string; preventedMatchId: number; takerOrderId: number; makerSymbol: string; makerOrderId: number; tradeGroupId: number; selfTradePreventionMode: SelfTradePreventionMode; price: string; makerPreventedQuantity: string; transactTime: number; } ⋮---- export interface AllocationsParams { symbol: string; startTime?: number; endTime?: number; fromAllocationId?: number; limit?: number; orderId?: number; } ⋮---- export interface Allocation { symbol: string; allocationId: number; allocationType: string; orderId: number; orderListId: number; price: string; qty: string; quoteQty: string; commission: string; commissionAsset: string; time: number; isBuyer: boolean; isMaker: boolean; isAllocator: boolean; } ⋮---- export interface CommissionRates { symbol: string; standardCommission: { maker: string; taker: string; buyer: string; seller: string; }; taxCommission: { maker: string; taker: string; buyer: string; seller: string; }; discount: { enabledForAccount: boolean; enabledForSymbol: boolean; discountAsset: string; discount: string; }; } ⋮---- export interface GetCrossMarginTransferHistoryParams { asset?: string; type?: 'ROLL_IN' | 'ROLL_OUT'; startTime?: number; endTime?: number; current?: number; size?: number; isolatedSymbol?: string; } ⋮---- export interface CrossMarginTransferHistory { amount: string; asset: string; status: string; timestamp: number; txId: number; type: 'ROLL_IN' | 'ROLL_OUT'; transFrom?: string; transTo?: string; fromSymbol?: string; toSymbol?: string; } ⋮---- export interface GetMarginInterestHistoryParams { asset?: string; isolatedSymbol?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface MarginInterestHistory { txId: number; interestAccuredTime: number; asset: string; rawAsset?: string; principal: string; interest: string; interestRate: string; type: | 'PERIODIC' | 'ON_BORROW' | 'PERIODIC_CONVERTED' | 'ON_BORROW_CONVERTED' | 'PORTFOLIO'; isolatedSymbol?: string; } ⋮---- export interface GetForceLiquidationRecordParams { startTime?: number; endTime?: number; isolatedSymbol?: string; current?: number; size?: number; } ⋮---- export interface ForceLiquidationRecord { avgPrice: string; executedQty: string; orderId: number; price: string; qty: string; side: 'BUY' | 'SELL'; symbol: string; timeInForce: string; isIsolated: boolean; updatedTime: number; } ⋮---- export interface QueryMarginAccountAllOCOParams { isIsolated?: 'TRUE' | 'FALSE'; symbol?: string; fromId?: number; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface QueryMarginAccountTradeListParams { symbol: string; isIsolated?: 'TRUE' | 'FALSE'; orderId?: number; startTime?: number; endTime?: number; fromId?: number; limit?: number; } ⋮---- export interface IsolatedMarginSymbol { base: string; isBuyAllowed: boolean; isMarginTrade: boolean; isSellAllowed: boolean; quote: string; symbol: string; delistTime?: number; } ⋮---- export interface ToggleBNBBurnParams { spotBNBBurn?: 'true' | 'false'; interestBNBBurn?: 'true' | 'false'; } ⋮---- export interface BNBBurnResponse { spotBNBBurn: boolean; interestBNBBurn: boolean; } ⋮---- export interface QueryMarginInterestRateHistoryParams { asset: string; vipLevel?: number; startTime?: number; endTime?: number; } ⋮---- export interface MarginInterestRateHistory { asset: string; dailyInterestRate: string; timestamp: number; vipLevel: number; } ⋮---- export interface QueryCrossMarginFeeDataParams { vipLevel?: number; coin?: string; } ⋮---- export interface CrossMarginFeeData { vipLevel: number; coin: string; transferIn: boolean; borrowable: boolean; dailyInterest: string; yearlyInterest: string; borrowLimit: string; marginablePairs: string[]; } ⋮---- export interface IsolatedMarginFeeData { vipLevel: number; symbol: string; leverage: string; data: { coin: string; dailyInterest: string; borrowLimit: string; }[]; } ⋮---- export interface QueryIsolatedMarginTierDataParams { symbol: string; tier?: number; } ⋮---- export interface IsolatedMarginTierData { symbol: string; tier: number; effectiveMultiple: string; initialRiskRatio: string; liquidationRiskRatio: string; baseAssetMaxBorrowable: string; quoteAssetMaxBorrowable: string; } ⋮---- export interface GetMarginOrderCountUsageParams { isIsolated?: string; symbol?: string; } ⋮---- export interface MarginOrderCountUsageResponse { rateLimitType: string; interval: string; intervalNum: number; limit: number; count: number; } ⋮---- export interface Collateral { minUsdValue: string; maxUsdValue?: string; discountRate: string; } ⋮---- export interface SmallLiabilityExchangeCoin { asset: string; interest: string; principal: string; liabilityAsset: string; liabilityQty: number; } export interface GetSmallLiabilityExchangeHistoryParams { current: number; size: number; startTime?: number; endTime?: number; } ⋮---- export interface SmallLiabilityExchangeHistory { asset: string; amount: string; targetAsset: string; targetAmount: string; bizType: string; timestamp: number; } ⋮---- export interface GetNextHourlyInterestRateParams { assets: string; isIsolated: boolean; } ⋮---- export interface NextHourlyInterestRate { asset: string; nextHourlyInterestRate: string; } ⋮---- export interface GetMarginCapitalFlowParams { asset?: string; symbol?: string; type?: string; startTime?: number; endTime?: number; fromId?: number; limit?: number; } ⋮---- export interface MarginCapitalFlow { id: number; tranId: number; timestamp: number; asset: string; symbol: string; type: string; amount: string; } ⋮---- export interface MarginDelistSchedule { delistTime: number; crossMarginAssets: string[]; isolatedMarginSymbols: string[]; updateTime: number; } ⋮---- export interface MarginAvailableInventoryResponse { assets: any; updateTime: number; } ⋮---- export interface ManualLiquidationParams { type: string; symbol?: string; } ⋮---- export interface ManualLiquidationResponse { asset: string; interest: string; principal: string; liabilityAsset: string; liabilityQty: number; } ⋮---- export interface LeverageBracket { leverage: number; maxDebt: number; maintenanceMarginRate: number; initialMarginRate: number; fastNum: number; } ⋮---- export interface LiabilityCoinLeverageBracket { assetNames: string[]; rank: number; brackets: LeverageBracket[]; } export interface GetFlexibleSubscriptionRecordParams { productId?: string; purchaseId?: string; asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface GetFlexibleSubscriptionRecordResponse { amount: string; asset: string; time: number; purchaseId: number; type: string; sourceAccount: string; amtFromSpot?: string; amtFromFunding?: string; status: string; } ⋮---- export interface GetLockedSubscriptionRecordParams { purchaseId?: string; asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface LockedSubscriptionRecord { positionId: string; purchaseId: number; time: number; asset: string; amount: string; lockPeriod: string; type: string; sourceAccount: string; amtFromSpot?: string; amtFromFunding?: string; status: string; } ⋮---- export interface GetFlexibleRedemptionRecordParams { productId?: string; redeemId?: string; asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface FlexibleRedemptionRecord { amount: string; asset: string; time: number; productId: string; redeemId: number; destAccount: string; status: string; } ⋮---- export interface GetLockedRedemptionRecordParams { positionId?: string; redeemId?: string; asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface LockedRedemptionRecord { positionId: string; redeemId: number; time: number; asset: string; lockPeriod: string; amount: string; type: string; deliverDate: string; status: string; } ⋮---- export interface GetFlexibleRewardsHistoryParams { productId?: string; asset?: string; startTime?: number; endTime?: number; type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; current?: number; size?: number; } ⋮---- export interface FlexibleRewardsHistory { asset: string; rewards: string; projectId: string; type: string; time: number; } ⋮---- export interface GetLockedRewardsHistoryParams { positionId?: string; asset?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface GetLockedRewardsHistory { positionId: string; time: number; asset: string; lockPeriod: string; amount: string; type: string; } ⋮---- export interface SetAutoSubscribeParams { productId: string; autoSubscribe: boolean; } ⋮---- export interface GetFlexibleSubscriptionPreviewParams { productId: string; amount: number; } ⋮---- export interface FlexibleSubscriptionPreview { totalAmount: string; rewardAsset: string; airDropAsset: string; estDailyBonusRewards: string; estDailyRealTimeRewards: string; estDailyAirdropRewards: string; } ⋮---- export interface GetLockedSubscriptionPreviewParams { projectId: string; amount: number; autoSubscribe?: boolean; } ⋮---- export interface LockedSubscriptionPreview { rewardAsset: string; totalRewardAmt: string; extraRewardAsset: string; estTotalExtraRewardAmt: string; nextPay: string; nextPayDate: string; valueDate: string; rewardsEndDate: string; deliverDate: string; nextSubscriptionDate: string; boostRewardAsset: string; estDailyRewardAmt: string; } ⋮---- export interface GetRateHistoryParams { productId: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface GetRateHistory { productId: string; asset: string; annualPercentageRate: string; time: number; } ⋮---- export interface GetCollateralRecordParams { productId?: string; startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface CollateralRecord { amount: string; productId: string; asset: string; createTime: number; type: string; productName: string; orderId: number; } ⋮---- export interface GetDualInvestmentProductListParams { optionType: string; exercisedCoin: string; investCoin: string; pageSize?: number; pageIndex?: number; } ⋮---- export interface DualInvestmentProduct { id: string; investCoin: string; exercisedCoin: string; strikePrice: string; duration: number; settleDate: number; purchaseDecimal: number; purchaseEndTime: number; canPurchase: boolean; apr: string; orderId: number; minAmount: string; maxAmount: string; createTimestamp: number; optionType: string; isAutoCompoundEnable: boolean; autoCompoundPlanList: string[]; } ⋮---- export interface SubscribeDualInvestmentProductParams { id: string; orderId: string; depositAmount: number; autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; } ⋮---- export interface SubscribeDualInvestmentProductResponse { positionId: number; investCoin: string; exercisedCoin: string; subscriptionAmount: string; duration: number; autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; strikePrice: string; settleDate: number; purchaseStatus: string; apr: string; orderId: number; purchaseTime: number; optionType: string; } ⋮---- export interface GetDualInvestmentPositionsParams { status?: | 'PENDING' | 'PURCHASE_SUCCESS' | 'SETTLED' | 'PURCHASE_FAIL' | 'REFUNDING' | 'REFUND_SUCCESS' | 'SETTLING'; pageSize?: number; pageIndex?: number; } ⋮---- export interface DualInvestmentPosition { id: string; investCoin: string; exercisedCoin: string; subscriptionAmount: string; strikePrice: string; duration: number; settleDate: number; purchaseStatus: string; apr: string; orderId: number; purchaseEndTime: number; optionType: string; autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; settlePrice?: string; isExercised?: boolean; settleAsset?: string; settleAmount?: string; } ⋮---- export interface CheckDualInvestmentAccountsResponse { totalAmountInBTC: string; totalAmountInUSDT: string; } ⋮---- export interface ChangeAutoCompoundStatusParams { positionId: string; autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; } ⋮---- export interface ChangeAutoCompoundStatusResponse { positionId: string; autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; } ⋮---- export interface GetTargetAssetListParams { targetAsset?: string; size?: number; current?: number; } ⋮---- export interface RoiAndDimensionType { simulateRoi: string; dimensionValue: string; dimensionUnit: string; } ⋮---- export interface AutoInvestAsset { targetAsset: string; roiAndDimensionTypeList: RoiAndDimensionType[]; } ⋮---- export interface GetTargetAssetListResponse { targetAssets: string[]; autoInvestAssetList: AutoInvestAsset[]; } ⋮---- export interface GetTargetAssetROIParams { targetAsset: string; hisRoiType: | 'FIVE_YEAR' | 'THREE_YEAR' | 'ONE_YEAR' | 'SIX_MONTH' | 'THREE_MONTH' | 'SEVEN_DAY'; } ⋮---- export interface TargetAssetROI { date: string; simulateRoi: string; } ⋮---- export interface GetSourceAssetListParams { targetAsset?: string[]; indexId?: number; usageType: 'RECURRING' | 'ONE_TIME'; flexibleAllowedToUse?: boolean; sourceType?: 'MAIN_SITE' | 'TR'; } ⋮---- export interface SourceAsset { sourceAsset: string; assetMinAmount: string; assetMaxAmount: string; scale: string; flexibleAmount: string; } ⋮---- export interface GetSourceAssetListResponse { feeRate: string; taxRate: string; sourceAssets: SourceAsset[]; } ⋮---- export interface AutoInvestPortfolioDetail { targetAsset: string; percentage: number; } ⋮---- export interface CreateInvestmentPlanParams { UID: string; sourceType: 'MAIN_SITE' | 'TR'; requestId?: string; planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; indexId?: number; subscriptionAmount: number; subscriptionCycle: | 'H1' | 'H4' | 'H8' | 'H12' | 'WEEKLY' | 'DAILY' | 'MONTHLY' | 'BI_WEEKLY'; subscriptionStartDay?: number; subscriptionStartWeekday?: | 'MON' | 'TUE' | 'WED' | 'THU' | 'FRI' | 'SAT' | 'SUN'; subscriptionStartTime: number; sourceAsset: string; flexibleAllowedToUse: boolean; details: AutoInvestPortfolioDetail[]; } ⋮---- export interface CreateInvestmentPlanResponse { planId: number; nextExecutionDateTime: number; } ⋮---- export interface EditInvestmentPlanParams { planId: number; subscriptionAmount: number; subscriptionCycle: | 'H1' | 'H4' | 'H8' | 'H12' | 'WEEKLY' | 'DAILY' | 'MONTHLY' | 'BI_WEEKLY'; subscriptionStartDay?: number; subscriptionStartWeekday?: | 'MON' | 'TUE' | 'WED' | 'THU' | 'FRI' | 'SAT' | 'SUN'; subscriptionStartTime: number; sourceAsset: string; flexibleAllowedToUse?: boolean; details: AutoInvestPortfolioDetail[]; } ⋮---- export interface EditInvestmentPlanResponse { planId: number; nextExecutionDateTime: number; } ⋮---- export interface ChangePlanStatusParams { planId: number; status: 'ONGOING' | 'PAUSED' | 'REMOVED'; } ⋮---- export interface ChangePlanStatusResponse { planId: number; nextExecutionDateTime: number; status: 'ONGOING' | 'PAUSED' | 'REMOVED'; } ⋮---- export interface GetPlanDetailsParams { planId?: number; requestId?: string; } ⋮---- export interface GetSubscriptionTransactionHistoryParams { planId?: number; startTime?: number; endTime?: number; targetAsset?: string; planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; size?: number; current?: number; } ⋮---- export interface AssetAllocation { targetAsset: string; allocation: string; } ⋮---- export interface GetIndexDetailsResponse { indexId: number; indexName: string; status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; assetAllocation: AssetAllocation[]; } ⋮---- export interface IndexLinkedPlanDetail { targetAsset: string; averagePriceInUSD: string; totalInvestedInUSD: string; currentInvestedInUSD: string; purchasedAmount: string; pnlInUSD: string; roi: string; percentage: string; availableAmount: string; redeemedAmount: string; assetValueInUSD: string; } ⋮---- export interface GetIndexLinkedPlanPositionDetailsResponse { indexId: number; totalInvestedInUSD: string; currentInvestedInUSD: string; pnlInUSD: string; roi: string; assetAllocation: { targetAsset: string; allocation: string }[]; details: IndexLinkedPlanDetail[]; } ⋮---- export interface SubmitOneTimeTransactionParams { sourceType: 'MAIN_SITE' | 'TR'; requestId?: string; subscriptionAmount: number; sourceAsset: string; flexibleAllowedToUse?: boolean; planId?: number; indexId?: number; details: AutoInvestPortfolioDetail[]; } ⋮---- export interface SubmitOneTimeTransactionResponse { transactionId: number; waitSecond: number; } ⋮---- export interface GetOneTimeTransactionStatusParams { transactionId: number; requestId?: string; } ⋮---- export interface GetOneTimeTransactionStatusResponse { transactionId: number; status: 'SUCCESS' | 'CONVERTING'; } ⋮---- export interface SubmitIndexLinkedPlanRedemptionParams { indexId: number; requestId?: string; redemptionPercentage: number; } ⋮---- export interface GetIndexLinkedPlanRedemptionHistoryParams { requestId: number; startTime?: number; endTime?: number; current?: number; asset?: string; size?: number; } ⋮---- export interface IndexLinkedPlanRedemptionRecord { indexId: number; indexName: string; redemptionId: number; status: 'SUCCESS' | 'FAILED'; asset: string; amount: string; redemptionDateTime: number; transactionFee: string; transactionFeeUnit: string; } ⋮---- export interface GetIndexLinkedPlanRebalanceHistoryParams { startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface RebalanceTransactionDetail { asset: string; transactionDateTime: number; rebalanceDirection: 'BUY' | 'SELL'; rebalanceAmount: string; } ⋮---- export interface IndexLinkedPlanRebalanceRecord { indexId: number; indexName: string; rebalanceId: number; status: 'SUCCESS' | 'INIT'; rebalanceFee: string; rebalanceFeeUnit: string; transactionDetails: RebalanceTransactionDetail[]; } ⋮---- export interface SubscribeEthStakingV2Response { success: boolean; wbethAmount: string; conversionRatio: string; } ⋮---- export interface RedeemEthParams { asset?: string; amount: number; } ⋮---- export interface RedeemEthResponse { success: boolean; arrivalTime: number; ethAmount: string; conversionRatio: string; } ⋮---- export interface GetEthStakingHistoryParams { startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface EthStakingHistory { time: number; asset: string; amount: string; status: 'PENDING' | 'SUCCESS' | 'FAILED'; distributeAmount: string; conversionRatio: string; } ⋮---- export interface GetEthRedemptionHistoryParams { startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface EthRedemptionHistory { time: number; arrivalTime: number; asset: string; amount: string; status: 'PENDING' | 'SUCCESS' | 'FAILED'; distributeAsset: string; distributeAmount: string; conversionRatio: string; } ⋮---- export interface GetBethRewardsHistoryParams { startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface BethRewardsHistory { time: number; asset: string; holding: string; amount: string; annualPercentageRate: string; status: 'PENDING' | 'SUCCESS' | 'FAILED'; } ⋮---- export interface GetEthStakingQuotaResponse { leftStakingPersonalQuota: string; leftRedemptionPersonalQuota: string; } ⋮---- export interface GetETHRateHistoryParams { startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface ETHRateHistory { annualPercentageRate: string; exchangeRate: string; time: number; } ⋮---- export interface GetEthStakingAccountResponse { cumulativeProfitInBETH: string; lastDayProfitInBETH: string; } ⋮---- export interface GetEthStakingAccountV2Response { holdingInETH: string; holdings: { wbethAmount: string; bethAmount: string; }; thirtyDaysProfitInETH: string; profit: { amountFromWBETH: string; amountFromBETH: string; }; } ⋮---- export interface WrapBethResponse { success: boolean; wbethAmount: string; exchangeRate: string; } ⋮---- export interface GetWrapHistoryParams { startTime?: number; endTime?: number; current?: number; size?: number; } ⋮---- export interface WrapHistory { time: number; fromAsset: string; fromAmount: string; toAsset: string; toAmount: string; exchangeRate: string; status: 'PENDING' | 'SUCCESS' | 'FAILED'; } ⋮---- export interface WbethRewardsHistory { time: number; amountInETH: string; holding: string; holdingInETH: string; annualPercentageRate: string; } ⋮---- export interface GetWbethRewardsHistoryResponse { estRewardsInETH: string; rows: WbethRewardsHistory[]; total: number; } ⋮---- export interface GetMiningAlgoListResponse { algoName: string; // Algorithm name algoId: number; // Algorithm ID poolIndex: number; // Sequence unit: string; // Unit } ⋮---- algoName: string; // Algorithm name algoId: number; // Algorithm ID poolIndex: number; // Sequence unit: string; // Unit ⋮---- export interface GetMiningCoinListResponse { coinName: string; // Coin name coinId: number; // Coin ID poolIndex: number; // Sequence unit: string; // Unit } ⋮---- coinName: string; // Coin name coinId: number; // Coin ID poolIndex: number; // Sequence unit: string; // Unit ⋮---- export interface GetMinerDetailsParams { algo: string; userName: string; workerName: string; } ⋮---- export interface HashrateData { time: number; hashrate: string; reject: number; } ⋮---- export interface MinerDetail { workerName: string; type: string; hashrateDatas: HashrateData[]; } ⋮---- export interface GetMinerDetailsResponse { code: number; msg: string; data: MinerDetail[]; } ⋮---- export interface GetMinerListParams { algo: string; userName: string; pageIndex?: number; sort?: number; sortColumn?: number; workerStatus?: number; } ⋮---- export interface WorkerData { workerId: string; workerName: string; status: number; hashRate: number; dayHashRate: number; rejectRate: number; lastShareTime: number; } ⋮---- export interface GetMinerListResponse { code: number; msg: string; data: { workerDatas: WorkerData[]; totalNum: number; pageSize: number; }; } ⋮---- export interface GetEarningsListParams { algo: string; userName: string; coin?: string; startDate?: number; endDate?: number; pageIndex?: number; pageSize?: number; } ⋮---- export interface AccountEarningsProfit { time: number; type: number; hashTransfer: number | null; transferAmount: number | null; dayHashRate: number; profitAmount: number; coinName: string; status: number; } ⋮---- export interface GetEarningsListResponse { code: number; msg: string; data: { accountProfits: AccountEarningsProfit[]; totalNum: number; pageSize: number; }; } ⋮---- export interface GetExtraBonusListParams { algo: string; userName: string; coin?: string; startDate?: number; endDate?: number; pageIndex?: number; pageSize?: number; } ⋮---- export interface OtherProfit { time: number; coinName: string; type: number; profitAmount: number; status: number; } ⋮---- export interface GetExtraBonusListResponse { code: number; msg: string; data: { otherProfits: OtherProfit[]; totalNum: number; pageSize: number; }; } ⋮---- export interface GetHashrateResaleListParams { pageIndex?: number; pageSize?: number; } ⋮---- export interface ConfigDetail { configId: number; poolUsername: string; toPoolUsername: string; algoName: string; hashRate: number; startDay: number; endDay: number; status: number; } ⋮---- export interface GetHashrateResaleListResponse { code: number; msg: string; data: { configDetails: ConfigDetail[]; totalNum: number; pageSize: number; }; } ⋮---- export interface GetHashrateResaleDetailParams { configId: number; userName: string; pageIndex?: number; pageSize?: number; } ⋮---- export interface ProfitTransferDetail { poolUsername: string; toPoolUsername: string; algoName: string; hashRate: number; day: number; amount: number; coinName: string; } ⋮---- export interface GetHashrateResaleDetailResponse { code: number; msg: string; data: { profitTransferDetails: ProfitTransferDetail[]; totalNum: number; pageSize: number; }; } export interface SubmitHashrateResaleParams { userName: string; algo: string; endDate: number; startDate: number; toPoolUser: string; hashRate: number; } ⋮---- export interface CancelHashrateResaleConfigParams { configId: number; userName: string; } ⋮---- export interface GetStatisticListParams { algo: string; userName: string; } ⋮---- export interface Profit { BTC: string; BSV: string; BCH: string; } ⋮---- export interface GetStatisticListResponse { code: number; msg: string; data: { fifteenMinHashRate: string; dayHashRate: string; validNum: number; invalidNum: number; profitToday: Profit; profitYesterday: Profit; userName: string; unit: string; algo: string; }; } ⋮---- export interface getMiningAccountsListParams { algo: string; userName: string; } ⋮---- export interface MiningHashrateData { time: number; hashrate: string; reject: string; } ⋮---- export interface MiningAccountData { type: string; userName: string; list: MiningHashrateData[]; } ⋮---- export interface getMiningAccountsListResponse { code: number; msg: string; data: MiningAccountData[]; } ⋮---- export interface GetMiningAccountEarningParams { algo: string; startDate?: number; endDate?: number; pageIndex?: number; pageSize?: number; } ⋮---- export interface AccountMiningProfit { time: number; coinName: string; type: number; puid: number; subName: string; amount: number; } ⋮---- export interface GetMiningAccountEarningResponse { code: number; msg: string; data: { accountProfits: AccountMiningProfit[]; totalNum: number; pageSize: number; }; } ⋮---- export interface GetFutureTickLevelOrderbookDataLinkParams { symbol: string; dataType: 'T_DEPTH' | 'S_DEPTH'; startTime: number; endTime: number; } ⋮---- export interface HistoricalDataLink { day: string; url: string; } ⋮---- export interface SubmitVpNewOrderParams { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; quantity: number; urgency: 'LOW' | 'MEDIUM' | 'HIGH'; clientAlgoId?: string; reduceOnly?: boolean; limitPrice?: number; } ⋮---- export interface SubmitVpNewOrderResponse { clientAlgoId: string; success: boolean; code: number; msg: string; } ⋮---- export interface SubmitTwapNewOrderParams { symbol: string; side: 'BUY' | 'SELL'; positionSide?: 'BOTH' | 'LONG' | 'SHORT'; quantity: number; duration: number; clientAlgoId?: string; reduceOnly?: boolean; limitPrice?: number; } ⋮---- export interface SubmitTwapNewOrderResponse { clientAlgoId: string; success: boolean; code: number; msg: string; } ⋮---- export interface CancelAlgoOrderResponse { algoId: number; success: boolean; code: number; msg: string; } ⋮---- export interface AlgoOrder { algoId: number; symbol: string; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; totalQty: string; executedQty: string; executedAmt: string; avgPrice: string; clientAlgoId: string; bookTime: number; endTime: number; algoStatus: string; algoType: string; urgency: string; } ⋮---- export interface GetAlgoHistoricalOrdersParams { symbol?: string; side?: 'BUY' | 'SELL'; startTime?: number; endTime?: number; page?: number; pageSize?: number; } ⋮---- export interface HistoricalAlgoOrder { algoId: number; symbol: string; side: 'BUY' | 'SELL'; positionSide: 'BOTH' | 'LONG' | 'SHORT'; totalQty: string; executedQty: string; executedAmt: string; avgPrice: string; clientAlgoId: string; bookTime: number; endTime: number; algoStatus: string; algoType: string; urgency: string; } ⋮---- export interface GetAlgoSubOrdersParams { algoId: number; page?: number; pageSize?: number; } ⋮---- export interface SubOrder { algoId: number; orderId: number; orderStatus: string; executedQty: string; executedAmt: string; feeAmt: string; feeAsset: string; bookTime: number; avgPrice: string; side: 'BUY' | 'SELL'; symbol: string; subId: number; timeInForce: string; origQty: string; } ⋮---- export interface GetAlgoSubOrdersResponse { total: number; executedQty: string; executedAmt: string; subOrders: SubOrder[]; } ⋮---- export interface SubmitSpotTwapNewOrderParams { symbol: string; side: 'BUY' | 'SELL'; quantity: number; duration: number; clientAlgoId?: string; limitPrice?: number; stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; } ⋮---- export interface SubmitSpotTwapNewOrderResponse { clientAlgoId: string; success: boolean; code: number; msg: string; } ⋮---- export interface CancelSpotAlgoOrderResponse { algoId: number; success: boolean; code: number; msg: string; } ⋮---- export interface SpotAlgoOrder { algoId: number; symbol: string; side: 'BUY' | 'SELL'; totalQty: string; executedQty: string; executedAmt: string; avgPrice: string; clientAlgoId: string; bookTime: number; endTime: number; algoStatus: string; algoType: string; urgency: string; } ⋮---- export interface GetSpotAlgoHistoricalOrdersParams { symbol?: string; side?: 'BUY' | 'SELL'; startTime?: number; endTime?: number; page?: number; pageSize?: number; } ⋮---- export interface HistoricalSpotAlgoOrder { algoId: number; symbol: string; side: 'BUY' | 'SELL'; totalQty: string; executedQty: string; executedAmt: string; avgPrice: string; clientAlgoId: string; bookTime: number; endTime: number; algoStatus: string; algoType: string; urgency: string; } ⋮---- export interface GetSpotAlgoSubOrdersParams { algoId: number; page?: number; pageSize?: number; } ⋮---- export interface SpotSubOrder { algoId: number; orderId: number; orderStatus: string; executedQty: string; executedAmt: string; feeAmt: string; feeAsset: string; bookTime: number; avgPrice: string; side: 'BUY' | 'SELL'; symbol: string; subId: number; timeInForce: string; origQty: string; } ⋮---- export interface GetSpotAlgoSubOrdersResponse { total: number; executedQty: string; executedAmt: string; subOrders: SpotSubOrder[]; } ⋮---- export interface GetPortfolioMarginProAccountInfoResponse { uniMMR: string; accountEquity: string; actualEquity: string; accountMaintMargin: string; accountStatus: string; accountType: string; } ⋮---- export interface GetPortfolioMarginProCollateralRateResponse { asset: string; collateralRate: string; } ⋮---- export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { asset: string; amount: string; } ⋮---- export interface GetPortfolioMarginProInterestHistoryParams { asset?: string; startTime?: number; endTime?: number; size?: number; } ⋮---- export interface GetPortfolioMarginProInterestHistoryResponse { asset: string; interest: string; interestAccruedTime: number; interestRate: string; principal: string; } ⋮---- export interface GetPortfolioMarginAssetIndexPriceResponse { asset: string; assetIndexPrice: string; time: number; } ⋮---- export interface BnbTransferParams { amount: number; transferSide: 'TO_UM' | 'FROM_UM'; } ⋮---- export interface GetPortfolioMarginAssetLeverageResponse { asset: string; leverage: number; } ⋮---- export interface 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 GetC2CTradeHistoryParams { tradeType: string; startTimestamp?: number; endTimestamp?: number; page?: number; rows?: number; } ⋮---- export interface c2cTradeData { orderNumber: string; advNo: string; tradeType: string; asset: string; fiat: string; fiatSymbol: string; amount: string; totalPrice: string; unitPrice: string; orderStatus: string; createTime: number; commission: string; counterPartNickName: string; advertisementRole: string; } export interface GetC2CTradeHistoryResponse { code: string; message: string; data: c2cTradeData[]; total: number; success: boolean; } ⋮---- export interface GetVipLoanOngoingOrdersParams { orderId?: number; collateralAccountId?: number; loanCoin?: string; collateralCoin?: string; current?: number; limit?: number; } ⋮---- export interface VipOngoingOrder { orderId: number; loanCoin: string; totalDebt: string; loanRate: string; residualInterest: string; collateralAccountId: string; collateralCoin: string; totalCollateralValueAfterHaircut: string; lockedCollateralValue: string; currentLTV: string; expirationTime: number; loanDate: string; loanTerm: string; initialLtv: string; marginCallLtv: string; liquidationLtv: string; } ⋮---- export interface VipLoanRepayParams { orderId: number; amount: number; } ⋮---- export interface VipLoanRepayResponse { loanCoin: string; repayAmount: string; remainingPrincipal: string; remainingInterest: string; collateralCoin: string; currentLTV: string; repayStatus: string; } ⋮---- export interface GetVipLoanRepaymentHistoryParams { orderId?: number; loanCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface VipLoanRepaymentHistory { loanCoin: string; repayAmount: string; collateralCoin: string; repayStatus: string; loanDate: string; repayTime: string; orderId: string; } ⋮---- export interface VipLoanRenewParams { orderId: number; loanTerm?: number; } ⋮---- export interface VipLoanRenewResponse { loanAccountId: string; loanCoin: string; loanAmount: string; collateralAccountId: string; collateralCoin: string; loanTerm: string; } ⋮---- export interface CheckVipCollateralAccountParams { orderId?: number; collateralAccountId?: number; } ⋮---- export interface VipCollateralAccount { collateralAccountId: string; collateralCoin: string; } ⋮---- export interface VipLoanBorrowParams { loanAccountId: number; loanCoin: string; loanAmount: number; collateralAccountId: string; collateralCoin: string; isFlexibleRate: boolean; loanTerm?: number; } ⋮---- export interface VipLoanBorrowResponse { loanAccountId: string; requestId: string; loanCoin: string; isFlexibleRate: string; loanAmount: string; collateralAccountId: string; collateralCoin: string; loanTerm?: string; } ⋮---- export interface GetLoanableAssetsDataParams { loanCoin?: string; vipLevel?: number; } ⋮---- export interface GetApplicationStatusParams { current?: number; limit?: number; } ⋮---- export interface ApplicationStatus { loanAccountId: string; orderId: string; requestId: string; loanCoin: string; loanAmount: string; collateralAccountId: string; collateralCoin: string; loanTerm: string; status: string; loanDate: string; } ⋮---- export interface BorrowInterestRate { asset: string; flexibleDailyInterestRate: string; flexibleYearlyInterestRate: string; time: number; } ⋮---- export interface GetCryptoLoansIncomeHistoryParams { asset?: string; type?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface GetCryptoLoansIncomeHistoryResponse { asset: string; type: string; amount: string; timestamp: number; tranId: string; } ⋮---- export interface BorrowCryptoLoanParams { loanCoin: string; loanAmount?: number; collateralCoin: string; collateralAmount?: number; loanTerm: number; } ⋮---- export interface BorrowCryptoLoanResponse { loanCoin: string; loanAmount: string; collateralCoin: string; collateralAmount: string; hourlyInterestRate: string; orderId: string; } ⋮---- export interface GetLoanBorrowHistoryParams { orderId?: number; loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface LoanBorrowHistory { orderId: number; loanCoin: string; initialLoanAmount: string; hourlyInterestRate: string; loanTerm: string; collateralCoin: string; initialCollateralAmount: string; borrowTime: number; status: string; } ⋮---- export interface GetLoanOngoingOrdersParams { orderId?: number; loanCoin?: string; collateralCoin?: string; current?: number; limit?: number; } ⋮---- export interface LoanOngoingOrder { orderId: number; loanCoin: string; totalDebt: string; residualInterest: string; collateralCoin: string; collateralAmount: string; currentLTV: string; expirationTime: number; } ⋮---- export interface RepayCryptoLoanParams { orderId: number; amount: number; type?: number; collateralReturn?: boolean; } ⋮---- export interface RepayCryptoLoanResponse { loanCoin: string; remainingPrincipal?: string; remainingInterest?: string; collateralCoin: string; remainingCollateral?: string; currentLTV?: string; repayStatus: string; } ⋮---- export interface GetLoanRepaymentHistoryParams { orderId?: number; loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface LoanRepaymentHistory { loanCoin: string; repayAmount: string; collateralCoin: string; collateralUsed: string; collateralReturn: string; repayType: string; repayStatus: string; repayTime: number; orderId: number; } ⋮---- export interface AdjustCryptoLoanLTVParams { orderId: number; amount: number; direction: 'ADDITIONAL' | 'REDUCED'; } ⋮---- export interface AdjustCryptoLoanLTVResponse { loanCoin: string; collateralCoin: string; direction: 'ADDITIONAL' | 'REDUCED'; amount: string; currentLTV: string; } ⋮---- export interface GetLoanLTVAdjustmentHistoryParams { orderId?: number; loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface LoanLTVAdjustmentHistory { loanCoin: string; collateralCoin: string; direction: 'ADDITIONAL' | 'REDUCED'; amount: string; preLTV: string; afterLTV: string; adjustTime: number; orderId: number; } ⋮---- export interface LoanableAssetData { loanCoin: string; _7dHourlyInterestRate: string; _7dDailyInterestRate: string; _14dHourlyInterestRate: string; _14dDailyInterestRate: string; _30dHourlyInterestRate: string; _30dDailyInterestRate: string; _90dHourlyInterestRate: string; _90dDailyInterestRate: string; _180dHourlyInterestRate: string; _180dDailyInterestRate: string; minLimit: string; maxLimit: string; vipLevel: number; } ⋮---- export interface GetCollateralAssetDataParams { collateralCoin?: string; vipLevel?: number; } ⋮---- export interface CollateralAssetData { collateralCoin: string; initialLTV: string; marginCallLTV: string; liquidationLTV: string; maxLimit: string; vipLevel: number; } ⋮---- export interface CheckCollateralRepayRateParams { loanCoin: string; collateralCoin: string; repayAmount: number; } ⋮---- export interface CheckCollateralRepayRateResponse { loanCoin: string; collateralCoin: string; repayAmount: string; rate: string; } ⋮---- export interface CustomizeMarginCallParams { orderId?: number; collateralCoin?: string; marginCall: number; } ⋮---- export interface CustomizeMarginCall { orderId: string; collateralCoin: string; preMarginCall: string; afterMarginCall: string; customizeTime: number; } ⋮---- export interface BorrowFlexibleLoanParams { loanCoin: string; loanAmount?: number; collateralCoin: string; collateralAmount?: number; } ⋮---- export interface BorrowFlexibleLoanResponse { loanCoin: string; loanAmount: string; collateralCoin: string; collateralAmount: string; status: 'Succeeds' | 'Failed' | 'Processing'; } ⋮---- export interface GetFlexibleLoanOngoingOrdersParams { loanCoin?: string; collateralCoin?: string; current?: number; limit?: number; } ⋮---- export interface FlexibleLoanOngoingOrder { loanCoin: string; totalDebt: string; collateralCoin: string; collateralAmount: string; currentLTV: string; } ⋮---- export interface GetFlexibleLoanLiquidationHistoryParams { loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; // Default: 1, max: 1000 limit?: number; // Default: 10, max: 100 recvWindow?: number; } ⋮---- current?: number; // Default: 1, max: 1000 limit?: number; // Default: 10, max: 100 ⋮---- export interface FlexibleLoanLiquidationHistoryRecord { loanCoin: string; liquidationDebt: string; collateralCoin: string; liquidationCollateralAmount: string; returnCollateralAmount: string; liquidationFee: string; liquidationStartingPrice: string; liquidationStartingTime: number; status: 'Liquidated' | 'Liquidating'; } ⋮---- export interface GetFlexibleCryptoLoanBorrowHistoryParams { loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface FlexibleCryptoLoanBorrowHistory { loanCoin: string; initialLoanAmount: string; collateralCoin: string; initialCollateralAmount: string; borrowTime: number; status: 'Succeeds' | 'Failed' | 'Processing'; } ⋮---- export interface RepayCryptoFlexibleLoanParams { loanCoin: string; collateralCoin: string; repayAmount: number; collateralReturn?: boolean; fullRepayment?: boolean; } ⋮---- export interface RepayCryptoFlexibleLoanResponse { loanCoin: string; collateralCoin: string; remainingDebt: string; remainingCollateral: string; fullRepayment: boolean; currentLTV: string; repayStatus: 'Repaid' | 'Repaying' | 'Failed'; } ⋮---- export interface RepayCryptoLoanFlexibleWithCollateralParams { loanCoin: string; collateralCoin: string; repayAmount: number; // Amount of loan to repay fullRepayment?: boolean; // Default: FALSE } ⋮---- repayAmount: number; // Amount of loan to repay fullRepayment?: boolean; // Default: FALSE ⋮---- export interface RepayCryptoLoanFlexibleWithCollateralResponse { loanCoin: string; collateralCoin: string; remainingDebt: string; remainingCollateral: string; fullRepayment: boolean; currentLTV: string; repayStatus: 'Repaid' | 'Repaying' | 'Failed'; } export interface GetFlexibleCryptoLoanRepaymentHistoryParams { loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface FlexibleCryptoLoanRepaymentHistory { loanCoin: string; repayAmount: string; collateralCoin: string; collateralReturn: string; repayStatus: 'Repaid' | 'Repaying' | 'Failed'; repayTime: number; } ⋮---- export interface AdjustFlexibleCryptoLoanLTVParams { loanCoin: string; collateralCoin: string; adjustmentAmount: number; direction: 'ADDITIONAL' | 'REDUCED'; } ⋮---- export interface AdjustFlexibleCryptoLoanLTVResponse { loanCoin: string; collateralCoin: string; direction: 'ADDITIONAL' | 'REDUCED'; adjustmentAmount: string; currentLTV: string; } ⋮---- export interface GetFlexibleLoanLTVAdjustmentHistoryParams { loanCoin?: string; collateralCoin?: string; startTime?: number; endTime?: number; current?: number; limit?: number; } ⋮---- export interface FlexibleLoanLTVAdjustmentHistory { loanCoin: string; collateralCoin: string; direction: 'ADDITIONAL' | 'REDUCED'; collateralAmount: string; preLTV: string; afterLTV: string; adjustTime: number; } ⋮---- export interface FlexibleLoanAssetData { loanCoin: string; flexibleInterestRate: string; flexibleMinLimit: string; flexibleMaxLimit: string; } ⋮---- export interface FlexibleLoanCollateralAssetData { collateralCoin: string; initialLTV: string; marginCallLTV: string; liquidationLTV: string; maxLimit: string; } ⋮---- export interface GetFuturesLeadTraderStatusResponse { code: string; message: string; data: { isLeadTrader: boolean; time: number; }; success: boolean; } ⋮---- export interface GetFuturesLeadTradingSymbolWhitelistResponse { code: string; message: string; data: { symbol: string; baseAsset: string; quoteAsset: string; }[]; } ⋮---- export interface GetPayTradeHistoryParams { startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface GetAllConvertPairsParams { fromAsset?: string; toAsset?: string; } ⋮---- export interface SubmitConvertLimitOrderParams { baseAsset: string; quoteAsset: string; limitPrice: number; baseAmount?: number; quoteAmount?: number; side: 'BUY' | 'SELL'; walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; expiredType: '1_D' | '3_D' | '7_D' | '30_D'; } ⋮---- export interface ConvertLimitOpenOrder { quoteId: string; orderId: number; orderStatus: string; fromAsset: string; fromAmount: string; toAsset: string; toAmount: string; ratio: string; inverseRatio: string; createTime: number; expiredTimestamp: number; } ⋮---- export interface GetSpotRebateHistoryRecordsParams { startTime?: number; endTime?: number; page?: number; } ⋮---- export interface SpotRebateHistoryRecord { asset: string; type: number; amount: string; updateTime: number; } ⋮---- export interface GetSpotRebateHistoryRecordsResponse { status: string; type: string; code: string; data: { page: number; totalRecords: number; totalPageNum: number; data: SpotRebateHistoryRecord[]; }; } ⋮---- export interface GetNftTransactionHistoryParams { orderType: number; startTime?: number; endTime?: number; limit?: number; page?: number; } ⋮---- export interface NftToken { network: string; tokenId: string; contractAddress: string; } ⋮---- export interface NftTransaction { orderNo: string; tokens: NftToken[]; tradeTime: number; tradeAmount: string; tradeCurrency: string; } ⋮---- export interface GetNftDepositHistoryParams { startTime?: number; endTime?: number; limit?: number; page?: number; } ⋮---- export interface NftDeposit { network: string; txID: string | null; contractAdrress: string; tokenId: string; timestamp: number; } ⋮---- export interface GetNftWithdrawHistoryParams { startTime?: number; endTime?: number; limit?: number; page?: number; } ⋮---- export interface NftWithdraw { network: string; txID: string; contractAdrress: string; tokenId: string; timestamp: number; fee: number; feeAsset: string; } ⋮---- export interface GetNftAssetParams { limit?: number; page?: number; } ⋮---- export interface NftAsset { network: string; contractAddress: string; tokenId: string; } ⋮---- export interface CreateGiftCardParams { token: string; amount: number; } ⋮---- export interface CreateDualTokenGiftCardParams { baseToken: string; faceToken: string; baseTokenAmount: number; discount?: number; } ⋮---- export interface RedeemGiftCardParams { code: string; externalUid?: string; } ⋮---- export interface SimpleEarnProductListParams { asset?: string; current?: number; size?: number; } ⋮---- export interface SimpleEarnFlexibleProduct { asset: string; latestAnnualInterestRate: string; tierAnnualPercentageRate: Record; airDropPercentageRate: string; canPurchase: boolean; canRedeem: boolean; isSoldOut: boolean; hot: boolean; minPurchaseAmount: string; productId: string; subscriptionStartTime: number; status: string; } ⋮---- export interface SimpleEarnLockedProduct { projectId: string; detail: { asset: string; rewardAsset: string; duration: number; renewable: boolean; isSoldOut: boolean; apr: string; status: string; subscriptionStartTime: number; extraRewardAsset: string; extraRewardAPR: string; boostRewardAsset: string; boostApr: string; boostEndTime: string; }; quota: { totalPersonalQuota: string; minimum: string; }; } ⋮---- export interface SimpleEarnSubscribeProductParams { productId: string; amount: number; autoSubscribe?: boolean; sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; } ⋮---- export interface SimpleEarnSubscribeFlexibleProductResponse { purchaseId: string; success: boolean; } ⋮---- export interface SimpleEarnSubscribeLockedProductResponse { purchaseId: string; positionId: string; success: boolean; } ⋮---- export interface SimpleEarnRedeemFlexibleProductParams { productId: string; redeemAll?: boolean; amount?: number; destAccount?: 'SPOT' | 'FUND'; } ⋮---- export interface SimpleEarnRedeemResponse { success: boolean; redeemId: string; } ⋮---- export interface SimpleEarnFlexibleProductPositionParams { asset?: string; productId?: string; current?: number; size?: number; } ⋮---- export interface SimpleEarnLockedProductPositionParams { asset?: string; productId?: string; current?: number; size?: number; positionId?: string; } ⋮---- export interface SimpleEarnLockedProductPosition { positionId: string; projectId: string; asset: string; amount: string; purchaseTime: string; duration: string; accrualDays: string; rewardAsset: string; APY: string; isRenewable: boolean; isAutoRenew: boolean; redeemDate: string; boostRewardAsset: string; boostApr: string; totalBoostRewardAmt: string; } ⋮---- export interface SimpleEarnAccountResponse { totalAmountInBTC: string; totalAmountInUSDT: string; totalFlexibleAmountInBTC: string; totalFlexibleAmountInUSDT: string; totalLockedinBTC: string; totalLockedinUSDT: string; } ⋮---- export interface GetSubAccountDepositHistoryParams { subAccountId?: string; coin?: string; status?: number; startTime?: number; endTime?: number; limit?: number; offset?: number; } ⋮---- export interface SubAccountDeposit { depositId: number; subAccountId: string; address: string; addressTag: string; amount: string; coin: string; insertTime: number; transferType: number; network: string; status: number; txId: string; sourceAddress: string; confirmTimes: string; selfReturnStatus: number; } ⋮---- // Request interface for querying sub account spot asset info export interface QuerySubAccountSpotMarginAssetInfoParams { subAccountId?: string; page?: number; size?: number; } ⋮---- export interface SubaccountBrokerSpotAsset { subAccountId: string; totalBalanceOfBtc: string; } ⋮---- export interface SubAccountBrokerMarginAsset { marginEnable: boolean; subAccountId: string; totalAssetOfBtc?: string; totalLiabilityOfBtc?: string; totalNetAssetOfBtc?: string; marginLevel?: string; } ⋮---- // Request interface for querying sub account futures asset info export interface QuerySubAccountFuturesAssetInfoParams { subAccountId?: string; futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures page?: number; size?: number; } ⋮---- futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures ⋮---- // Response interface for querying sub account futures asset info (USD Margined Futures) export interface UsdtMarginedFuturesResponse { subAccountId: string; totalInitialMargin: string; totalMaintenanceMargin: string; totalWalletBalance: string; totalUnrealizedProfit: string; totalMarginBalance: string; totalPositionInitialMargin: string; totalOpenOrderInitialMargin: string; futuresEnable: boolean; asset: string; } ⋮---- // Response interface for querying sub account futures asset info (COIN Margined Futures) export interface CoinMarginedFuturesResponse { subAccountId: string; totalWalletBalanceOfUsdt: string; totalUnrealizedProfitOfUsdt: string; totalMarginBalanceOfUsdt: string; futuresEnable: boolean; } ⋮---- // Combined response interface for querying sub account futures asset info export interface BrokerFuturesSubAccountAssets { data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; timestamp: number; } ⋮---- export interface BrokerUniversalTransfer { toId: string; asset: string; qty: string; time: number; status: string; txnId: string; clientTranId: string; fromAccountType: string; toAccountType: string; } ⋮---- // Request interface for changing sub account commission export interface ChangeSubAccountCommissionParams { subAccountId: string; makerCommission: number; takerCommission: number; marginMakerCommission?: number; marginTakerCommission?: number; } ⋮---- // Response interface for changing sub account commission export interface ChangeSubAccountCommissionResponse { subAccountId: string; makerCommission: number; takerCommission: number; marginMakerCommission: number; marginTakerCommission: number; } ⋮---- // Request interface for changing sub account USDT-Ⓜ futures commission adjustment export interface ChangeSubAccountFuturesCommissionParams { subAccountId: string; symbol: string; makerAdjustment: number; takerAdjustment: number; } ⋮---- // Response interface for changing sub account USDT-Ⓜ futures commission adjustment export interface ChangeSubAccountFuturesCommissionResponse { subAccountId: string; symbol: string; makerAdjustment: number; takerAdjustment: number; makerCommission: number; takerCommission: number; } ⋮---- // Request interface for querying sub account USDT-Ⓜ futures commission adjustment export interface QuerySubAccountFuturesCommissionParams { subAccountId: string; symbol?: string; } ⋮---- // Response interface for querying sub account USDT-Ⓜ futures commission adjustment export interface BrokerSubAccountFuturesCommission { subAccountId: string; symbol: string; makerCommission: number; takerCommission: number; } ⋮---- export interface ChangeSubAccountCoinFuturesCommissionParams { subAccountId: string; pair: string; makerAdjustment: number; takerAdjustment: number; recvWindow?: number; timestamp: number; } ⋮---- export interface QuerySubAccountCoinFuturesCommissionParams { subAccountId: string; pair?: string; recvWindow?: number; timestamp: number; } ⋮---- // Response interface for querying sub account COIN-Ⓜ futures commission adjustment export interface BrokerSubAccountCoinFuturesCommission { subAccountId: string; pair: string; makerCommission: number; takerCommission: number; } ⋮---- export interface QueryBrokerSpotCommissionRebateParams { subAccountId?: string; startTime?: number; endTime?: number; page?: number; size?: number; recvWindow?: number; timestamp: number; } ⋮---- // Response interface for querying spot commission rebate recent record export interface BrokerCommissionRebate { subaccountId: string; income: string; asset: string; symbol: string; tradeId: number; time: number; status: number; } ⋮---- export interface QueryBrokerFuturesCommissionRebateParams { futuresType: number; // 1: USDT Futures, 2: Coin Futures startTime: number; endTime: number; page?: number; size?: number; filterResult?: boolean; recvWindow?: number; timestamp: number; } ⋮---- futuresType: number; // 1: USDT Futures, 2: Coin Futures ⋮---- export interface SubmitMarginOTOOrderParams { symbol: string; isIsolated?: 'TRUE' | 'FALSE'; listClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; sideEffectType?: SideEffects; selfTradePreventionMode?: | 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; autoRepayAtCancel?: boolean; workingType: 'LIMIT' | 'LIMIT_MAKER'; workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: number; workingQuantity: number; workingIcebergQty?: number; workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; pendingType: OrderType; pendingSide: 'BUY' | 'SELL'; pendingClientOrderId?: string; pendingPrice?: number; pendingStopPrice?: number; pendingTrailingDelta?: number; pendingQuantity: number; pendingIcebergQty?: number; pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; } ⋮---- export interface MarginOTOOrder { orderListId: number; contingencyType: string; listStatusType: string; listOrderStatus: string; listClientOrderId: string; transactionTime: number; symbol: string; isIsolated: boolean; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; orderReports: { symbol: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: string; timeInForce: string; type: string; side: string; selfTradePreventionMode: string; }[]; } ⋮---- export interface SubmitMarginOTOCOOrderParams { symbol: string; isIsolated?: 'TRUE' | 'FALSE'; sideEffectType?: SideEffects; autoRepayAtCancel?: boolean; listClientOrderId?: string; newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; selfTradePreventionMode?: | 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; workingType: 'LIMIT' | 'LIMIT_MAKER'; workingSide: 'BUY' | 'SELL'; workingClientOrderId?: string; workingPrice: string; workingQuantity: string; workingIcebergQty?: string; workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; pendingSide: 'BUY' | 'SELL'; pendingQuantity: string; pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; pendingAboveClientOrderId?: string; pendingAbovePrice?: string; pendingAboveStopPrice?: string; pendingAboveTrailingDelta?: string; pendingAboveIcebergQty?: string; pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; pendingBelowClientOrderId?: string; pendingBelowPrice?: string; pendingBelowStopPrice?: string; pendingBelowTrailingDelta?: string; pendingBelowIcebergQty?: string; pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; } ⋮---- export interface MarginOTOCOOrder { orderListId: number; contingencyType: 'OTO'; listStatusType: 'EXEC_STARTED'; listOrderStatus: 'EXECUTING'; listClientOrderId: string; transactionTime: number; symbol: string; isIsolated: boolean; orders: { symbol: string; orderId: number; clientOrderId: string; }[]; orderReports: { symbol: string; orderId: number; orderListId: number; clientOrderId: string; transactTime: number; price: string; origQty: string; executedQty: string; cummulativeQuoteQty: string; status: | 'NEW' | 'PARTIALLY_FILLED' | 'FILLED' | 'CANCELED' | 'PENDING_CANCEL' | 'REJECTED' | 'EXPIRED' | 'PENDING_NEW'; timeInForce: 'GTC' | 'IOC' | 'FOK'; type: | 'LIMIT' | 'MARKET' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT' | 'TAKE_PROFIT' | 'TAKE_PROFIT_LIMIT' | 'LIMIT_MAKER'; side: 'BUY' | 'SELL'; stopPrice?: string; selfTradePreventionMode: | 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; }[]; } ⋮---- export interface CreateSpecialLowLatencyKeyParams { apiName: string; symbol?: string; ip?: string; publicKey?: string; } ⋮---- export interface SpecialLowLatencyKeyResponse { apiKey: string; secretKey: string | null; type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; } ⋮---- export interface SpecialLowLatencyKeyInfo { apiName: string; apiKey: string; ip: string; type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; } ⋮---- export interface 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; } ⋮---- // Institutional Loan types export interface InstitutionalLoanLiability { assetName: string; principal: string; interest: string; } ⋮---- export interface InstitutionalLoanWallet { accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; netEquity: string; maintainMargin: string; } ⋮---- export interface InstitutionalLoanCollateralAccount { email: string; type: 'CREDIT' | 'COLLATERAL'; wallets: InstitutionalLoanWallet[]; } ⋮---- export interface InstitutionalLoanRiskUnitDetails { groupId: number; parentEmail: string; creditEmail: string; updateTime: number; ltv: string; totalNetEquity: string; totalMaintenanceMargin: string; totalLiability: string; liabilities: InstitutionalLoanLiability[]; collateralAccounts: InstitutionalLoanCollateralAccount[]; } ⋮---- export interface GetInstitutionalLoanRiskUnitDetailsParams { groupId?: number; } ⋮---- export interface CloseInstitutionalLoanRiskUnitResponse { groupId: number; status: 'CLOSED'; } ⋮---- export interface AddInstitutionalLoanCollateralAccountParams { groupId: number; subEmail: string; enableSpot: boolean; enableMargin: boolean; } ⋮---- export interface InstitutionalLoanRiskUnitMember { email: string; type: 'CREDIT' | 'COLLATERAL'; enableMargin: boolean; enableSpot: boolean; } ⋮---- export interface ActiveInstitutionalLoanRiskUnit { groupId: number; members: InstitutionalLoanRiskUnitMember[]; createTime: number; } export interface ClosedInstitutionalLoanRiskUnit { groupId: number; parentEmail: string; creditEmail: string; enabled: boolean; createTime: number; closeTime: number; } ⋮---- export interface GetClosedInstitutionalLoanRiskUnitsParams { current?: number; size?: number; } ⋮---- export interface GetClosedInstitutionalLoanRiskUnitsResponse { total: number; rows: ClosedInstitutionalLoanRiskUnit[]; } ⋮---- // Institutional Loan Force Liquidation interfaces export interface InstitutionalLoanLiquidationSnapshot { subEmail: string; memberType: 'CREDIT' | 'COLLATERAL'; walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; netEquity: string; maintainMargin: string; } ⋮---- export interface InstitutionalLoanLiquidationSnapshotData { snapshots: InstitutionalLoanLiquidationSnapshot[]; liabilities: InstitutionalLoanLiability[]; } ⋮---- export interface InstitutionalLoanForceLiquidationRecord { groupId: number; startLtv: number; endLtv: number; liquidationStartTime: number; liquidationEndTime: number; totalNetEquity: string; totalMaintenanceMargin: string; totalLiability: string; liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; } ⋮---- export interface GetInstitutionalLoanForceLiquidationParams { groupId?: number; startTime?: number; endTime?: number; current?: number; size?: number; recvWindow?: number; timestamp: number; } ⋮---- export interface GetInstitutionalLoanForceLiquidationResponse { total: number; rows: InstitutionalLoanForceLiquidationRecord[]; } ⋮---- // Risk Unit Transfer interfaces export interface InstitutionalLoanRiskUnitTransferParams { subEmail?: string; // Optional: subEmail can be credit account or collateral account asset: string; // Asset Name amount: number; // Transfer amount of the asset } ⋮---- subEmail?: string; // Optional: subEmail can be credit account or collateral account asset: string; // Asset Name amount: number; // Transfer amount of the asset ⋮---- // Additional institutional loan types for borrow, repay, and interest history export interface 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[]; } ⋮---- // 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 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; } ================ File: src/websocket-api-client.ts ================ import { ExchangeInfo, SpotAmendKeepPriorityResult } from './types/spot'; import { WSAPIResponse, WSAPIUserDataListenKeyRequest, } from './types/websockets/ws-api'; import { WSAPIAccountCommissionWSAPIRequest, WSAPIAccountInformationRequest, WSAPIAllOrderListsRequest, WSAPIAllOrdersRequest, WSAPIAvgPriceRequest, WSAPIExchangeInfoRequest, WSAPIFuturesOrderBookRequest, WSAPIFuturesOrderCancelRequest, WSAPIFuturesOrderModifyRequest, WSAPIFuturesOrderStatusRequest, WSAPIFuturesPositionRequest, WSAPIFuturesPositionV2Request, WSAPIFuturesTickerBookRequest, WSAPIFuturesTickerPriceRequest, WSAPIKlinesRequest, WSAPIMyAllocationsRequest, WSAPIMyPreventedMatchesRequest, WSAPIMyTradesRequest, WSAPINewFuturesOrderRequest, WSAPINewSpotOrderRequest, WSAPIOpenOrdersCancelAllRequest, WSAPIOpenOrdersStatusRequest, WSAPIOrderAmendKeepPriorityRequest, WSAPIOrderBookRequest, WSAPIOrderCancelReplaceRequest, WSAPIOrderCancelRequest, WSAPIOrderListCancelRequest, WSAPIOrderListPlaceOCORequest, WSAPIOrderListPlaceOTOCORequest, WSAPIOrderListPlaceOTORequest, WSAPIOrderListPlaceRequest, WSAPIOrderListStatusRequest, WSAPIOrderStatusRequest, WSAPIOrderTestRequest, WSAPIRecvWindowTimestamp, WSAPISOROrderPlaceRequest, WSAPISOROrderTestRequest, WSAPITicker24hrRequest, WSAPITickerBookRequest, WSAPITickerPriceRequest, WSAPITickerRequest, WSAPITickerTradingDayRequest, WSAPITradesAggregateRequest, WSAPITradesHistoricalRequest, WSAPITradesRecentRequest, } from './types/websockets/ws-api-requests'; import { WSAPIAccountCommission, WSAPIAccountInformation, WSAPIAggregateTrade, WSAPIAllocation, WSAPIAvgPrice, WSAPIBookTicker, WSAPIFullTicker, WSAPIFuturesAccountBalanceItem, WSAPIFuturesAccountStatus, WSAPIFuturesBookTicker, WSAPIFuturesOrder, WSAPIFuturesOrderBook, WSAPIFuturesPosition, WSAPIFuturesPositionV2, WSAPIFuturesPriceTicker, WSAPIKline, WSAPIMiniTicker, WSAPIOrder, WSAPIOrderBook, WSAPIOrderCancel, WSAPIOrderCancelReplaceResponse, WSAPIOrderListCancelResponse, WSAPIOrderListPlaceResponse, WSAPIOrderListStatusResponse, WSAPIOrderTestResponse, WSAPIOrderTestWithCommission, WSAPIPreventedMatch, WSAPIPriceTicker, WSAPIRateLimit, WSAPIServerTime, WSAPISessionStatus, WSAPISOROrderPlaceResponse, WSAPISOROrderTestResponse, WSAPISOROrderTestResponseWithCommission, WSAPISpotOrderResponse, WSAPITrade, } from './types/websockets/ws-api-responses'; import { WSClientConfigurableOptions } from './types/websockets/ws-general'; import { DefaultLogger } from './util/logger'; import { isWSAPIWsKey } from './util/typeGuards'; import { getTestnetWsKey, WS_KEY_MAP, WS_LOGGER_CATEGORY, WSAPIWsKey, WSAPIWsKeyFutures, WSAPIWsKeyMain, WsKey, } from './util/websockets/websocket-util'; import { WebsocketClient } from './websocket-client'; ⋮---- function getFuturesMarketWsKey(market: 'usdm' | 'coinm'): WSAPIWsKeyFutures ⋮---- /** * Configurable options specific to only the REST-like WebsocketAPIClient */ export interface WSAPIClientConfigurableOptions { /** * Default: true * * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected */ resubscribeUserDataStreamAfterReconnect: boolean; /** * Default: 2 seconds * * Delay automatic userdata resubscribe by x seconds. */ resubscribeUserDataStreamDelaySeconds: number; /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ attachEventListeners: boolean; } ⋮---- /** * Default: true * * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected */ ⋮---- /** * Default: 2 seconds * * Delay automatic userdata resubscribe by x seconds. */ ⋮---- /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ ⋮---- /** * Used to track that a connection had an active user data stream before it disconnected. * * Note: This is not the same as the "listenKey" WS API workflow (the listenKey workflow is deprecated). * * This does not return a listen key. This also does not require a regular "ping" on the listen key. */ interface ActiveUserDataStreamState { subscribedAt: Date; subscribeAttempt: number; respawnTimeout?: ReturnType; } ⋮---- /** * This is a minimal Websocket API wrapper around the WebsocketClient. * * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should * be used to transmit that message. This is only useful if you wish to use an alternative wss * domain that is supported by the SDK. * * Note: To use testnet, don't set the wsKey - use `testnet: true` in * the constructor instead. * * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some * may find the below methods slightly more intuitive. * * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: * https://github.com/tiagosiebler/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108 */ export class WebsocketAPIClient ⋮---- /** * Minimal state store around automating sticky "userDataStream.subscribe" sessions */ ⋮---- constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, ) ⋮---- public getWSClient(): WebsocketClient ⋮---- public setTimeOffsetMs(newOffset: number): void ⋮---- /* * * SPOT - General requests * */ ⋮---- /** * Test connectivity to the WebSocket API */ testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> ⋮---- /** * Test connectivity to the WebSocket API and get the current server time */ getSpotServerTime( wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query current exchange trading rules, rate limits, and symbol information */ getSpotExchangeInfo( params?: WSAPIExchangeInfoRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /* * * SPOT - Market data requests * */ ⋮---- /** * Get current order book * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams */ getSpotOrderBook( params: WSAPIOrderBookRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get recent trades * Note: If you need access to real-time trading activity, consider using WebSocket Streams */ getSpotRecentTrades( params: WSAPITradesRecentRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get historical trades * Note: If fromId is not specified, the most recent trades are returned */ getSpotHistoricalTrades( params: WSAPITradesHistoricalRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get aggregate trades * Note: An aggregate trade represents one or more individual trades that fill at the same time */ getSpotAggregateTrades( params: WSAPITradesAggregateRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get klines (candlestick bars) * Note: If you need access to real-time kline updates, consider using WebSocket Streams */ getSpotKlines( params: WSAPIKlinesRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get klines (candlestick bars) optimized for presentation * Note: This request is similar to klines, having the same parameters and response */ getSpotUIKlines( params: WSAPIKlinesRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get current average price for a symbol */ getSpotAveragePrice( params: WSAPIAvgPriceRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get 24-hour rolling window price change statistics * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams */ getSpot24hrTicker( params?: WSAPITicker24hrRequest, wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse< WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] > > { return this.wsClient.sendWSAPIRequest( wsKey || WS_KEY_MAP.mainWSAPI, 'ticker.24hr', params, { authIsOptional: true }, ); ⋮---- /** * Get price change statistics for a trading day */ getSpotTradingDayTicker( params: WSAPITickerTradingDayRequest, wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse< WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] > > { return this.wsClient.sendWSAPIRequest( wsKey || WS_KEY_MAP.mainWSAPI, 'ticker.tradingDay', params, { authIsOptional: true }, ); ⋮---- /** * Get rolling window price change statistics with a custom window * Note: Window size precision is limited to 1 minute */ getSpotTicker( params: WSAPITickerRequest, wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse< WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] > > { return this.wsClient.sendWSAPIRequest( wsKey || WS_KEY_MAP.mainWSAPI, 'ticker', params, { authIsOptional: true }, ); ⋮---- /** * Get the latest market price for a symbol * Note: If you need access to real-time price updates, consider using WebSocket Streams */ getSpotSymbolPriceTicker( params?: WSAPITickerPriceRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get the current best price and quantity on the order book * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams */ getSpotSymbolOrderBookTicker( params?: WSAPITickerBookRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /* * * SPOT - Session authentication requests * * Note: authentication is automatic * */ ⋮---- getSpotSessionStatus( wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /* * * SPOT - Trading requests * */ ⋮---- /** * Submit a spot order */ submitNewSpotOrder( params: WSAPINewSpotOrderRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Test order placement * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine */ testSpotOrder( params: WSAPIOrderTestRequest, wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse > { return this.wsClient.sendWSAPIRequest( wsKey || WS_KEY_MAP.mainWSAPI, 'order.test', params, ); ⋮---- /** * Check execution status of an order * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used */ getSpotOrderStatus( params: WSAPIOrderStatusRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Cancel an active order * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used */ cancelSpotOrder( params: WSAPIOrderCancelRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Cancel an existing order and immediately place a new order * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used */ cancelReplaceSpotOrder( params: WSAPIOrderCancelReplaceRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Reduce the quantity of an existing open order. * * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority */ amendSpotOrderKeepPriority( params: WSAPIOrderAmendKeepPriorityRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query execution status of all open orders * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams */ getSpotOpenOrders( params: WSAPIOpenOrdersStatusRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Cancel all open orders on a symbol * Note: This includes orders that are part of an order list */ cancelAllSpotOpenOrders( params: WSAPIOpenOrdersCancelAllRequest, wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]> > { return this.wsClient.sendWSAPIRequest( wsKey || WS_KEY_MAP.mainWSAPI, 'openOrders.cancelAll', params, ); ⋮---- /** * Place a new order list * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead */ placeSpotOrderList( params: WSAPIOrderListPlaceRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Place a new OCO (One-Cancels-the-Other) order list * Note: Activation of one order immediately cancels the other */ placeSpotOCOOrderList( params: WSAPIOrderListPlaceOCORequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Place a new OTO (One-Triggers-the-Other) order list * Note: The pending order is placed only when the working order is fully filled */ placeSpotOTOOrderList( params: WSAPIOrderListPlaceOTORequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list * Note: The pending orders are placed only when the working order is fully filled */ placeSpotOTOCOOrderList( params: WSAPIOrderListPlaceOTOCORequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Check execution status of an order list * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used */ getSpotOrderListStatus( params: WSAPIOrderListStatusRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Cancel an active order list * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used */ cancelSpotOrderList( params: WSAPIOrderListCancelRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query execution status of all open order lists * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams */ getSpotOpenOrderLists( params: WSAPIRecvWindowTimestamp, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Place a new order using Smart Order Routing (SOR) * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported */ placeSpotSOROrder( params: WSAPISOROrderPlaceRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) * Note: Creates and validates a new order but does not send it into the matching engine */ testSpotSOROrder( params: WSAPISOROrderTestRequest, wsKey?: WSAPIWsKeyMain, ): Promise< WSAPIResponse< WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission > > { return this.wsClient.sendWSAPIRequest( wsKey || WS_KEY_MAP.mainWSAPI, 'sor.order.test', params, ); ⋮---- /* * * SPOT - Account requests * */ ⋮---- /** * Query information about your account, including balances * Note: Weight: 20 */ getSpotAccountInformation( params: WSAPIAccountInformationRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query your current unfilled order count for all intervals * Note: Weight: 40 */ getSpotOrderRateLimits( params: WSAPIRecvWindowTimestamp, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query information about all your orders – active, canceled, filled – filtered by time range * Note: Weight: 20 */ getSpotAllOrders( params: WSAPIAllOrdersRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query information about all your order lists, filtered by time range * Note: Weight: 20 */ getSpotAllOrderLists( params: WSAPIAllOrderListsRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Query information about all your trades, filtered by time range * Note: Weight: 20 */ getSpotMyTrades( params: WSAPIMyTradesRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Displays the list of orders that were expired due to STP * Note: Weight varies based on query type (2-20) */ getSpotPreventedMatches( params: WSAPIMyPreventedMatchesRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Retrieves allocations resulting from SOR order placement * Note: Weight: 20 */ getSpotAllocations( params: WSAPIMyAllocationsRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /** * Get current account commission rates * Note: Weight: 20 */ getSpotAccountCommission( params: WSAPIAccountCommissionWSAPIRequest, wsKey?: WSAPIWsKeyMain, ): Promise> ⋮---- /* * * FUTURES - Market data requests * */ ⋮---- /** * Get current order book for futures * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams */ getFuturesOrderBook( params: WSAPIFuturesOrderBookRequest, ): Promise> ⋮---- /** * Get latest price for a futures symbol or symbols * Note: If symbol is not provided, prices for all symbols will be returned */ getFuturesSymbolPriceTicker( params?: WSAPIFuturesTickerPriceRequest, ): Promise< WSAPIResponse > { return this.wsClient.sendWSAPIRequest( WS_KEY_MAP.usdmWSAPI, 'ticker.price', params, { authIsOptional: true }, ); ⋮---- /** * Get best price/qty on the order book for a futures symbol or symbols * Note: If symbol is not provided, bookTickers for all symbols will be returned */ getFuturesSymbolOrderBookTicker( params?: WSAPIFuturesTickerBookRequest, ): Promise> ⋮---- /* * * FUTURES - Trading requests * */ ⋮---- /** * Submit a futures order * * This endpoint is used for both USDM and COINM futures. */ submitNewFuturesOrder( market: 'usdm' | 'coinm', params: WSAPINewFuturesOrderRequest, ): Promise> ⋮---- /** * Modify an existing futures order * * This endpoint is used for both USDM and COINM futures. */ modifyFuturesOrder( market: 'usdm' | 'coinm', params: WSAPIFuturesOrderModifyRequest, ): Promise> ⋮---- /** * Cancel a futures order * * This endpoint is used for both USDM and COINM futures. */ cancelFuturesOrder( market: 'usdm' | 'coinm', params: WSAPIFuturesOrderCancelRequest, ): Promise> ⋮---- /** * Query futures order status * * This endpoint is used for both USDM and COINM futures. */ getFuturesOrderStatus( market: 'usdm' | 'coinm', params: WSAPIFuturesOrderStatusRequest, ): Promise> ⋮---- /** * Get current position information (V2) * Note: Only symbols that have positions or open orders will be returned */ getFuturesPositionV2( params: WSAPIFuturesPositionV2Request, ): Promise> ⋮---- /** * Get current position information * Note: Only symbols that have positions or open orders will be returned * * This endpoint is used for both USDM and COINM futures. */ getFuturesPosition( market: 'usdm' | 'coinm', params: WSAPIFuturesPositionRequest, ): Promise> ⋮---- /* * * FUTURES - Account requests * */ ⋮---- /** * Get account balance information (V2) * Note: Returns balance information for all assets */ getFuturesAccountBalanceV2( params: WSAPIRecvWindowTimestamp, ): Promise> ⋮---- /** * Get account balance information * Note: Returns balance information for all assets * * This endpoint is used for both USDM and COINM futures. */ getFuturesAccountBalance( market: 'usdm' | 'coinm', params: WSAPIRecvWindowTimestamp, ): Promise> ⋮---- /** * Get account information (V2) * Note: Returns detailed account information including positions and assets */ getFuturesAccountStatusV2( params: WSAPIRecvWindowTimestamp, ): Promise> ⋮---- /** * Get account information * Note: Returns detailed account information including positions and assets * * This endpoint is used for both USDM and COINM futures. */ getFuturesAccountStatus( market: 'usdm' | 'coinm', params: WSAPIRecvWindowTimestamp, ): Promise> ⋮---- /* * * User data stream requests * */ ⋮---- /** * Start the user data stream for an apiKey (passed as param). * * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. * * @param params * @param wsKey * @returns listenKey */ startUserDataStreamForKey( params: { apiKey: string }, wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, ): Promise> ⋮---- /** * Stop the user data stream listen key. * * @param params * @param wsKey * @returns */ stopUserDataStreamForKey( params: WSAPIUserDataListenKeyRequest, wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, ): Promise> ⋮---- /** * Request user data stream subscription on the currently authenticated connection. * * If reconnected, this will automatically resubscribe unless you unsubscribe manually. */ async subscribeUserDataStream( wsKey: WSAPIWsKey, ): Promise> ⋮---- // Used to track whether this connection had the general "userDataStream.subscribe" called. // Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub. ⋮---- /** * Unsubscribe from the user data stream subscription on the currently authenticated connection. * * If reconnected, this will also stop it from automatically resubscribing after reconnect. */ unsubscribeUserDataStream( wsKey: WSAPIWsKey, ): Promise SDK Logo

[1]: https://www.npmjs.com/package/binance Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets: - Professional, robust & performant Binance SDK with leading trading volume in production (livenet). - Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. - Complete TypeScript support (with type declarations for all API requests & responses). - Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. - Strongly typed requests and responses. - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. - Actively maintained with a modern, promise-driven interface. - Support for all authentication mechanisms available on Binance: - HMAC - RSA - Ed25519 (required for WS API). - 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). ## 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) - [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) - [WebSockets](#websockets) - [WebSocket Consumers](#websocket-consumers) - [WebSocket API](#websocket-api) - [Event Driven API](#event-driven-api) - [Promise Driven API](#async-await-api) - [Customise Logging](#customise-logging) - [Frontend Usage](#browserfrontend-usage) - [Import](#import) - [Webpack](#webpack) - [LLMs & AI](#use-with-llms--ai) - [Contributions & Thanks](#contributions--thanks) ## Installation `npm install binance --save` ## Examples Refer to the [examples](./examples) folder for implementation demos. ## Issues & Discussion - Issues? Check the [issues tab](https://github.com/tiagosiebler/binance/issues). - Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. - Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. - Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) ## Related projects Check out my related JavaScript/TypeScript/Node.js projects: - Try my REST API & WebSocket SDKs: - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) ## Documentation Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. - Binance API Documentation - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) - [ Derivatives ](https://developers.binance.com/docs/derivatives) - [ Margin ](https://developers.binance.com/docs/margin_trading) - [ Wallet ](https://developers.binance.com/docs/wallet) - [Find all products here](https://developers.binance.com/en) - [REST Endpoint Function List](./docs/endpointFunctionList.md) - [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) ## Structure This project uses typescript. Resources are stored in 3 key structures: - [src](./src) - the whole connector written in typescript - [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. - [dist](./dist) - the packed bundle of the project for use in browser environments. --- # Usage Create API credentials at Binance - [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) - [Testnet](https://testnet.binance.vision/). - [Testnet Futures](testnet.binancefuture.com). ## 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 Refer to the following links for a complete list of available endpoints: - [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/tiagosiebler/binance/blob/master/docs/endpointFunctionList.md) - [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. ```javascript import { MainClient } from 'binance'; // or, if you prefer `require()`: // const { MainClient } = require('binance'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new MainClient({ api_key: API_KEY, api_secret: API_SECRET, // Connect to testnet environment // testnet: true, }); client .getAccountTradeList({ symbol: 'BTCUSDT' }) .then((result) => { console.log('getAccountTradeList result: ', result); }) .catch((err) => { console.error('getAccountTradeList error: ', err); }); client .getExchangeInfo() .then((result) => { console.log('getExchangeInfo inverse result: ', result); }) .catch((err) => { console.error('getExchangeInfo inverse error: ', err); }); ``` See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. ### REST USD-M Futures Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. ```javascript import { USDMClient } from 'binance'; // or, if you prefer `require()`: // const { USDMClient } = require('binance'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new USDMClient({ api_key: API_KEY, api_secret: API_SECRET, // Connect to testnet environment // testnet: true, }); client .getBalance() .then((result) => { console.log('getBalance result: ', result); }) .catch((err) => { console.error('getBalance error: ', err); }); client .submitNewOrder({ side: 'SELL', symbol: 'BTCUSDT', type: 'MARKET', quantity: 0.001, }) .then((result) => { console.log('submitNewOrder result: ', result); }) .catch((err) => { console.error('submitNewOrder error: ', err); }); ``` See [usdm-client.ts](./src/usdm-client.ts) for further information. ### REST COIN-M Futures Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. ```javascript import { CoinMClient } from 'binance'; // or, if you prefer `require()`: // const { CoinMClient } = require('binance'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new CoinMClient({ api_key: API_KEY, api_secret: API_SECRET, // Connect to testnet environment // testnet: true, }); client .getSymbolOrderBookTicker() .then((result) => { console.log('getSymbolOrderBookTicker result: ', result); }) .catch((err) => { console.error('getSymbolOrderBookTicker error: ', err); }); ``` See [coinm-client.ts](./src/coinm-client.ts) for further information. ## WebSockets ### WebSocket Consumers All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: ```javascript import { WebsocketClient } from 'binance'; // or, if you prefer `require()`: // const { WebsocketClient } = require('binance'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; /** * The WebsocketClient will manage individual connections for you, under the hood. * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. */ const wsClient = new WebsocketClient( { api_key: key, api_secret: secret, // Optional: when enabled, the SDK will try to format incoming data into more readable objects. // Beautified data is emitted via the "formattedMessage" event beautify: true, // Disable ping/pong ws heartbeat mechanism (not recommended) // disableHeartbeat: true, // Connect to testnet environment // testnet: true, }, ); // receive raw events wsClient.on('message', (data) => { console.log('raw message received ', JSON.stringify(data, null, 2)); }); // notification when a connection is opened wsClient.on('open', (data) => { console.log('connection opened open:', data.wsKey, data.wsUrl); }); // receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. wsClient.on('formattedMessage', (data) => { console.log('formattedMessage: ', data); }); // read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) wsClient.on('response', (data) => { console.log('log response: ', JSON.stringify(data, null, 2)); }); // receive notification when a ws connection is reconnecting automatically wsClient.on('reconnecting', (data) => { console.log('ws automatically reconnecting.... ', data?.wsKey); }); // receive notification that a reconnection completed successfully (e.g use REST to check for missing data) wsClient.on('reconnected', (data) => { console.log('ws has reconnected ', data?.wsKey); }); // Recommended: receive error events (e.g. first reconnection failed) wsClient.on('exception', (data) => { console.log('ws saw error ', data?.wsKey); }); /** * Subscribe to public topics either one at a time or many in an array */ // E.g. one at a time, routed to the coinm futures websockets: wsClient.subscribe('btcusd@indexPrice', 'coinm'); wsClient.subscribe('btcusd@miniTicker', 'coinm'); // Or send many topics at once to a stream, e.g. the usdm futures stream: wsClient.subscribe( [ 'btcusdt@aggTrade', 'btcusdt@markPrice', '!ticker@arr', '!miniTicker@arr', ], 'usdm', ); // spot & margin topics should go to "main" // (similar how the MainClient is for REST APIs in that product group) wsClient.subscribe( [ // All Market Rolling Window Statistics Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams '!ticker_1h@arr', // Individual Symbol Book Ticker Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams 'btcusdt@bookTicker', // Average Price // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price 'btcusdt@avgPrice', // Partial Book Depth Streams // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams 'btcusdt@depth10@100ms', // Diff. Depth Stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream 'btcusdt@depth', ], // Look at the `WS_KEY_URL_MAP` for a list of values here: // https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts // "main" connects to wss://stream.binance.com:9443/stream // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams 'main', ); /** * For the user data stream, these convenient subscribe methods open a dedicated * connection with the listen key workflow: */ wsClient.subscribeSpotUserDataStream(); wsClient.subscribeMarginUserDataStream(); wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); wsClient.subscribeUsdFuturesUserDataStream(); ``` See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. ### 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. Note: the WebSocket API requires the use of Ed25519 keys. HMAC & RSA keys are not supported by Binance for the WebSocket API (as of Apr 2025). #### 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'); /** * The WS API only works with an Ed25519 API key. * * Check the rest-private-ed25519.md in this folder for more guidance * on preparing this Ed25519 API key. */ const publicKey = `-----BEGIN PUBLIC KEY----- MCexampleQTxwLU9o= -----END PUBLIC KEY----- `; const privateKey = `-----BEGIN PRIVATE KEY----- MC4CAQAexamplewqj5CzUuTy1 -----END PRIVATE KEY----- `; // API Key returned by binance, generated using the publicKey (above) via Binance's website const apiKey = 'TQpJexamplerobdG'; // Make an instance of the WS API Client const wsClient = new WebsocketAPIClient({ api_key: apiKey, api_secret: privateKey, beautify: true, // Enforce testnet ws connections, regardless of supplied wsKey // testnet: true, }); // Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! // https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow // wsClient.setTimeOffsetMs(-5000); // Optional, see above. Can be used to prepare a connection before sending commands // await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); // Make WebSocket API calls, very similar to a REST API: wsClient .getFuturesAccountBalanceV2({ timestamp: Date.now(), recvWindow: 5000, }) .then((result) => { console.log('getFuturesAccountBalanceV2 result: ', result); }) .catch((err) => { console.error('getFuturesAccountBalanceV2 error: ', err); }); wsClient .submitNewFuturesOrder('usdm', { side: 'SELL', symbol: 'BTCUSDT', type: 'MARKET', quantity: 0.001, timestamp: Date.now(), // recvWindow: 5000, }) .then((result) => { console.log('getFuturesAccountBalanceV2 result: ', result); }) .catch((err) => { console.error('getFuturesAccountBalanceV2 error: ', err); }); ``` --- ## Customise Logging Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. ```javascript import { WebsocketClient, DefaultLogger } from 'binance'; // or, if you prefer `require()`: // const { WebsocketClient, DefaultLogger } = require('binance'); // Enable all logging on the trace level (disabled by default) DefaultLogger.trace = (...params) => { console.trace('trace: ', params); }; // Pass the updated logger as the 2nd parameter const ws = new WebsocketClient( { api_key: key, api_secret: secret, beautify: true, }, DefaultLogger ); // Or, create a completely custom logger with the 3 available functions const customLogger = { trace: (...params: LogParams): void => { console.trace(new Date(), params); }, info: (...params: LogParams): void => { console.info(new Date(), params); }, error: (...params: LogParams): void => { console.error(new Date(), params); }, } // Pass the custom logger as the 2nd parameter const ws = new WebsocketClient( { api_key: key, api_secret: secret, beautify: true, }, customLogger ); ``` ## Browser/Frontend Usage ### Import This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. 1. Install these dependencies ```sh npm install crypto-browserify stream-browserify ``` 2. Add this to your `tsconfig.json` ```json { "compilerOptions": { "paths": { "crypto": [ "./node_modules/crypto-browserify" ], "stream": [ "./node_modules/stream-browserify" ] } ``` 3. Declare this in the global context of your application (ex: in polyfills for angular) ```js (window as any).global = window; ``` ### Webpack This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. Build a bundle using webpack: - `npm install` - `npm build` - `npm pack` The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. ## Use with LLMs & AI This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. --- ### Contributions & Thanks Have my projects helped you? Share the love, there are many ways you can show your thanks: - Star & share my projects. - Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler - Have an interesting project? Get in touch & invite me to it. - Or buy me all the coffee: - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` ### Contributions & Pull Requests Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. ## Used By [![Repository Users Preview Image](https://dependents.info/tiagosiebler/binance/image)](https://dependents.info/tiagosiebler/binance) ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) ================ File: src/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 } 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, getWsUrl, getWsURLSuffix, isPrivateWsTopic, isWSPingFrameAvailable, isWSPongFrameAvailable, MiscUserDataConnectionState, parseEventTypeFromMessage, parseRawWsMessage, resolveUserDataMarketForWsKey, resolveWsKeyForLegacyMarket, WS_AUTH_ON_CONNECT_KEYS, WS_KEY_MAP, WSAPIWsKey, WsKey, WsTopicRequest, } from './util/websockets/websocket-util'; import { WSConnectedResult } from './util/websockets/WsStore.types'; ⋮---- 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 */ ⋮---- /** * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. * * When possible, it will subscribe to all requested topics on a single websocket connection. A list of * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. * * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. * * If any connection is reconnected, the WS client will: * - Emit the "reconnecting" event when the process begins. * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed * while disconnected. * * User data streams will use a dedicated connection per stream for increased resilience. */ ⋮---- export class WebsocketClient extends BaseWebsocketClient< ⋮---- constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- /** * Binance uses native WebSocket ping/pong frames, which cannot be directly used in * some environents (e.g. most browsers do not support sending raw ping/pong frames). * * This disables heartbeats in those environments, if ping/pong frames are unavailable. * * Some browsers may still handle these automatically. Some discussion around this can * be found here: https://stackoverflow.com/questions/10585355/sending-websocket-ping-pong-frame-from-browser */ ⋮---- // fn pointers: ⋮---- private getUserDataStreamManager(): UserDataStreamManager ⋮---- private getRestClientOptions(): RestClientOptions ⋮---- /** * Request connection of all dependent (public & WS API) websockets in prod, instead of waiting * for automatic connection by SDK. * * For the Binance SDK, this will only open public connections (without auth), but is almost definitely overkill if you're only working with one product group. */ public connectAll(): Promise[] ⋮---- /** * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if * you're only working with one product group. */ public connectPublic(): Promise[] ⋮---- /** * This function serves no purpose in the Binance SDK */ public async connectPrivate(): Promise ⋮---- /** * 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 ⋮---- /** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- /** * 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 ⋮---- /** * 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. ⋮---- // 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: 'market' | 'userData' = 'market', ): Promise ⋮---- private async signMessage( paramsStr: string, secret: string, method: 'hex' | 'base64', algorithm: SignAlgorithm, ): Promise ⋮---- // return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); ⋮---- private async signWSAPIRequest( requestEvent: WsRequestOperationBinance, ): 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. // 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. ⋮---- // If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. ⋮---- // Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. ⋮---- // Note: You still have to specify the timestamp parameter for SIGNED requests. ⋮---- protected sendPingEvent(wsKey: WsKey) ⋮---- // this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- // Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- protected sendPongEvent(wsKey: WsKey) ⋮---- // this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- // Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- /** Force subscription requests to be sent in smaller batches, if a number is returned */ protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ protected async getWsRequestEvents( wsKey: WsKey, operation: WsOperation, requests: WsTopicRequest[], ): Promise>[]> ⋮---- // Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- // Cache midflight subs on the req ID // Enrich response with subs for that req ID ⋮---- protected getPrivateWSKeys(): WsKey[] ⋮---- protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** * Determines if a topic is for a private channel, using a hardcoded list of strings */ protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any protected isWsPing(msg: any): boolean ⋮---- // For binance, all ping/pong events are frame events ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any protected isWsPong(msg: any): boolean ⋮---- // For binance, all ping/pong events are frame events ⋮---- /** * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ protected resolveEmittableEvents( wsKey: WsKey, event: MessageEventLike, ): EmittableEvent[] ⋮---- // this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); ⋮---- /** * * Extract event from JSON * */ ⋮---- /** * * Minor data normalisation & preparation * */ ⋮---- // ws consumers: { data: ... } // ws api consumers (user data): { event: ... } // other responses: { ... } ⋮---- // First try, the child node ⋮---- // Second try, the parent ⋮---- // Some events don't include the topic (event name) // This tries to extract and append it, using available context ⋮---- // This attaches `wsMarket` and `streamName` to incoming events // If the event is an array, it's attached to each element in the array ⋮---- /** * * * Main parsing logic below: * * */ ⋮---- // parsed: JSON.stringify(parsed, null, 2), ⋮---- // WS API response ⋮---- /** * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): * * { * result: null, * id: 1, * }; * * Currently there's no simple way to tell this apart from an actual WS API response with * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, * but that will not affect usage. * * Unrelated, example wsapi error for reference: * { id: 1, status: 400, error: { code: -1021, msg: "Timestamp for this request was 1000ms ahead of the server's time." }, rateLimits: [ { rateLimitType: 'REQUEST_WEIGHT', interval: 'MINUTE', intervalNum: 1, limit: 6000, count: 4 } ], wsKey: 'mainWSAPI', isWSAPIResponse: true } */ ⋮---- // This is the counterpart to getPromiseRefForWSAPIRequest ⋮---- // WS API Exception ⋮---- // authenticated ⋮---- // Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests ⋮---- // WS API Success ⋮---- // Handle incoming event that listen key expired ⋮---- // handle this how? ⋮---- // 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 ⋮---- // Suffix all events for the beautifier, if market is options // Options has some conflicting keys with different intentions, so will be suffixed ⋮---- // emit an additional event for user data messages ⋮---- // Messages for a subscribed topic all include the "topic" property ⋮---- // Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property ⋮---- // Failed request ⋮---- // These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- // Request/reply pattern for authentication success ⋮---- // In case of catastrophic failure, fallback to noisy emit update ⋮---- /** * * * * * * User Data Streams * * * * * */ ⋮---- /** * -------------------------- * User data listen key tracking & persistence * -------------------------- **/ ⋮---- /** * 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 ⋮---- /** * 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 ⋮---- public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise ⋮---- /** * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ public async subscribeCrossMarginUserDataStream( wsKey: WsKey = 'main', forceNewConnection?: boolean, miscState?: MiscUserDataConnectionState, ): Promise ⋮---- public unsubscribeCrossMarginUserDataStream( wsKey: WsKey = 'main', ): Promise ⋮---- /** * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ public async subscribeIsolatedMarginUserDataStream( symbol: string, wsKey: WsKey = 'main', forceNewConnection?: boolean, miscState?: MiscUserDataConnectionState, ): Promise ⋮---- public unsubscribeIsolatedMarginUserDataStream( symbol: string, wsKey: WsKey = 'main', ): Promise ⋮---- /** * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ public async subscribeMarginRiskUserDataStream( wsKey: WsKey = 'main', forceNewConnection?: boolean, miscState?: MiscUserDataConnectionState, ): Promise ⋮---- public unsubscribeMarginRiskUserDataStream( wsKey: WsKey = 'main', ): Promise ⋮---- /** * -------------------------- * End of SPOT market websocket streams * -------------------------- **/ ⋮---- /** * 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( wsKey: WsKey = 'usdm', // usdm | usdmTestnet forceNewConnection?: boolean, miscState?: MiscUserDataConnectionState, ): Promise ⋮---- wsKey: WsKey = 'usdm', // usdm | usdmTestnet ⋮---- public unsubscribeUsdFuturesUserDataStream( wsKey: WsKey = 'usdm', ): Promise ⋮---- /** * 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 ⋮---- wsKey: WsKey = 'coinm', // coinm | coinmTestnet ⋮---- public unsubscribeCoinFuturesUserDataStream( wsKey: WsKey = 'coinm', ): Promise ⋮---- /** * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. */ public async subscribePortfolioMarginUserDataStream( wsKey: WsKey = 'portfolioMarginUserData', forceNewConnection?: boolean, miscState?: MiscUserDataConnectionState, ): Promise ⋮---- public unsubscribePortfolioMarginUserDataStream( wsKey: WsKey = 'portfolioMarginUserData', ): Promise ⋮---- /** * 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 ⋮---- // built around the assumption in how per-connection listen key wskeys are created // isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main // coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm ⋮---- // todo: close? ⋮---- protected isCustomReconnectionNeeded(wsKey: string): boolean ⋮---- protected async triggerCustomReconnectionWorkflow( legacyWsKey: string, ): Promise ⋮---- private async respawnUserDataStream( 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 ⋮---- /** * 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(); ⋮---- // 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, // }); // } // } ⋮---- /** * * * * * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. * * * * */ ⋮---- /** * -------------------------- * Universal market websocket streams (may apply to one or more API markets) * -------------------------- **/ ⋮---- /** * 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 ⋮---- /** * Subscribe to aggregate trades for a symbol in a market category */ public subscribeAggregateTrades( symbol: string, market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to trades for a symbol in a market category * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning */ public subscribeTrades( symbol: string, market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to coin index for a symbol in COINM Futures markets */ public subscribeCoinIndexPrice( symbol: string, updateSpeedMs: 1000 | 3000 = 3000, ): Promise ⋮---- /** * Subscribe to mark price for a symbol in a market category */ public subscribeMarkPrice( symbol: string, market: 'usdm' | 'coinm', updateSpeedMs: 1000 | 3000 = 3000, ): Promise ⋮---- /** * Subscribe to mark price for all symbols in a market category */ public subscribeAllMarketMarkPrice( market: 'usdm' | 'coinm', updateSpeedMs: 1000 | 3000 = 3000, ): Promise ⋮---- /** * Subscribe to klines(candles) for a symbol in a market category */ public subscribeKlines( symbol: string, interval: KlineInterval, market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to continuous contract klines(candles) for a symbol futures */ public subscribeContinuousContractKlines( symbol: string, contractType: 'perpetual' | 'current_quarter' | 'next_quarter', interval: KlineInterval, market: 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to index klines(candles) for a symbol in a coinm futures */ public subscribeIndexKlines( symbol: string, interval: KlineInterval, ): Promise ⋮---- /** * Subscribe to index klines(candles) for a symbol in a coinm futures */ public subscribeMarkPriceKlines( symbol: string, interval: KlineInterval, ): Promise ⋮---- /** * Subscribe to mini 24hr ticker for a symbol in market category. */ public subscribeSymbolMini24hrTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to mini 24hr mini ticker in market category. */ public subscribeAllMini24hrTickers( market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to 24hr ticker for a symbol in any market. */ public subscribeSymbol24hrTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to 24hr ticker in any market. */ public subscribeAll24hrTickers( market: 'spot' | 'usdm' | 'coinm', ): 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', ): Promise ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. */ public subscribeSymbolBookTicker( symbol: string, market: 'spot' | 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeAllBookTickers(market: 'usdm' | 'coinm'): Promise ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. */ public subscribeSymbolLiquidationOrders( symbol: string, market: 'usdm' | 'coinm', ): Promise ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeAllLiquidationOrders( market: 'usdm' | 'coinm', ): 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', ): 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', ): Promise ⋮---- /** * Subscribe to best bid/ask for all symbols in spot markets. */ public subscribeContractInfoStream( market: 'usdm' | 'coinm', ): Promise ⋮---- /** * -------------------------- * SPOT market websocket streams * -------------------------- **/ ⋮---- /** * Subscribe to aggregate trades for a symbol in spot markets. */ public subscribeSpotAggregateTrades(symbol: string): Promise ⋮---- /** * Subscribe to trades for a symbol in spot markets. */ public subscribeSpotTrades(symbol: string): Promise ⋮---- /** * Subscribe to candles for a symbol in spot markets. */ public subscribeSpotKline( symbol: string, interval: KlineInterval, ): Promise ⋮---- /** * Subscribe to mini 24hr ticker for a symbol in spot markets. */ public subscribeSpotSymbolMini24hrTicker(symbol: string): Promise ⋮---- /** * Subscribe to mini 24hr mini ticker in spot markets. */ public subscribeSpotAllMini24hrTickers(): Promise ⋮---- /** * Subscribe to 24hr ticker for a symbol in spot markets. */ public subscribeSpotSymbol24hrTicker(symbol: string): Promise ⋮---- /** * Subscribe to 24hr ticker in spot markets. */ public subscribeSpotAll24hrTickers(): Promise ⋮---- /** * Subscribe to best bid/ask for symbol in spot markets. */ public subscribeSpotSymbolBookTicker(symbol: string): Promise ⋮---- /** * Subscribe to top bid/ask levels for symbol in spot markets. */ public subscribeSpotPartialBookDepth( symbol: string, levels: 5 | 10 | 20, updateMs: 1000 | 100 = 1000, ): Promise ⋮---- /** * Subscribe to spot orderbook depth updates to locally manage an order book. */ public subscribeSpotDiffBookDepth( symbol: string, updateMs: 1000 | 100 = 1000, ): Promise ================ File: package.json ================ { "name": "binance", "version": "3.0.4", "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", "files": [ "lib/*", "index.js", "llms.txt" ], "scripts": { "test": "jest", "test:watch": "jest --watch", "clean": "rimraf lib dist", "build": "tsc", "build:clean": "npm run clean && npm run build", "build:watch": "npm run clean && tsc --watch", "pack": "webpack --config webpack/webpack.config.js", "lint": "eslint src", "prepublishOnly": "npm run build:clean", "betapublish": "npm publish --tag beta" }, "author": "Tiago Siebler (https://github.com/tiagosiebler)", "contributors": [ "Zoey Garvey", "Clifford Roche (http://www.cliffordroche.ca)", "Aslam Hadi H (https://www.commitcode.com)", "Andrey Vorobyov ", "Dylan Sproule (https://github.com/dylansproule)", "Gavy Aggarwal (http://gavyaggarwal.com/)", "Tony Pettigrew (https://github.com/NeverEnder4)", "Chris (https://github.com/apexearth)", "Bruno Lobo (https://brunolobo.xyz)", "0xSmartCrypto <0xsmartcrypto@gmail.com> (https://twitter.com/0xSmartCrypto)" ], "dependencies": { "axios": "^1.7.9", "isomorphic-ws": "^4.0.1", "nanoid": "^3.1.30", "ws": "^7.4.0" }, "devDependencies": { "@types/jest": "^29.1.1", "@types/node": "^22.10.2", "@typescript-eslint/eslint-plugin": "^8.18.0", "eslint": "^8.24.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.2.1", "eslint-plugin-require-extensions": "^0.1.3", "eslint-plugin-simple-import-sort": "^12.1.1", "jest": "^29.7.0", "ts-jest": "^29.1.2", "typescript": "^5.7.3" }, "optionalDependencies": { "source-map-loader": "^2.0.0", "ts-loader": "^8.0.11", "webpack": "^5.97.1", "webpack-cli": "^5.1.4" }, "keywords": [ "binance", "binance api", "binance futures api", "binance spot api", "binance margin api", "api", "websocket", "rest", "rest api", "inverse", "linear", "usdt", "trading bots", "nodejs", "node", "trading", "cryptocurrency", "bitcoin", "best" ], "funding": { "type": "individual", "url": "https://github.com/sponsors/tiagosiebler" }, "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/tiagosiebler/binance.git" }, "bugs": { "url": "https://github.com/tiagosiebler/binance/issues" }, "homepage": "https://github.com/tiagosiebler/binance#readme" } ================================================================ End of Codebase ================================================================