UNPKG

@binance/common

Version:

Binance Common Types and Utilities for Binance Connectors

1,151 lines (1,150 loc) 52.5 kB
import { Agent } from "https"; import { AxiosError, AxiosResponseHeaders, RawAxiosRequestConfig, RawAxiosResponseHeaders } from "axios"; import WebSocketClient from "ws"; //#region src/constants.d.ts declare const TimeUnit: { readonly MILLISECOND: "MILLISECOND"; readonly millisecond: "millisecond"; readonly MICROSECOND: "MICROSECOND"; readonly microsecond: "microsecond"; }; type TimeUnit = (typeof TimeUnit)[keyof typeof TimeUnit]; declare const ALGO_REST_API_PROD_URL = "https://api.binance.com"; declare const ALPHA_REST_API_PROD_URL = "https://www.binance.com"; declare const C2C_REST_API_PROD_URL = "https://api.binance.com"; declare const CONVERT_REST_API_PROD_URL = "https://api.binance.com"; declare const COPY_TRADING_REST_API_PROD_URL = "https://api.binance.com"; declare const CRYPTO_LOAN_REST_API_PROD_URL = "https://api.binance.com"; declare const DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL = "https://dapi.binance.com"; declare const DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL = "https://testnet.binancefuture.com"; declare const DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL = "wss://ws-dapi.binance.com/ws-dapi/v1"; declare const DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL = "wss://testnet.binancefuture.com/ws-dapi/v1"; declare const DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL = "wss://dstream.binance.com"; declare const DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TESTNET_URL = "wss://dstream.binancefuture.com"; declare const DERIVATIVES_TRADING_USDS_FUTURES_REST_API_PROD_URL = "https://fapi.binance.com"; declare const DERIVATIVES_TRADING_USDS_FUTURES_REST_API_TESTNET_URL = "https://testnet.binancefuture.com"; declare const DERIVATIVES_TRADING_USDS_FUTURES_WS_API_PROD_URL = "wss://ws-fapi.binance.com/ws-fapi/v1"; declare const DERIVATIVES_TRADING_USDS_FUTURES_WS_API_TESTNET_URL = "wss://testnet.binancefuture.com/ws-fapi/v1"; declare const DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL = "wss://fstream.binance.com"; declare const DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_TESTNET_URL = "wss://stream.binancefuture.com"; declare const DERIVATIVES_TRADING_OPTIONS_REST_API_PROD_URL = "https://eapi.binance.com"; declare const DERIVATIVES_TRADING_OPTIONS_REST_API_TESTNET_URL = "https://testnet.binancefuture.com"; declare const DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_PROD_URL = "wss://fstream.binance.com"; declare const DERIVATIVES_TRADING_OPTIONS_WS_STREAMS_TESTNET_URL = "wss://fstream.binancefuture.com"; declare const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_PROD_URL = "https://papi.binance.com"; declare const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_REST_API_TESTNET_URL = "https://testnet.binancefuture.com"; declare const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_PROD_URL = "wss://fstream.binance.com/pm"; declare const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_WS_STREAMS_TESTNET_URL = "wss://fstream.binancefuture.com/pm"; declare const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_REST_API_PROD_URL = "https://api.binance.com"; declare const DERIVATIVES_TRADING_PORTFOLIO_MARGIN_PRO_WS_STREAMS_PROD_URL = "wss://fstream.binance.com/pm-classic"; declare const DUAL_INVESTMENT_REST_API_PROD_URL = "https://api.binance.com"; declare const FIAT_REST_API_PROD_URL = "https://api.binance.com"; declare const GIFT_CARD_REST_API_PROD_URL = "https://api.binance.com"; declare const MARGIN_TRADING_REST_API_PROD_URL = "https://api.binance.com"; declare const MARGIN_TRADING_WS_STREAMS_PROD_URL = "wss://stream.binance.com:9443"; declare const MARGIN_TRADING_RISK_WS_STREAMS_PROD_URL = "wss://margin-stream.binance.com"; declare const MINING_REST_API_PROD_URL = "https://api.binance.com"; declare const NFT_REST_API_PROD_URL = "https://api.binance.com"; declare const PAY_REST_API_PROD_URL = "https://api.binance.com"; declare const REBATE_REST_API_PROD_URL = "https://api.binance.com"; declare const SIMPLE_EARN_REST_API_PROD_URL = "https://api.binance.com"; declare const SPOT_REST_API_PROD_URL = "https://api.binance.com"; declare const SPOT_REST_API_TESTNET_URL = "https://testnet.binance.vision"; declare const SPOT_WS_API_PROD_URL = "wss://ws-api.binance.com:443/ws-api/v3"; declare const SPOT_WS_API_TESTNET_URL = "wss://ws-api.testnet.binance.vision/ws-api/v3"; declare const SPOT_WS_STREAMS_PROD_URL = "wss://stream.binance.com:9443"; declare const SPOT_WS_STREAMS_TESTNET_URL = "wss://stream.testnet.binance.vision"; declare const SPOT_REST_API_MARKET_URL = "https://data-api.binance.vision"; declare const SPOT_WS_STREAMS_MARKET_URL = "wss://data-stream.binance.vision"; declare const STAKING_REST_API_PROD_URL = "https://api.binance.com"; declare const SUB_ACCOUNT_REST_API_PROD_URL = "https://api.binance.com"; declare const VIP_LOAN_REST_API_PROD_URL = "https://api.binance.com"; declare const WALLET_REST_API_PROD_URL = "https://api.binance.com"; //#endregion //#region src/configuration.d.ts declare class ConfigurationRestAPI { /** * The API key used for authentication. * @memberof ConfigurationRestAPI */ apiKey: string; /** * The API secret used for authentication. * @memberof ConfigurationRestAPI */ apiSecret?: string; /** * override base path * @type {string} * @memberof ConfigurationRestAPI */ basePath?: string; /** * set a timeout (in milliseconds) for the request * @default 1000 * @type {number} * @memberof ConfigurationRestAPI */ timeout?: number; /** * HTTP/HTTPS proxy configuration * @default false * @type {object} * @property {string} host - Proxy server hostname * @property {number} port - Proxy server port number * @property {string} protocol - Proxy server protocol * @property {object} [auth] - Proxy authentication credentials * @property {string} auth.username - Proxy authentication username * @property {string} auth.password - Proxy authentication password * @memberof ConfigurationRestAPI */ proxy?: { host: string; port: number; protocol?: string; auth?: { username: string; password: string; }; }; /** * Optional custom headers to be sent with the request * @default {} * @type {Record<string, string | string[]>} * @memberof ConfigurationRestAPI */ customHeaders?: Record<string, string | string[]>; /** * enables keep-alive functionality for the connection (if httpsAgent is set then we use httpsAgent.keepAlive instead) * @default true * @type {boolean} * @memberof ConfigurationRestAPI */ keepAlive?: boolean; /** * enables response compression * @default true * @type {boolean} * @memberof ConfigurationRestAPI */ compression?: boolean; /** * number of retry attempts for failed requests * @default 3 * @type {number} * @memberof ConfigurationRestAPI */ retries?: number; /** * delay between retry attempts in milliseconds * @default 1000 * @type {number} * @memberof ConfigurationRestAPI */ backoff?: number; /** * https agent * @default false * @type {boolean | Agent} * @memberof ConfigurationRestAPI */ httpsAgent?: boolean | Agent; /** * private key * @type {string | Buffer} * @memberof ConfigurationRestAPI */ privateKey?: string | Buffer; /** * private key passphrase * @type {string} * @memberof ConfigurationRestAPI */ privateKeyPassphrase?: string; /** * timeUnit (used only on SPOT API) * @type {TimeUnit} * @memberof ConfigurationRestAPI */ timeUnit?: TimeUnit; constructor(param?: ConfigurationRestAPI); } declare class ConfigurationWebsocketAPI { /** * The API key used for authentication. * @memberof ConfigurationWebsocketAPI */ apiKey: string; /** * The API secret used for authentication. * @memberof ConfigurationWebsocketAPI */ apiSecret?: string; /** * override websocket url * @type {string} * @memberof ConfigurationWebsocketAPI */ wsURL?: string; /** * set a timeout (in milliseconds) for the request * @default 5000 * @type {number} * @memberof ConfigurationWebsocketAPI */ timeout?: number; /** * reconnction delay * @default 5000 * @type {number} * @memberof ConfigurationWebsocketAPI */ reconnectDelay?: number; /** * use compression for websocket messages * @default true * @type {boolean} * @memberof ConfigurationWebsocketAPI */ compression?: boolean; /** * websocket agent * @default false * @type {boolean | Agent} * @memberof ConfigurationWebsocketAPI */ agent?: boolean | Agent; /** * the mode of the connection, either 'single' or 'pool'. * @default 'single' * @type {'single' | 'pool'} * @memberof ConfigurationWebsocketAPI */ mode?: 'single' | 'pool'; /** * the size of the connection pool, if the mode is set to 'pool'. * @default 1 * @type {number} * @memberof ConfigurationWebsocketAPI */ poolSize?: number; /** * private key * @type {string | Buffer} * @memberof ConfigurationWebsocketAPI */ privateKey?: string | Buffer; /** * private key passphrase * @type {string} * @memberof ConfigurationWebsocketAPI */ privateKeyPassphrase?: string; /** * timeUnit (used only on SPOT API) * @type {TimeUnit} * @memberof ConfigurationWebsocketAPI */ timeUnit?: TimeUnit; /** * auto session re-logon on reconnects/renewals * @default true * @type {boolean} * @memberof ConfigurationWebsocketAPI */ autoSessionReLogon?: boolean; constructor(param?: ConfigurationWebsocketAPI); } declare class ConfigurationWebsocketStreams { /** * override websocket url * @type {string} * @memberof ConfigurationWebsocketStreams */ wsURL?: string; /** * reconnction delay * @default 5000 * @type {number} * @memberof ConfigurationWebsocketStreams */ reconnectDelay?: number; /** * use compression for websocket messages * @default true * @type {boolean} * @memberof ConfigurationWebsocketAPI */ compression?: boolean; /** * websocket agent * @default false * @type {boolean | Agent} * @memberof ConfigurationWebsocketStreams */ agent?: boolean | Agent; /** * the mode of the connection, either 'single' or 'pool'. * @default single * @type {'single' | 'pool'} * @memberof ConfigurationWebsocketStreams */ mode?: 'single' | 'pool'; /** * the size of the connection pool, if the mode is set to 'pool'. * @default 1 * @type {number} * @memberof ConfigurationWebsocketStreams */ poolSize?: number; /** * timeUnit (used only on SPOT API) * @type {TimeUnit} * @memberof ConfigurationWebsocketStreams */ timeUnit?: TimeUnit; constructor(param?: ConfigurationWebsocketStreams); } //#endregion //#region src/errors.d.ts /** * Represents an error that occurred in the Connector client. * @param msg - An optional error message. */ declare class ConnectorClientError extends Error { code?: number; constructor(msg?: string, code?: number); } /** * Represents an error that occurs when a required parameter is missing or undefined. * @param field - The name of the missing parameter. * @param msg - An optional error message. */ declare class RequiredError extends Error { field: string; constructor(field: string, msg?: string); } /** * Represents an error that occurs when a client is unauthorized to access a resource. * @param msg - An optional error message. */ declare class UnauthorizedError extends Error { code?: number; constructor(msg?: string, code?: number); } /** * Represents an error that occurs when a resource is forbidden to the client. * @param msg - An optional error message. */ declare class ForbiddenError extends Error { code?: number; constructor(msg?: string, code?: number); } /** * Represents an error that occurs when client is doing too many requests. * @param msg - An optional error message. */ declare class TooManyRequestsError extends Error { code?: number; constructor(msg?: string, code?: number); } /** * Represents an error that occurs when client's IP has been banned. * @param msg - An optional error message. */ declare class RateLimitBanError extends Error { code?: number; constructor(msg?: string, code?: number); } /** * Represents an error that occurs when there is an internal server error. * @param msg - An optional error message. * @param statusCode - An optional HTTP status code associated with the error. */ declare class ServerError extends Error { statusCode?: number | undefined; constructor(msg?: string, statusCode?: number | undefined); } /** * Represents an error that occurs when a network error occurs. * @param msg - An optional error message. */ declare class NetworkError extends Error { constructor(msg?: string); } /** * Represents an error that occurs when the requested resource was not found. * @param msg - An optional error message. */ declare class NotFoundError extends Error { code?: number; constructor(msg?: string, code?: number); } /** * Represents an error that occurs when a request is invalid or cannot be otherwise served. * @param msg - An optional error message. */ declare class BadRequestError extends Error { code?: number; constructor(msg?: string, code?: number); } //#endregion //#region src/logger.d.ts declare enum LogLevel { NONE = "", DEBUG = "debug", INFO = "info", WARN = "warn", ERROR = "error", } declare class Logger { private static instance; private minLogLevel; private readonly levelsOrder; constructor(); static getInstance(): Logger; setMinLogLevel(level: LogLevel): void; private isValidLogLevel; private log; private allowLevelLog; debug(...message: unknown[]): void; info(...message: unknown[]): void; warn(...message: unknown[]): void; error(...message: unknown[]): void; } //#endregion //#region src/types.d.ts /** * Represents the rate limit information for a REST API response. * @property {string} rateLimitType - The type of rate limit, either 'REQUEST_WEIGHT' or 'ORDERS'. * @property {string} interval - The time interval for the rate limit, one of 'SECOND', 'MINUTE', 'HOUR', or 'DAY'. * @property {number} intervalNum - The number of intervals for the rate limit. * @property {number} count - The current count of requests or orders for the rate limit. * @property {number} [retryAfter] - The number of seconds to wait before retrying the request. */ interface RestApiRateLimit { rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS'; interval: 'SECOND' | 'MINUTE' | 'HOUR' | 'DAY'; intervalNum: number; count: number; retryAfter?: number; } /** * Represents the response from a REST API request. * @template T - The type of the data returned in the response. * @property {() => Promise<T>} data - A function that returns a Promise resolving to the data from the API response. * @property {number} status - The HTTP status code of the response. * @property {Record<string, string>} headers - The headers of the response. * @property {RestApiRateLimit[]} [rateLimits] - An optional array of rate limit information for the response. */ type RestApiResponse<T> = { data: () => Promise<T>; status: number; headers: Record<string, string>; rateLimits?: RestApiRateLimit[]; }; /** * Represents the rate limit information for a WebSocket API response. * @property {string} rateLimitType - The type of rate limit, either 'REQUEST_WEIGHT' or 'ORDERS'. * @property {string} interval - The time interval for the rate limit, one of 'SECOND', 'MINUTE', 'HOUR', or 'DAY'. * @property {number} intervalNum - The number of intervals for the rate limit. * @property {number} limit - The maximum number of requests or orders allowed within the specified interval. * @property {number} count - The current count of requests or orders for the rate limit. */ interface WebsocketApiRateLimit { rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS'; interval: 'SECOND' | 'MINUTE' | 'HOUR' | 'DAY'; intervalNum: number; limit: number; count: number; } /** * Extracts the result or response from a WebSocket API response type. * @template T - The type of the WebSocket API response. * @returns {T['result'] | T['response'] | never} The extracted result or response, or never if neither exists. * @description Checks if the type T has a 'result' or 'response' key and returns its value, otherwise returns never. */ type ExtractWebsocketApiResponse<T> = 'result' extends keyof T ? T['result'] : 'response' extends keyof T ? T['response'] : unknown; /** * Represents the response from a WebSocket API. * @template T - The type of the WebSocket API response. * @property {NonNullable<ExtractWebsocketApiResponse<T>>} data - The extracted, non-null data from the WebSocket API response. * @property {WebsocketApiRateLimit[]} [rateLimits] - An optional array of rate limit information for the response. */ type WebsocketApiResponse<T> = { data: NonNullable<ExtractWebsocketApiResponse<T>>; rateLimits?: WebsocketApiRateLimit[]; }; /** * Represents the options for sending a message. * The object can have any number of properties, where the keys are strings and the values can be strings, numbers, booleans, objects, or undefined. */ interface SendMessageOptions { [key: string]: string | number | boolean | object | undefined; } /** * Represents an object type where the keys are strings and the values can be strings, numbers, booleans, or objects. */ interface ObjectType { [key: string]: string | number | boolean | object; } /** * Represents the arguments for an Axios request. * @property {string} url - The URL for the request. * @property {RawAxiosRequestConfig} options - The options for the Axios request. */ interface AxiosRequestArgs { url: string; options: RawAxiosRequestConfig; } /** * Represents the arguments for a request. * @property {string} endpoint - The endpoint for the request. * @property {'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH'} method - The HTTP method for the request. * @property {Record<string, unknown>} queryParams - The query parameters for the request. * @property {Record<string, unknown>} bodyParams - The body parameters for the request. * @property {TimeUnit} [timeUnit] - The optional time unit for the request. */ interface RequestArgs { endpoint: string; method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH'; queryParams: Record<string, unknown>; bodyParams: Record<string, unknown>; timeUnit?: TimeUnit; } //#endregion //#region src/utils.d.ts /** * Resets the signer cache to a new empty WeakMap. * * This function clears the existing signer cache, creating a fresh WeakMap * to store RequestSigner instances associated with configuration objects. */ declare const clearSignerCache: () => void; /** * Builds a URL query string from the given parameters object. * * Iterates over the key-value pairs in the `params` object, serializes each value, * and encodes it for use in a URL. Only keys with non-null and non-undefined values * are included in the resulting query string. * * @param params - An object containing key-value pairs to be serialized into a query string. * @returns A URL-encoded query string representing the provided parameters. */ declare function buildQueryString(params: Record<string, unknown>): string; /** * Generates a random string of 16 hexadecimal characters. * * @returns A random string of 16 hexadecimal characters. */ declare function randomString(): string; /** * Generates a cryptographically secure random 32-bit unsigned integer. * * Uses the Web Crypto API to generate a random value between 0 and 4,294,967,295 (2^32 - 1). * * @returns A random 32-bit unsigned integer. */ declare function randomInteger(): number; /** * Normalizes a stream ID to ensure it is valid, generating a random ID if needed. * * For string inputs: * - Returns the input if it's a valid 32-character hexadecimal string (case-insensitive) * - Otherwise, generates a new random hexadecimal string using `randomString()` * * For number inputs: * - Returns the input if it's a finite, non-negative integer within the safe integer range * - Otherwise, generates a new random integer using `randomInteger()` * * For null or undefined inputs: * - Generates a new random hexadecimal string using `randomString()` * * @param id - The stream ID to normalize (string, number, null, or undefined). * @param streamIdIsStrictlyNumber - Boolean forcing an id to be a number or not. * @returns A valid stream ID as either a 32-character hexadecimal string or a safe integer. */ declare function normalizeStreamId(id: string | number | null | undefined, streamIdIsStrictlyNumber?: boolean): string | number; /** * Validates the provided time unit string and returns it if it is either 'MILLISECOND' or 'MICROSECOND'. * * @param timeUnit - The time unit string to be validated. * @returns The validated time unit string, or `undefined` if the input is falsy. * @throws {Error} If the time unit is not 'MILLISECOND' or 'MICROSECOND'. */ declare function validateTimeUnit(timeUnit: string): string | undefined; /** * Delays the execution of the current function for the specified number of milliseconds. * * @param ms - The number of milliseconds to delay the function. * @returns A Promise that resolves after the specified delay. */ declare function delay(ms: number): Promise<void>; /** * Generates the current timestamp in milliseconds. * * @returns The current timestamp in milliseconds. */ declare function getTimestamp(): number; /** * Generates a signature for the given configuration and query parameters using a cached request signer. * * @param configuration - Configuration object containing API secret, private key, and optional passphrase. * @param queryParams - The query parameters to be signed. * @returns A string representing the generated signature. */ declare const getSignature: (configuration: { apiSecret?: string; privateKey?: string | Buffer; privateKeyPassphrase?: string; }, queryParams: Record<string, unknown>, bodyParams?: Record<string, unknown>) => string; /** * Asserts that a function parameter exists and is not null or undefined. * * @param functionName - The name of the function that the parameter belongs to. * @param paramName - The name of the parameter to check. * @param paramValue - The value of the parameter to check. * @throws {RequiredError} If the parameter is null or undefined. */ declare const assertParamExists: (functionName: string, paramName: string, paramValue: unknown) => void; /** * Sets the search parameters of a given URL object based on the provided key-value pairs. * Only parameters with non-null and non-undefined values are included. * Values are serialized using the `serializeValue` function before being set. * * @param url - The URL object whose search parameters will be updated. * @param params - An object containing key-value pairs to be set as search parameters. */ declare function setSearchParams(url: URL, params: Record<string, unknown>): void; /** * Converts a URL object to a full path string, including pathname, search parameters, and hash. * * @param url The URL object to convert to a path string. * @returns A complete path string representation of the URL. */ declare const toPathString: (url: URL) => string; /** * A type utility that transforms numbers in a type to their string representation when in scientific notation, * while preserving the structure of arrays and objects. * * @template T The input type to be transformed * @returns A type where numbers potentially become strings, maintaining the original type's structure */ type ScientificToString<T> = T extends number ? string | number : T extends Array<infer U> ? Array<ScientificToString<U>> : T extends object ? { [K in keyof T]: ScientificToString<T[K]> } : T; /** * Normalizes scientific notation numbers in an object or array to a fixed number of decimal places. * * This function recursively processes objects, arrays, and numbers, converting scientific notation * to a fixed decimal representation. Non-numeric values are left unchanged. * * @template T The type of the input object or value * @param obj The object, array, or value to normalize * @returns A new object or value with scientific notation numbers normalized */ declare function normalizeScientificNumbers<T>(obj: T): ScientificToString<T>; /** * Determines whether a request should be retried based on the provided error. * * This function checks the HTTP method, response status, and number of retries left to determine if a request should be retried. * * @param error The error object to check. * @param method The HTTP method of the request (optional). * @param retriesLeft The number of retries left (optional). * @returns `true` if the request should be retried, `false` otherwise. */ declare const shouldRetryRequest: (error: AxiosError | object, method?: string, retriesLeft?: number) => boolean; /** * Performs an HTTP request using the provided Axios instance and configuration. * * This function handles retries, rate limit handling, and error handling for the HTTP request. * * @param axiosArgs The request arguments to be passed to Axios. * @param configuration The configuration options for the request. * @returns A Promise that resolves to the API response, including the data and rate limit headers. */ declare const httpRequestFunction: <T>(axiosArgs: AxiosRequestArgs, configuration?: ConfigurationRestAPI) => Promise<RestApiResponse<T>>; /** * Parses the rate limit headers from the Axios response headers and returns an array of `RestApiRateLimit` objects. * * @param headers - The Axios response headers. * @returns An array of `RestApiRateLimit` objects containing the parsed rate limit information. */ declare const parseRateLimitHeaders: (headers: RawAxiosResponseHeaders | AxiosResponseHeaders) => RestApiRateLimit[]; /** * Generic function to send a request with optional API key and signature. * @param endpoint - The API endpoint to call. * @param method - HTTP method to use (GET, POST, DELETE, etc.). * @param params - Query parameters for the request. * @param timeUnit - The time unit for the request. * @param options - Additional request options (isSigned). * @returns A promise resolving to the response data object. */ declare const sendRequest: <T>(configuration: ConfigurationRestAPI, endpoint: string, method: "GET" | "POST" | "DELETE" | "PUT" | "PATCH", queryParams?: Record<string, unknown>, bodyParams?: Record<string, unknown>, timeUnit?: TimeUnit, options?: { isSigned?: boolean; }) => Promise<RestApiResponse<T>>; /** * Removes any null, undefined, or empty string values from the provided object. * * @param obj - The object to remove empty values from. * @returns A new object with empty values removed. */ declare function removeEmptyValue(obj: object): SendMessageOptions; /** * Sorts the properties of the provided object in alphabetical order and returns a new object with the sorted properties. * * @param obj - The object to be sorted. * @returns A new object with the properties sorted in alphabetical order. */ declare function sortObject(obj: ObjectType): ObjectType; /** * Replaces placeholders in the format <field> with corresponding values from the provided variables object. * * @param {string} str - The input string containing placeholders. * @param {Object} variables - An object where keys correspond to placeholder names and values are the replacements. * @returns {string} - The resulting string with placeholders replaced by their corresponding values. */ declare function replaceWebsocketStreamsPlaceholders(str: string, variables: Record<string, unknown>): string; /** * Generates a standardized user agent string for the application. * * @param {string} packageName - The name of the package/application. * @param {string} packageVersion - The version of the package/application. * @returns {string} A formatted user agent string including package details, Node.js version, platform, and architecture. */ declare function buildUserAgent(packageName: string, packageVersion: string): string; /** * Builds a WebSocket API message with optional authentication and signature. * * @param {ConfigurationWebsocketAPI} configuration - The WebSocket API configuration. * @param {string} method - The method name for the WebSocket message. * @param {WebsocketSendMsgOptions} payload - The payload data to be sent. * @param {WebsocketSendMsgConfig} options - Configuration options for message sending. * @param {boolean} [skipAuth=false] - Flag to skip authentication if needed. * @returns {Object} A structured WebSocket message with id, method, and params. */ declare function buildWebsocketAPIMessage(configuration: ConfigurationWebsocketAPI, method: string, payload: WebsocketSendMsgOptions, options: WebsocketSendMsgConfig, skipAuth?: boolean): { id: string; method: string; params: Record<string, unknown>; }; /** * Sanitizes a header value by checking for and preventing carriage return and line feed characters. * * @param {string | string[]} value - The header value or array of header values to sanitize. * @returns {string | string[]} The sanitized header value(s). * @throws {Error} If the header value contains CR/LF characters. */ declare function sanitizeHeaderValue(value: string | string[]): string | string[]; /** * Parses and sanitizes custom headers, filtering out forbidden headers. * * @param {Record<string, string | string[]>} headers - The input headers to be parsed. * @returns {Record<string, string | string[]>} A new object with sanitized and allowed headers. * @description Removes forbidden headers like 'host', 'authorization', and 'cookie', * and sanitizes remaining header values to prevent injection of carriage return or line feed characters. */ declare function parseCustomHeaders(headers: Record<string, string | string[]>): Record<string, string | string[]>; //#endregion //#region src/websocket.d.ts declare class WebsocketEventEmitter { private eventEmitter; constructor(); on(event: 'open' | 'message' | 'error' | 'close' | 'ping' | 'pong', listener: (...args: any[]) => void): void; off(event: 'open' | 'message' | 'error' | 'close' | 'ping' | 'pong', listener: (...args: any[]) => void): void; protected emit(event: 'open' | 'message' | 'error' | 'close' | 'ping' | 'pong', ...args: any[]): void; } interface TimerRecord { timer?: NodeJS.Timeout; type: 'timeout' | 'interval'; } interface WebsocketConnection { id: string; reconnectionPending: boolean; renewalPending: boolean; closeInitiated: boolean; pendingRequests: Map<string, { resolve: (value: any) => void; reject: (reason?: unknown) => void; }>; pendingSubscriptions?: string[]; ws?: WebSocketClient; urlPath?: string; isSessionLoggedOn?: boolean; sessionLogonReq?: { method: string; payload: WebsocketSendMsgOptions; options: WebsocketSendMsgConfig; }; } declare class WebsocketCommon extends WebsocketEventEmitter { protected configuration: ConfigurationWebsocketAPI | ConfigurationWebsocketStreams; private static readonly MAX_CONNECTION_DURATION; private readonly connectionQueue; private queueProcessing; protected connectionTimers: Map<WebSocketClient, Set<TimerRecord>>; private mode; private poolSize; private roundRobinIndex; connectionPool: WebsocketConnection[]; logger: Logger; constructor(configuration: ConfigurationWebsocketAPI | ConfigurationWebsocketStreams, connectionPool?: WebsocketConnection[]); /** * Initializes the WebSocket connection pool by creating a specified number of connection objects * and adding them to the `connectionPool` array. Each connection object has the following properties: * - `closeInitiated`: a boolean indicating whether the connection has been closed * - `reconnectionPending`: a boolean indicating whether a reconnection is pending * - `pendingRequests`: a Map that tracks pending requests for the connection * @param size - The number of connection objects to create and add to the pool. * @returns void */ private initializePool; /** * Retrieves available WebSocket connections based on the connection mode and readiness. * In 'single' mode, returns the first connection in the pool. * In 'pool' mode, filters and returns connections that are ready for use. * @param allowNonEstablishedWebsockets - Optional flag to include non-established WebSocket connections. * @param urlPath - Optional URL path to filter connections. * @returns An array of available WebSocket connections. */ protected getAvailableConnections(allowNonEstablishedWebsockets?: boolean, urlPath?: string): WebsocketConnection[]; /** * Gets a WebSocket connection from the pool or single connection. * If the connection mode is 'single', it returns the first connection in the pool. * If the connection mode is 'pool', it returns an available connection from the pool, * using a round-robin selection strategy. If no available connections are found, it throws an error. * @param allowNonEstablishedWebsockets - A boolean indicating whether to allow connections that are not established. * @param urlPath - An optional URL path to filter connections. * @returns {WebsocketConnection} The selected WebSocket connection. */ protected getConnection(allowNonEstablishedWebsockets?: boolean, urlPath?: string): WebsocketConnection; /** * Checks if the provided WebSocket connection is ready for use. * A connection is considered ready if it is open, has no pending reconnection, and has not been closed. * @param connection - The WebSocket connection to check. * @param allowNonEstablishedWebsockets - An optional flag to allow non-established WebSocket connections. * @returns `true` if the connection is ready, `false` otherwise. */ protected isConnectionReady(connection: WebsocketConnection, allowNonEstablishedWebsockets?: boolean): boolean; /** * Schedules a timer for a WebSocket connection and tracks it * @param connection WebSocket client instance * @param callback Function to execute when timer triggers * @param delay Time in milliseconds before callback execution * @param type Timer type ('timeout' or 'interval') * @returns Timer handle */ protected scheduleTimer(connection: WebSocketClient, callback: () => void, delay: number, type?: 'timeout' | 'interval'): NodeJS.Timeout; /** * Clears all timers associated with a WebSocket connection. * @param connection - The WebSocket client instance to clear timers for. * @returns void */ protected clearTimers(connection: WebSocketClient): void; /** * Processes the connection queue, reconnecting or renewing connections as needed. * This method is responsible for iterating through the connection queue and initiating * the reconnection or renewal process for each connection in the queue. It throttles * the queue processing to avoid overwhelming the server with too many connection * requests at once. * @param throttleRate - The time in milliseconds to wait between processing each * connection in the queue. * @returns A Promise that resolves when the queue has been fully processed. */ private processQueue; /** * Enqueues a reconnection or renewal for a WebSocket connection. * This method adds the connection, URL, and renewal flag to the connection queue, * and then calls the `processQueue` method to initiate the reconnection or renewal * process. * @param connection - The WebSocket connection to reconnect or renew. * @param url - The URL to use for the reconnection or renewal. * @param isRenewal - A flag indicating whether this is a renewal (true) or a reconnection (false). */ private enqueueReconnection; /** * Gracefully closes a WebSocket connection after pending requests complete. * This method waits for any pending requests to complete before closing the connection. * It sets up a timeout to force-close the connection after 30 seconds if the pending requests * do not complete. Once all pending requests are completed, the connection is closed. * @param connectionToClose - The WebSocket client instance to close. * @param WebsocketConnectionToClose - The WebSocket connection to close. * @param connection - The WebSocket connection to close. * @returns Promise that resolves when the connection is closed. */ private closeConnectionGracefully; /** * Attempts to re-establish a session for a WebSocket connection. * If a session logon request exists and the connection is not already logged on, * it sends an authentication request and updates the connection's logged-on status. * @param connection - The WebSocket connection to re-authenticate. * @private */ private sessionReLogon; /** * Cleans up WebSocket connection resources. * Removes all listeners and clears any associated timers for the provided WebSocket client. * @param ws - The WebSocket client to clean up. * @returns void */ protected cleanup(ws: WebSocketClient): void; /** * Handles incoming WebSocket messages * @param data Raw message data received * @param connection Websocket connection */ protected onMessage(data: string, connection: WebsocketConnection): void; /** * Handles the opening of a WebSocket connection. * @param url - The URL of the WebSocket server. * @param targetConnection - The WebSocket connection being opened. * @param oldWSConnection - The WebSocket client instance associated with the old connection. */ protected onOpen(url: string, targetConnection: WebsocketConnection, oldWSConnection: WebSocketClient): void; /** * Returns the URL to use when reconnecting. * Derived classes should override this to provide dynamic URLs. * @param defaultURL The URL originally passed during the first connection. * @param targetConnection The WebSocket connection being connected. * @returns The URL to reconnect to. */ protected getReconnectURL(defaultURL: string, targetConnection: WebsocketConnection): string; /** * Connects all WebSocket connections in the pool * @param url - The Websocket server URL. * @param connections - An optional array of WebSocket connections to connect. If not provided, all connections in the pool are connected. * @returns A promise that resolves when all connections are established. */ protected connectPool(url: string, connections?: WebsocketConnection[]): Promise<void>; /** * Creates a new WebSocket client instance. * @param url - The URL to connect to. * @returns A new WebSocket client instance. */ protected createWebSocket(url: string): WebSocketClient; /** * Initializes a WebSocket connection. * @param url - The Websocket server URL. * @param isRenewal - Whether this is a connection renewal. * @param connection - An optional WebSocket connection to use. * @returns The WebSocket connection. */ protected initConnect(url: string, isRenewal?: boolean, connection?: WebsocketConnection): WebsocketConnection | undefined; /** * Checks if the WebSocket connection is currently open. * @param connection - An optional WebSocket connection to check. If not provided, the entire connection pool is checked. * @returns `true` if the connection is open, `false` otherwise. */ isConnected(connection?: WebsocketConnection): boolean; /** * Disconnects from the WebSocket server. * If there is no active connection, a warning is logged. * Otherwise, all connections in the connection pool are closed gracefully, * and a message is logged indicating that the connection has been disconnected. * @returns A Promise that resolves when all connections have been closed. * @throws Error if the WebSocket client is not set. */ disconnect(): Promise<void>; /** * Sends a ping message to all connected Websocket servers in the pool. * If no connections are ready, a warning is logged. * For each active connection, the ping message is sent, and debug logs provide details. * @throws Error if a Websocket client is not set for a connection. */ pingServer(): void; /** * Sends a payload through the WebSocket connection. * @param payload - Message to send. * @param id - Optional request identifier. * @param promiseBased - Whether to return a promise. * @param timeout - Timeout duration in milliseconds. * @param connection - The WebSocket connection to use. * @returns A promise if `promiseBased` is true, void otherwise. * @throws Error if not connected or WebSocket client is not set. */ protected send<T = unknown>(payload: string, id?: string, promiseBased?: boolean, timeout?: number, connection?: WebsocketConnection): Promise<WebsocketApiResponse<T>> | void; } interface WebsocketSendMsgOptions { id?: string; [key: string]: string | number | boolean | object | undefined; } interface WebsocketSendMsgConfig { withApiKey?: boolean; isSigned?: boolean; isSessionLogon?: boolean; isSessionLogout?: boolean; } declare class WebsocketAPIBase extends WebsocketCommon { private isConnecting; streamCallbackMap: Map<string, Set<(data: unknown) => void>>; configuration: ConfigurationWebsocketAPI; logger: Logger; constructor(configuration: ConfigurationWebsocketAPI, connectionPool?: WebsocketConnection[]); /** * Prepares the WebSocket URL by adding optional timeUnit parameter * @param wsUrl The base WebSocket URL * @returns The formatted WebSocket URL with parameters */ private prepareURL; /** * Processes incoming WebSocket messages * @param data The raw message data received */ protected onMessage<T>(data: string, connection: WebsocketConnection): void; /** * Establishes a WebSocket connection to Binance * @returns Promise that resolves when connection is established * @throws Error if connection times out */ connect(): Promise<void>; sendMessage<T>(method: string, payload: WebsocketSendMsgOptions, options: WebsocketSendMsgConfig & { isSessionLogon: true; }): Promise<WebsocketApiResponse<T>[]>; sendMessage<T>(method: string, payload: WebsocketSendMsgOptions, options: WebsocketSendMsgConfig & { isSessionLogout: true; }): Promise<WebsocketApiResponse<T>[]>; sendMessage<T>(method: string, payload?: WebsocketSendMsgOptions, options?: WebsocketSendMsgConfig): Promise<WebsocketApiResponse<T>>; } declare class WebsocketStreamsBase extends WebsocketCommon { private streamConnectionMap; protected urlPaths: string[]; protected configuration: ConfigurationWebsocketStreams; protected wsURL: string; streamIdIsStrictlyNumber?: boolean; streamCallbackMap: Map<string, Set<(data: unknown) => void>>; logger: Logger; constructor(configuration: ConfigurationWebsocketStreams, connectionPool?: WebsocketConnection[], urlPaths?: string[]); /** * Ensures the connection pool has the required size based on the configured mode and number of URL paths. * * If no URL paths are configured, the method returns early without modifications. * In 'pool' mode, the pool size is multiplied by the number of URL paths. * In 'single' mode, only one connection per URL path is maintained. * * New connections are initialized with unique IDs and default state flags when the pool * size is less than the expected size. * * @private * @returns {void} */ private ensurePoolSizeForUrlPaths; /** * Formats the WebSocket URL for a given stream or streams. * @param streams - Array of stream names to include in the URL. * @param urlPath - Optional URL path to include in the WebSocket URL. * @returns The formatted WebSocket URL with the provided streams. */ private prepareURL; /** * Formats the WebSocket URL with stream and configuration parameters to be used for reconnection. * @param url - The base WebSocket URL. * @param targetConnection - The target WebSocket connection. * @returns The formatted WebSocket URL with streams and optional parameters. */ protected getReconnectURL(url: string, targetConnection: WebsocketConnection): string; /** * Handles subscription to streams and assigns them to specific connections * @param streams Array of stream names to subscribe to * @param urlPath Optional URL path for the streams * @returns Map of connections to streams */ private handleStreamAssignment; /** * Sends a subscription payload for specified streams on a given connection. * @param connection The WebSocket connection to use for sending the subscription. * @param streams The streams to subscribe to. * @param id Optional ID for the subscription. */ private sendSubscriptionPayload; /** * Processes pending subscriptions for a given connection. * Sends all queued subscriptions in a single payload. * @param connection The WebSocket connection to process. */ private processPendingSubscriptions; /** * Handles incoming WebSocket messages, parsing the data and invoking the appropriate callback function. * If the message contains a stream name that is registered in the `streamCallbackMap`, the corresponding * callback function is called with the message data. * If the message cannot be parsed, an error is logged. * @param data The raw WebSocket message data. * @param connection The WebSocket connection that received the message. */ protected onMessage(data: string, connection: WebsocketConnection): void; /** * Called when the WebSocket connection is opened. * Processes any pending subscriptions for the target connection. * @param url The URL of the WebSocket connection. * @param targetConnection The WebSocket connection that was opened. * @param oldConnection The previous WebSocket connection, if any. */ protected onOpen(url: string, targetConnection: WebsocketConnection, oldWSConnection: WebSocketClient): void; /** * Generates a stream key by combining a stream name with an optional URL path. * @param stream - The stream name to use as the key or suffix. * @param urlPath - Optional URL path to prepend to the stream name. * @returns A stream key in the format `urlPath::stream` if urlPath is provided, otherwise just the stream name. */ streamKey(stream: string, urlPath?: string): string; /** * Connects to the WebSocket server and subscribes to the specified streams. * This method returns a Promise that resolves when the connection is established, * or rejects with an error if the connection fails to be established within 10 seconds. * @param stream - A single stream name or an array of stream names to subscribe to. * @returns A Promise that resolves when the connection is established. */ connect(stream?: string | string[]): Promise<void>; /** * Disconnects the WebSocket connection and clears the stream callback map. * This method is called to clean up the connection and associated resources. */ disconnect(): Promise<void>; /** * Subscribes to one or multiple WebSocket streams * Handles both single and pool modes * @param stream Single stream name or array of stream names to subscribe to * @param id Optional subscription ID * @param urlPath Optional URL path for the streams * @returns void */ subscribe(stream: string | string[], id?: number | string, urlPath?: string): void; /** * Unsubscribes from one or multiple WebSocket streams * Handles both single and pool modes * @param stream Single stream name or array of stream names to unsubscribe from * @param id Optional unsubscription ID * @param urlPath Optional URL path for the streams * @returns void */ unsubscribe(stream: string | string[], id?: number | string, urlPath?: string): void; /** * Checks if the specified stream is currently subscribed. * @param stream - The name of the stream to check. * @returns `true` if the stream is currently subscribed, `false` otherwise. */ isSubscribed(stream: string): boolean; } interface WebsocketStream<T> { /** * Attach a listener for the stream. * @param event - Event name (currently supports "message"). * @param callback - Callback function to handle incoming data. */ on(event: 'message', callback: (data: T) => void | Promise<void>): void; /** * Unsubscribe from the stream and clean up resources. */ unsubscribe(): void; } /** * Creates a WebSocket stream handler for managing stream subscriptions and callbacks. * * @template T The type of data expected in the stream messages * @param {WebsocketAPIBase | WebsocketStreamsBase} websocketBase The WebSocket base instance * @param {string} streamOrId The stream identifier * @param {string} [id] Optional additional identifier * @param {string} [urlPath] Optional URL path for the stream * @returns {WebsocketStream<T>} A stream handler with methods to register callbacks and unsubscribe */ declare function createStreamHandler<T>(websocketBase: WebsocketAPIBase | WebsocketStreamsBase, streamOrId: string, id?: number | string, urlPath?: string): WebsocketStream<T>; //#endregion export { ALGO_REST_API_PROD_URL, ALPHA_REST_API_PROD_URL, AxiosRequestArgs, BadRequestError, C2C_REST_API_PROD_URL, CONVERT_REST_API_PROD_URL, COPY_TRADING_REST_API_PROD_URL, CRYPTO_LOAN_REST_API_PROD_URL, ConfigurationRestAPI, ConfigurationWebsocketAPI, ConfigurationWebsocketStreams, ConnectorClientError, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_REST_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_API_TESTNET_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_PROD_URL, DERIVATIVES_TRADING_COIN_FUTURES_WS_STREAMS_TES