diff --git a/README.md b/README.md index 57a4f26..8e63010 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,8 @@ client }); ``` +Accounts already upgraded to the unified V5 account can get error 6023 ("The current API version has expired. Please upgrade to the V5 interface") on legacy USDT-M private calls such as `getLinearSwapCrossAccountInfo` and `submitLinearSwapCrossOrder`. Use the `getMultiAsset*` and `submitMultiAsset*` methods (cancel, update, close, and margin helpers are named the same way). Accounts that are not on the unified V5 account can keep the legacy methods. Those methods stay in the SDK. + See [FuturesClient](./src/FuturesClient.ts) for further information. ## WebSockets @@ -339,7 +341,7 @@ Key WebSocket features: - Event driven messaging - Smart WebSocket persistence with automatic reconnection -- Heartbeat mechanisms to detect disconnections +- Heartbeat mechanisms to detect disconnections. Futures public sockets (`linearSwapPublic`) allow 200 concurrent connections per IP per backend instance, with no minute-level connect-rate limit. Going over that cap returns error 4000. A connection with no ping for 25 seconds is closed without notice. The SDK default `pingInterval` is 10 seconds. - Automatic resubscription after reconnection - Support for Spot and Derivatives markets (linear swap, coin swap, delivery) - Support for both public and private WebSocket streams @@ -403,6 +405,11 @@ wsClient.subscribe( WS_KEY_MAP.linearSwapPublic, ); +// Futures public WS (linearSwapPublic): 200 connections per IP per backend +// instance, no per-minute connect cap. Over the cap returns error 4000. +// A socket with no ping for 25s is closed with no notice. The SDK pings +// on pingInterval (default 10s) and answers server pings. + // Derivatives index/mark price streams wsClient.subscribe( ['market.BTC-USDT.index.1min', 'market.BTC-USDT.mark_price.1min'], diff --git a/llms.txt b/llms.txt index c9258a3..603acf9 100644 --- a/llms.txt +++ b/llms.txt @@ -4242,6 +4242,61 @@ export function removeInternalParamFields(params: TParams): TParams ⋮---- export function getStringOrUndefined(value: unknown): string | undefined +================ +File: src/types/response/shared.types.ts +================ +import { RestClientOptions } from '../../lib/requestUtils.js'; +⋮---- +export interface GenericAPIError { + code: number; + message: string; + body: TBody; + headers: Record; + requestOptions: RestClientOptions; + requestParams: Record; +} +⋮---- +// HTX TYPES +⋮---- +/** HTX spot API success response. TData is the payload. TPayloadKey defaults to "data" but can be overridden (e.g. "tick"). */ +export type SpotAPISuccessResponse< + TData, + TPayloadKey extends string = 'data', +> = { + status: string; + success?: boolean; + ok?: boolean; + code?: string; + ch?: string; + ts?: number; +} & Record; +⋮---- +/** HTX spot API error response. */ +export interface SpotAPIErrorResponse { + message?: string; + 'err-code'?: string; + 'err-msg'?: string; +} +⋮---- +/** HTX linear-swap (futures) API success response. TPayloadKey: data (default), tick, ticks. */ +export type FuturesAPISuccessResponse< + TData, + TPayloadKey extends string = 'data', +> = { + code?: number; + msg?: string; + status?: string; + ch?: string; + ts?: number; +} & Record; +⋮---- +export type SpotAPIResponse = + | SpotAPISuccessResponse + | SpotAPIErrorResponse; +⋮---- +export type OrderIdProperty = 'client-order-id'; +export type SpotOrderIdProperty = OrderIdProperty | 'clientOrderId'; + ================ File: src/types/response/ws.ts ================ @@ -4339,157 +4394,6 @@ export interface WsLinearSwapTradeDetail { ⋮---- /** Whether the trade involved an RPI order */ -================ -File: src/types/websockets/ws-general.ts -================ -import { AxiosRequestConfig } from 'axios'; -⋮---- -import { RestClientOptions } from '../../lib/requestUtils.js'; -import { HtxWSNetwork } from '../../lib/websocket/websocket-util.js'; -import { WSConnectionOptions } from './ws-portable.js'; -⋮---- -/** General configuration for the WebsocketClient */ -export interface WSClientConfigurableOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds. */ - recvWindow?: number; - - /** 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?: WSConnectionOptions; - - wsUrl?: string; - - /** - * Switch between the AWS and Standard WebSocket domains. The AWS domain has better connectivity from certain regions. If you have trouble maintaining a stable connection, try switching the domain. - * - * AWS is used by default. If this field isn't set, but you're setting the baseUrlKey in the embedded restOptions, the WS domain will automatically switch to match the REST domain. - */ - wsEnvironment?: HtxWSNetwork; - - /** - * 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; - - /** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ - reauthWSAPIOnReconnect?: boolean; - - /** - * Whether to use native WebSocket ping/pong frames for heartbeats. - */ - useNativeHeartbeats?: boolean; -} -⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds. */ -⋮---- -/** 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 */ -⋮---- -/** - * Switch between the AWS and Standard WebSocket domains. The AWS domain has better connectivity from certain regions. If you have trouble maintaining a stable connection, try switching the domain. - * - * AWS is used by default. If this field isn't set, but you're setting the baseUrlKey in the embedded restOptions, the WS domain will automatically switch to match the REST domain. - */ -⋮---- -/** - * 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. - */ -⋮---- -/** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ -⋮---- -/** - * Whether to use native WebSocket ping/pong frames for heartbeats. - */ -⋮---- -/** - * 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 { - pingInterval: number; - pongTimeout: number; - reconnectTimeout: number; - recvWindow: number; - - /** - * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) - */ - requireConnectionReadyConfirmation: boolean; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequests: boolean; - reauthWSAPIOnReconnect: boolean; - - /** - * Whether to use native WebSocket ping/pong frames for heartbeats - */ - useNativeHeartbeats: boolean; -} -⋮---- -/** - * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) - */ -⋮---- -/** - * Whether to use native WebSocket ping/pong frames for heartbeats - */ -⋮---- -export type WsMarket = 'spot' | 'futures'; -⋮---- -export type WsEventInternalSrc = 'event' | 'function' | 'frame'; -⋮---- -export interface WsSpotAuthParams { - authType: 'api'; - accessKey: string; - signatureMethod: 'HmacSHA256' | 'Ed25519'; - signatureVersion: '2.1'; - timestamp: string; - signature: string; -} -⋮---- -export interface WsDerivativesAuthParams { - op: 'auth'; - type: 'api'; - AccessKeyId: string; - SignatureMethod: 'HmacSHA256' | 'Ed25519'; - SignatureVersion: '2'; - Timestamp: string; - Signature: string; -} -⋮---- -/** Vague structure for JSON-parsed incoming msg */ -export type ParsedWsMessage = Record; - ================ File: examples/Derivatives/WebSockets/privateWs.ts ================ @@ -4616,2179 +4520,1840 @@ async function start() // https://siebly.io/reference/glossary#custom-order-id ================ -File: src/lib/websocket/websocket-util.ts +File: src/types/request/futures.types.ts ================ -import { MessageEventLike } from '../../types/websockets/ws-events.js'; -import { - WebSocketBinaryData, - WebSocketLike, -} from '../../types/websockets/ws-portable.js'; -import { WSTopic } from '../../types/websockets/ws-subscriptions.js'; -⋮---- -/** Spot Market Data */ -⋮---- -/** Spot high-frequency market data */ +/** + * Union Types (Request) + */ ⋮---- -/** Spot Account Events */ +/** Pagination direction */ +export type FuturesDirect = 'next' | 'prev'; ⋮---- -/** Spot WS API */ +/** Buy or sell */ +export type FuturesDirection = 'buy' | 'sell'; ⋮---- -/** Linear futures market data */ +/** Open or close position */ +export type FuturesOffset = 'open' | 'close'; ⋮---- -/** Linear futures account events */ +/** Open, close, or both (hedge mode) */ +export type FuturesOffsetBoth = 'open' | 'close' | 'both'; ⋮---- -/** Linear futures WS API */ +/** Position side (long, short, both) */ +export type FuturesPositionSide = 'long' | 'short' | 'both'; ⋮---- -/** V5 unified derivatives account events */ +/** Margin mode */ +export type FuturesMarginMode = 'cross' | 'isolated'; ⋮---- -/** This is used to differentiate between each of the available websocket streams. */ -export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; +/** Margin mode including all */ +export type FuturesMarginModeAll = 'cross' | 'isolated' | 'all'; ⋮---- -export type WSOperation = 'subscribe' | 'unsubscribe'; +/** Business type filter */ +export type FuturesBusinessType = 'futures' | 'swap' | 'all'; ⋮---- -export type HtxWSNetwork = 'standard' | 'aws'; +/** Contract type (delivery) */ +export type FuturesContractType = + | 'this_week' + | 'next_week' + | 'quarter' + | 'next_quarter'; ⋮---- -/** - * Normalised internal format for a request on a topic, with optional parameters. - * - * - Topic: the exchange topic string. - * - Payload: optional exchange-specific fields to merge into the request. - */ -export interface WSTopicRequest< - TWSTopic extends WSTopic = WSTopic, - TWSPayload = Record, -> { - topic: TWSTopic; - payload?: TWSPayload; -} +/** Kline period */ +export type FuturesKlinePeriod = + | '1min' + | '5min' + | '15min' + | '30min' + | '60min' + | '1hour' + | '4hour' + | '12hour' + | '1day' + | '1week' + | '1mon'; ⋮---- -/** Conveniently allow users to request either string topics or topic objects. */ -export type WSTopicRequestOrStringTopic< - TWSTopic extends WSTopic, - TWSPayload = Record, -> = WSTopicRequest | string; +/** Open interest / funding period */ +export type FuturesOpenInterestPeriod = '60min' | '4hour' | '12hour' | '1day'; ⋮---- -export interface HTXSpotMarketWSRequest { - sub?: string | string[]; - unsub?: string | string[]; - req?: string; - id?: string | number; -} +/** Sort field */ +export type FuturesSortBy = 'created_at' | 'update_time'; ⋮---- -export interface HTXSpotPrivateWSRequest { - action: 'sub' | 'unsub' | 'req' | 'ping' | 'pong'; - ch?: string; - params?: Record; - data?: Record; -} +/** Sort field (extended) */ +export type FuturesSortByExtended = + | 'create_date' + | 'update_time' + | 'created_at'; ⋮---- -export interface HTXDerivativesWSRequest { - op: 'sub' | 'unsub' | 'req' | 'ping' | 'pong' | 'auth' | string; - cid?: string; - topic?: string; - data?: Record | Record[]; - [key: string]: unknown; -} +/** Sort field (CmPerp) */ +export type FuturesSortByCmPerp = 'create_date' | 'update_time'; ⋮---- -export type HTXWSRequest = - | HTXSpotMarketWSRequest - | HTXSpotPrivateWSRequest - | HTXDerivativesWSRequest; +/** Trigger condition */ +export type FuturesTriggerType = 'ge' | 'le'; ⋮---- -export interface HTXSpotWSAPIRawRequest< - TOperation extends string = string, - TParams = unknown, -> { - cid: string; - ch: TOperation; - params?: TParams; -} +/** Basis price type */ +export type FuturesBasisPriceType = + | 'open' + | 'close' + | 'high' + | 'low' + | 'average'; ⋮---- -export interface HTXDerivativesWSAPIRawRequest< - TOperation extends string = string, - TParams = unknown, -> { - op: TOperation; - cid: string; - data?: TParams; -} +/** Transfer type */ +export type FuturesTransferType = 'master_to_sub' | 'sub_to_master'; ⋮---- -export type HTXWSAPIRawRequest = - | HTXSpotWSAPIRawRequest - | HTXDerivativesWSAPIRawRequest; +/** Margin adjust type */ +export type FuturesMarginAdjustType = 'add' | 'reduce'; ⋮---- -/** - * ws.terminate() is undefined in browsers. - * This only works in node.js, not in browsers. - * Does nothing if `ws` is undefined. Does nothing in browsers. - */ -export function safeTerminateWs( - ws?: WebSocketLike | unknown, - fallbackToClose?: boolean, -): boolean +/** Self-match prevention */ +export type FuturesSelfMatchPrevent = + | 'cancel_taker' + | 'cancel_maker' + | 'cancel_both'; ⋮---- -export function isSpotWsKey(wsKey: WsKey): boolean +/** Lightning order price type */ +export type FuturesLightningOrderPriceType = + | 'market' + | 'lightning_fok' + | 'lightning_ioc'; ⋮---- -export function isDerivativesWsKey(wsKey: WsKey): boolean +/** Lightning order price type (CmDelivery) */ +export type FuturesLightningOrderPriceTypeCm = + | 'lightning' + | 'lightning_fok' + | 'lightning_ioc'; ⋮---- -export function isPrivateWsKey(wsKey: WsKey): boolean +/** Trigger order price type */ +export type FuturesTriggerOrderPriceType = + | 'limit' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; ⋮---- -export function isTradeWsKey(wsKey: WsKey): boolean +/** Trailing order price type */ +export type FuturesTrailingOrderPriceType = + | 'optimal_5' + | 'optimal_10' + | 'optimal_20' + | 'formula_price'; ⋮---- -export function isGzipWsKey(wsKey: WsKey): boolean +/** V5 order type */ +export type FuturesV5OrderType = 'market' | 'limit' | 'post_only'; ⋮---- -export function getWsBaseUrl(wsKey: WsKey, network: HtxWSNetwork): string +/** Time in force. `rpi` places an RPI order. */ +export type FuturesTimeInForce = 'fok' | 'ioc' | 'gtc' | 'rpi'; ⋮---- -export function getWsUrl(wsKey: WsKey, network: HtxWSNetwork): string +/** Trigger price type */ +export type FuturesTriggerPriceType = 'last' | 'market'; ⋮---- -export function getPromiseRefForWSAPIRequest( - wsKey: WsKey, - requestEvent: HTXWSAPIRawRequest, -): string +/** Price match type */ +export type FuturesPriceMatch = + | 'opponent' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; ⋮---- -export function getPromiseRefPrefixForWSAPIRequest(wsKey: WsKey): string +/** Base order price types: limit, opponent, optimal_*, ioc, fok, *_ioc, *_fok */ +export type FuturesOrderPriceTypeBase = + | 'limit' + | 'opponent' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20' + | 'ioc' + | 'fok' + | 'opponent_ioc' + | 'optimal_5_ioc' + | 'optimal_10_ioc' + | 'optimal_20_ioc' + | 'opponent_fok' + | 'optimal_5_fok' + | 'optimal_10_fok' + | 'optimal_20_fok'; ⋮---- -export function isBufferMessageEvent( - msg: unknown, -): msg is MessageEventLike +/** Order price type for swap_order and swap_cross_order. Base + market + post_only */ +export type FuturesSubmitOrderPriceType = + | FuturesOrderPriceTypeBase + | 'market' + | 'post_only'; ⋮---- -export function isBinaryLike(data: unknown): data is WebSocketBinaryData +/** Order price type for swap_order_limit and contract_order_limit. Base + lightning variants */ +export type FuturesGetOrderLimitPriceType = + | FuturesOrderPriceTypeBase + | 'lightning' + | 'lightning_ioc' + | 'lightning_fok'; ⋮---- -export function binaryDataToUint8Array( - data: WebSocketBinaryData, -): Uint8Array +/** Order price type for contract_order_limit (alias) */ +export type FuturesCmDeliveryOrderLimitPriceType = + FuturesGetOrderLimitPriceType; ⋮---- -export function bufferLooksLikeText( - data?: WebSocketBinaryData | null, -): boolean +/** Order price type for contract_order and swap_order (Delivery/CMPerp). Base + post_only */ +export type FuturesCmDeliverySubmitOrderPriceType = + | FuturesOrderPriceTypeBase + | 'post_only'; ⋮---- -export async function decompressMessageEvent( - event: MessageEventLike, - format: WebSocketCompressionFormat = 'gzip', -): Promise> +/** Order price type for swap_order and swap_batchorder (CMPerp) (alias) */ +export type FuturesCmPerpSubmitOrderPriceType = + FuturesCmDeliverySubmitOrderPriceType; ⋮---- -start(controller) +/** + * Reference Data + */ ⋮---- -export type WebSocketCompressionFormat = 'deflate' | 'deflate-raw' | 'gzip'; +/** Req for GET /linear-swap-api/v1/swap_historical_funding_rate */ +export interface FuturesGetHistoricalFundingRateReq { + /** Contract code (e.g. BTC-USDT). Case-insensitive */ + contract_code: string; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -function isNodeBuffer(data: unknown): data is Uint8Array +/** Contract code (e.g. BTC-USDT). Case-insensitive */ ⋮---- -Buffer?: - -================ -File: src/lib/BaseWSClient.ts -================ -import WebSocketImplementation from 'isomorphic-ws'; +/** Page index. Default 1 */ ⋮---- -import { - isMessageEvent, - MessageEventLike, -} from '../types/websockets/ws-events.js'; -import { - WebsocketClientOptions, - WSClientConfigurableOptions, - WsEventInternalSrc, -} from '../types/websockets/ws-general.js'; -import { - EventListener, - WebSocketLike, - WSConnectionOptions, -} from '../types/websockets/ws-portable.js'; -import { WSTopic } from '../types/websockets/ws-subscriptions.js'; -import { EventEmitter } from './event-emitter.js'; -import { isObjectLike } from './misc-util.js'; -import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; -import { DefaultLogger } from './websocket/logger.js'; -import { - decompressMessageEvent, - isBufferMessageEvent, - safeTerminateWs, - WSOperation, - WSTopicRequest, - WSTopicRequestOrStringTopic, -} from './websocket/websocket-util.js'; -import { WsStore } from './websocket/WsStore.js'; -import { - DeferredPromise, - WSConnectedResult, - WsConnectionStateEnum, -} from './websocket/WsStore.types.js'; +/** Page size. Default 20, max 50 */ ⋮---- -interface WebSocketConstructor { - new ( - url: string, - protocols?: string | string[], - options?: Omit, - ): WebSocketLike; +/** Req for GET /linear-swap-api/v3/swap_liquidation_orders. One of pair and contract must be filled; contract preferred. */ +export interface FuturesGetLiquidationOrdersReq { + /** Contract code (e.g. BTC-USDT). Case-insensitive */ + contract: string; + /** 0:All; 1:Open long; 2:Open short; 3:Close short; 4:Close long; 5:Liquidate long; 6:Liquidate short; 17:buy(one-way); 18:sell(one-way) */ + trade_type: number; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** Query start time (ms). Window max 2h, within 90 days */ + start_time?: number; + /** Query end time (ms). Default now. Within 90 days */ + end_time?: number; + /** next=chronological, prev=reverse. Default prev */ + direct?: FuturesDirect; + /** Search from query_id for pagination */ + from_id?: number; } ⋮---- -function isNativeBrowserWebSocket(ws: WebSocketLike): boolean -⋮---- -type UseTheExceptionEventInstead = never; -type WSClientEventPayload = Record & { - wsKey: WsKey; -}; -⋮---- -type WSClientEventPayloadOrArray = - | WSClientEventPayload - | WSClientEventPayload[]; +/** Contract code (e.g. BTC-USDT). Case-insensitive */ ⋮---- -interface WSClientEventMap { - /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ - open: (evt: { - wsKey: WsKey; - event: unknown; - wsUrl: string; - ws: WebSocketLike; - }) => void; - - /** Reconnecting a dropped connection */ - reconnecting: (evt: { wsKey: WsKey; event: unknown }) => void; - - /** Successfully reconnected a connection that dropped */ - reconnected: (evt: { - wsKey: WsKey; - event: unknown; - wsUrl: string; - ws: WebSocketLike; - }) => void; - - /** Connection closed */ - close: (evt: { wsKey: WsKey; event: unknown }) => void; - - /** Received reply to websocket command (e.g. after subscribing to topics) */ - response: (response: WSClientEventPayloadOrArray) => void; - - /** Received data for topic */ - message: (response: WSClientEventPayloadOrArray) => void; - - /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ - exception: (response: WSClientEventPayloadOrArray) => void; - - /** - * See for more information: https://github.com/tiagosiebler/bybit-api/issues/413 - * @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection. - */ - error: UseTheExceptionEventInstead; - - /** Confirmation that a connection successfully authenticated */ - authenticated: (event: WSClientEventPayload) => void; -} +/** 0:All; 1:Open long; 2:Open short; 3:Close short; 4:Close long; 5:Liquidate long; 6:Liquidate short; 17:buy(one-way); 18:sell(one-way) */ ⋮---- -/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** Reconnecting a dropped connection */ +/** Query start time (ms). Window max 2h, within 90 days */ ⋮---- -/** Successfully reconnected a connection that dropped */ +/** Query end time (ms). Default now. Within 90 days */ ⋮---- -/** Connection closed */ +/** next=chronological, prev=reverse. Default prev */ ⋮---- -/** Received reply to websocket command (e.g. after subscribing to topics) */ +/** Search from query_id for pagination */ ⋮---- -/** Received data for topic */ +/** Req for GET /linear-swap-api/v1/swap_settlement_records */ +export interface FuturesGetSettlementRecordsReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code: string; + /** Start time (ms). Default: now - 90 days. Within 90 days */ + start_time?: number; + /** End time (ms). Default: now. Must be after start_time */ + end_time?: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- -/** - * See for more information: https://github.com/tiagosiebler/bybit-api/issues/413 - * @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection. - */ +/** Start time (ms). Default: now - 90 days. Within 90 days */ ⋮---- -/** Confirmation that a connection successfully authenticated */ +/** End time (ms). Default: now. Must be after start_time */ ⋮---- -export interface EmittableEvent< - TEventType extends keyof WSClientEventMap = - keyof WSClientEventMap, -> { - eventType: - | TEventType - | 'pong' - | 'connectionReady' // tied to "requireConnectionReadyConfirmation"; - | 'connectionReadyForAuth'; // tied to specific events we need to wait for, before we can begin post-connect auth - event: Parameters[TEventType]>[0]; - isWSAPIResponse?: boolean; -} +/** Page index. Default 1 */ ⋮---- -| 'connectionReady' // tied to "requireConnectionReadyConfirmation"; -| 'connectionReadyForAuth'; // tied to specific events we need to wait for, before we can begin post-connect auth +/** Page size. Default 20, max 50 */ ⋮---- -// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 -export interface BaseWebsocketClient< - TWSKey extends string, - TWSRequestEvent extends object, -> { - /** @internal preserves the request-event generic on the merged class type. */ - readonly __requestEventType?: TWSRequestEvent; - - on>( - event: U, - listener: WSClientEventMap[U], - ): this; - - addListener>( - event: U, - listener: WSClientEventMap[U], - ): this; - - once>( - event: U, - listener: WSClientEventMap[U], - ): this; - - prependListener>( - event: U, - listener: WSClientEventMap[U], - ): this; - - prependOnceListener>( - event: U, - listener: WSClientEventMap[U], - ): this; - - off>( - event: U, - listener: WSClientEventMap[U], - ): this; - - removeListener>( - event: U, - listener: WSClientEventMap[U], - ): this; - - removeAllListeners(event?: keyof WSClientEventMap): this; - - listeners(event: keyof WSClientEventMap): EventListener[]; - - listenerCount( - event: keyof WSClientEventMap, - listener?: WSClientEventMap[keyof WSClientEventMap], - ): number; - - emit>( - event: U, - ...args: Parameters[U]> - ): boolean; +/** Req for GET /linear-swap-api/v1/swap_cross_ladder_margin. When all filled, contract_code preferred. business_type required for futures. */ +export interface FuturesGetCrossTieredMarginReq { + /** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** Default swap. futures, swap, all. Required for futures contract query */ + business_type?: FuturesBusinessType; } ⋮---- -/** @internal preserves the request-event generic on the merged class type. */ +/** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- -on>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Pair (e.g. BTC-USDT) */ ⋮---- -addListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -once>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Default swap. futures, swap, all. Required for futures contract query */ ⋮---- -prependListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +export type FuturesGetEstimatedSettlementPriceReq = + FuturesGetCrossTieredMarginReq; +export type FuturesGetCrossAdjustFactorReq = FuturesGetCrossTieredMarginReq; +export type FuturesGetContractPriceLimitReq = FuturesGetCrossTieredMarginReq; +export type FuturesGetOpenInterestReq = FuturesGetCrossTieredMarginReq; ⋮---- -prependOnceListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Req for GET /v1/insurance_fund_history */ +export interface FuturesGetRiskReserveHistoryReq { + /** Query start time (ms) */ + start_time?: number; + /** Query end time (ms) */ + end_time?: number; + /** next=chronological, prev=reverse. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result depending on direct */ + from_id?: number; + /** Items per page [1-100]. Default 10 */ + limit?: number; +} ⋮---- -off>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Query start time (ms) */ ⋮---- -removeListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Query end time (ms) */ ⋮---- -removeAllListeners(event?: keyof WSClientEventMap): this; +/** next=chronological, prev=reverse. Default prev */ ⋮---- -listeners(event: keyof WSClientEventMap): EventListener[]; +/** Pagination: min/max query_id from last result depending on direct */ ⋮---- -listenerCount( - event: keyof WSClientEventMap, - listener?: WSClientEventMap[keyof WSClientEventMap], - ): number; +/** Items per page [1-100]. Default 10 */ ⋮---- -emit>( - event: U, - ...args: Parameters[U]> - ): boolean; -⋮---- -/** - * A midflight WS request event (e.g. subscribe to these topics). - * - * - requestKey: unique identifier for this request, if available. Can be anything as a string. - * - requestEvent: the raw request, as an object, that will be sent on the ws connection. This may contain multiple topics/requests in one object, if the exchange supports it. - */ -export interface MidflightWsRequestEvent { - requestKey: string | number; - requestEvent: TEvent; +/** Req for GET /linear-swap-api/v1/swap_contract_info. When isolated, contract_type/business_type cannot be futures. */ +export interface FuturesGetContractInfoReq { + /** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code?: string; + /** cross, isolated, or all. Filter by supported margin mode */ + support_margin_mode?: FuturesMarginModeAll; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** Default swap. futures, swap, all. Required for futures query */ + business_type?: FuturesBusinessType; } ⋮---- -/** - * Appends wsKey and isWSAPIResponse to all events. - * Some events are arrays, this handles that nested scenario too. - */ -function getFinalEmittable( - emittable: EmittableEvent, - wsKey: TWSKey, - isWSAPIResponse?: boolean, -): WSClientEventPayload; -function getFinalEmittable( - emittable: EmittableEvent[], - wsKey: TWSKey, - isWSAPIResponse?: boolean, -): WSClientEventPayload[]; -function getFinalEmittable( - emittable: EmittableEvent | EmittableEvent[], - wsKey: TWSKey, - isWSAPIResponse?: boolean, -): WSClientEventPayload | WSClientEventPayload[] +/** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- -// Some topics just emit an array. -// This is consistent with how it was before the WS API upgrade: +/** cross, isolated, or all. Filter by supported margin mode */ ⋮---- -// const { event, ...others } = emittable; -// return { -// ...others, -// event: event.map((subEvent) => -// getFinalEmittable(subEvent, wsKey, isWSAPIResponse), -// ), -// }; +/** Pair (e.g. BTC-USDT) */ +⋮---- +/** swap, this_week, next_week, quarter, next_quarter */ +⋮---- +/** Default swap. futures, swap, all. Required for futures query */ ⋮---- /** - * Users can conveniently pass topics as strings or objects (object has topic name + optional params). - * - * This method normalises topics into objects (object has topic name + optional params). + * Market Data */ -function getNormalisedTopicRequests( - wsTopicRequests: WSTopicRequestOrStringTopic[], -): WSTopicRequest[] ⋮---- -// passed as string, convert to object +/** Req for GET /linear-swap-ex/market/history/kline. Either size or (from+to) required. */ +export interface FuturesGetKlinesReq { + /** Contract code or type. swap: BTC-USDT; future: BTC-USDT-220325 or BTC-USDT-CW/NW/CQ/NQ */ + contract_code: string; + /** 1min, 5min, 15min, 30min, 60min, 1hour, 4hour, 1day, 1mon */ + period: FuturesKlinePeriod; + /** Items [1-2000]. Default 150. Ignored if from+to provided */ + size?: number; + /** Start timestamp (seconds) */ + from?: number; + /** End timestamp (seconds). Required if from provided */ + to?: number; +} ⋮---- -// already a normalised object, thanks to user +/** Contract code or type. swap: BTC-USDT; future: BTC-USDT-220325 or BTC-USDT-CW/NW/CQ/NQ */ ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -export abstract class BaseWebsocketClient< -TWSKey extends string, +/** 1min, 5min, 15min, 30min, 60min, 1hour, 4hour, 1day, 1mon */ ⋮---- -constructor( - options?: WSClientConfigurableOptions & { wsLoggerCategory: string }, - logger?: DefaultLogger, -) +/** Items [1-2000]. Default 150. Ignored if from+to provided */ ⋮---- -// Requires a confirmation "response" from the ws connection before assuming it is ready +/** Start timestamp (seconds) */ ⋮---- -// Automatically auth after opening a connection? +/** End timestamp (seconds). Required if from provided */ ⋮---- -// Automatically include auth/sign/token with every WS request. -// Automatically handled during getWsRequestEvents. +/** Req for GET /linear-swap-api/v1/swap_his_open_interest. One of (pair+contract_type) or contract_code required. */ +export interface FuturesGetHistoricalOpenInterestReq { + /** Contract code. Omit if pair+contract_type provided */ + contract_code?: string; + /** Pair (e.g. BTC-USDT). Use with contract_type */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** 60min, 4hour, 12hour, 1day */ + period: FuturesOpenInterestPeriod; + /** Items [1-200]. Default 48 */ + size?: number; + /** 1: cont, 2: cryptocurrency */ + amount_type: 1 | 2; +} ⋮---- -// Automatically re-auth WS API, if we were auth'd before and get reconnected +/** Contract code. Omit if pair+contract_type provided */ ⋮---- -// Whether to use native heartbeats (depends on the exchange) +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** - * Return true if this wsKey connection should automatically authenticate immediately after connecting - */ -protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; +/** 60min, 4hour, 12hour, 1day */ ⋮---- -protected abstract isCustomReconnectionNeeded(wsKey: TWSKey): boolean; +/** Items [1-200]. Default 48 */ ⋮---- -protected abstract triggerCustomReconnectionWorkflow( - wsKey: TWSKey, - ): Promise; +/** 1: cont, 2: cryptocurrency */ ⋮---- -protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocketLike): boolean; +/** Req for GET /index/market/history/linear_swap_mark_price_kline. Also used for premium index and estimated rate kline. */ +export interface FuturesGetMarkKlinesReq { + /** Contract code or type. swap: BTC-USDT; future: BTC-USDT-210625 or BTC-USDT-CW/NW/CQ/NQ */ + contract_code: string; + /** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1week, 1mon */ + period: string; + /** Items [1-2000] */ + size: number; +} ⋮---- -protected abstract sendPongEvent( - wsKey: TWSKey, - ws: WebSocketLike, - event?: unknown, - ): void; +/** Contract code or type. swap: BTC-USDT; future: BTC-USDT-210625 or BTC-USDT-CW/NW/CQ/NQ */ ⋮---- -protected abstract isWsPing(data: unknown): boolean; +/** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1week, 1mon */ ⋮---- -protected abstract isWsPong(data: unknown): boolean; +/** Items [1-2000] */ ⋮---- -protected abstract authPrivateConnectionsOnConnect(_wsKey: TWSKey): boolean; +export type FuturesGetPremiumIndexKlinesReq = FuturesGetMarkKlinesReq; +export type FuturesGetFundingRateKlinesReq = FuturesGetMarkKlinesReq; ⋮---- -/** - * Return the event sent to the server to trigger authentication. If the event requires waiting for another event first (e.g. a challenge), return 'waitForEvent' and the library will wait for that event before calling this method again. - * - * Usually only called once per connection, unless the connection drops/is reset. - */ -protected abstract getWsAuthRequestEvent( - wsKey: TWSKey, - eventToAuth?: object, - ): Promise; +/** Req for GET /index/market/history/linear_swap_basis */ +export interface FuturesGetBasisDataReq { + /** Contract code or type */ + contract_code: string; + /** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1mon */ + period: FuturesKlinePeriod; + /** Items [1-2000]. Default 150 */ + size: number; + /** open, close, high, low, average. Default open */ + basis_price_type?: FuturesBasisPriceType; +} ⋮---- -protected abstract isPrivateTopicRequest( - request: WSTopicRequest, - wsKey: TWSKey, - ): boolean; +/** Contract code or type */ ⋮---- -protected abstract getPrivateWSKeys(): TWSKey[]; +/** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1mon */ ⋮---- -protected abstract getWsUrl(wsKey: TWSKey): Promise; +/** Items [1-2000]. Default 150 */ ⋮---- -protected abstract getMaxTopicsPerSubscribeEvent( - wsKey: TWSKey, - ): number | null; +/** open, close, high, low, average. Default open */ ⋮---- /** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected abstract getWsRequestEvents( - wsKey: TWSKey, - operation: WSOperation, - requests: WSTopicRequest[], - ): Promise[]>; + * Account + */ ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected abstract resolveEmittableEvents( - wsKey: TWSKey, - event: MessageEventLike, - ): EmittableEvent[]; +/** Req for POST /linear-swap-api/v1/swap_cross_position_info */ +export interface FuturesGetCrossPositionsReq { + /** Contract code. Omit for all */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; +} ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -protected abstract connectAll(): Promise[]; +/** Contract code. Omit for all */ ⋮---- -protected isPrivateWsKey(wsKey: TWSKey): boolean +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** Returns auto-incrementing request ID, used to track promise references for async requests */ -protected getNewRequestId(): number +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - operation: string, - params?: unknown, - ): Promise; +/** Req for GET /linear-swap-api/v1/swap_sub_auth_list. getSubPermissions. */ +export interface FuturesGetSubPermissionsReq { + /** Sub-account UIDs, comma-separated. Max 10 */ + sub_uid?: string; + /** Start time of sub-account creation (ms) */ + start_time?: number; + /** End time of sub-account creation (ms) */ + end_time?: number; + /** next=chronological, prev=reverse */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; +} ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - channel: string, - params: unknown, - ): Promise; +/** Sub-account UIDs, comma-separated. Max 10 */ ⋮---- -public getTimeOffsetMs() +/** Start time of sub-account creation (ms) */ ⋮---- -public setTimeOffsetMs(newOffset: number) +/** End time of sub-account creation (ms) */ ⋮---- -/** - * Don't call directly! Use subscribe() instead! - * - * Subscribe to one or more topics on a WS connection (identified by WS Key). - * - * - Topics are automatically cached - * - Connections are automatically opened, if not yet connected - * - Authentication is automatically handled - * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). - * - * @param wsTopicRequests array of topics to subscribe to - * @param wsKey ws key referring to the ws connection these topics should be subscribed on - */ -protected async subscribeTopicsForWsKey( - wsTopicRequests: WSTopicRequestOrStringTopic[], - wsKey: TWSKey, -) +/** next=chronological, prev=reverse */ ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +/** Pagination: min/max query_id from last result */ ⋮---- -// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +/** Req for POST /linear-swap-api/v1/swap_sub_account_list. Isolated margin only. */ +export interface FuturesGetIsolatedSubAccountsReq { + /** Contract code (e.g. BTC-USDT). Omit for all */ + contract_code?: string; + /** next=chronological, prev=reverse. Default next */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result depending on direct */ + from_id?: number; +} ⋮---- -// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. +/** Contract code (e.g. BTC-USDT). Omit for all */ ⋮---- -/** - * Are we in the process of connection? Nothing to send yet. - */ +/** next=chronological, prev=reverse. Default next */ ⋮---- -// We're connected. Check if auth is needed and if already authenticated +/** Pagination: min/max query_id from last result depending on direct */ ⋮---- -/** - * If not authenticated yet and auth is required, don't request topics yet. - * - * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. - */ +/** Req for POST /linear-swap-api/v1/swap_cross_sub_account_list. Cross margin only. */ +export interface FuturesGetCrossSubAccountsReq { + /** Margin account (e.g. USDT). Omit for all */ + margin_account?: string; + /** next=chronological, prev=reverse. Default next */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result depending on direct */ + from_id?: number; +} ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +/** Margin account (e.g. USDT). Omit for all */ ⋮---- -protected async unsubscribeTopicsForWsKey( - wsTopicRequests: WSTopicRequestOrStringTopic[], - wsKey: TWSKey, -): Promise +/** next=chronological, prev=reverse. Default next */ ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +/** Pagination: min/max query_id from last result depending on direct */ ⋮---- -// If not connected, don't need to do anything. -// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. +/** Req for POST /linear-swap-api/v1/swap_sub_account_info_list. Isolated margin only. */ +export interface FuturesGetSubAccountsAssetsReq { + /** Contract code (e.g. BTC-USDT). Omit for all */ + contract_code?: string; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -// We're connected. Check if auth is needed and if already authenticated +/** Contract code (e.g. BTC-USDT). Omit for all */ ⋮---- -/** - * If not authenticated yet and auth is required, don't need to do anything. - * We don't subscribe to topics until auth is complete anyway. - */ +/** Page index. Default 1 */ ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +/** Page size. Default 20, max 50 */ ⋮---- -/** - * Splits topic requests into two groups, public & private topic requests - */ -private sortTopicRequestsIntoPublicPrivate( - wsTopicRequests: WSTopicRequest[], - wsKey: TWSKey, -): +/** Req for POST /linear-swap-api/v1/swap_cross_sub_account_info_list. Cross margin only. */ +export interface FuturesGetCrossSubAccountsAssetsReq { + /** Margin account (e.g. USDT). Omit for all */ + margin_account?: string; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -/** Get the WsStore that tracks websockets & topics */ -public getWsStore(): WsStore> +/** Margin account (e.g. USDT). Omit for all */ ⋮---- -public close(wsKey: TWSKey, force?: boolean) +/** Page index. Default 1 */ ⋮---- -public closeAll(force?: boolean) +/** Page size. Default 20, max 50 */ ⋮---- -public isConnected(wsKey: TWSKey): boolean +/** Req for POST /linear-swap-api/v1/swap_cross_sub_position_info. Cross margin only. */ +export interface FuturesGetCrossSubPositionsReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all. contract_code preferred when all filled */ + contract_code?: string; + /** Sub-account UID */ + sub_uid: number; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; +} ⋮---- -/** - * Request connection to a specific websocket, instead of waiting for automatic connection. - */ -public async connect( - wsKey: TWSKey, - customUrl?: string | undefined, - throwOnError?: boolean, -): Promise +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all. contract_code preferred when all filled */ ⋮---- -// Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()! +/** Sub-account UID */ ⋮---- -private connectToWsUrl(url: string, wsKey: TWSKey): WebSocketLike +/** Pair (e.g. BTC-USDT) */ ⋮---- -// Event handlers for native heartbeats / ping/pong frames +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -private parseWsError( - context: string, - error: unknown, - wsKey: TWSKey, -): boolean +/** Req for POST /linear-swap-api/v3/swap_financial_record. Supports cross and isolated. */ +export interface FuturesGetFinancialRecordsReq { + /** Margin account. swap: BTC-USDT, future: BTC-USDT-210625. Required */ + mar_acct: string; + /** Contract code (e.g. BTC-USDT). Omit for all */ + contract?: string; + /** Comma-separated type codes. Omit for all. e.g. 3,4,5,6 */ + type?: string; + /** Query start time (ms). Window max 48h, within 90 days */ + start_time?: number; + /** Query end time (ms). Default now. Within 90 days */ + end_time?: number; + /** next=chronological, prev=reverse. Default next */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result depending on direct */ + from_id?: number; +} ⋮---- -// Allow retry by default (in some places that call this). Prevent deadloop in hard failure (401) +/** Margin account. swap: BTC-USDT, future: BTC-USDT-210625. Required */ ⋮---- -/** Get a signature, build the auth request and send it */ -private async sendAuthRequest( - wsKey: TWSKey, - eventToAuth?: object, -): Promise +/** Contract code (e.g. BTC-USDT). Omit for all */ ⋮---- -private async advanceAuthRequest( - wsKey: TWSKey, - authPromise: DeferredPromise, - eventToAuth?: object, -): Promise +/** Comma-separated type codes. Omit for all. e.g. 3,4,5,6 */ ⋮---- -// If not required, this won't return anything +/** Query start time (ms). Window max 48h, within 90 days */ ⋮---- -// Short-circuit this for the next time it's called +/** Query end time (ms). Default now. Within 90 days */ ⋮---- -private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) +/** next=chronological, prev=reverse. Default next */ ⋮---- -// Some streams need a specialist reconnection workflow. -// E.g. the user data stream can't just be reconnected as is. +/** Pagination: min/max query_id from last result depending on direct */ ⋮---- -private ping(wsKey: TWSKey) +/** Req for POST /linear-swap-api/v3/swap_financial_record_exact. Same params as swap_financial_record; API default direct is prev. */ +export type FuturesGetFinancialRecordsExactReq = FuturesGetFinancialRecordsReq; ⋮---- -/** - * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. - * If closed, trigger a reconnect immediately - */ -protected executeReconnectableClose(wsKey: TWSKey, reason: string) +/** Req for POST /linear-swap-api/v1/swap_cross_available_level_rate. Cross margin only. */ +export interface FuturesGetCrossAvailableLeverageReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** futures, swap, all. Required for futures. Default swap */ + business_type?: FuturesBusinessType; +} ⋮---- -private clearTimers(wsKey: TWSKey) +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: TWSKey) +/** Pair (e.g. BTC-USDT) */ ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: TWSKey) +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); +/** futures, swap, all. Required for futures. Default swap */ ⋮---- -// this.logger.trace(`No active pong timer for "${wsKey}"`); +/** Req for POST /linear-swap-api/v1/swap_order_limit. Supports cross and isolated. */ +export interface FuturesGetOrderLimitReq { + /** Order price type. Required */ + order_price_type: FuturesGetOrderLimitPriceType; + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** futures, swap, all. Required for futures. Default swap */ + business_type?: FuturesBusinessType; +} ⋮---- -private clearReconnectTimer(wsKey: TWSKey) +/** Order price type. Required */ ⋮---- -/** - * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics - * - * If events are an object, these should be stringified (`return JSON.stringify(event);`) - * Each event returned by this will be sent one at a time - * - * Events are automatically split into smaller batches, by this method, if needed. - */ -protected async getWsOperationEventsForTopics( - topics: WSTopicRequest[], - wsKey: TWSKey, - operation: WSOperation, -): Promise[]> +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ ⋮---- -// Events that are ready to send (usually stringified JSON) +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** - * Simply builds and sends subscribe events for a list of topics for a ws key - * - * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. - */ -private async requestSubscribeTopics( - wsKey: TWSKey, - wsTopicRequests: WSTopicRequest[], -) +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -// Automatically splits requests into smaller batches, if needed +/** futures, swap, all. Required for futures. Default swap */ ⋮---- -`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" +/** Req for POST /linear-swap-api/v1/swap_fee. Supports cross and isolated. */ +export interface FuturesGetFeeReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** futures, swap, all. Required for futures. Default swap */ + business_type?: FuturesBusinessType; +} ⋮---- -/** - * Simply builds and sends unsubscribe events for a list of topics for a ws key - * - * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. - */ -private async requestUnsubscribeTopics( - wsKey: TWSKey, - wsTopicRequests: WSTopicRequest[], -) +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ ⋮---- -/** - * Try sending a string event on a WS connection (identified by the WS Key) - */ -private tryWsSendWithResult( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -): boolean +/** Pair (e.g. BTC-USDT) */ ⋮---- -public tryWsSend( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -): void +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** Send a message while reporting whether it reached the socket API. */ -protected tryWsSendWithStatus( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -): boolean +/** futures, swap, all. Required for futures. Default swap */ ⋮---- -private async onWsOpen( - event: unknown, - wsKey: TWSKey, - url: string, - ws: WebSocketLike, -) +/** Req for POST /linear-swap-api/v1/swap_cross_position_limit. Cross margin only. */ +export interface FuturesGetCrossPositionLimitReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** futures, swap, all. Required for futures. Default swap */ + business_type?: FuturesBusinessType; +} ⋮---- -private resolveConnectionInProgressPromise(wsKey: TWSKey) +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ ⋮---- -// Resolve & cleanup deferred "connection attempt in progress" promise +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** - * Called automatically once a connection is ready. - * - Some exchanges are ready immediately after the connections open. - * - Some exchanges send an event to confirm the connection is ready for us. - * - * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called. - */ -private async onWsReadyForEvents(wsKey: TWSKey) +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -// Some websockets require an auth packet to be sent after opening the connection +/** futures, swap, all. Required for futures. Default swap */ ⋮---- -// Reconnect to topics known before it connected +/** Req for POST /linear-swap-api/v1/swap_cross_lever_position_limit. Cross margin only. */ +export interface FuturesGetCrossLeverageLimitsReq { + /** futures, swap, all. Required for futures */ + business_type?: FuturesBusinessType; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** Contract code. swap: BTC-USDT, future: BTC-USDT-211231. Omit for all */ + contract_code?: string; + /** Leverage rate. Omit for all */ + lever_rate?: number; +} ⋮---- -// Request sub to public topics, if any +/** futures, swap, all. Required for futures */ ⋮---- -// Request sub to private topics, if auth on connect isn't needed +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** - * Handle subscription to private topics _after_ authentication successfully completes asynchronously. - * - * Only used for exchanges that require auth before sending private topic subscription requests - */ -private onWsAuthenticated(wsKey: TWSKey, event: unknown) +/** Pair (e.g. BTC-USDT) */ ⋮---- -// Resolve & cleanup deferred "auth attempt in progress" promise +/** Contract code. swap: BTC-USDT, future: BTC-USDT-211231. Omit for all */ ⋮---- -// Remove before continuing, in case there's more requests queued +/** Leverage rate. Omit for all */ ⋮---- -private onWsPing( - event: unknown, - wsKey: TWSKey, - ws: WebSocketLike, - source: WsEventInternalSrc, -) +/** Req for POST /linear-swap-api/v1/swap_master_sub_transfer. Supports cross and isolated. */ +export interface FuturesTransferMasterSubReq { + /** Sub-account UID */ + sub_uid: number; + /** Asset (e.g. USDT) */ + asset: string; + /** From margin account (e.g. USDT, BTC-USDT) */ + from_margin_account: string; + /** To margin account */ + to_margin_account: string; + /** Transfer amount */ + amount: number | string; + /** master_to_sub or sub_to_master */ + type: FuturesTransferType; + /** Optional client order ID [1, 9223372036854775807]. Valid 8h per transfer path */ + client_order_id?: number; +} ⋮---- -private onWsPong(event: unknown, wsKey: TWSKey, source: WsEventInternalSrc) +/** Sub-account UID */ ⋮---- -// Necessary when native heartbeats are used +/** Asset (e.g. USDT) */ ⋮---- -private async onWsMessage( - event: unknown, - wsKey: TWSKey, - ws: WebSocketLike, - didDecompress = false, -): Promise +/** From margin account (e.g. USDT, BTC-USDT) */ ⋮---- -// console.log('onMessageRaw: ', (event as any).data); -// any message can clear the pong timer - wouldn't get a message if the ws wasn't working +/** To margin account */ ⋮---- -// console.log(`raw event: `, { data, dataType, emittableEvents }); +/** Transfer amount */ ⋮---- -// Other event types are automatically emitted here +/** master_to_sub or sub_to_master */ ⋮---- -// this.logger.trace( -// `onWsMessage().emit(${emittable.eventType}).done()`, -// emittableFinalEvent, -// ); +/** Optional client order ID [1, 9223372036854775807]. Valid 8h per transfer path */ ⋮---- -// this.logger.trace('Decompressed message event from buffer', { -// ...this.WS_LOGGER_CATEGORY, -// wsKey, -// decompressed, -// }); +/** Req for POST /linear-swap-api/v1/swap_master_sub_transfer_record. Supports cross and isolated. */ +export interface FuturesGetMasterSubTransfersReq { + /** Margin account (e.g. BTC-USDT, USDT). Required */ + margin_account: string; + /** 34: to sub, 35: from sub. Comma-separated for multiple. Omit for all */ + transfer_type?: string; + /** Days to query. Max 90 */ + create_date: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -private onWsClose(event: unknown, wsKey: TWSKey) +/** Margin account (e.g. BTC-USDT, USDT). Required */ ⋮---- -// unintentional close, attempt recovery +/** 34: to sub, 35: from sub. Comma-separated for multiple. Omit for all */ ⋮---- -// clean up any pending promises for this connection +/** Days to query. Max 90 */ ⋮---- -// this.clearTopicsPendingSubscriptions(wsKey, true, 'WS Closed'); +/** Page index. Default 1 */ ⋮---- -// intentional close - clean up -// clean up any pending promises for this connection +/** Page size. Default 20, max 50 */ ⋮---- -// This was an intentional close, delete all state for this connection, as if it never existed: +/** Req for POST /linear-swap-api/v1/swap_transfer_inner. Transfer between margin accounts under same account. */ +export interface FuturesTransferInnerReq { + /** Asset (e.g. USDT) */ + asset: string; + /** From margin account (e.g. BTC-USDT, USDT) */ + from_margin_account: string; + /** To margin account */ + to_margin_account: string; + /** Transfer amount */ + amount: number | string; + /** Optional client order ID [1, 9223372036854775807]. Valid 8h */ + client_order_id?: number; +} ⋮---- -private getWs(wsKey: TWSKey) +/** Asset (e.g. USDT) */ ⋮---- -private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) +/** From margin account (e.g. BTC-USDT, USDT) */ ⋮---- -/** - * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) - */ -protected async assertIsConnected(wsKey: TWSKey): Promise +/** To margin account */ ⋮---- -// Already in progress? Await shared promise and retry +/** Transfer amount */ ⋮---- -// Start connection, it should automatically store/return a promise. +/** Optional client order ID [1, 9223372036854775807]. Valid 8h */ ⋮---- -/** - * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) - */ -public async assertIsAuthenticated(wsKey: TWSKey): Promise +/** Req for POST /linear-swap-api/v1/swap_order. Isolated margin only. */ +export interface FuturesSubmitOrderReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract_code: string; + /** buy or sell */ + direction: FuturesDirection; + /** Order quantity */ + volume: number; + /** Leverage rate */ + lever_rate: number; + /** Order price type */ + order_price_type: FuturesSubmitOrderPriceType; + /** open, close, both. Required in hedge mode */ + offset?: FuturesOffsetBoth; + /** Price. Required for limit, post_only, ioc, fok */ + price?: number | string; + /** 0: no, 1: yes */ + reduce_only?: 0 | 1; + /** Client order ID [1, 9223372036854775807] */ + client_order_id?: number; + /** Take-profit trigger price */ + tp_trigger_price?: number | string; + /** Take-profit order price */ + tp_order_price?: number | string; + /** Take-profit order type */ + tp_order_price_type?: string; + /** Stop-loss trigger price */ + sl_trigger_price?: number | string; + /** Stop-loss order price */ + sl_order_price?: number | string; + /** Stop-loss order type */ + sl_order_price_type?: string; + /** Price protection when setting tp/sl */ + price_protect?: boolean; + /** 0: allow self-trade, 1: prevent (default) */ + self_match_prevent?: 0 | 1; + /** cancel_taker, cancel_maker, cancel_both */ + self_match_prevent_new?: FuturesSelfMatchPrevent; +} ⋮---- -// Already in progress? Await shared promise and retry +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -// Start authentication, it should automatically store/return a promise. - -================ -File: src/types/response/shared.types.ts -================ -import { RestClientOptions } from '../../lib/requestUtils.js'; +/** buy or sell */ ⋮---- -export interface GenericAPIError { - code: number; - message: string; - body: TBody; - headers: Record; - requestOptions: RestClientOptions; - requestParams: Record; -} +/** Order quantity */ ⋮---- -// HTX TYPES +/** Leverage rate */ ⋮---- -/** HTX spot API success response. TData is the payload. TPayloadKey defaults to "data" but can be overridden (e.g. "tick"). */ -export type SpotAPISuccessResponse< - TData, - TPayloadKey extends string = 'data', -> = { - status: string; - success?: boolean; - ok?: boolean; - code?: string; - ch?: string; - ts?: number; -} & Record; +/** Order price type */ ⋮---- -/** HTX spot API error response. */ -export interface SpotAPIErrorResponse { - message?: string; - 'err-code'?: string; - 'err-msg'?: string; -} +/** open, close, both. Required in hedge mode */ ⋮---- -/** HTX linear-swap (futures) API success response. TPayloadKey: data (default), tick, ticks. */ -export type FuturesAPISuccessResponse< - TData, - TPayloadKey extends string = 'data', -> = { - code?: number; - msg?: string; - status?: string; - ch?: string; - ts?: number; -} & Record; +/** Price. Required for limit, post_only, ioc, fok */ ⋮---- -export type SpotAPIResponse = - | SpotAPISuccessResponse - | SpotAPIErrorResponse; +/** 0: no, 1: yes */ ⋮---- -export type OrderIdProperty = 'client-order-id'; -export type SpotOrderIdProperty = OrderIdProperty | 'clientOrderId'; - -================ -File: src/types/websockets/ws-subscriptions.ts -================ -/** - * HTX websocket topics are string templates, e.g.: - * - * - `market.btcusdt.kline.1min` - * - `market.btcusdt.mbp.150` - * - `orders#btcusdt` - * - `orders.btc-usdt` - * - * The exchange publishes a large and evolving topic surface, so the SDK keeps - * the topic type open while exporting common topic groups for discovery and - * private/public routing. - */ +/** Client order ID [1, 9223372036854775807] */ ⋮---- -export type WSSpotPublicTopic = (typeof WS_SPOT_PUBLIC_TOPICS)[number]; -export type WSSpotPrivateTopic = (typeof WS_SPOT_PRIVATE_TOPICS)[number]; -export type WSDerivativesPublicTopic = - (typeof WS_DERIVATIVES_PUBLIC_TOPICS)[number]; -export type WSDerivativesPrivateTopic = - (typeof WS_DERIVATIVES_PRIVATE_TOPICS)[number]; +/** Take-profit trigger price */ ⋮---- -export type WSTopic = - | WSSpotPublicTopic - | WSSpotPrivateTopic - | WSDerivativesPublicTopic - | WSDerivativesPrivateTopic - | string; +/** Take-profit order price */ ⋮---- -export function isPrivateTopic(topic: string): boolean - -================ -File: src/index.ts -================ - - -================ -File: src/WebsocketClient.ts -================ -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './lib/BaseWSClient.js'; -import { - getStringOrUndefined, - isRecord, - omitKeys, - removeInternalParamFields, -} from './lib/misc-util.js'; -import { - APIIDMain, - generateNewOrderID, - getOrderIdPrefix, - logInvalidOrderId, - REST_CLIENT_TYPE_ENUM, - serializeParams, - validateWSAPICustomOrderID, - validateWSAPIDerivativesChannelKey, -} from './lib/requestUtils.js'; -import { - getSignKeyType, - SignAlgorithm, - SignEncodeMethod, - signMessage as signRawMessage, -} from './lib/webCryptoAPI.js'; -import { DefaultLogger } from './lib/websocket/logger.js'; -import { - getPromiseRefForWSAPIRequest, - getPromiseRefPrefixForWSAPIRequest, - getWsUrl as getHtxWsUrl, - HTXDerivativesWSAPIRawRequest, - HTXDerivativesWSRequest, - HTXSpotPrivateWSRequest, - HTXSpotWSAPIRawRequest, - HTXWSAPIRawRequest, - HtxWSNetwork, - HTXWSRequest, - isPrivateWsKey, - PRIVATE_WS_KEYS, - TRADE_WS_KEYS, - WS_KEY_MAP, - WS_KEY_PATH_MAP, - WsKey, - WSOperation, - WSTopicRequest, -} from './lib/websocket/websocket-util.js'; -import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; -import { - SpotV1OrderAutoPlaceReq, - SpotV1OrderPlaceReq, -} from './types/request/spot.types.js'; -import { OrderIdProperty } from './types/response/shared.types.js'; -import { - Exact, - WS_API_Operations, - WSAPIDerivativesOperation, - WSAPIOperation, - WSAPISpotOperation, - WSAPITopicRequestParamMap, - WSAPITopicResponseMap, - WSAPIWsKey, - WSAPIWsKeyTopicMap, -} from './types/websockets/ws-api.js'; -import { MessageEventLike } from './types/websockets/ws-events.js'; -import { - ParsedWsMessage, - WSClientConfigurableOptions, - WsDerivativesAuthParams, - WsSpotAuthParams, -} from './types/websockets/ws-general.js'; -import { - WebSocketLike, - WebSocketReadyState, -} from './types/websockets/ws-portable.js'; -import { - isPrivateTopic, - WSTopic, -} from './types/websockets/ws-subscriptions.js'; +/** Take-profit order type */ ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for this WS API request. */ - authIsOptional?: boolean | undefined; - /** Optional caller-supplied correlation id. Generated automatically when omitted. */ - cid?: string; -} +/** Stop-loss trigger price */ ⋮---- -/** If true, will skip auth requirement for this WS API request. */ +/** Stop-loss order price */ ⋮---- -/** Optional caller-supplied correlation id. Generated automatically when omitted. */ +/** Stop-loss order type */ ⋮---- -interface WsEndpointParts { - url: string; - host: string; - path: string; -} +/** Price protection when setting tp/sl */ ⋮---- -interface WSAPIInflightRequestRef { - wsKey: WSAPIWsKey; - operation: WSAPIOperation; - cid: string; +/** 0: allow self-trade, 1: prevent (default) */ +⋮---- +/** cancel_taker, cancel_maker, cancel_both */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_cross_order. Cross margin only. One of contract_code or (pair+contract_type) required. */ +export interface FuturesCrossSubmitOrderReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit if pair+contract_type */ + contract_code?: string; + /** Pair (e.g. BTC-USDT). Use with contract_type */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** buy or sell */ + direction: FuturesDirection; + /** Order quantity */ + volume: number; + /** Leverage rate */ + lever_rate: number; + /** Order price type */ + order_price_type: FuturesSubmitOrderPriceType; + /** open, close, both. Required in hedge mode */ + offset?: FuturesOffsetBoth; + /** Price. Required for limit, post_only, ioc, fok */ + price?: number | string; + /** 0: no, 1: yes */ + reduce_only?: 0 | 1; + /** Client order ID [1, 9223372036854775807] */ + client_order_id?: number; + /** Take-profit trigger price */ + tp_trigger_price?: number | string; + /** Take-profit order price */ + tp_order_price?: number | string; + /** Take-profit order type */ + tp_order_price_type?: string; + /** Stop-loss trigger price */ + sl_trigger_price?: number | string; + /** Stop-loss order price */ + sl_order_price?: number | string; + /** Stop-loss order type */ + sl_order_price_type?: string; + /** 0: allow self-trade, 1: prevent (default) */ + self_match_prevent?: 0 | 1; + /** cancel_taker, cancel_maker, cancel_both */ + self_match_prevent_new?: FuturesSelfMatchPrevent; } ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit if pair+contract_type */ ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- -// For most connections, heartbeats are messages for HTX, not WS-level frames +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** - * Request connection of all market/private sockets that are useful for subscriptions. - * Trade-command sockets are intentionally opened lazily by sendWSAPIRequest(). - */ -public connectAll(): Promise[] +/** buy or sell */ ⋮---- -/** - * Ensures a WS API connection is active and, unless skipped, authenticated. - */ -public connectWSAPI( - wsKey: WSAPIWsKey = WS_KEY_MAP.spotTrade, - skipAuth?: boolean, -): Promise +/** Order quantity */ ⋮---- -public subscribe( - requests: - | (WSTopicRequest | WSTopic) - | (WSTopicRequest | WSTopic)[], - wsKey: WsKey, -) +/** Leverage rate */ ⋮---- -public unsubscribe( - requests: - | (WSTopicRequest | WSTopic) - | (WSTopicRequest | WSTopic)[], - wsKey: WsKey, -) +/** Order price type */ ⋮---- -/** - * WS API Methods - similar to the REST API, but via WebSockets - */ +/** open, close, both. Required in hedge mode */ ⋮---- -/** - * Send a Websocket API event on a connection. Returns a promise that resolves on reply. - * - * 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). - * - * After a fresh connection, you should always send a login request first. - * - * If you authenticated once and you're reconnected later (e.g. connection temporarily lost), the SDK will by default automatically: - * - Detect you were authenticated to the WS API before - * - Try to re-authenticate (up to 5 times, in case something (bad timestamp) goes wrong) - * - If it succeeds, it will emit the 'authenticated' event. - * - If it fails and gives up, it will emit an 'exception' event (type: 'wsapi.auth', reason: detailed text). - * - * You can turn off the automatic re-auth WS API logic using `reauthWSAPIOnReconnect: false` in the WSClient config. - * - * @param wsKey - The connection this event is for. - * @param channel - The channel this event is for (e.g. "spot.login" to authenticate) - * @param params - Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs. - * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response - */ -async sendWSAPIRequest< - TWSKey extends keyof WSAPIWsKeyTopicMap, - TWSOperation extends keyof WSAPITopicRequestParamMap & - WSAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact, - TWSAPIResponse extends WSAPITopicResponseMap[TWSOperation] | object = - WSAPITopicResponseMap[TWSOperation], - >( - wsKey: TWSKey, - operation: TWSOperation, - params?: TWSParams, - requestFlags?: WSAPIRequestFlags, - ): Promise; +/** Price. Required for limit, post_only, ioc, fok */ ⋮---- -async sendWSAPIRequest< - TWSKey extends keyof WSAPIWsKeyTopicMap, - TWSOperation extends keyof WSAPITopicRequestParamMap & - WSAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact, - TWSAPIResponse extends WSAPITopicResponseMap[TWSOperation] | object = - WSAPITopicResponseMap[TWSOperation], - >( - wsKey: TWSKey, - operation: TWSOperation, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, -): Promise +/** 0: no, 1: yes */ ⋮---- -// Used by other exchanges for commands that don't require authentication. +/** Client order ID [1, 9223372036854775807] */ ⋮---- -protected isCustomReconnectionNeeded(): boolean +/** Take-profit trigger price */ ⋮---- -public generateNewOrderID(): string +/** Take-profit order price */ ⋮---- -public getOrderIdPrefix(): string +/** Take-profit order type */ ⋮---- -protected async triggerCustomReconnectionWorkflow(): Promise +/** Stop-loss trigger price */ ⋮---- -protected async getWsUrl(wsKey: WsKey): Promise +/** Stop-loss order price */ ⋮---- -protected sendPingEvent(wsKey: WsKey, ws: WebSocketLike): boolean +/** Stop-loss order type */ ⋮---- -// These WS Keys use native ping frames, since the JSON ping is not supported for these websocket endpoints (confirmed by HTX) +/** 0: allow self-trade, 1: prevent (default) */ ⋮---- -protected sendPongEvent(wsKey: WsKey, _ws: WebSocketLike, event?: unknown) +/** cancel_taker, cancel_maker, cancel_both */ ⋮---- -protected isWsPing(event: unknown): boolean +/** Req for POST /linear-swap-api/v1/swap_batchorder. Isolated. Max 10 orders. */ +export interface FuturesSubmitBatchOrderReq { + orders_data: FuturesSubmitOrderReq[]; +} ⋮---- -protected isWsPong(event: unknown): boolean +/** Req for POST /linear-swap-api/v1/swap_cross_batchorder. Cross. Max 25 orders. */ +export interface FuturesSubmitCrossBatchOrderReq { + orders_data: FuturesCrossSubmitOrderReq[]; +} ⋮---- -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] +/** Req for POST /linear-swap-api/v1/swap_cancel. Isolated. One of order_id or client_order_id required. Max 25 IDs. */ +export interface FuturesCancelOrderReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract_code: string; + /** Order IDs, comma-separated. Max 25 */ + order_id?: string; + /** Client order IDs, comma-separated. Max 25 */ + client_order_id?: string; +} ⋮---- -protected isPrivateTopicRequest( - request: WSTopicRequest, - wsKey: WsKey, -): boolean +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -protected getPrivateWSKeys(): WsKey[] +/** Order IDs, comma-separated. Max 25 */ ⋮---- -protected authPrivateConnectionsOnConnect(wsKey: WsKey): boolean +/** Client order IDs, comma-separated. Max 25 */ ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +/** Req for POST /linear-swap-api/v1/swap_cross_cancel. Cross. One of order_id/client_order_id and one of contract_code/(pair+contract_type) required. */ +export interface FuturesCancelCrossOrderReq { + /** Order IDs, comma-separated. Max 25 */ + order_id?: string; + /** Client order IDs, comma-separated. Max 25 */ + client_order_id?: string; + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; +} ⋮---- -protected getMaxTopicsPerSubscribeEvent(): number | null +/** Order IDs, comma-separated. Max 25 */ ⋮---- -protected async getWsRequestEvents( - wsKey: WsKey, - operation: WSOperation, - requests: WSTopicRequest[], -): Promise[]> +/** Client order IDs, comma-separated. Max 25 */ ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, -): Promise +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -private getWsApiRequestEvent< - TWSKey extends keyof WSAPIWsKeyTopicMap, - TWSOperation extends keyof WSAPITopicRequestParamMap & - WSAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact, - >( - wsKey: TWSKey, - operation: TWSOperation, - params: TWSParams | undefined, - cid: string, -): HTXWSAPIRawRequest +/** Pair (e.g. BTC-USDT) */ ⋮---- -private resolveWSAPIResponse( - wsKey: WsKey, - parsed: ParsedWsMessage, -): EmittableEvent[] +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -private async getSpotAuthParams(wsKey: WsKey): Promise +/** Req for POST /linear-swap-api/v1/swap_cancelall. Isolated. One of direction or offset optional. */ +export interface FuturesCancelAllOrdersReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract_code: string; + /** buy or sell. Omit for all */ + direction?: FuturesDirection; + /** open or close. Omit for all */ + offset?: FuturesOffset; +} ⋮---- -private async getDerivativesAuthParams( - wsKey: WsKey, -): Promise +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -private async signHtxParams( - host: string, - path: string, - params: Record, -): Promise +/** buy or sell. Omit for all */ ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: SignEncodeMethod, - algorithm: SignAlgorithm, -): Promise +/** open or close. Omit for all */ ⋮---- -private getSignatureMethod(): 'HmacSHA256' | 'Ed25519' +/** Req for POST /linear-swap-api/v1/swap_cross_cancelall. Cross. One of contract_code or (pair+contract_type) required. */ +export interface FuturesCancelCrossAllOrdersReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** buy or sell. Omit for all */ + direction?: FuturesDirection; + /** open or close. Omit for all */ + offset?: FuturesOffset; +} ⋮---- -private getTimestampForSignature(): string +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -private async getWsEndpointParts(wsKey: WsKey): Promise +/** Pair (e.g. BTC-USDT) */ ⋮---- -private getWsNetwork(): HtxWSNetwork +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -private isMarketProtocolWsKey(wsKey: WsKey): boolean +/** buy or sell. Omit for all */ ⋮---- -private isSpotPrivateProtocolWsKey(wsKey: WsKey): boolean +/** open or close. Omit for all */ ⋮---- -private isDerivativesTopicProtocolWsKey(wsKey: WsKey): boolean +/** Req for POST /linear-swap-api/v1/swap_cross_switch_lever_rate. Cross margin only. One of contract_code or (pair+contract_type) required. */ +export interface FuturesUpdateCrossLeverageReq { + /** Leverage multiple. Required */ + lever_rate: number; + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; +} ⋮---- -private isDerivativesOperationProtocolWsKey(wsKey: WsKey): boolean +/** Leverage multiple. Required */ ⋮---- -private parseWsMessage(event: unknown): ParsedWsMessage | undefined +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -private getHeartbeatTimestamp(parsed?: ParsedWsMessage): string | number +/** Pair (e.g. BTC-USDT) */ ⋮---- -private getPayloadRecord(payload: unknown): Record +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -private getPayloadStringOrNumber( - payload: Record, - key: string, -): string | number | undefined +/** Req for POST /linear-swap-api/v1/swap_order_info. Isolated. One of order_id or client_order_id required. Max 50 IDs. */ +export interface FuturesGetOrderInfoReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract_code: string; + /** Order IDs, comma-separated. Max 50 */ + order_id?: string; + /** Client order IDs, comma-separated. Max 50 */ + client_order_id?: string; +} ⋮---- -private isAuthResponse(parsed: ParsedWsMessage): boolean +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -private isWSAPIResponse(wsKey: WsKey, parsed: ParsedWsMessage): boolean +/** Order IDs, comma-separated. Max 50 */ ⋮---- -private isSubscriptionResponse(parsed: ParsedWsMessage): boolean +/** Client order IDs, comma-separated. Max 50 */ ⋮---- -private isRequestResponse(parsed: ParsedWsMessage): boolean +/** Req for POST /linear-swap-api/v1/swap_cross_order_info. Cross. One of order_id/client_order_id and one of contract_code/pair required. */ +export interface FuturesGetCrossOrderInfoReq { + /** Order IDs, comma-separated. Max 50 */ + order_id?: string; + /** Client order IDs, comma-separated. Max 50 */ + client_order_id?: string; + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; +} ⋮---- -private isErrorEvent(parsed: ParsedWsMessage): boolean +/** Order IDs, comma-separated. Max 50 */ ⋮---- -private getEventOperation(parsed: ParsedWsMessage): string | undefined +/** Client order IDs, comma-separated. Max 50 */ ⋮---- -private trackWSAPIRequestRef( - promiseRef: string, - wsKey: WSAPIWsKey, - operation: WSAPIOperation, - cid: string, -): void +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -private getPromiseRefForWSAPIResponse( - wsKey: WsKey, - parsed: ParsedWsMessage, -): string | undefined +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** - * - * Misc Utility Methods - * - */ +/** Req for POST /linear-swap-api/v1/swap_order_detail. Isolated. Order details with trades. */ +export interface FuturesGetOrderDetailReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract_code: string; + /** Order ID. Required */ + order_id: number | string; + /** Created timestamp (ms). Improves query performance. Cannot be 0 */ + created_at?: number; + /** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ + order_type?: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -/** - * Validate syntax meets requirements set by HTX. - * Log warning if not. - */ -public validateOrderId( - params: SpotV1OrderPlaceReq | SpotV1OrderAutoPlaceReq, - orderIdProperty: OrderIdProperty, -): void - -================ -File: src/types/request/futures.types.ts -================ -/** - * Union Types (Request) - */ +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -/** Pagination direction */ -export type FuturesDirect = 'next' | 'prev'; +/** Order ID. Required */ ⋮---- -/** Buy or sell */ -export type FuturesDirection = 'buy' | 'sell'; +/** Created timestamp (ms). Improves query performance. Cannot be 0 */ ⋮---- -/** Open or close position */ -export type FuturesOffset = 'open' | 'close'; +/** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ ⋮---- -/** Open, close, or both (hedge mode) */ -export type FuturesOffsetBoth = 'open' | 'close' | 'both'; +/** Page index. Default 1 */ ⋮---- -/** Position side (long, short, both) */ -export type FuturesPositionSide = 'long' | 'short' | 'both'; +/** Page size. Default 20, max 50 */ ⋮---- -/** Margin mode */ -export type FuturesMarginMode = 'cross' | 'isolated'; +/** Req for POST /linear-swap-api/v1/swap_cross_order_detail. Cross. One of contract_code or pair required. */ +export interface FuturesGetCrossOrderDetailReq { + /** Order ID. Required */ + order_id: number | string; + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** Created timestamp (ms). Cannot be 0 */ + created_at?: number; + /** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ + order_type?: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; +} ⋮---- -/** Margin mode including all */ -export type FuturesMarginModeAll = 'cross' | 'isolated' | 'all'; +/** Order ID. Required */ ⋮---- -/** Business type filter */ -export type FuturesBusinessType = 'futures' | 'swap' | 'all'; +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -/** Contract type (delivery) */ -export type FuturesContractType = - | 'this_week' - | 'next_week' - | 'quarter' - | 'next_quarter'; +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** Kline period */ -export type FuturesKlinePeriod = - | '1min' - | '5min' - | '15min' - | '30min' - | '60min' - | '1hour' - | '4hour' - | '12hour' - | '1day' - | '1week' - | '1mon'; +/** Created timestamp (ms). Cannot be 0 */ ⋮---- -/** Open interest / funding period */ -export type FuturesOpenInterestPeriod = '60min' | '4hour' | '12hour' | '1day'; +/** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ ⋮---- -/** Sort field */ -export type FuturesSortBy = 'created_at' | 'update_time'; +/** Page index. Default 1 */ ⋮---- -/** Sort field (extended) */ -export type FuturesSortByExtended = - | 'create_date' - | 'update_time' - | 'created_at'; +/** Page size. Default 20, max 50 */ ⋮---- -/** Sort field (CmPerp) */ -export type FuturesSortByCmPerp = 'create_date' | 'update_time'; +/** Req for POST /linear-swap-api/v1/swap_openorders. Isolated. Current unfilled orders. */ +export interface FuturesGetOpenOrdersReq { + /** Contract code (e.g. BTC-USDT). Omit for all */ + contract_code?: string; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** created_at or update_time. Default created_at */ + sort_by?: FuturesSortBy; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; +} ⋮---- -/** Trigger condition */ -export type FuturesTriggerType = 'ge' | 'le'; +/** Contract code (e.g. BTC-USDT). Omit for all */ ⋮---- -/** Basis price type */ -export type FuturesBasisPriceType = - | 'open' - | 'close' - | 'high' - | 'low' - | 'average'; +/** Page index. Default 1 */ ⋮---- -/** Transfer type */ -export type FuturesTransferType = 'master_to_sub' | 'sub_to_master'; +/** Page size. Default 20, max 50 */ ⋮---- -/** Margin adjust type */ -export type FuturesMarginAdjustType = 'add' | 'reduce'; +/** created_at or update_time. Default created_at */ ⋮---- -/** Self-match prevention */ -export type FuturesSelfMatchPrevent = - | 'cancel_taker' - | 'cancel_maker' - | 'cancel_both'; +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Lightning order price type */ -export type FuturesLightningOrderPriceType = - | 'market' - | 'lightning_fok' - | 'lightning_ioc'; +/** Req for POST /linear-swap-api/v1/swap_cross_openorders. Cross. Omit all for all contracts. */ +export interface FuturesGetCrossOpenOrdersReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** created_at or update_time */ + sort_by?: FuturesSortBy; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; +} ⋮---- -/** Lightning order price type (CmDelivery) */ -export type FuturesLightningOrderPriceTypeCm = - | 'lightning' - | 'lightning_fok' - | 'lightning_ioc'; +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -/** Trigger order price type */ -export type FuturesTriggerOrderPriceType = - | 'limit' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20'; +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** Trailing order price type */ -export type FuturesTrailingOrderPriceType = - | 'optimal_5' - | 'optimal_10' - | 'optimal_20' - | 'formula_price'; +/** Page index. Default 1 */ ⋮---- -/** V5 order type */ -export type FuturesV5OrderType = 'market' | 'limit' | 'post_only'; +/** Page size. Default 20, max 50 */ ⋮---- -/** Time in force. `rpi` places an RPI order. */ -export type FuturesTimeInForce = 'fok' | 'ioc' | 'gtc' | 'rpi'; +/** created_at or update_time */ ⋮---- -/** Trigger price type */ -export type FuturesTriggerPriceType = 'last' | 'market'; +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Price match type */ -export type FuturesPriceMatch = - | 'opponent' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20'; +/** Req for POST /linear-swap-api/v3/swap_hisorders. Isolated. History orders. */ +export interface FuturesGetHistoryOrdersReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract: string; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** 1: All Orders, 2: Order in Finished Status */ + type: 1 | 2; + /** 0: all, or comma-separated e.g. "3,4,5" */ + status: string; + /** Start time (ms). Window max 48h, within 90 days */ + start_time?: number; + /** End time (ms). Default now */ + end_time?: number; + /** next or prev. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; +} ⋮---- -/** Base order price types: limit, opponent, optimal_*, ioc, fok, *_ioc, *_fok */ -export type FuturesOrderPriceTypeBase = - | 'limit' - | 'opponent' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20' - | 'ioc' - | 'fok' - | 'opponent_ioc' - | 'optimal_5_ioc' - | 'optimal_10_ioc' - | 'optimal_20_ioc' - | 'opponent_fok' - | 'optimal_5_fok' - | 'optimal_10_fok' - | 'optimal_20_fok'; +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -/** Order price type for swap_order and swap_cross_order. Base + market + post_only */ -export type FuturesSubmitOrderPriceType = - | FuturesOrderPriceTypeBase - | 'market' - | 'post_only'; +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Order price type for swap_order_limit and contract_order_limit. Base + lightning variants */ -export type FuturesGetOrderLimitPriceType = - | FuturesOrderPriceTypeBase - | 'lightning' - | 'lightning_ioc' - | 'lightning_fok'; -⋮---- -/** Order price type for contract_order_limit (alias) */ -export type FuturesCmDeliveryOrderLimitPriceType = - FuturesGetOrderLimitPriceType; -⋮---- -/** Order price type for contract_order and swap_order (Delivery/CMPerp). Base + post_only */ -export type FuturesCmDeliverySubmitOrderPriceType = - | FuturesOrderPriceTypeBase - | 'post_only'; -⋮---- -/** Order price type for swap_order and swap_batchorder (CMPerp) (alias) */ -export type FuturesCmPerpSubmitOrderPriceType = - FuturesCmDeliverySubmitOrderPriceType; +/** 1: All Orders, 2: Order in Finished Status */ ⋮---- -/** - * Reference Data - */ +/** 0: all, or comma-separated e.g. "3,4,5" */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_historical_funding_rate */ -export interface FuturesGetHistoricalFundingRateReq { - /** Contract code (e.g. BTC-USDT). Case-insensitive */ - contract_code: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; -} +/** Start time (ms). Window max 48h, within 90 days */ ⋮---- -/** Contract code (e.g. BTC-USDT). Case-insensitive */ +/** End time (ms). Default now */ ⋮---- -/** Page index. Default 1 */ +/** next or prev. Default prev */ ⋮---- -/** Page size. Default 20, max 50 */ +/** Pagination: min/max query_id from last result */ ⋮---- -/** Req for GET /linear-swap-api/v3/swap_liquidation_orders. One of pair and contract must be filled; contract preferred. */ -export interface FuturesGetLiquidationOrdersReq { - /** Contract code (e.g. BTC-USDT). Case-insensitive */ +/** Req for POST /linear-swap-api/v3/swap_hisorders_exact. Isolated. History orders via multiple fields; adds price_type filter. */ +export interface FuturesGetHistoryOrdersExactReq { + /** Contract code (e.g. BTC-USDT). Required */ contract: string; - /** 0:All; 1:Open long; 2:Open short; 3:Close short; 4:Close long; 5:Liquidate long; 6:Liquidate short; 17:buy(one-way); 18:sell(one-way) */ - trade_type: number; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** Query start time (ms). Window max 2h, within 90 days */ + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** 1: All Orders, 2: Order in Finished Status */ + type: 1 | 2; + /** 0: all, or comma-separated e.g. "3,4,5" */ + status: string; + /** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ + price_type?: string; + /** Start time (ms). Window max 48h, within 90 days */ start_time?: number; - /** Query end time (ms). Default now. Within 90 days */ + /** End time (ms). Default now */ end_time?: number; - /** next=chronological, prev=reverse. Default prev */ + /** next or prev. Default prev */ direct?: FuturesDirect; - /** Search from query_id for pagination */ + /** Pagination: min/max query_id from last result */ from_id?: number; } ⋮---- -/** Contract code (e.g. BTC-USDT). Case-insensitive */ -⋮---- -/** 0:All; 1:Open long; 2:Open short; 3:Close short; 4:Close long; 5:Liquidate long; 6:Liquidate short; 17:buy(one-way); 18:sell(one-way) */ +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** Query start time (ms). Window max 2h, within 90 days */ +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Query end time (ms). Default now. Within 90 days */ +/** 1: All Orders, 2: Order in Finished Status */ ⋮---- -/** next=chronological, prev=reverse. Default prev */ +/** 0: all, or comma-separated e.g. "3,4,5" */ ⋮---- -/** Search from query_id for pagination */ +/** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_settlement_records */ -export interface FuturesGetSettlementRecordsReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code: string; - /** Start time (ms). Default: now - 90 days. Within 90 days */ +/** Start time (ms). Window max 48h, within 90 days */ +⋮---- +/** End time (ms). Default now */ +⋮---- +/** next or prev. Default prev */ +⋮---- +/** Pagination: min/max query_id from last result */ +⋮---- +/** Req for POST /linear-swap-api/v3/swap_cross_hisorders_exact. Cross. History orders via multiple fields; adds price_type filter. */ +export interface FuturesGetCrossHistoryOrdersExactReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. When both pair and contract filled, contract preferred */ + contract: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** 1: All Orders, 2: Order in Finished Status */ + type: 1 | 2; + /** 0: all, or comma-separated e.g. "3,4,5" */ + status: string; + /** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ + price_type?: string; + /** Start time (ms). Window max 48h, within 90 days */ start_time?: number; - /** End time (ms). Default: now. Must be after start_time */ + /** End time (ms). Default now */ end_time?: number; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; + /** next or prev. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. When both pair and contract filled, contract preferred */ ⋮---- -/** Start time (ms). Default: now - 90 days. Within 90 days */ +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** End time (ms). Default: now. Must be after start_time */ +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Page index. Default 1 */ +/** 1: All Orders, 2: Order in Finished Status */ ⋮---- -/** Page size. Default 20, max 50 */ +/** 0: all, or comma-separated e.g. "3,4,5" */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_cross_ladder_margin. When all filled, contract_code preferred. business_type required for futures. */ -export interface FuturesGetCrossTieredMarginReq { - /** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; +/** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ +⋮---- +/** Start time (ms). Window max 48h, within 90 days */ +⋮---- +/** End time (ms). Default now */ +⋮---- +/** next or prev. Default prev */ +⋮---- +/** Pagination: min/max query_id from last result */ +⋮---- +/** Req for POST /linear-swap-api/v3/swap_cross_hisorders. Cross. One of contract or pair required. */ +export interface FuturesGetCrossHistoryOrdersReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** Default swap. futures, swap, all. Required for futures contract query */ - business_type?: FuturesBusinessType; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** 1: All Orders, 2: Order in Finished Status */ + type: 1 | 2; + /** 0: all, or comma-separated e.g. "3,4,5" */ + status: string; + /** Start time (ms). Window max 48h, within 90 days */ + start_time?: number; + /** End time (ms). Default now */ + end_time?: number; + /** next or prev. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; } ⋮---- -/** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Default swap. futures, swap, all. Required for futures contract query */ +/** 1: All Orders, 2: Order in Finished Status */ ⋮---- -export type FuturesGetEstimatedSettlementPriceReq = - FuturesGetCrossTieredMarginReq; -export type FuturesGetCrossAdjustFactorReq = FuturesGetCrossTieredMarginReq; -export type FuturesGetContractPriceLimitReq = FuturesGetCrossTieredMarginReq; -export type FuturesGetOpenInterestReq = FuturesGetCrossTieredMarginReq; +/** 0: all, or comma-separated e.g. "3,4,5" */ ⋮---- -/** Req for GET /v1/insurance_fund_history */ -export interface FuturesGetRiskReserveHistoryReq { - /** Query start time (ms) */ +/** Start time (ms). Window max 48h, within 90 days */ +⋮---- +/** End time (ms). Default now */ +⋮---- +/** next or prev. Default prev */ +⋮---- +/** Pagination: min/max query_id from last result */ +⋮---- +/** Req for POST /linear-swap-api/v3/swap_matchresults. getFills. Isolated. One of contract or pair required. */ +export interface FuturesGetFillsReq { + /** Contract code (e.g. BTC-USDT) */ + contract?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** Start time (ms). Window max 48h, within 90 days */ start_time?: number; - /** Query end time (ms) */ + /** End time (ms). Default now */ end_time?: number; - /** next=chronological, prev=reverse. Default prev */ + /** next or prev. Default prev */ direct?: FuturesDirect; - /** Pagination: min/max query_id from last result depending on direct */ + /** Pagination: min/max query_id from last result */ from_id?: number; - /** Items per page [1-100]. Default 10 */ - limit?: number; } ⋮---- -/** Query start time (ms) */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** Query end time (ms) */ +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** next=chronological, prev=reverse. Default prev */ +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Pagination: min/max query_id from last result depending on direct */ +/** Start time (ms). Window max 48h, within 90 days */ ⋮---- -/** Items per page [1-100]. Default 10 */ +/** End time (ms). Default now */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_contract_info. When isolated, contract_type/business_type cannot be futures. */ -export interface FuturesGetContractInfoReq { - /** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; - /** cross, isolated, or all. Filter by supported margin mode */ - support_margin_mode?: FuturesMarginModeAll; +/** next or prev. Default prev */ +⋮---- +/** Pagination: min/max query_id from last result */ +⋮---- +/** Req for POST /linear-swap-api/v3/swap_cross_matchresults. getCrossFills. Cross. One of contract or pair required. */ +export interface FuturesGetCrossFillsReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** Default swap. futures, swap, all. Required for futures query */ - business_type?: FuturesBusinessType; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** Start time (ms). Window max 48h, within 90 days */ + start_time?: number; + /** End time (ms). Default now */ + end_time?: number; + /** next or prev. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; } ⋮---- -/** Contract code. Omit for all. swap: BTC-USDT; future: BTC-USDT-210625 */ -⋮---- -/** cross, isolated, or all. Filter by supported margin mode */ +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Default swap. futures, swap, all. Required for futures query */ +/** Start time (ms). Window max 48h, within 90 days */ ⋮---- -/** - * Market Data - */ +/** End time (ms). Default now */ ⋮---- -/** Req for GET /linear-swap-ex/market/history/kline. Either size or (from+to) required. */ -export interface FuturesGetKlinesReq { - /** Contract code or type. swap: BTC-USDT; future: BTC-USDT-220325 or BTC-USDT-CW/NW/CQ/NQ */ - contract_code: string; - /** 1min, 5min, 15min, 30min, 60min, 1hour, 4hour, 1day, 1mon */ - period: FuturesKlinePeriod; - /** Items [1-2000]. Default 150. Ignored if from+to provided */ - size?: number; - /** Start timestamp (seconds) */ - from?: number; - /** End timestamp (seconds). Required if from provided */ - to?: number; -} -⋮---- -/** Contract code or type. swap: BTC-USDT; future: BTC-USDT-220325 or BTC-USDT-CW/NW/CQ/NQ */ +/** next or prev. Default prev */ ⋮---- -/** 1min, 5min, 15min, 30min, 60min, 1hour, 4hour, 1day, 1mon */ +/** Pagination: min/max query_id from last result */ ⋮---- -/** Items [1-2000]. Default 150. Ignored if from+to provided */ +/** Req for POST /linear-swap-api/v3/swap_matchresults_exact. getFillsExact. Isolated. No pair param. */ +export interface FuturesGetFillsExactReq { + /** Contract code (e.g. BTC-USDT). Required */ + contract: string; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** Start time (ms). Window max 48h, within 90 days */ + start_time?: number; + /** End time (ms). Default now */ + end_time?: number; + /** next or prev. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; +} ⋮---- -/** Start timestamp (seconds) */ +/** Contract code (e.g. BTC-USDT). Required */ ⋮---- -/** End timestamp (seconds). Required if from provided */ +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_his_open_interest. One of (pair+contract_type) or contract_code required. */ -export interface FuturesGetHistoricalOpenInterestReq { - /** Contract code. Omit if pair+contract_type provided */ - contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** 60min, 4hour, 12hour, 1day */ - period: FuturesOpenInterestPeriod; - /** Items [1-200]. Default 48 */ - size?: number; - /** 1: cont, 2: cryptocurrency */ - amount_type: 1 | 2; -} +/** Start time (ms). Window max 48h, within 90 days */ ⋮---- -/** Contract code. Omit if pair+contract_type provided */ +/** End time (ms). Default now */ ⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** next or prev. Default prev */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Pagination: min/max query_id from last result */ ⋮---- -/** 60min, 4hour, 12hour, 1day */ +/** Req for POST /linear-swap-api/v3/swap_cross_matchresults_exact. getCrossFillsExact. Cross. When both filled, contract preferred. */ +export interface FuturesGetCrossFillsExactReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ + contract: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; + /** Start time (ms). Window max 48h, within 90 days */ + start_time?: number; + /** End time (ms). Default now */ + end_time?: number; + /** next or prev. Default prev */ + direct?: FuturesDirect; + /** Pagination: min/max query_id from last result */ + from_id?: number; +} ⋮---- -/** Items [1-200]. Default 48 */ +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ ⋮---- -/** 1: cont, 2: cryptocurrency */ +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** Req for GET /index/market/history/linear_swap_mark_price_kline. Also used for premium index and estimated rate kline. */ -export interface FuturesGetMarkKlinesReq { - /** Contract code or type. swap: BTC-USDT; future: BTC-USDT-210625 or BTC-USDT-CW/NW/CQ/NQ */ - contract_code: string; - /** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1week, 1mon */ - period: string; - /** Items [1-2000] */ - size: number; -} +/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Contract code or type. swap: BTC-USDT; future: BTC-USDT-210625 or BTC-USDT-CW/NW/CQ/NQ */ +/** Start time (ms). Window max 48h, within 90 days */ ⋮---- -/** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1week, 1mon */ +/** End time (ms). Default now */ ⋮---- -/** Items [1-2000] */ +/** next or prev. Default prev */ ⋮---- -export type FuturesGetPremiumIndexKlinesReq = FuturesGetMarkKlinesReq; -export type FuturesGetFundingRateKlinesReq = FuturesGetMarkKlinesReq; +/** Pagination: min/max query_id from last result */ ⋮---- -/** Req for GET /index/market/history/linear_swap_basis */ -export interface FuturesGetBasisDataReq { - /** Contract code or type */ +/** Req for POST /linear-swap-api/v1/swap_lightning_close_position. Isolated. Lightning close order. */ +export interface FuturesSubmitLightningCloseOrderReq { + /** Contract code (e.g. BTC-USDT). Case-insensitive */ contract_code: string; - /** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1mon */ - period: FuturesKlinePeriod; - /** Items [1-2000]. Default 150 */ - size: number; - /** open, close, high, low, average. Default open */ - basis_price_type?: FuturesBasisPriceType; + /** buy: open, sell: close */ + direction: FuturesDirection; + /** Client order ID. Unique per API, user-maintained */ + client_order_id?: number; + /** market (default), lightning_fok, lightning_ioc */ + order_price_type?: FuturesLightningOrderPriceType; } ⋮---- -/** Contract code or type */ -⋮---- -/** 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1mon */ +/** Contract code (e.g. BTC-USDT). Case-insensitive */ ⋮---- -/** Items [1-2000]. Default 150 */ +/** buy: open, sell: close */ ⋮---- -/** open, close, high, low, average. Default open */ +/** Client order ID. Unique per API, user-maintained */ ⋮---- -/** - * Account - */ +/** market (default), lightning_fok, lightning_ioc */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_position_info */ -export interface FuturesGetCrossPositionsReq { - /** Contract code. Omit for all */ +/** Req for POST /linear-swap-api/v1/swap_cross_lightning_close_position. Cross. One of (pair+contract_type) or contract_code required. */ +export interface FuturesSubmitCrossLightningCloseOrderReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Preferred when all filled */ contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; /** swap, this_week, next_week, quarter, next_quarter */ contract_type?: string; + /** buy or sell */ + direction: FuturesDirection; + /** Client order ID [1, 9223372036854775807] */ + client_order_id?: number; + /** market (default), lightning_fok, lightning_ioc */ + order_price_type?: FuturesLightningOrderPriceType; } ⋮---- -/** Contract code. Omit for all */ +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Preferred when all filled */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- /** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_sub_auth_list. getSubPermissions. */ -export interface FuturesGetSubPermissionsReq { - /** Sub-account UIDs, comma-separated. Max 10 */ - sub_uid?: string; - /** Start time of sub-account creation (ms) */ - start_time?: number; - /** End time of sub-account creation (ms) */ - end_time?: number; - /** next=chronological, prev=reverse */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; -} -⋮---- -/** Sub-account UIDs, comma-separated. Max 10 */ -⋮---- -/** Start time of sub-account creation (ms) */ -⋮---- -/** End time of sub-account creation (ms) */ +/** buy or sell */ ⋮---- -/** next=chronological, prev=reverse */ +/** Client order ID [1, 9223372036854775807] */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** market (default), lightning_fok, lightning_ioc */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_sub_account_list. Isolated margin only. */ -export interface FuturesGetIsolatedSubAccountsReq { - /** Contract code (e.g. BTC-USDT). Omit for all */ +/** Req for GET /linear-swap-api/v1/swap_cross_trade_state. Cross margin only. */ +export interface FuturesGetCrossTradeStateReq { + /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ contract_code?: string; - /** next=chronological, prev=reverse. Default next */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result depending on direct */ - from_id?: number; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** futures, swap, all. Required for futures. Default swap */ + business_type?: FuturesBusinessType; } ⋮---- -/** Contract code (e.g. BTC-USDT). Omit for all */ -⋮---- -/** next=chronological, prev=reverse. Default next */ -⋮---- -/** Pagination: min/max query_id from last result depending on direct */ +/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_sub_account_list. Cross margin only. */ -export interface FuturesGetCrossSubAccountsReq { - /** Margin account (e.g. USDT). Omit for all */ - margin_account?: string; - /** next=chronological, prev=reverse. Default next */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result depending on direct */ - from_id?: number; -} +/** Pair (e.g. BTC-USDT) */ ⋮---- -/** Margin account (e.g. USDT). Omit for all */ +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** next=chronological, prev=reverse. Default next */ +/** futures, swap, all. Required for futures. Default swap */ ⋮---- -/** Pagination: min/max query_id from last result depending on direct */ +/** + * Swap Strategy Order Interface + */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_sub_account_info_list. Isolated margin only. */ -export interface FuturesGetSubAccountsAssetsReq { - /** Contract code (e.g. BTC-USDT). Omit for all */ - contract_code?: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; +/** Req for POST /linear-swap-api/v1/swap_trigger_order. [Isolated] Submit Trigger Order. Isolated margin only. Trade. 5/s. */ +export interface FuturesSubmitTriggerOrderReq { + /** Contract type (e.g. BTC-USDT) */ + contract_code: string; + /** ge: Equal to or Greater than; le: Less than or Equal to */ + trigger_type: FuturesTriggerType; + /** Trigger price */ + trigger_price: number | string; + /** Order price (required when order_price_type is limit) */ + order_price?: number | string; + /** limit (default), optimal_5, optimal_10, optimal_20 */ + order_price_type?: FuturesTriggerOrderPriceType; + /** Volume (number of contracts) */ + volume: number; + /** buy or sell */ + direction: FuturesDirection; + /** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ + offset?: FuturesOffsetBoth; + /** Leverage. Must match current position leverage when holding. High leverage = high risk */ + lever_rate?: number; + /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ + reduce_only?: 0 | 1; } ⋮---- -/** Contract code (e.g. BTC-USDT). Omit for all */ +/** Contract type (e.g. BTC-USDT) */ ⋮---- -/** Page index. Default 1 */ +/** ge: Equal to or Greater than; le: Less than or Equal to */ ⋮---- -/** Page size. Default 20, max 50 */ +/** Trigger price */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_sub_account_info_list. Cross margin only. */ -export interface FuturesGetCrossSubAccountsAssetsReq { - /** Margin account (e.g. USDT). Omit for all */ - margin_account?: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; -} +/** Order price (required when order_price_type is limit) */ ⋮---- -/** Margin account (e.g. USDT). Omit for all */ +/** limit (default), optimal_5, optimal_10, optimal_20 */ ⋮---- -/** Page index. Default 1 */ +/** Volume (number of contracts) */ ⋮---- -/** Page size. Default 20, max 50 */ +/** buy or sell */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_sub_position_info. Cross margin only. */ -export interface FuturesGetCrossSubPositionsReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all. contract_code preferred when all filled */ +/** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ +⋮---- +/** Leverage. Must match current position leverage when holding. High leverage = high risk */ +⋮---- +/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_cross_trigger_order. [Cross] Submit Trigger Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ +export interface FuturesSubmitCrossTriggerOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ contract_code?: string; - /** Sub-account UID */ - sub_uid: number; - /** Pair (e.g. BTC-USDT) */ + /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; /** swap, this_week, next_week, quarter, next_quarter */ contract_type?: string; + /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ + reduce_only?: 0 | 1; + /** ge: Equal to or Greater than; le: Less than or Equal to */ + trigger_type: FuturesTriggerType; + /** Trigger price */ + trigger_price: number | string; + /** Order price (required when order_price_type is limit) */ + order_price?: number | string; + /** limit (default), optimal_5, optimal_10, optimal_20 */ + order_price_type?: FuturesTriggerOrderPriceType; + /** Volume (number of contracts) */ + volume: number; + /** buy or sell */ + direction: FuturesDirection; + /** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ + offset?: FuturesOffsetBoth; + /** Leverage. Long = short leverage. High leverage = high risk */ + lever_rate?: number; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all. contract_code preferred when all filled */ -⋮---- -/** Sub-account UID */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- /** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_financial_record. Supports cross and isolated. */ -export interface FuturesGetFinancialRecordsReq { - /** Margin account. swap: BTC-USDT, future: BTC-USDT-210625. Required */ - mar_acct: string; - /** Contract code (e.g. BTC-USDT). Omit for all */ - contract?: string; - /** Comma-separated type codes. Omit for all. e.g. 3,4,5,6 */ - type?: string; - /** Query start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** Query end time (ms). Default now. Within 90 days */ - end_time?: number; - /** next=chronological, prev=reverse. Default next */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result depending on direct */ - from_id?: number; -} +/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ ⋮---- -/** Margin account. swap: BTC-USDT, future: BTC-USDT-210625. Required */ +/** ge: Equal to or Greater than; le: Less than or Equal to */ ⋮---- -/** Contract code (e.g. BTC-USDT). Omit for all */ +/** Trigger price */ ⋮---- -/** Comma-separated type codes. Omit for all. e.g. 3,4,5,6 */ +/** Order price (required when order_price_type is limit) */ ⋮---- -/** Query start time (ms). Window max 48h, within 90 days */ +/** limit (default), optimal_5, optimal_10, optimal_20 */ ⋮---- -/** Query end time (ms). Default now. Within 90 days */ +/** Volume (number of contracts) */ ⋮---- -/** next=chronological, prev=reverse. Default next */ +/** buy or sell */ ⋮---- -/** Pagination: min/max query_id from last result depending on direct */ +/** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_financial_record_exact. Same params as swap_financial_record; API default direct is prev. */ -export type FuturesGetFinancialRecordsExactReq = FuturesGetFinancialRecordsReq; +/** Leverage. Long = short leverage. High leverage = high risk */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_available_level_rate. Cross margin only. */ -export interface FuturesGetCrossAvailableLeverageReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** futures, swap, all. Required for futures. Default swap */ - business_type?: FuturesBusinessType; +/** Req for POST /linear-swap-api/v1/swap_trigger_cancelall. [Isolated] Cancel All Trigger Orders. Isolated margin only. Trade. 5/s. Can fill only one of direction and offset to filter. */ +export interface FuturesCancelAllTriggerOrdersReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** Transaction direction; omit for all */ + direction?: FuturesDirection; + /** open, close; omit for all */ + offset?: FuturesOffset; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ -⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Transaction direction; omit for all */ ⋮---- -/** futures, swap, all. Required for futures. Default swap */ +/** open, close; omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_order_limit. Supports cross and isolated. */ -export interface FuturesGetOrderLimitReq { - /** Order price type. Required */ - order_price_type: FuturesGetOrderLimitPriceType; - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ +/** Req for POST /linear-swap-api/v1/swap_cross_trigger_cancelall. [Cross] Cancel All Trigger Orders. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. Can fill only one of direction and offset to filter. */ +export interface FuturesCancelAllCrossTriggerOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ contract_code?: string; - /** Pair (e.g. BTC-USDT) */ + /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; /** swap, this_week, next_week, quarter, next_quarter */ contract_type?: string; - /** futures, swap, all. Required for futures. Default swap */ - business_type?: FuturesBusinessType; + /** Transaction direction; omit for all */ + direction?: FuturesDirection; + /** open, close; omit for all */ + offset?: FuturesOffset; } ⋮---- -/** Order price type. Required */ -⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- /** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** futures, swap, all. Required for futures. Default swap */ +/** Transaction direction; omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_fee. Supports cross and isolated. */ -export interface FuturesGetFeeReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ +/** open, close; omit for all */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_cross_trigger_cancel. [Cross] Cancel Trigger Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ +export interface FuturesCancelCrossTriggerOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ contract_code?: string; - /** Pair (e.g. BTC-USDT) */ + /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; /** swap, this_week, next_week, quarter, next_quarter */ contract_type?: string; - /** futures, swap, all. Required for futures. Default swap */ - business_type?: FuturesBusinessType; + /** Order ID(s). Comma-separated, max 10 */ + order_id: string; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- /** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** futures, swap, all. Required for futures. Default swap */ +/** Order ID(s). Comma-separated, max 10 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_position_limit. Cross margin only. */ -export interface FuturesGetCrossPositionLimitReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** futures, swap, all. Required for futures. Default swap */ - business_type?: FuturesBusinessType; +/** Req for POST /linear-swap-api/v1/swap_trigger_openorders. [Isolated] Query Trigger Order Open Orders. Isolated margin only. Read. 5/s. */ +export interface FuturesGetTriggerOpenOrdersReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Page index. Default 1 */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Page size. Default 20, max 50 */ ⋮---- -/** futures, swap, all. Required for futures. Default swap */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_lever_position_limit. Cross margin only. */ -export interface FuturesGetCrossLeverageLimitsReq { - /** futures, swap, all. Required for futures */ - business_type?: FuturesBusinessType; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; +/** Req for POST /linear-swap-api/v1/swap_cross_trigger_openorders. [Cross] Query Trigger Order Open Orders. Cross margin only. When both pair and contract_code filled, contract_code preferred; when none, all open orders. Read. */ +export interface FuturesGetCrossTriggerOpenOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** Contract code. swap: BTC-USDT, future: BTC-USDT-211231. Omit for all */ - contract_code?: string; - /** Leverage rate. Omit for all */ - lever_rate?: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; } ⋮---- -/** futures, swap, all. Required for futures */ -⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-211231. Omit for all */ -⋮---- -/** Leverage rate. Omit for all */ -⋮---- -/** Req for POST /linear-swap-api/v1/swap_master_sub_transfer. Supports cross and isolated. */ -export interface FuturesTransferMasterSubReq { - /** Sub-account UID */ - sub_uid: number; - /** Asset (e.g. USDT) */ - asset: string; - /** From margin account (e.g. USDT, BTC-USDT) */ - from_margin_account: string; - /** To margin account */ - to_margin_account: string; - /** Transfer amount */ - amount: number | string; - /** master_to_sub or sub_to_master */ - type: FuturesTransferType; - /** Optional client order ID [1, 9223372036854775807]. Valid 8h per transfer path */ - client_order_id?: number; -} -⋮---- -/** Sub-account UID */ -⋮---- -/** Asset (e.g. USDT) */ -⋮---- -/** From margin account (e.g. USDT, BTC-USDT) */ -⋮---- -/** To margin account */ -⋮---- -/** Transfer amount */ +/** Page index. Default 1 */ ⋮---- -/** master_to_sub or sub_to_master */ +/** Page size. Default 20, max 50 */ ⋮---- -/** Optional client order ID [1, 9223372036854775807]. Valid 8h per transfer path */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_master_sub_transfer_record. Supports cross and isolated. */ -export interface FuturesGetMasterSubTransfersReq { - /** Margin account (e.g. BTC-USDT, USDT). Required */ - margin_account: string; - /** 34: to sub, 35: from sub. Comma-separated for multiple. Omit for all */ - transfer_type?: string; - /** Days to query. Max 90 */ +/** Req for POST /linear-swap-api/v1/swap_trigger_hisorders. getTriggerHistoryOrders. Isolated. Read. Default query completed (status 4,5,6). */ +export interface FuturesGetTriggerHistoryOrdersReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; + /** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ + status: string; + /** Days. Positive integer, max 90; beyond 90 returns last 90 days */ create_date: number; /** Page index. Default 1 */ page_index?: number; /** Page size. Default 20, max 50 */ page_size?: number; + /** created_at (default) or update_time; descending */ + sort_by?: FuturesSortBy; } ⋮---- -/** Margin account (e.g. BTC-USDT, USDT). Required */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** 34: to sub, 35: from sub. Comma-separated for multiple. Omit for all */ +/** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Days to query. Max 90 */ +/** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ +⋮---- +/** Days. Positive integer, max 90; beyond 90 returns last 90 days */ ⋮---- /** Page index. Default 1 */ ⋮---- /** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_transfer_inner. Transfer between margin accounts under same account. */ -export interface FuturesTransferInnerReq { - /** Asset (e.g. USDT) */ - asset: string; - /** From margin account (e.g. BTC-USDT, USDT) */ - from_margin_account: string; - /** To margin account */ - to_margin_account: string; - /** Transfer amount */ - amount: number | string; - /** Optional client order ID [1, 9223372036854775807]. Valid 8h */ - client_order_id?: number; -} -⋮---- -/** Asset (e.g. USDT) */ -⋮---- -/** From margin account (e.g. BTC-USDT, USDT) */ -⋮---- -/** To margin account */ -⋮---- -/** Transfer amount */ -⋮---- -/** Optional client order ID [1, 9223372036854775807]. Valid 8h */ +/** created_at (default) or update_time; descending */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_order. Isolated margin only. */ -export interface FuturesSubmitOrderReq { - /** Contract code (e.g. BTC-USDT). Required */ +/** Req for POST /linear-swap-api/v1/swap_tpsl_order. [Isolated] Set Take-profit and Stop-loss for existing position. Isolated margin only. At least one of tp_trigger_price and sl_trigger_price required. Trade. 5/s. */ +export interface FuturesSubmitTpslOrderReq { + /** Contract code (e.g. BTC-USDT) */ contract_code: string; /** buy or sell */ direction: FuturesDirection; - /** Order quantity */ - volume: number; - /** Leverage rate */ - lever_rate: number; - /** Order price type */ - order_price_type: FuturesSubmitOrderPriceType; - /** open, close, both. Required in hedge mode */ - offset?: FuturesOffsetBoth; - /** Price. Required for limit, post_only, ioc, fok */ - price?: number | string; - /** 0: no, 1: yes */ - reduce_only?: 0 | 1; - /** Client order ID [1, 9223372036854775807] */ - client_order_id?: number; + /** Volume (number of contracts) */ + volume: number | string; /** Take-profit trigger price */ tp_trigger_price?: number | string; - /** Take-profit order price */ + /** Take-profit order price (not required for optimal_5/10/20) */ tp_order_price?: number | string; - /** Take-profit order type */ - tp_order_price_type?: string; + /** market (default), limit, optimal_5, optimal_10, optimal_20 */ + tp_order_price_type?: + | 'market' + | 'limit' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; /** Stop-loss trigger price */ sl_trigger_price?: number | string; - /** Stop-loss order price */ + /** Stop-loss order price (not required for optimal_5/10/20) */ sl_order_price?: number | string; - /** Stop-loss order type */ - sl_order_price_type?: string; - /** Price protection when setting tp/sl */ + /** market (default), limit, optimal_5, optimal_10, optimal_20 */ + sl_order_price_type?: + | 'market' + | 'limit' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; + /** Price protection. Default false. Only when setting tp/sl */ price_protect?: boolean; - /** 0: allow self-trade, 1: prevent (default) */ - self_match_prevent?: 0 | 1; - /** cancel_taker, cancel_maker, cancel_both */ - self_match_prevent_new?: FuturesSelfMatchPrevent; } ⋮---- -/** Contract code (e.g. BTC-USDT). Required */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- /** buy or sell */ ⋮---- -/** Order quantity */ -⋮---- -/** Leverage rate */ -⋮---- -/** Order price type */ -⋮---- -/** open, close, both. Required in hedge mode */ -⋮---- -/** Price. Required for limit, post_only, ioc, fok */ -⋮---- -/** 0: no, 1: yes */ -⋮---- -/** Client order ID [1, 9223372036854775807] */ +/** Volume (number of contracts) */ ⋮---- /** Take-profit trigger price */ ⋮---- -/** Take-profit order price */ +/** Take-profit order price (not required for optimal_5/10/20) */ ⋮---- -/** Take-profit order type */ +/** market (default), limit, optimal_5, optimal_10, optimal_20 */ ⋮---- /** Stop-loss trigger price */ ⋮---- -/** Stop-loss order price */ -⋮---- -/** Stop-loss order type */ -⋮---- -/** Price protection when setting tp/sl */ +/** Stop-loss order price (not required for optimal_5/10/20) */ ⋮---- -/** 0: allow self-trade, 1: prevent (default) */ +/** market (default), limit, optimal_5, optimal_10, optimal_20 */ ⋮---- -/** cancel_taker, cancel_maker, cancel_both */ +/** Price protection. Default false. Only when setting tp/sl */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_order. Cross margin only. One of contract_code or (pair+contract_type) required. */ -export interface FuturesCrossSubmitOrderReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit if pair+contract_type */ +/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_order. [Cross] Set Take-profit and Stop-loss for existing position. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. At least one of tp_trigger_price and sl_trigger_price required. Trade. 5/s. */ +export interface FuturesSubmitCrossTpslOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ contract_code?: string; /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; @@ -6796,39 +6361,35 @@ export interface FuturesCrossSubmitOrderReq { contract_type?: string; /** buy or sell */ direction: FuturesDirection; - /** Order quantity */ - volume: number; - /** Leverage rate */ - lever_rate: number; - /** Order price type */ - order_price_type: FuturesSubmitOrderPriceType; - /** open, close, both. Required in hedge mode */ - offset?: FuturesOffsetBoth; - /** Price. Required for limit, post_only, ioc, fok */ - price?: number | string; - /** 0: no, 1: yes */ - reduce_only?: 0 | 1; - /** Client order ID [1, 9223372036854775807] */ - client_order_id?: number; + /** Volume (number of contracts) */ + volume: number | string; /** Take-profit trigger price */ tp_trigger_price?: number | string; - /** Take-profit order price */ + /** Take-profit order price (not required for optimal_5/10/20) */ tp_order_price?: number | string; - /** Take-profit order type */ - tp_order_price_type?: string; + /** market (default), limit, optimal_5, optimal_10, optimal_20 */ + tp_order_price_type?: + | 'market' + | 'limit' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; /** Stop-loss trigger price */ sl_trigger_price?: number | string; - /** Stop-loss order price */ + /** Stop-loss order price (not required for optimal_5/10/20) */ sl_order_price?: number | string; - /** Stop-loss order type */ - sl_order_price_type?: string; - /** 0: allow self-trade, 1: prevent (default) */ - self_match_prevent?: 0 | 1; - /** cancel_taker, cancel_maker, cancel_both */ - self_match_prevent_new?: FuturesSelfMatchPrevent; + /** market (default), limit, optimal_5, optimal_10, optimal_20 */ + sl_order_price_type?: + | 'market' + | 'limit' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; + /** Price protection. Default false. Only when setting tp/sl */ + price_protect?: boolean; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit if pair+contract_type */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- /** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- @@ -6836,16343 +6397,16801 @@ export interface FuturesCrossSubmitOrderReq { ⋮---- /** buy or sell */ ⋮---- -/** Order quantity */ -⋮---- -/** Leverage rate */ -⋮---- -/** Order price type */ -⋮---- -/** open, close, both. Required in hedge mode */ -⋮---- -/** Price. Required for limit, post_only, ioc, fok */ -⋮---- -/** 0: no, 1: yes */ -⋮---- -/** Client order ID [1, 9223372036854775807] */ +/** Volume (number of contracts) */ ⋮---- /** Take-profit trigger price */ ⋮---- -/** Take-profit order price */ +/** Take-profit order price (not required for optimal_5/10/20) */ ⋮---- -/** Take-profit order type */ +/** market (default), limit, optimal_5, optimal_10, optimal_20 */ ⋮---- /** Stop-loss trigger price */ ⋮---- -/** Stop-loss order price */ +/** Stop-loss order price (not required for optimal_5/10/20) */ ⋮---- -/** Stop-loss order type */ +/** market (default), limit, optimal_5, optimal_10, optimal_20 */ ⋮---- -/** 0: allow self-trade, 1: prevent (default) */ +/** Price protection. Default false. Only when setting tp/sl */ ⋮---- -/** cancel_taker, cancel_maker, cancel_both */ +/** Req for POST /linear-swap-api/v1/swap_tpsl_cancel. [Isolated] Cancel a Take-profit and Stop-loss Order. Isolated margin only. Trade. 5/s. Inlined in cancelTpslOrder - params: { contract_code, order_id } */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_batchorder. Isolated. Max 10 orders. */ -export interface FuturesSubmitBatchOrderReq { - orders_data: FuturesSubmitOrderReq[]; +/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_cancel. [Cross] Cancel a Take-profit and Stop-loss Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ +export interface FuturesCancelCrossTpslOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ + contract_code?: string; + /** Pair (e.g. BTC-USDT). Use with contract_type */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** Order ID(s). Comma-separated, max 10 */ + order_id: string; } ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_batchorder. Cross. Max 25 orders. */ -export interface FuturesSubmitCrossBatchOrderReq { - orders_data: FuturesCrossSubmitOrderReq[]; -} +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cancel. Isolated. One of order_id or client_order_id required. Max 25 IDs. */ -export interface FuturesCancelOrderReq { - /** Contract code (e.g. BTC-USDT). Required */ - contract_code: string; - /** Order IDs, comma-separated. Max 25 */ - order_id?: string; - /** Client order IDs, comma-separated. Max 25 */ - client_order_id?: string; -} +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- -/** Contract code (e.g. BTC-USDT). Required */ +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** Order IDs, comma-separated. Max 25 */ +/** Order ID(s). Comma-separated, max 10 */ ⋮---- -/** Client order IDs, comma-separated. Max 25 */ +/** Req for POST /linear-swap-api/v1/swap_tpsl_cancelall. [Isolated] Cancel all Take-profit and Stop-loss Orders. Isolated margin only. Trade. 5/s. Inlined in cancelAllTpslOrders - params: { contract_code, direction? } */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_cancel. Cross. One of order_id/client_order_id and one of contract_code/(pair+contract_type) required. */ -export interface FuturesCancelCrossOrderReq { - /** Order IDs, comma-separated. Max 25 */ - order_id?: string; - /** Client order IDs, comma-separated. Max 25 */ - client_order_id?: string; - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_cancelall. [Cross] Cancel all Take-profit and Stop-loss Orders. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ +export interface FuturesCancelAllCrossTpslOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ contract_code?: string; - /** Pair (e.g. BTC-USDT) */ + /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; /** swap, this_week, next_week, quarter, next_quarter */ contract_type?: string; + /** buy or sell; omit for all */ + direction?: FuturesDirection; } ⋮---- -/** Order IDs, comma-separated. Max 25 */ -⋮---- -/** Client order IDs, comma-separated. Max 25 */ -⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- /** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cancelall. Isolated. One of direction or offset optional. */ -export interface FuturesCancelAllOrdersReq { - /** Contract code (e.g. BTC-USDT). Required */ - contract_code: string; - /** buy or sell. Omit for all */ - direction?: FuturesDirection; - /** open or close. Omit for all */ - offset?: FuturesOffset; -} -⋮---- -/** Contract code (e.g. BTC-USDT). Required */ -⋮---- -/** buy or sell. Omit for all */ -⋮---- -/** open or close. Omit for all */ +/** buy or sell; omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_cancelall. Cross. One of contract_code or (pair+contract_type) required. */ -export interface FuturesCancelCrossAllOrdersReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** buy or sell. Omit for all */ - direction?: FuturesDirection; - /** open or close. Omit for all */ - offset?: FuturesOffset; -} -⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ -⋮---- -/** Pair (e.g. BTC-USDT) */ -⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ -⋮---- -/** buy or sell. Omit for all */ -⋮---- -/** open or close. Omit for all */ -⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_switch_lever_rate. Cross margin only. One of contract_code or (pair+contract_type) required. */ -export interface FuturesUpdateCrossLeverageReq { - /** Leverage multiple. Required */ - lever_rate: number; - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Req for POST /linear-swap-api/v1/swap_cross_trigger_hisorders. getCrossTriggerHistoryOrders. Cross. One of pair or contract_code required. Read. */ +export interface FuturesGetCrossTriggerHistoryOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; + /** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; + /** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ + status: string; + /** Days. Positive integer, max 90 */ + create_date: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** created_at (default) or update_time; descending */ + sort_by?: FuturesSortBy; } ⋮---- -/** Leverage multiple. Required */ -⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ -⋮---- -/** Req for POST /linear-swap-api/v1/swap_order_info. Isolated. One of order_id or client_order_id required. Max 50 IDs. */ -export interface FuturesGetOrderInfoReq { - /** Contract code (e.g. BTC-USDT). Required */ - contract_code: string; - /** Order IDs, comma-separated. Max 50 */ - order_id?: string; - /** Client order IDs, comma-separated. Max 50 */ - client_order_id?: string; -} -⋮---- -/** Contract code (e.g. BTC-USDT). Required */ -⋮---- -/** Order IDs, comma-separated. Max 50 */ -⋮---- -/** Client order IDs, comma-separated. Max 50 */ +/** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_order_info. Cross. One of order_id/client_order_id and one of contract_code/pair required. */ -export interface FuturesGetCrossOrderInfoReq { - /** Order IDs, comma-separated. Max 50 */ - order_id?: string; - /** Client order IDs, comma-separated. Max 50 */ - client_order_id?: string; - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; -} +/** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ ⋮---- -/** Order IDs, comma-separated. Max 50 */ +/** Days. Positive integer, max 90 */ ⋮---- -/** Client order IDs, comma-separated. Max 50 */ +/** Page index. Default 1 */ ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Page size. Default 20, max 50 */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** created_at (default) or update_time; descending */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_order_detail. Isolated. Order details with trades. */ -export interface FuturesGetOrderDetailReq { - /** Contract code (e.g. BTC-USDT). Required */ +/** Req for POST /linear-swap-api/v1/swap_tpsl_openorders. [Isolated] Query Open Take-profit and Stop-loss Orders. Isolated margin only. Read. */ +export interface FuturesGetTpslOpenOrdersReq { + /** Contract code (e.g. BTC-USDT) */ contract_code: string; - /** Order ID. Required */ - order_id: number | string; - /** Created timestamp (ms). Improves query performance. Cannot be 0 */ - created_at?: number; - /** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ - order_type?: number; /** Page index. Default 1 */ page_index?: number; /** Page size. Default 20, max 50 */ page_size?: number; + /** 0: all, 3: buy short, 4: sell long */ + trade_type?: 0 | 3 | 4; } ⋮---- -/** Contract code (e.g. BTC-USDT). Required */ -⋮---- -/** Order ID. Required */ -⋮---- -/** Created timestamp (ms). Improves query performance. Cannot be 0 */ -⋮---- -/** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- /** Page index. Default 1 */ ⋮---- /** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_order_detail. Cross. One of contract_code or pair required. */ -export interface FuturesGetCrossOrderDetailReq { - /** Order ID. Required */ - order_id: number | string; - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** 0: all, 3: buy short, 4: sell long */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_openorders. [Cross] Query Open Take-profit and Stop-loss Orders. Cross margin only. When both filled, contract_code preferred; when none, all data. Read. */ +export interface FuturesGetCrossTpslOpenOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** Created timestamp (ms). Cannot be 0 */ - created_at?: number; - /** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ - order_type?: number; /** Page index. Default 1 */ page_index?: number; /** Page size. Default 20, max 50 */ page_size?: number; + /** 0: all, 3: buy short, 4: sell long */ + trade_type?: 0 | 3 | 4; } ⋮---- -/** Order ID. Required */ -⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** Created timestamp (ms). Cannot be 0 */ -⋮---- -/** 1: Quotation, 2: Cancelled, 3: Forced liquidation, 4: Delivery, 22: ADL */ -⋮---- /** Page index. Default 1 */ ⋮---- /** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_openorders. Isolated. Current unfilled orders. */ -export interface FuturesGetOpenOrdersReq { - /** Contract code (e.g. BTC-USDT). Omit for all */ - contract_code?: string; +/** 0: all, 3: buy short, 4: sell long */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_tpsl_hisorders. [Isolated] Query Take-profit and Stop-loss History Orders. Isolated margin only. Read. */ +export interface FuturesGetTpslHistoryOrdersReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ + status: string; + /** Days. Positive integer, max 90 */ + create_date: number; /** Page index. Default 1 */ page_index?: number; /** Page size. Default 20, max 50 */ page_size?: number; - /** created_at or update_time. Default created_at */ + /** created_at (default) or update_time; descending */ sort_by?: FuturesSortBy; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; } ⋮---- -/** Contract code (e.g. BTC-USDT). Omit for all */ +/** Contract code (e.g. BTC-USDT) */ +⋮---- +/** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ +⋮---- +/** Days. Positive integer, max 90 */ ⋮---- /** Page index. Default 1 */ ⋮---- /** Page size. Default 20, max 50 */ ⋮---- -/** created_at or update_time. Default created_at */ -⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ +/** created_at (default) or update_time; descending */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_openorders. Cross. Omit all for all contracts. */ -export interface FuturesGetCrossOpenOrdersReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_hisorders. [Cross] Query Take-profit and Stop-loss History Orders. Cross margin only. One of pair or contract_code required; contract_code preferred when both filled. Read. */ +export interface FuturesGetCrossTpslHistoryOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; + /** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ + status: string; + /** Days. Positive integer, max 90 */ + create_date: number; /** Page index. Default 1 */ page_index?: number; /** Page size. Default 20, max 50 */ page_size?: number; - /** created_at or update_time */ + /** created_at (default) or update_time; descending */ sort_by?: FuturesSortBy; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- +/** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ +⋮---- +/** Days. Positive integer, max 90 */ +⋮---- /** Page index. Default 1 */ ⋮---- /** Page size. Default 20, max 50 */ ⋮---- -/** created_at or update_time */ +/** created_at (default) or update_time; descending */ ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ +/** Req for POST /linear-swap-api/v1/swap_cross_relation_tpsl_order. getCrossRelationTpslOrder. Cross. One of pair or contract_code required. Read. */ +export interface FuturesGetCrossRelationTpslOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code?: string; + /** Pair (e.g. BTC-USDT) */ + pair?: string; + /** Position opening order ID */ + order_id: number | string; +} ⋮---- -/** Req for POST /linear-swap-api/v3/swap_hisorders. Isolated. History orders. */ -export interface FuturesGetHistoryOrdersReq { - /** Contract code (e.g. BTC-USDT). Required */ - contract: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** 1: All Orders, 2: Order in Finished Status */ - type: 1 | 2; - /** 0: all, or comma-separated e.g. "3,4,5" */ - status: string; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +⋮---- +/** Pair (e.g. BTC-USDT) */ +⋮---- +/** Position opening order ID */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_track_order. [Isolated] Submit a Trailing Order. Isolated margin only. Trade. 5/s. */ +export interface FuturesSubmitTrailingOrderReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ + reduce_only?: 0 | 1; + /** buy or sell */ + direction: FuturesDirection; + /** open, close, both. Hedge mode required; one-way optional, must be both when filled */ + offset?: FuturesOffsetBoth; + /** Leverage. Required when open, optional when close */ + lever_rate?: number; + /** Volume (contracts) */ + volume: number | string; + /** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ + callback_rate: number | string; + /** Active price */ + active_price: number | string; + /** optimal_5, optimal_10, optimal_20, formula_price */ + order_price_type: FuturesTrailingOrderPriceType; } ⋮---- -/** Contract code (e.g. BTC-USDT). Required */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ +/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ ⋮---- -/** 1: All Orders, 2: Order in Finished Status */ +/** buy or sell */ ⋮---- -/** 0: all, or comma-separated e.g. "3,4,5" */ +/** open, close, both. Hedge mode required; one-way optional, must be both when filled */ ⋮---- -/** Start time (ms). Window max 48h, within 90 days */ +/** Leverage. Required when open, optional when close */ ⋮---- -/** End time (ms). Default now */ +/** Volume (contracts) */ ⋮---- -/** next or prev. Default prev */ +/** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** Active price */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_hisorders_exact. Isolated. History orders via multiple fields; adds price_type filter. */ -export interface FuturesGetHistoryOrdersExactReq { - /** Contract code (e.g. BTC-USDT). Required */ - contract: string; - /** Pair (e.g. BTC-USDT) */ +/** optimal_5, optimal_10, optimal_20, formula_price */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_cross_track_order. [Cross] Submit a Trailing Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ +export interface FuturesSubmitCrossTrailingOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ + contract_code?: string; + /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** 1: All Orders, 2: Order in Finished Status */ - type: 1 | 2; - /** 0: all, or comma-separated e.g. "3,4,5" */ - status: string; - /** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ - price_type?: string; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ + reduce_only?: 0 | 1; + /** buy or sell */ + direction: FuturesDirection; + /** open, close, both. Hedge mode required; one-way optional, must be both when filled */ + offset?: FuturesOffsetBoth; + /** Leverage. Required when open, optional when close */ + lever_rate?: number; + /** Volume (contracts) */ + volume: number | string; + /** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ + callback_rate: number | string; + /** Active price */ + active_price: number | string; + /** optimal_5, optimal_10, optimal_20, formula_price */ + order_price_type: FuturesTrailingOrderPriceType; } ⋮---- -/** Contract code (e.g. BTC-USDT). Required */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** 1: All Orders, 2: Order in Finished Status */ +/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ ⋮---- -/** 0: all, or comma-separated e.g. "3,4,5" */ +/** buy or sell */ ⋮---- -/** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ +/** open, close, both. Hedge mode required; one-way optional, must be both when filled */ ⋮---- -/** Start time (ms). Window max 48h, within 90 days */ +/** Leverage. Required when open, optional when close */ ⋮---- -/** End time (ms). Default now */ +/** Volume (contracts) */ ⋮---- -/** next or prev. Default prev */ +/** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** Active price */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_cross_hisorders_exact. Cross. History orders via multiple fields; adds price_type filter. */ -export interface FuturesGetCrossHistoryOrdersExactReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. When both pair and contract filled, contract preferred */ - contract: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** 1: All Orders, 2: Order in Finished Status */ - type: 1 | 2; - /** 0: all, or comma-separated e.g. "3,4,5" */ - status: string; - /** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ - price_type?: string; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; -} +/** optimal_5, optimal_10, optimal_20, formula_price */ ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. When both pair and contract filled, contract preferred */ +/** Req for POST /linear-swap-api/v1/swap_track_cancel. [Isolated] Cancel a Trailing Order. Isolated margin only. Trade. 5/s. Inlined in cancelTrailingOrder - params: { contract_code, order_id } */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Req for POST /linear-swap-api/v1/swap_cross_track_cancel. [Cross] Cancel a Trailing Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ +export interface FuturesCancelCrossTrailingOrderReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ + contract_code?: string; + /** Pair (e.g. BTC-USDT). Use with contract_type */ + pair?: string; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** Trailing order ID(s). Comma-separated, max 10 */ + order_id: string; +} ⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** 1: All Orders, 2: Order in Finished Status */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- -/** 0: all, or comma-separated e.g. "3,4,5" */ +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** Order price type filter: limit, opponent, post_only, optimal_5, optimal_10, optimal_20, ioc, fok, opponent_ioc, optimal_5_ioc, optimal_10_ioc, optimal_20_ioc, opponent_fok, optimal_5_fok, optimal_10_fok, optimal_20_fok */ +/** Trailing order ID(s). Comma-separated, max 10 */ ⋮---- -/** Start time (ms). Window max 48h, within 90 days */ +/** Req for POST /linear-swap-api/v1/swap_track_cancelall. [Isolated] Cancel All Trailing Orders. Isolated margin only. Can fill only one of direction and offset to filter. Trade. 5/s. */ +export interface FuturesCancelAllTrailingOrdersReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** buy or sell; omit for all */ + direction?: FuturesDirection; + /** open or close; omit for all */ + offset?: FuturesOffset; +} ⋮---- -/** End time (ms). Default now */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** next or prev. Default prev */ +/** buy or sell; omit for all */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** open or close; omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_cross_hisorders. Cross. One of contract or pair required. */ -export interface FuturesGetCrossHistoryOrdersReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ - contract?: string; - /** Pair (e.g. BTC-USDT) */ +/** Req for POST /linear-swap-api/v1/swap_cross_track_cancelall. [Cross] Cancel All Trailing Orders. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Can fill only one of direction and offset to filter. Trade. 5/s. */ +export interface FuturesCancelAllCrossTrailingOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ + contract_code?: string; + /** Pair (e.g. BTC-USDT). Use with contract_type */ pair?: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** 1: All Orders, 2: Order in Finished Status */ - type: 1 | 2; - /** 0: all, or comma-separated e.g. "3,4,5" */ - status: string; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; + /** swap, this_week, next_week, quarter, next_quarter */ + contract_type?: string; + /** buy or sell; omit for all */ + direction?: FuturesDirection; + /** open or close; omit for all */ + offset?: FuturesOffset; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ -⋮---- -/** Pair (e.g. BTC-USDT) */ -⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ -⋮---- -/** 1: All Orders, 2: Order in Finished Status */ -⋮---- -/** 0: all, or comma-separated e.g. "3,4,5" */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ ⋮---- -/** Start time (ms). Window max 48h, within 90 days */ +/** Pair (e.g. BTC-USDT). Use with contract_type */ ⋮---- -/** End time (ms). Default now */ +/** swap, this_week, next_week, quarter, next_quarter */ ⋮---- -/** next or prev. Default prev */ +/** buy or sell; omit for all */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** open or close; omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_matchresults. getFills. Isolated. One of contract or pair required. */ -export interface FuturesGetFillsReq { +/** Req for POST /linear-swap-api/v1/swap_track_openorders. [Isolated] Current unfilled trailing orders. Isolated margin only. Read. */ +export interface FuturesGetTrailingOpenOrdersReq { /** Contract code (e.g. BTC-USDT) */ - contract?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; + contract_code: string; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; } ⋮---- /** Contract code (e.g. BTC-USDT) */ ⋮---- -/** Pair (e.g. BTC-USDT) */ -⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ -⋮---- -/** Start time (ms). Window max 48h, within 90 days */ -⋮---- -/** End time (ms). Default now */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** next or prev. Default prev */ +/** Page index. Default 1 */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_cross_matchresults. getCrossFills. Cross. One of contract or pair required. */ -export interface FuturesGetCrossFillsReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ - contract?: string; +/** Req for POST /linear-swap-api/v1/swap_cross_track_openorders. [Cross] Current unfilled trailing orders. Cross margin only. When both filled, contract_code preferred; when none, all open orders. Read. */ +export interface FuturesGetCrossTrailingOpenOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ -⋮---- -/** Start time (ms). Window max 48h, within 90 days */ -⋮---- -/** End time (ms). Default now */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** next or prev. Default prev */ +/** Page index. Default 1 */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_matchresults_exact. getFillsExact. Isolated. No pair param. */ -export interface FuturesGetFillsExactReq { - /** Contract code (e.g. BTC-USDT). Required */ - contract: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; +/** Req for POST /linear-swap-api/v1/swap_track_hisorders. [Isolated] Get History Trailing Orders. Isolated margin only. Read. */ +export interface FuturesGetTrailingHistoryOrdersReq { + /** Contract code (e.g. BTC-USDT) */ + contract_code: string; + /** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ + status: string; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; + /** Days. Positive integer, max 90 */ + create_date: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** create_date or update_time; descending */ + sort_by?: FuturesSortByExtended; } ⋮---- -/** Contract code (e.g. BTC-USDT). Required */ +/** Contract code (e.g. BTC-USDT) */ ⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ +/** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ ⋮---- -/** Start time (ms). Window max 48h, within 90 days */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** End time (ms). Default now */ +/** Days. Positive integer, max 90 */ ⋮---- -/** next or prev. Default prev */ +/** Page index. Default 1 */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v3/swap_cross_matchresults_exact. getCrossFillsExact. Cross. When both filled, contract preferred. */ -export interface FuturesGetCrossFillsExactReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ - contract: string; +/** create_date or update_time; descending */ +⋮---- +/** Req for POST /linear-swap-api/v1/swap_cross_track_hisorders. [Cross] Get History Trailing Orders. Cross margin only. One of pair or contract_code required; contract_code preferred when both filled. Read. */ +export interface FuturesGetCrossTrailingHistoryOrdersReq { + /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ + contract_code?: string; /** Pair (e.g. BTC-USDT) */ pair?: string; - /** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18; - /** Start time (ms). Window max 48h, within 90 days */ - start_time?: number; - /** End time (ms). Default now */ - end_time?: number; - /** next or prev. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result */ - from_id?: number; + /** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ + status: string; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ + trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; + /** Days. Positive integer, max 90 */ + create_date: number; + /** Page index. Default 1 */ + page_index?: number; + /** Page size. Default 20, max 50 */ + page_size?: number; + /** create_date or update_time; descending */ + sort_by?: FuturesSortByExtended; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625 */ +/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ ⋮---- /** Pair (e.g. BTC-USDT) */ ⋮---- -/** 0: All, 1: Open long, 2: Open short, 3: Close short, 4: Close long, 5: Liquidate long, 6: Liquidate short, 17: buy(one-way), 18: sell(one-way) */ +/** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ ⋮---- -/** Start time (ms). Window max 48h, within 90 days */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ ⋮---- -/** End time (ms). Default now */ +/** Days. Positive integer, max 90 */ ⋮---- -/** next or prev. Default prev */ +/** Page index. Default 1 */ ⋮---- -/** Pagination: min/max query_id from last result */ +/** Page size. Default 20, max 50 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_lightning_close_position. Isolated. Lightning close order. */ -export interface FuturesSubmitLightningCloseOrderReq { - /** Contract code (e.g. BTC-USDT). Case-insensitive */ +/** create_date or update_time; descending */ +⋮---- +/** + * Unified Account + */ +⋮---- +/** Req for POST /linear-swap-api/v3/fix_position_margin_change. Adjust margin for isolated positions. Trade. */ +export interface FuturesUpdateUnifiedMarginReq { + /** Adjustment amount */ + amount: number | string; + /** Currency (e.g. USDT) */ + asset: string; + /** Contract code (e.g. BTC-USDT, ETH-USDT) */ contract_code: string; - /** buy: open, sell: close */ - direction: FuturesDirection; - /** Client order ID. Unique per API, user-maintained */ - client_order_id?: number; - /** market (default), lightning_fok, lightning_ioc */ - order_price_type?: FuturesLightningOrderPriceType; + /** 1: increase isolated margin; 2: reduce isolated margin */ + type: 1 | 2; + /** 1: buy; 2: sell */ + direction: 1 | 2; + /** Client order ID */ + clientOrderId?: number | string; } ⋮---- -/** Contract code (e.g. BTC-USDT). Case-insensitive */ +/** Adjustment amount */ ⋮---- -/** buy: open, sell: close */ +/** Currency (e.g. USDT) */ ⋮---- -/** Client order ID. Unique per API, user-maintained */ +/** Contract code (e.g. BTC-USDT, ETH-USDT) */ ⋮---- -/** market (default), lightning_fok, lightning_ioc */ +/** 1: increase isolated margin; 2: reduce isolated margin */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_lightning_close_position. Cross. One of (pair+contract_type) or contract_code required. */ -export interface FuturesSubmitCrossLightningCloseOrderReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Preferred when all filled */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** buy or sell */ - direction: FuturesDirection; - /** Client order ID [1, 9223372036854775807] */ - client_order_id?: number; - /** market (default), lightning_fok, lightning_ioc */ - order_price_type?: FuturesLightningOrderPriceType; +/** 1: buy; 2: sell */ +⋮---- +/** Client order ID */ +⋮---- +/** Req for GET /linear-swap-api/v3/fix_position_margin_change_record. Query margin adjustment records of isolated positions. Read. */ +export interface FuturesGetUnifiedMarginAdjustmentsReq { + /** Currency (e.g. USDT) */ + asset: string; + /** Contract code (e.g. BTC-USDT, ETH-USDT) */ + contract_code: string; + /** Query start time (ms). Window max 48h, within 90 days. [(end_time - 48h), end_time] */ + start_time?: number; + /** Query end time (ms). [(present-90d), present] */ + end_time?: number; + /** prev: forward query; next: backward query */ + direct?: FuturesDirect; + /** prev: min query_id from last result; next: max query_id from last result */ + from_id?: number; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Preferred when all filled */ +/** Currency (e.g. USDT) */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Contract code (e.g. BTC-USDT, ETH-USDT) */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Query start time (ms). Window max 48h, within 90 days. [(end_time - 48h), end_time] */ ⋮---- -/** buy or sell */ +/** Query end time (ms). [(present-90d), present] */ ⋮---- -/** Client order ID [1, 9223372036854775807] */ +/** prev: forward query; next: backward query */ ⋮---- -/** market (default), lightning_fok, lightning_ioc */ +/** prev: min query_id from last result; next: max query_id from last result */ ⋮---- -/** Req for GET /linear-swap-api/v1/swap_cross_trade_state. Cross margin only. */ -export interface FuturesGetCrossTradeStateReq { - /** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ +/** Req for GET /v5/account/bills. Query financial records. */ +export interface FuturesV5BillsReq { + /** Contract code (e.g. BTC-USDT, ETH-USDT) */ contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** futures, swap, all. Required for futures. Default swap */ - business_type?: FuturesBusinessType; + /** cross: Cross margin; isolated: Isolated margin */ + margin_mode?: FuturesMarginMode; + /** + * Financial type code. Comma-separated for multiple, e.g. 3,4,30,160. + * 160: dividend settlement income. 161: dividend settlement expense. + */ + type?: string; + /** Start time (ms). Default: now - 48h */ + start_time?: string | number; + /** End time (ms). Default: now */ + end_time?: string | number; + /** Query offset, default 0 */ + from?: number; + /** Page size, default 10, max 100 */ + limit?: number; + /** prev | next */ + direct?: FuturesDirect; } ⋮---- -/** Contract code. swap: BTC-USDT, future: BTC-USDT-210625. Omit for all */ -⋮---- -/** Pair (e.g. BTC-USDT) */ -⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Contract code (e.g. BTC-USDT, ETH-USDT) */ ⋮---- -/** futures, swap, all. Required for futures. Default swap */ +/** cross: Cross margin; isolated: Isolated margin */ ⋮---- /** - * Swap Strategy Order Interface - */ + * Financial type code. Comma-separated for multiple, e.g. 3,4,30,160. + * 160: dividend settlement income. 161: dividend settlement expense. + */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_trigger_order. [Isolated] Submit Trigger Order. Isolated margin only. Trade. 5/s. */ -export interface FuturesSubmitTriggerOrderReq { - /** Contract type (e.g. BTC-USDT) */ - contract_code: string; - /** ge: Equal to or Greater than; le: Less than or Equal to */ - trigger_type: FuturesTriggerType; - /** Trigger price */ - trigger_price: number | string; - /** Order price (required when order_price_type is limit) */ - order_price?: number | string; - /** limit (default), optimal_5, optimal_10, optimal_20 */ - order_price_type?: FuturesTriggerOrderPriceType; - /** Volume (number of contracts) */ - volume: number; - /** buy or sell */ - direction: FuturesDirection; - /** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ - offset?: FuturesOffsetBoth; - /** Leverage. Must match current position leverage when holding. High leverage = high risk */ - lever_rate?: number; - /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ - reduce_only?: 0 | 1; -} +/** Start time (ms). Default: now - 48h */ ⋮---- -/** Contract type (e.g. BTC-USDT) */ +/** End time (ms). Default: now */ ⋮---- -/** ge: Equal to or Greater than; le: Less than or Equal to */ +/** Query offset, default 0 */ ⋮---- -/** Trigger price */ +/** Page size, default 10, max 100 */ ⋮---- -/** Order price (required when order_price_type is limit) */ +/** prev | next */ ⋮---- -/** limit (default), optimal_5, optimal_10, optimal_20 */ +/** Req for POST /v5/trade/cancel_order. Cancel a single order. */ +export interface FuturesV5CancelOrderReq { + contract_code: string; + /** Order ID. One of order_id or client_order_id required */ + order_id?: string; + /** Client order ID. One of order_id or client_order_id required */ + client_order_id?: string; +} ⋮---- -/** Volume (number of contracts) */ +/** Order ID. One of order_id or client_order_id required */ ⋮---- -/** buy or sell */ +/** Client order ID. One of order_id or client_order_id required */ ⋮---- -/** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ +/** Req for POST /v5/trade/cancel_batch_orders. Max 10 orders per request. */ +export interface FuturesV5CancelBatchOrdersReq { + contract_code: string; + /** Order IDs. One of order_id or client_order_id required */ + order_id?: string[]; + /** Client order IDs. One of order_id or client_order_id required */ + client_order_id?: string[]; +} ⋮---- -/** Leverage. Must match current position leverage when holding. High leverage = high risk */ +/** Order IDs. One of order_id or client_order_id required */ ⋮---- -/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ +/** Client order IDs. One of order_id or client_order_id required */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_trigger_order. [Cross] Submit Trigger Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ -export interface FuturesSubmitCrossTriggerOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for POST /v5/trade/cancel_all_orders. Cancel all open orders. */ +export interface FuturesV5CancelAllOrdersReq { contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ - reduce_only?: 0 | 1; - /** ge: Equal to or Greater than; le: Less than or Equal to */ - trigger_type: FuturesTriggerType; - /** Trigger price */ - trigger_price: number | string; - /** Order price (required when order_price_type is limit) */ - order_price?: number | string; - /** limit (default), optimal_5, optimal_10, optimal_20 */ - order_price_type?: FuturesTriggerOrderPriceType; - /** Volume (number of contracts) */ - volume: number; - /** buy or sell */ - direction: FuturesDirection; - /** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ - offset?: FuturesOffsetBoth; - /** Leverage. Long = short leverage. High leverage = high risk */ - lever_rate?: number; + side?: FuturesDirection; + position_side?: FuturesPositionSide; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ -⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ -⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ -⋮---- -/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open in one-way triggers error 1492 */ -⋮---- -/** ge: Equal to or Greater than; le: Less than or Equal to */ -⋮---- -/** Trigger price */ -⋮---- -/** Order price (required when order_price_type is limit) */ -⋮---- -/** limit (default), optimal_5, optimal_10, optimal_20 */ -⋮---- -/** Volume (number of contracts) */ -⋮---- -/** buy or sell */ -⋮---- -/** open, close, both. In hedge mode required; in one-way mode optional, must be both when filled */ -⋮---- -/** Leverage. Long = short leverage. High leverage = high risk */ -⋮---- -/** Req for POST /linear-swap-api/v1/swap_trigger_cancelall. [Isolated] Cancel All Trigger Orders. Isolated margin only. Trade. 5/s. Can fill only one of direction and offset to filter. */ -export interface FuturesCancelAllTriggerOrdersReq { - /** Contract code (e.g. BTC-USDT) */ +/** Req for POST /v5/trade/position. Close all of a symbol at market price. */ +export interface FuturesV5ClosePositionReq { contract_code: string; - /** Transaction direction; omit for all */ - direction?: FuturesDirection; - /** open, close; omit for all */ - offset?: FuturesOffset; + margin_mode: FuturesMarginMode; + position_side: FuturesPositionSide; + client_order_id?: string; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ -⋮---- -/** Transaction direction; omit for all */ -⋮---- -/** open, close; omit for all */ -⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_trigger_cancelall. [Cross] Cancel All Trigger Orders. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. Can fill only one of direction and offset to filter. */ -export interface FuturesCancelAllCrossTriggerOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for GET /v5/trade/order/opens. Get unfilled orders. */ +export interface FuturesV5OpenOrdersReq { contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** Transaction direction; omit for all */ - direction?: FuturesDirection; - /** open, close; omit for all */ - offset?: FuturesOffset; + margin_mode?: FuturesMarginMode; + order_id?: string; + client_order_id?: string; + from?: number; + limit?: number; + direct?: FuturesDirect; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ -⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ -⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ -⋮---- -/** Transaction direction; omit for all */ -⋮---- -/** open, close; omit for all */ -⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_trigger_cancel. [Cross] Cancel Trigger Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ -export interface FuturesCancelCrossTriggerOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for GET /v5/trade/order/details. Execution details (last 3 days). */ +export interface FuturesV5OrderDetailsReq { contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** Order ID(s). Comma-separated, max 10 */ - order_id: string; + order_id?: string; + start_time?: string | number; + end_time?: string | number; + from?: number; + limit?: number; + direct?: FuturesDirect; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ -⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ -⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ -⋮---- -/** Order ID(s). Comma-separated, max 10 */ +/** Req for GET /v5/trade/order/history. Get order history. */ +export interface FuturesV5OrderHistoryReq { + contract_code: string; + margin_mode: FuturesMarginMode; + state?: string; + type?: FuturesV5OrderType; + price_match?: string; + start_time?: string | number; + end_time?: string | number; + from?: number; + limit?: number; + direct?: FuturesDirect; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_trigger_openorders. [Isolated] Query Trigger Order Open Orders. Isolated margin only. Read. 5/s. */ -export interface FuturesGetTriggerOpenOrdersReq { - /** Contract code (e.g. BTC-USDT) */ +/** Req for GET /v5/trade/order. Get single order info. */ +export interface FuturesV5OrderInfoReq { contract_code: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; + margin_mode?: FuturesMarginMode; + order_id?: string; + client_order_id?: string; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** Req for POST /v5/trade/cancel-after. Automatic order cancellation (Dead Man's Switch). */ +export interface FuturesV5CancelAfterReq { + on_off: '0' | '1'; + time_out?: number | string; +} ⋮---- -/** Page index. Default 1 */ +/** Req for POST /v5/trade/order. Place a single order. */ +export interface FuturesV5SubmitOrderReq { + contract_code: string; + margin_mode: FuturesMarginMode; + side: FuturesDirection; + type: FuturesV5OrderType; + volume: string; + position_side?: FuturesPositionSide; + price_match?: FuturesPriceMatch; + client_order_id?: string; + price?: string | number; + reduce_only?: 0 | 1; + time_in_force?: FuturesTimeInForce; + tp_trigger_price?: string; + tp_order_price?: string; + tp_type?: FuturesTriggerOrderPriceType | 'market'; + tp_trigger_price_type?: FuturesTriggerPriceType; + sl_trigger_price?: string; + sl_order_price?: string; + sl_type?: FuturesTriggerOrderPriceType | 'market'; + sl_trigger_price_type?: FuturesTriggerPriceType; + price_protect?: boolean; + self_match_prevent?: FuturesSelfMatchPrevent; +} ⋮---- -/** Page size. Default 20, max 50 */ +/** + * USDT Margined Futures Multi Asset - Positions (v5 API) + */ ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ +/** Req for GET /v5/trade/position/opens. Get current positions. Inlined in getMultiAssetPositions - params?: { contract_code? } */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_trigger_openorders. [Cross] Query Trigger Order Open Orders. Cross margin only. When both pair and contract_code filled, contract_code preferred; when none, all open orders. Read. */ -export interface FuturesGetCrossTriggerOpenOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Req for GET /v5/position/lever. Get leverage list. */ +export interface FuturesV5LeverListReq { contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; + margin_mode?: FuturesMarginMode; + position_side?: FuturesPositionSide; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Req for POST /v5/position/lever. Set leverage. */ +export interface FuturesV5SetLeverageReq { + contract_code: string; + margin_mode: FuturesMarginMode; + lever_rate: string | number; + /** Required when isolated margin in two-way position mode */ + position_side?: FuturesPositionSide; +} ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Required when isolated margin in two-way position mode */ ⋮---- -/** Page index. Default 1 */ +/** Req for POST /v5/position/mode. Set position mode. Inlined in updateMultiAssetPositionMode - params: { position_mode } */ ⋮---- -/** Page size. Default 20, max 50 */ +/** Req for GET /v5/position/risk/limit. Get current position risk limit. */ +export interface FuturesV5RiskLimitReq { + contract_code?: string; + margin_mode?: FuturesMarginMode; + position_side?: FuturesPositionSide; +} ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ +/** Req for GET /v5/position/risk/limit_tier. Query risk limit tiers. Inlined in getMultiAssetRiskLimitTiers - params: { contract_code, margin_mode? } */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_trigger_hisorders. getTriggerHistoryOrders. Isolated. Read. Default query completed (status 4,5,6). */ -export interface FuturesGetTriggerHistoryOrdersReq { - /** Contract code (e.g. BTC-USDT) */ +/** Req for POST /v5/position/margin. Adjust margin for isolated positions. */ +export interface FuturesV5AdjustMarginReq { contract_code: string; - /** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; - /** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ - status: string; - /** Days. Positive integer, max 90; beyond 90 returns last 90 days */ - create_date: number; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** created_at (default) or update_time; descending */ - sort_by?: FuturesSortBy; + position_side: FuturesPositionSide; + type: FuturesMarginAdjustType; + amount: string; + currency?: string; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** V5 algo order type */ +export type FuturesV5AlgoOrderType = + | 'tp' + | 'sl' + | 'tp_sl' + | 'tpsl' + | 'trigger' + | 'trailing_stop'; ⋮---- -/** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ -⋮---- -/** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ -⋮---- -/** Days. Positive integer, max 90; beyond 90 returns last 90 days */ -⋮---- -/** Page index. Default 1 */ -⋮---- -/** Page size. Default 20, max 50 */ +/** V5 algo trigger price type */ +export type FuturesV5AlgoTriggerPriceType = 'last' | 'mark' | 'index'; ⋮---- -/** created_at (default) or update_time; descending */ +/** V5 algo TP/SL order type */ +export type FuturesV5AlgoTpSlType = + | 'market' + | 'limit' + | 'optimal_5' + | 'optimal_10' + | 'optimal_20'; ⋮---- -/** Req for POST /linear-swap-api/v1/swap_tpsl_order. [Isolated] Set Take-profit and Stop-loss for existing position. Isolated margin only. At least one of tp_trigger_price and sl_trigger_price required. Trade. 5/s. */ -export interface FuturesSubmitTpslOrderReq { - /** Contract code (e.g. BTC-USDT) */ +/** Req for POST /v5/algo/order. Place an algo order. */ +export interface FuturesV5SubmitAlgoOrderReq { contract_code: string; - /** buy or sell */ - direction: FuturesDirection; - /** Volume (number of contracts) */ - volume: number | string; - /** Take-profit trigger price */ - tp_trigger_price?: number | string; - /** Take-profit order price (not required for optimal_5/10/20) */ - tp_order_price?: number | string; - /** market (default), limit, optimal_5, optimal_10, optimal_20 */ - tp_order_price_type?: - | 'market' - | 'limit' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20'; - /** Stop-loss trigger price */ - sl_trigger_price?: number | string; - /** Stop-loss order price (not required for optimal_5/10/20) */ - sl_order_price?: number | string; - /** market (default), limit, optimal_5, optimal_10, optimal_20 */ - sl_order_price_type?: - | 'market' - | 'limit' + type: FuturesV5AlgoOrderType; + position_side: FuturesPositionSide; + side: FuturesDirection; + margin_mode: FuturesMarginMode; + algo_client_order_id?: string; + volume?: string; + tp_trigger_price?: string; + tp_order_price?: string; + tp_type?: FuturesV5AlgoTpSlType; + tp_trigger_price_type?: FuturesV5AlgoTriggerPriceType; + sl_trigger_price?: string; + sl_order_price?: string; + sl_type?: FuturesV5AlgoTpSlType; + sl_trigger_price_type?: FuturesV5AlgoTriggerPriceType; + price?: string; + price_type?: 'optimal_5' | 'optimal_10' | 'optimal_20'; + trigger_price?: string; + trigger_price_type?: FuturesV5AlgoTriggerPriceType; + activation_price?: string; + active_price?: string; + order_price_type?: | 'optimal_5' | 'optimal_10' - | 'optimal_20'; - /** Price protection. Default false. Only when setting tp/sl */ - price_protect?: boolean; + | 'optimal_20' + | 'trailing_mark'; + callback_rate?: string; + reduce_only?: boolean; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** Req for POST /v5/algo/cancel_orders. Cancel unfilled algo orders. Max 10 per request. */ +export interface FuturesV5CancelAlgoOrderReq { + contract_code: string; + algo_id?: string; + algo_client_order_id?: string; +} ⋮---- -/** buy or sell */ +/** Req for GET /v5/algo/order. Query one algo order. */ +export interface FuturesV5AlgoOrderInfoReq { + type: FuturesV5AlgoOrderType; + algo_id?: string; + algo_client_order_id?: string; +} ⋮---- -/** Volume (number of contracts) */ +/** Req for GET /v5/algo/order/opens. Untriggered algo orders. */ +export interface FuturesV5AlgoOpenOrdersReq { + type: FuturesV5AlgoOrderType; + contract_code?: string; + algo_id?: string; + algo_client_order_id?: string; + from?: number | string; + limit?: number; + direct?: FuturesDirect; +} ⋮---- -/** Take-profit trigger price */ +/** Req for GET /v5/algo/order/history. Algo order history. */ +export interface FuturesV5AlgoOrderHistoryReq { + type: FuturesV5AlgoOrderType; + contract_code?: string; + margin_mode?: FuturesMarginMode; + states?: string; + start_time?: string | number; + end_time?: string | number; + from?: number | string; + limit?: number; + direct?: FuturesDirect; +} ⋮---- -/** Take-profit order price (not required for optimal_5/10/20) */ +/** + * USDT Margined Futures Multi Asset - Basic Information (v5 API) + */ ⋮---- -/** market (default), limit, optimal_5, optimal_10, optimal_20 */ +/** Req for GET /v5/market/funding_rate_history. Historical funding rates. No signature. */ +export interface FuturesV5FundingRateHistoryReq { + /** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ + contract_code: string; + /** Start time (ms). Default: now - 48h */ + start_time?: string | number; + /** End time (ms). Default: now */ + end_time?: string | number; + /** Query id. Default 0 */ + from?: string | number; + /** Page size. Default 10, max 100 */ + limit?: number; + /** prev | next */ + direct?: FuturesDirect; +} ⋮---- -/** Stop-loss trigger price */ +/** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ ⋮---- -/** Stop-loss order price (not required for optimal_5/10/20) */ +/** Start time (ms). Default: now - 48h */ ⋮---- -/** market (default), limit, optimal_5, optimal_10, optimal_20 */ +/** End time (ms). Default: now */ ⋮---- -/** Price protection. Default false. Only when setting tp/sl */ +/** Query id. Default 0 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_order. [Cross] Set Take-profit and Stop-loss for existing position. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. At least one of tp_trigger_price and sl_trigger_price required. Trade. 5/s. */ -export interface FuturesSubmitCrossTpslOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Page size. Default 10, max 100 */ +⋮---- +/** prev | next */ +⋮---- +/** Req for GET /v5/market/risk/limit. Get futures risk limit table. */ +export interface FuturesV5MarketRiskLimitReq { contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** buy or sell */ - direction: FuturesDirection; - /** Volume (number of contracts) */ - volume: number | string; - /** Take-profit trigger price */ - tp_trigger_price?: number | string; - /** Take-profit order price (not required for optimal_5/10/20) */ - tp_order_price?: number | string; - /** market (default), limit, optimal_5, optimal_10, optimal_20 */ - tp_order_price_type?: - | 'market' - | 'limit' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20'; - /** Stop-loss trigger price */ - sl_trigger_price?: number | string; - /** Stop-loss order price (not required for optimal_5/10/20) */ - sl_order_price?: number | string; - /** market (default), limit, optimal_5, optimal_10, optimal_20 */ - sl_order_price_type?: - | 'market' - | 'limit' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20'; - /** Price protection. Default false. Only when setting tp/sl */ - price_protect?: boolean; + margin_mode?: FuturesMarginMode; + tier?: string | number; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** + * Coin-M Delivery - Reference Data (FuturesCmDelivery) + */ ⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** Req for GET /api/v1/contract_adjustfactor. Tiered adjustment factor. Inlined in getCoinMDeliveryAdjustFactor - params?: { symbol?: string } */ +/** Req for GET /api/v1/contract_ladder_margin. Tiered margin. Inlined in getCoinMDeliveryTieredMargin - params?: { symbol?: string } */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Req for GET /api/v1/contract_his_open_interest. Historical open interest. */ +export interface FuturesCmDeliveryOpenInterestReq { + symbol: string; + contract_type: FuturesContractType; + period: FuturesOpenInterestPeriod; + amount_type: 1 | 2; + size?: number; +} ⋮---- -/** buy or sell */ +/** Req for GET /api/v1/contract_elite_account_ratio. Top trader sentiment - account. Inlined in getCoinMDeliveryAccountRatio - params: { symbol, period } */ +/** Req for GET /api/v1/contract_elite_position_ratio. Top trader sentiment - position. Inlined in getCoinMDeliveryPositionRatio - params: { symbol, period } */ ⋮---- -/** Volume (number of contracts) */ +/** Req for GET /api/v3/contract_liquidation_orders. Liquidation orders. */ +export interface FuturesCmDeliveryLiquidationOrdersReq { + symbol: string; + trade_type: 0 | 5 | 6; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** Take-profit trigger price */ +/** Req for GET /api/v1/contract_settlement_records. Historical settlement records. */ +export interface FuturesCmDeliverySettlementRecordsReq { + symbol: string; + start_time?: number; + end_time?: number; + page_index?: number; + page_size?: number; +} ⋮---- -/** Take-profit order price (not required for optimal_5/10/20) */ +/** Req for GET /v1/insurance_fund_history. Historical risk reserves. Aligned with getCoinMDeliveryRiskReserveHistory. */ +export interface FuturesCmDeliveryRiskReserveHistoryReq { + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; + limit?: number; +} ⋮---- -/** market (default), limit, optimal_5, optimal_10, optimal_20 */ +/** Req for GET /api/v1/contract_price_limit. Contract price limits. Aligned with getCoinMDeliveryContractLimit. */ +export interface FuturesCmDeliveryContractLimitReq { + symbol?: string; + contract_type?: FuturesContractType; + contract_code?: string; +} ⋮---- -/** Stop-loss trigger price */ +/** Req for GET /api/v1/contract_open_interest. Current open interest. */ +export interface FuturesCmDeliveryContractOpenInterestReq { + symbol?: string; + contract_type?: FuturesContractType; + contract_code?: string; +} ⋮---- -/** Stop-loss order price (not required for optimal_5/10/20) */ +/** Req for GET /api/v1/contract_delivery_price. Estimated delivery price. Inlined in getCoinMDeliveryDeliveryPrice - params: { symbol: string } */ +/** Req for GET /api/v1/contract_estimated_settlement_price. Estimated settlement price. Inlined in getCoinMDeliveryEstimatedSettlementPrice - params?: { symbol?: string } */ +/** Req for GET /api/v1/contract_api_state. System status. Inlined in getCoinMDeliverySystemStatus - params?: { symbol?: string } */ ⋮---- -/** market (default), limit, optimal_5, optimal_10, optimal_20 */ +/** Req for GET /api/v1/contract_contract_info. Contract info. */ +export interface FuturesCmDeliveryContractInfoReq { + symbol?: string; + contract_type?: FuturesContractType; + contract_code?: string; +} ⋮---- -/** Price protection. Default false. Only when setting tp/sl */ +/** Req for GET /market/depth. Inlined in getCoinMDeliveryMarketDepth - params: { symbol, type } (type: step0–15) */ +/** Req for GET /market/bbo. Inlined in getCoinMDeliveryMarketBbo - params?: { symbol?: string } */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_tpsl_cancel. [Isolated] Cancel a Take-profit and Stop-loss Order. Isolated margin only. Trade. 5/s. Inlined in cancelTpslOrder - params: { contract_code, order_id } */ +/** Req for GET /market/history/kline. Either size or (from+to) required. Aligned with getCoinMDeliveryKlines. */ +export interface FuturesCmDeliveryKlinesReq { + symbol: string; + period: FuturesKlinePeriod; + size?: number; + from?: number; + to?: number; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_cancel. [Cross] Cancel a Take-profit and Stop-loss Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ -export interface FuturesCancelCrossTpslOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ - contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** Order ID(s). Comma-separated, max 10 */ - order_id: string; +/** Req for GET /index/market/history/mark_price_kline. Aligned with getCoinMDeliveryMarkKlines. */ +export interface FuturesCmDeliveryMarkPriceKlinesReq { + symbol: string; + period: FuturesKlinePeriod; + size: number; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for GET /api/v1/contract_index. Index price. Inlined in getCoinMDeliveryIndexPrice - params?: { symbol?: string } */ +/** Req for GET /api/market/contract_constituents. Index constituents. Inlined in getCoinMDeliveryIndexConstituents - params: { symbol: string } */ +/** Req for GET /api/v1/contract_query_elements. Contract elements. Inlined in getCoinMDeliveryContractElements - params?: { contract_code?: string } */ ⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** Req for GET /index/market/history/index. Index kline data. */ +export interface FuturesCmDeliveryIndexKlinesReq { + symbol: string; + period: FuturesKlinePeriod; + size: number; +} ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Req for GET /api/v1/contract_sub_auth_list. getCoinMDeliverySubPermissions. */ +export interface FuturesCmDeliverySubPermissionsReq { + sub_uid?: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** Order ID(s). Comma-separated, max 10 */ +/** Req for POST /api/v3/contract_financial_record. Account financial records. */ +export interface FuturesCmDeliveryFinancialRecordReq { + symbol: string; + type?: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_tpsl_cancelall. [Isolated] Cancel all Take-profit and Stop-loss Orders. Isolated margin only. Trade. 5/s. Inlined in cancelAllTpslOrders - params: { contract_code, direction? } */ +/** Req for POST /api/v3/contract_financial_record_exact. Same as contract_financial_record; from_id for pagination. */ +export type FuturesCmDeliveryFinancialRecordExactReq = + FuturesCmDeliveryFinancialRecordReq; ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_cancelall. [Cross] Cancel all Take-profit and Stop-loss Orders. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ -export interface FuturesCancelAllCrossTpslOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for POST /api/v1/contract_user_settlement_records. User settlement records. */ +export interface FuturesCmDeliveryUserSettlementRecordsReq { + symbol: string; + start_time?: number; + end_time?: number; + page_index?: number; + page_size?: number; +} +⋮---- +/** Req for POST /api/v1/contract_order_limit */ +export interface FuturesCmDeliveryOrderLimitReq { + order_price_type: FuturesCmDeliveryOrderLimitPriceType; + symbol?: string; +} +⋮---- +/** Req for POST /api/v1/contract_order. Place order. Delivery futures. One of contract_code or (symbol+contract_type). */ +export interface FuturesCmDeliverySubmitOrderReq { + /** Contract code (e.g. bch210326). Use if known. */ contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** buy or sell; omit for all */ - direction?: FuturesDirection; + /** Symbol (e.g. BTC, ETH). Case-insensitive. Use with contract_type. */ + symbol?: string; + /** this_week, next_week, quarter, next_quarter. Use with symbol. */ + contract_type?: FuturesContractType; + /** Client order ID [1, 9223372036854775807] */ + client_order_id?: number; + /** Price. Required for limit, post_only, ioc, fok */ + price?: number | string; + /** Order quantity. Required */ + volume: number; + /** buy or sell. Required */ + direction: FuturesDirection; + /** open or close. Required */ + offset: FuturesOffset; + /** Leverage rate. Required */ + lever_rate: number; + /** Order price type. Required */ + order_price_type: FuturesCmDeliverySubmitOrderPriceType; + /** Take-profit trigger price */ + tp_trigger_price?: number | string; + /** Take-profit order price */ + tp_order_price?: number | string; + /** Take-profit order type: limit, optimal_5, optimal_10, optimal_20 */ + tp_order_price_type?: string; + /** Stop-loss trigger price */ + sl_trigger_price?: number | string; + /** Stop-loss order price */ + sl_order_price?: number | string; + /** Stop-loss order type: limit, optimal_5, optimal_10, optimal_20 */ + sl_order_price_type?: string; + /** Price protection when setting tp/sl. Default false. */ + price_protect?: boolean; + /** 0: allow self-trade, 1: prevent. Default 1 */ + self_match_prevent?: 0 | 1; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Contract code (e.g. bch210326). Use if known. */ ⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** Symbol (e.g. BTC, ETH). Case-insensitive. Use with contract_type. */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** this_week, next_week, quarter, next_quarter. Use with symbol. */ ⋮---- -/** buy or sell; omit for all */ +/** Client order ID [1, 9223372036854775807] */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_trigger_hisorders. getCrossTriggerHistoryOrders. Cross. One of pair or contract_code required. Read. */ -export interface FuturesGetCrossTriggerHistoryOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; - /** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ - status: string; - /** Days. Positive integer, max 90 */ - create_date: number; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** created_at (default) or update_time; descending */ - sort_by?: FuturesSortBy; -} +/** Price. Required for limit, post_only, ioc, fok */ ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Order quantity. Required */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** buy or sell. Required */ ⋮---- -/** 0: all, 1: open long, 2: close short, 3: open short, 4: close long, 17: buy(one-way), 18: sell(one-way) */ +/** open or close. Required */ ⋮---- -/** Order status: 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated allowed */ +/** Leverage rate. Required */ ⋮---- -/** Days. Positive integer, max 90 */ +/** Order price type. Required */ ⋮---- -/** Page index. Default 1 */ +/** Take-profit trigger price */ ⋮---- -/** Page size. Default 20, max 50 */ +/** Take-profit order price */ ⋮---- -/** created_at (default) or update_time; descending */ +/** Take-profit order type: limit, optimal_5, optimal_10, optimal_20 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_tpsl_openorders. [Isolated] Query Open Take-profit and Stop-loss Orders. Isolated margin only. Read. */ -export interface FuturesGetTpslOpenOrdersReq { - /** Contract code (e.g. BTC-USDT) */ - contract_code: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** 0: all, 3: buy short, 4: sell long */ - trade_type?: 0 | 3 | 4; -} +/** Stop-loss trigger price */ ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** Stop-loss order price */ ⋮---- -/** Page index. Default 1 */ +/** Stop-loss order type: limit, optimal_5, optimal_10, optimal_20 */ ⋮---- -/** Page size. Default 20, max 50 */ +/** Price protection when setting tp/sl. Default false. */ ⋮---- -/** 0: all, 3: buy short, 4: sell long */ +/** 0: allow self-trade, 1: prevent. Default 1 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_openorders. [Cross] Query Open Take-profit and Stop-loss Orders. Cross margin only. When both filled, contract_code preferred; when none, all data. Read. */ -export interface FuturesGetCrossTpslOpenOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** 0: all, 3: buy short, 4: sell long */ - trade_type?: 0 | 3 | 4; +/** Req for POST /api/v1/contract_batchorder. Max 25 orders. */ +export interface FuturesCmDeliverySubmitBatchOrderReq { + orders_data: FuturesCmDeliverySubmitOrderReq[]; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Req for POST /api/v1/contract_cancel. One of order_id or client_order_id. Max 10 IDs. Symbol required. */ +export interface FuturesCmDeliveryCancelOrderReq { + symbol: string; + /** Order IDs, comma-separated. Max 10 */ + order_id?: string; + /** Client order IDs, comma-separated. Max 10 */ + client_order_id?: string; +} ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Order IDs, comma-separated. Max 10 */ ⋮---- -/** Page index. Default 1 */ +/** Client order IDs, comma-separated. Max 10 */ ⋮---- -/** Page size. Default 20, max 50 */ +/** Req for POST /api/v1/contract_switch_lever_rate. Inlined in updateCoinMDeliveryLeverage - params: { symbol, lever_rate } */ ⋮---- -/** 0: all, 3: buy short, 4: sell long */ +/** Req for POST /api/v1/contract_order_info. One of order_id or client_order_id. Max 50 IDs. Symbol required. */ +export interface FuturesCmDeliveryGetOrderInfoReq { + symbol: string; + /** Order IDs, comma-separated. Max 50 */ + order_id?: string; + /** Client order IDs, comma-separated. Max 50 */ + client_order_id?: string; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_tpsl_hisorders. [Isolated] Query Take-profit and Stop-loss History Orders. Isolated margin only. Read. */ -export interface FuturesGetTpslHistoryOrdersReq { - /** Contract code (e.g. BTC-USDT) */ - contract_code: string; - /** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ - status: string; - /** Days. Positive integer, max 90 */ - create_date: number; - /** Page index. Default 1 */ +/** Order IDs, comma-separated. Max 50 */ +⋮---- +/** Client order IDs, comma-separated. Max 50 */ +⋮---- +/** Req for POST /api/v1/contract_order_detail. created_at cannot be 0. */ +export interface FuturesCmDeliveryGetOrderDetailReq { + symbol: string; + order_id: number | string; + created_at: number; + order_type: number; + page_index?: number; + page_size?: number; +} +⋮---- +/** Req for POST /api/v1/contract_openorders. Omit symbol to query all. */ +export interface FuturesCmDeliveryGetOpenOrdersReq { + symbol?: string; page_index?: number; - /** Page size. Default 20, max 50 */ page_size?: number; - /** created_at (default) or update_time; descending */ sort_by?: FuturesSortBy; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ + trade_type?: 0 | 1 | 2 | 3 | 4; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ ⋮---- -/** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ -⋮---- -/** Days. Positive integer, max 90 */ +/** Req for POST /api/v3/contract_hisorders. Window max 48h, within 90 days. */ +export interface FuturesCmDeliveryGetHistoryOrdersReq { + symbol: string; + /** 0:all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 5: sell liq, 6: buy liq, 7: delivery long, 8: delivery short, 11: reduce close long, 12: reduce close short */ + trade_type: number; + /** 1: All Orders, 2: Order in Finished Status */ + type: 1 | 2; + /** 0: all, or comma-separated: 3,4,5,6,7 */ + status: string; + contract_code?: string; + order_type?: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; + limit?: number; +} ⋮---- -/** Page index. Default 1 */ +/** 0:all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 5: sell liq, 6: buy liq, 7: delivery long, 8: delivery short, 11: reduce close long, 12: reduce close short */ ⋮---- -/** Page size. Default 20, max 50 */ +/** 1: All Orders, 2: Order in Finished Status */ ⋮---- -/** created_at (default) or update_time; descending */ +/** 0: all, or comma-separated: 3,4,5,6,7 */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_tpsl_hisorders. [Cross] Query Take-profit and Stop-loss History Orders. Cross margin only. One of pair or contract_code required; contract_code preferred when both filled. Read. */ -export interface FuturesGetCrossTpslHistoryOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ +/** Req for POST /api/v3/contract_hisorders_exact. type filters by trade type. Window max 48h, within 90 days. */ +export interface FuturesCmDeliveryGetHistoryOrdersExactReq { + symbol: string; + /** Same as trade_type */ + trade_type: number; + /** Same values as trade_type (0-12) */ + type: number; + /** 0: all, or comma-separated: 3,4,5,6,7 */ status: string; - /** Days. Positive integer, max 90 */ - create_date: number; - /** Page index. Default 1 */ - page_index?: number; - /** Page size. Default 20, max 50 */ - page_size?: number; - /** created_at (default) or update_time; descending */ - sort_by?: FuturesSortBy; + contract_code?: string; + order_type?: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ -⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Same as trade_type */ ⋮---- -/** Status: 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated allowed */ +/** Same values as trade_type (0-12) */ ⋮---- -/** Days. Positive integer, max 90 */ +/** 0: all, or comma-separated: 3,4,5,6,7 */ ⋮---- -/** Page index. Default 1 */ +/** Req for POST /api/v3/contract_matchresults. Window max 48h, within 90 days. */ +export interface FuturesCmDeliveryGetFillsReq { + symbol: string; + /** Contract code (e.g. BTC-USD) */ + contract: string; + /** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ + trade_type: number; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** Page size. Default 20, max 50 */ +/** Contract code (e.g. BTC-USD) */ ⋮---- -/** created_at (default) or update_time; descending */ +/** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_relation_tpsl_order. getCrossRelationTpslOrder. Cross. One of pair or contract_code required. Read. */ -export interface FuturesGetCrossRelationTpslOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** Req for POST /api/v3/contract_matchresults_exact. Within 90 days. */ +export interface FuturesCmDeliveryGetFillsExactReq { + symbol: string; + /** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ + trade_type: number; contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** Position opening order ID */ - order_id: number | string; + start_time?: number; + end_time?: number; + from_id?: number; + /** Default 20, max 50 */ + size?: number; + direct?: FuturesDirect; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ +/** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ ⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Default 20, max 50 */ ⋮---- -/** Position opening order ID */ +/** Req for POST /api/v1/lightning_close_position. One of contract_code or (symbol+contract_type). */ +export interface FuturesCmDeliverySubmitFlashCloseOrderReq { + volume: number; + direction: FuturesDirection; + contract_code?: string; + symbol?: string; + contract_type?: FuturesContractType; + client_order_id?: number; + /** lightning (default), lightning_fok, lightning_ioc */ + order_price_type?: FuturesLightningOrderPriceTypeCm; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_track_order. [Isolated] Submit a Trailing Order. Isolated margin only. Trade. 5/s. */ -export interface FuturesSubmitTrailingOrderReq { - /** Contract code (e.g. BTC-USDT) */ - contract_code: string; - /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ - reduce_only?: 0 | 1; - /** buy or sell */ +/** lightning (default), lightning_fok, lightning_ioc */ +⋮---- +/** Req for POST /api/v1/contract_trigger_order. One of contract_code or (symbol+contract_type). */ +export interface FuturesCmDeliverySubmitTriggerOrderReq { + trigger_type: FuturesTriggerType; + trigger_price: number | string; + volume: number; direction: FuturesDirection; - /** open, close, both. Hedge mode required; one-way optional, must be both when filled */ - offset?: FuturesOffsetBoth; - /** Leverage. Required when open, optional when close */ - lever_rate?: number; - /** Volume (contracts) */ - volume: number | string; - /** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ - callback_rate: number | string; - /** Active price */ - active_price: number | string; - /** optimal_5, optimal_10, optimal_20, formula_price */ - order_price_type: FuturesTrailingOrderPriceType; + offset: FuturesOffset; + lever_rate: number; + contract_code?: string; + symbol?: string; + contract_type?: FuturesContractType; + order_price?: number | string; + /** limit (default), optimal_5, optimal_10, optimal_20 */ + order_price_type?: FuturesTriggerOrderPriceType; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** limit (default), optimal_5, optimal_10, optimal_20 */ ⋮---- -/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ +/** Req for POST /api/v1/contract_trigger_cancel. Max 10 order_ids. Inlined in cancelCoinMDeliveryTriggerOrder - params: { symbol, order_id } */ ⋮---- -/** buy or sell */ +/** Req for POST /api/v1/contract_trigger_cancelall. symbol required. */ +export interface FuturesCmDeliveryCancelAllTriggerOrdersReq { + symbol: string; + contract_code?: string; + contract_type?: FuturesContractType; + direction?: FuturesDirection; + offset?: FuturesOffset; +} ⋮---- -/** open, close, both. Hedge mode required; one-way optional, must be both when filled */ +/** Req for POST /api/v1/contract_trigger_openorders. Symbol required. */ +export interface FuturesCmDeliveryGetTriggerOpenOrdersReq { + symbol: string; + contract_code?: string; + page_index?: number; + page_size?: number; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ + trade_type?: 0 | 1 | 2 | 3 | 4; +} ⋮---- -/** Leverage. Required when open, optional when close */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ ⋮---- -/** Volume (contracts) */ +/** Req for POST /api/v1/contract_trigger_hisorders. Days within 90. */ +export interface FuturesCmDeliveryGetTriggerHistoryOrdersReq { + symbol: string; + /** 0: all, 1: open long, 2: close short, 3: open short, 4: close long */ + trade_type: 0 | 1 | 2 | 3 | 4; + /** 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated for multiple */ + status: string; + /** Days to query. Within 90. */ + create_date: number; + contract_code?: string; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortBy; +} ⋮---- -/** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ +/** 0: all, 1: open long, 2: close short, 3: open short, 4: close long */ ⋮---- -/** Active price */ +/** 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated for multiple */ ⋮---- -/** optimal_5, optimal_10, optimal_20, formula_price */ +/** Days to query. Within 90. */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_track_order. [Cross] Submit a Trailing Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ -export interface FuturesSubmitCrossTrailingOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for POST /api/v1/contract_tpsl_cancel. Max 10 order_ids. Inlined in cancelCoinMDeliveryTpslOrder - params: { symbol, order_id } */ +⋮---- +/** Req for POST /api/v1/contract_tpsl_cancelall. One of: symbol, contract_code, or (symbol+contract_type). */ +export interface FuturesCmDeliveryCancelAllTpslOrdersReq { + symbol?: string; contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ - reduce_only?: 0 | 1; - /** buy or sell */ - direction: FuturesDirection; - /** open, close, both. Hedge mode required; one-way optional, must be both when filled */ - offset?: FuturesOffsetBoth; - /** Leverage. Required when open, optional when close */ - lever_rate?: number; - /** Volume (contracts) */ - volume: number | string; - /** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ - callback_rate: number | string; - /** Active price */ - active_price: number | string; - /** optimal_5, optimal_10, optimal_20, formula_price */ - order_price_type: FuturesTrailingOrderPriceType; + contract_type?: FuturesContractType; + direction?: FuturesDirection; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for POST /api/v1/contract_tpsl_openorders. Symbol required. */ +export interface FuturesCmDeliveryGetTpslOpenOrdersReq { + symbol: string; + contract_code?: string; + page_index?: number; + page_size?: number; + /** 0: all, 3: buy short, 4: sell long */ + trade_type?: 0 | 3 | 4; +} ⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** 0: all, 3: buy short, 4: sell long */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** Req for POST /api/v1/contract_tpsl_hisorders. Days within 90. */ +export interface FuturesCmDeliveryGetTpslHistoryOrdersReq { + symbol: string; + contract_code: string; + /** 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated for multiple */ + status: string; + /** Days to query. Within 90. */ + create_date: number; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortBy; +} ⋮---- -/** 0: no, 1: yes. In hedge mode invalid; one-way: 0 when not filled. reduce_only=1 for open triggers error 1492 */ +/** 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated for multiple */ ⋮---- -/** buy or sell */ +/** Days to query. Within 90. */ ⋮---- -/** open, close, both. Hedge mode required; one-way optional, must be both when filled */ +/** Req for POST /api/v1/contract_relation_tpsl_order. TPSL orders related to position-opening order. Inlined in getCoinMDeliveryRelationTpslOrder - params: { symbol, order_id } */ ⋮---- -/** Leverage. Required when open, optional when close */ -⋮---- -/** Volume (contracts) */ -⋮---- -/** Callback rate (e.g. 0.01 = 1%). Min 0.001 (0.1%) */ +/** Req for POST /api/v1/contract_track_cancel. Max 10 order_ids. Inlined in cancelCoinMDeliveryTrailingOrder - params: { symbol, order_id } */ ⋮---- -/** Active price */ +/** Req for POST /api/v1/contract_track_cancelall. symbol required. */ +export interface FuturesCmDeliveryCancelAllTrailingOrdersReq { + symbol: string; + contract_code?: string; + contract_type?: FuturesContractType; + direction?: FuturesDirection; + offset?: FuturesOffset; +} ⋮---- -/** optimal_5, optimal_10, optimal_20, formula_price */ +/** Req for POST /api/v1/contract_track_openorders. Symbol required. */ +export interface FuturesCmDeliveryGetTrailingOpenOrdersReq { + symbol: string; + contract_code?: string; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ + trade_type?: 0 | 1 | 2 | 3 | 4; + page_index?: number; + page_size?: number; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_track_cancel. [Isolated] Cancel a Trailing Order. Isolated margin only. Trade. 5/s. Inlined in cancelTrailingOrder - params: { contract_code, order_id } */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_track_cancel. [Cross] Cancel a Trailing Order. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Trade. 5/s. */ -export interface FuturesCancelCrossTrailingOrderReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for POST /api/v1/contract_track_hisorders. Days within 90. */ +export interface FuturesCmDeliveryGetTrailingHistoryOrdersReq { + symbol: string; + /** 0: all, 4: success, 5: failed, 6: cancelled. Comma-separated for multiple */ + status: string; + /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ + trade_type: 0 | 1 | 2 | 3 | 4; + /** Days to query. Within 90. */ + create_date: number; contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** Trailing order ID(s). Comma-separated, max 10 */ - order_id: string; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortBy; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ -⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** 0: all, 4: success, 5: failed, 6: cancelled. Comma-separated for multiple */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ ⋮---- -/** Trailing order ID(s). Comma-separated, max 10 */ +/** Days to query. Within 90. */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_track_cancelall. [Isolated] Cancel All Trailing Orders. Isolated margin only. Can fill only one of direction and offset to filter. Trade. 5/s. */ -export interface FuturesCancelAllTrailingOrdersReq { - /** Contract code (e.g. BTC-USDT) */ - contract_code: string; - /** buy or sell; omit for all */ - direction?: FuturesDirection; - /** open or close; omit for all */ - offset?: FuturesOffset; +/** Req for POST /api/v1/contract_track_order. One of contract_code or (symbol+contract_type). lever_rate required when offset=open. */ +export interface FuturesCmDeliverySubmitTrailingOrderReq { + direction: FuturesDirection; + offset: FuturesOffset; + volume: number; + callback_rate: number; + active_price: number | string; + /** optimal_5, optimal_10, optimal_20, formula_price */ + order_price_type: FuturesTrailingOrderPriceType; + contract_code?: string; + symbol?: string; + contract_type?: FuturesContractType; + lever_rate?: number; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ -⋮---- -/** buy or sell; omit for all */ +/** optimal_5, optimal_10, optimal_20, formula_price */ ⋮---- -/** open or close; omit for all */ +/** Req for POST /api/v1/contract_tpsl_order. One of contract_code or (symbol+contract_type). At least one of tp or sl required. */ +export interface FuturesCmDeliverySubmitTpslOrderReq { + direction: FuturesDirection; + volume: number; + contract_code?: string; + symbol?: string; + contract_type?: FuturesContractType; + tp_trigger_price?: number | string; + tp_order_price?: number | string; + tp_order_price_type?: FuturesTriggerOrderPriceType; + sl_trigger_price?: number | string; + sl_order_price?: number | string; + sl_order_price_type?: FuturesTriggerOrderPriceType; + price_protect?: boolean; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_track_cancelall. [Cross] Cancel All Trailing Orders. Cross margin only. One of (pair+contract_type) or contract_code required; contract_code preferred when all filled. Can fill only one of direction and offset to filter. Trade. 5/s. */ -export interface FuturesCancelAllCrossTrailingOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Req for POST /api/v1/contract_cancelall. One of: symbol, contract_code, or (symbol+contract_type). */ +export interface FuturesCmDeliveryCancelAllOrdersReq { + /** Symbol (e.g. BTC). Cancel all contracts of this symbol. */ + symbol?: string; + /** Contract code (e.g. btc200925). Cancel orders for this contract. */ contract_code?: string; - /** Pair (e.g. BTC-USDT). Use with contract_type */ - pair?: string; - /** swap, this_week, next_week, quarter, next_quarter */ - contract_type?: string; - /** buy or sell; omit for all */ + /** this_week, next_week, quarter, next_quarter. Use with symbol. */ + contract_type?: FuturesContractType; + /** buy or sell. Omit for all */ direction?: FuturesDirection; - /** open or close; omit for all */ + /** open or close. Omit for all */ offset?: FuturesOffset; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625. Preferred when all filled */ +/** Symbol (e.g. BTC). Cancel all contracts of this symbol. */ ⋮---- -/** Pair (e.g. BTC-USDT). Use with contract_type */ +/** Contract code (e.g. btc200925). Cancel orders for this contract. */ ⋮---- -/** swap, this_week, next_week, quarter, next_quarter */ +/** this_week, next_week, quarter, next_quarter. Use with symbol. */ ⋮---- -/** buy or sell; omit for all */ +/** buy or sell. Omit for all */ ⋮---- -/** open or close; omit for all */ +/** open or close. Omit for all */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_track_openorders. [Isolated] Current unfilled trailing orders. Isolated margin only. Read. */ -export interface FuturesGetTrailingOpenOrdersReq { - /** Contract code (e.g. BTC-USDT) */ - contract_code: string; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; - /** Page index. Default 1 */ +/** Req for POST /api/v1/contract_master_sub_transfer_record */ +export interface FuturesCmDeliveryMasterSubTransferRecordReq { + symbol: string; + transfer_type?: string; + create_date: number; page_index?: number; - /** Page size. Default 20, max 50 */ page_size?: number; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ -⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ -⋮---- -/** Page index. Default 1 */ -⋮---- -/** Page size. Default 20, max 50 */ +/** Req for POST /api/v1/contract_master_sub_transfer */ +export interface FuturesCmDeliveryMasterSubTransferReq { + sub_uid: number; + symbol: string; + amount: number | string; + type: FuturesTransferType; + client_order_id?: number; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_track_openorders. [Cross] Current unfilled trailing orders. Cross margin only. When both filled, contract_code preferred; when none, all open orders. Read. */ -export interface FuturesGetCrossTrailingOpenOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type?: 0 | 1 | 2 | 3 | 4 | 17 | 18; - /** Page index. Default 1 */ +/** Req for POST /api/v1/contract_sub_account_info_list. Batch of sub-account assets with pagination. */ +export interface FuturesCmDeliverySubAccountInfoListReq { + symbol?: string; page_index?: number; - /** Page size. Default 20, max 50 */ page_size?: number; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ -⋮---- -/** Pair (e.g. BTC-USDT) */ +/** Req for POST /api/v1/contract_sub_account_list. Sub-account assets. */ +export interface FuturesCmDeliverySubAccountListReq { + symbol?: string; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ +/** Req for GET /index/market/history/basis. Basis (contract - index) data. */ +export interface FuturesCmDeliveryBasisDataReq { + symbol: string; + period: FuturesKlinePeriod; + size: number; + basis_price_type?: FuturesBasisPriceType; +} ⋮---- -/** Page index. Default 1 */ +/** Req for GET /v1/insurance_fund_history (CMPerp). Historical risk reserves. */ +export interface FuturesCmPerpRiskReserveHistoryReq { + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; + limit?: number; +} ⋮---- -/** Page size. Default 20, max 50 */ +/** Req for POST /swap-api/v1/swap_sub_account_list */ +export interface FuturesCmPerpSubAccountsReq { + contract_code?: string; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** Req for POST /linear-swap-api/v1/swap_track_hisorders. [Isolated] Get History Trailing Orders. Isolated margin only. Read. */ -export interface FuturesGetTrailingHistoryOrdersReq { - /** Contract code (e.g. BTC-USDT) */ - contract_code: string; - /** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ - status: string; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; - /** Days. Positive integer, max 90 */ - create_date: number; - /** Page index. Default 1 */ +/** Req for POST /swap-api/v1/swap_sub_account_info_list */ +export interface FuturesCmPerpSubAccountsAssetsReq { + contract_code?: string; page_index?: number; - /** Page size. Default 20, max 50 */ page_size?: number; - /** create_date or update_time; descending */ - sort_by?: FuturesSortByExtended; } ⋮---- -/** Contract code (e.g. BTC-USDT) */ +/** Req for POST /swap-api/v1/swap_order_limit */ +export interface FuturesCmPerpOrderLimitReq { + contract_code?: string; + order_price_type: string; +} ⋮---- -/** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ +/** Req for POST /swap-api/v1/swap_cancel_after. Dead Man's Switch: auto-cancel pending orders if not refreshed. Inlined in setCoinMPerpCancelAfter - params: { on_off: 0|1, time_out? } */ ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ +/** Req for POST /swap-api/v1/swap_order. Place order (CMPerp). */ +export interface FuturesCmPerpSubmitOrderReq { + contract_code: string; + direction: FuturesDirection; + offset: FuturesOffset; + volume: number; + lever_rate: number; + order_price_type: FuturesCmPerpSubmitOrderPriceType; + price?: number | string; + client_order_id?: number; + tp_trigger_price?: number | string; + tp_order_price?: number | string; + tp_order_price_type?: string; + sl_trigger_price?: number | string; + sl_order_price?: number | string; + sl_order_price_type?: string; + price_protect?: boolean; + self_match_prevent?: 0 | 1; +} ⋮---- -/** Days. Positive integer, max 90 */ +/** Req for POST /swap-api/v1/swap_batchorder. Max 25 orders (CMPerp). */ +export interface FuturesCmPerpSubmitBatchOrderReq { + orders_data: FuturesCmPerpSubmitOrderReq[]; +} ⋮---- -/** Page index. Default 1 */ +/** Req for cancelCoinMPerpOrder. One of order_id or client_order_id required. Max 10. */ +export interface FuturesCmPerpCancelOrderReq { + contract_code: string; + order_id?: string; + client_order_id?: string; +} ⋮---- -/** Page size. Default 20, max 50 */ +/** Req for cancelCoinMPerpAllOrders. Optional direction/offset filter. */ +export interface FuturesCmPerpCancelAllOrdersReq { + contract_code: string; + direction?: FuturesDirection; + offset?: FuturesOffset; +} ⋮---- -/** create_date or update_time; descending */ +/** Req for updateCoinMPerpLeverage. Rate limit 1/3s. Inlined in updateCoinMPerpLeverage - params: { contract_code, lever_rate } */ ⋮---- -/** Req for POST /linear-swap-api/v1/swap_cross_track_hisorders. [Cross] Get History Trailing Orders. Cross margin only. One of pair or contract_code required; contract_code preferred when both filled. Read. */ -export interface FuturesGetCrossTrailingHistoryOrdersReq { - /** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ - contract_code?: string; - /** Pair (e.g. BTC-USDT) */ - pair?: string; - /** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ - status: string; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ - trade_type: 0 | 1 | 2 | 3 | 4 | 17 | 18; - /** Days. Positive integer, max 90 */ - create_date: number; - /** Page index. Default 1 */ +/** Req for getCoinMPerpOrderInfo. One of order_id or client_order_id required. Max 50. */ +export interface FuturesCmPerpOrderInfoReq { + contract_code: string; + order_id?: string; + client_order_id?: string; +} +⋮---- +/** Req for getCoinMPerpOrderDetail. created_at improves query performance, cannot be 0. */ +export interface FuturesCmPerpOrderDetailReq { + contract_code: string; + order_id: number | string; + created_at?: number; + order_type?: number; page_index?: number; - /** Page size. Default 20, max 50 */ page_size?: number; - /** create_date or update_time; descending */ - sort_by?: FuturesSortByExtended; } ⋮---- -/** Contract code. swap: BTC-USDT; future: BTC-USDT-210625 */ -⋮---- -/** Pair (e.g. BTC-USDT) */ -⋮---- -/** Status: 0: all, 4: submitted success, 5: failed, 6: cancelled. Comma-separated allowed */ -⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 17: buy(one-way), 18: sell(one-way) */ -⋮---- -/** Days. Positive integer, max 90 */ -⋮---- -/** Page index. Default 1 */ -⋮---- -/** Page size. Default 20, max 50 */ -⋮---- -/** create_date or update_time; descending */ -⋮---- -/** - * Unified Account - */ +/** Req for getCoinMPerpOpenOrders. Omit contract_code for all. */ +export interface FuturesCmPerpOpenOrdersReq { + contract_code?: string; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortBy; + trade_type?: 0 | 1 | 2 | 3 | 4; +} ⋮---- -/** Req for POST /linear-swap-api/v3/fix_position_margin_change. Adjust margin for isolated positions. Trade. */ -export interface FuturesUpdateUnifiedMarginReq { - /** Adjustment amount */ - amount: number | string; - /** Currency (e.g. USDT) */ - asset: string; - /** Contract code (e.g. BTC-USDT, ETH-USDT) */ - contract_code: string; - /** 1: increase isolated margin; 2: reduce isolated margin */ +/** Req for getCoinMPerpHistoryOrders. contract required. Window max 48h, within 90d. Cancel info: last 2h. */ +export interface FuturesCmPerpHistoryOrdersReq { + contract: string; + /** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long, 5:sell liq, 6:buy liq, 7:Delivery long, 8:Delivery short, 11:reduce close long, 12:reduce close short */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 12; + /** 1:All Orders, 2:Order in Finished Status */ type: 1 | 2; - /** 1: buy; 2: sell */ - direction: 1 | 2; - /** Client order ID */ - clientOrderId?: number | string; + /** 0:all, or comma-separated e.g. "3,4,5" */ + status: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; } ⋮---- -/** Adjustment amount */ -⋮---- -/** Currency (e.g. USDT) */ -⋮---- -/** Contract code (e.g. BTC-USDT, ETH-USDT) */ -⋮---- -/** 1: increase isolated margin; 2: reduce isolated margin */ +/** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long, 5:sell liq, 6:buy liq, 7:Delivery long, 8:Delivery short, 11:reduce close long, 12:reduce close short */ ⋮---- -/** 1: buy; 2: sell */ +/** 1:All Orders, 2:Order in Finished Status */ ⋮---- -/** Client order ID */ +/** 0:all, or comma-separated e.g. "3,4,5" */ ⋮---- -/** Req for GET /linear-swap-api/v3/fix_position_margin_change_record. Query margin adjustment records of isolated positions. Read. */ -export interface FuturesGetUnifiedMarginAdjustmentsReq { - /** Currency (e.g. USDT) */ - asset: string; - /** Contract code (e.g. BTC-USDT, ETH-USDT) */ - contract_code: string; - /** Query start time (ms). Window max 48h, within 90 days. [(end_time - 48h), end_time] */ +/** Req for getCoinMPerpHistoryOrdersExact. Same as HistoryOrdersReq + price_type filter. */ +export interface FuturesCmPerpHistoryOrdersExactReq { + contract: string; + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 12; + type: 1 | 2; + status: string; + price_type?: string; start_time?: number; - /** Query end time (ms). [(present-90d), present] */ end_time?: number; - /** prev: forward query; next: backward query */ direct?: FuturesDirect; - /** prev: min query_id from last result; next: max query_id from last result */ from_id?: number; } ⋮---- -/** Currency (e.g. USDT) */ -⋮---- -/** Contract code (e.g. BTC-USDT, ETH-USDT) */ -⋮---- -/** Query start time (ms). Window max 48h, within 90 days. [(end_time - 48h), end_time] */ -⋮---- -/** Query end time (ms). [(present-90d), present] */ -⋮---- -/** prev: forward query; next: backward query */ -⋮---- -/** prev: min query_id from last result; next: max query_id from last result */ -⋮---- -/** Req for GET /v5/account/bills. Query financial records. */ -export interface FuturesV5BillsReq { - /** Contract code (e.g. BTC-USDT, ETH-USDT) */ - contract_code?: string; - /** cross: Cross margin; isolated: Isolated margin */ - margin_mode?: FuturesMarginMode; - /** - * Financial type code. Comma-separated for multiple, e.g. 3,4,30,160. - * 160: dividend settlement income. 161: dividend settlement expense. - */ - type?: string; - /** Start time (ms). Default: now - 48h */ - start_time?: string | number; - /** End time (ms). Default: now */ - end_time?: string | number; - /** Query offset, default 0 */ - from?: number; - /** Page size, default 10, max 100 */ - limit?: number; - /** prev | next */ +/** Req for getCoinMPerpFills. Window max 48h, within 90d. */ +export interface FuturesCmPerpFillsReq { + contract: string; + /** 0:All, 1:Open long, 2:Open short, 3:Close short, 4:Close long, 5:Liquidate long, 6:Liquidate short */ + trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6; + start_time?: number; + end_time?: number; direct?: FuturesDirect; + from_id?: number; } ⋮---- -/** Contract code (e.g. BTC-USDT, ETH-USDT) */ -⋮---- -/** cross: Cross margin; isolated: Isolated margin */ +/** 0:All, 1:Open long, 2:Open short, 3:Close short, 4:Close long, 5:Liquidate long, 6:Liquidate short */ ⋮---- -/** - * Financial type code. Comma-separated for multiple, e.g. 3,4,30,160. - * 160: dividend settlement income. 161: dividend settlement expense. - */ +/** Req for getCoinMPerpFillsExact. Same params as FillsReq. */ +export type FuturesCmPerpFillsExactReq = FuturesCmPerpFillsReq; ⋮---- -/** Start time (ms). Default: now - 48h */ +/** Req for submitCoinMPerpLightningClose. Lightning close = rival price + optimal 30 levels; unfilled becomes limit. */ +export interface FuturesCmPerpLightningCloseReq { + contract_code: string; + volume: number; + direction: FuturesDirection; + client_order_id?: number; + order_price_type?: FuturesLightningOrderPriceTypeCm; +} ⋮---- -/** End time (ms). Default: now */ +/** Req for submitCoinMPerpTriggerOrder. Rate limit 5/s. */ +export interface FuturesCmPerpTriggerOrderReq { + contract_code: string; + trigger_type: FuturesTriggerType; + trigger_price: number | string; + order_price?: number | string; + order_price_type?: FuturesTriggerOrderPriceType; + volume: number; + direction: FuturesDirection; + offset: FuturesOffset; + lever_rate?: number; +} ⋮---- -/** Query offset, default 0 */ +/** Req for cancelCoinMPerpTriggerOrder. Max 10 order_ids. Rate limit 5/s. Inlined in cancelCoinMPerpTriggerOrder - params: { contract_code, order_id } */ ⋮---- -/** Page size, default 10, max 100 */ +/** Req for cancelCoinMPerpAllTriggerOrders. Optional direction/offset filter. Rate limit 5/s. */ +export interface FuturesCmPerpCancelAllTriggerOrdersReq { + contract_code: string; + direction?: FuturesDirection; + offset?: FuturesOffset; +} ⋮---- -/** prev | next */ +/** Req for getCoinMPerpTriggerOpenOrders. */ +export interface FuturesCmPerpTriggerOpenOrdersReq { + contract_code: string; + page_index?: number; + page_size?: number; + trade_type?: 0 | 1 | 2 | 3 | 4; +} ⋮---- -/** Req for POST /v5/trade/cancel_order. Cancel a single order. */ -export interface FuturesV5CancelOrderReq { +/** Req for getCoinMPerpTriggerHistoryOrders. create_date: days, max 90. Default query completed (status 4,5,6). */ +export interface FuturesCmPerpTriggerHistoryOrdersReq { contract_code: string; - /** Order ID. One of order_id or client_order_id required */ - order_id?: string; - /** Client order ID. One of order_id or client_order_id required */ - client_order_id?: string; + /** 0:All, 1:Open Long, 2:Close Short, 3:Open Short, 4:Close Long */ + trade_type: 0 | 1 | 2 | 3 | 4; + /** 0:all, 4:submitted, 5:failed, 6:cancelled. Comma-separated allowed */ + status: string; + create_date: number; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortBy; } ⋮---- -/** Order ID. One of order_id or client_order_id required */ +/** 0:All, 1:Open Long, 2:Close Short, 3:Open Short, 4:Close Long */ ⋮---- -/** Client order ID. One of order_id or client_order_id required */ +/** 0:all, 4:submitted, 5:failed, 6:cancelled. Comma-separated allowed */ ⋮---- -/** Req for POST /v5/trade/cancel_batch_orders. Max 10 orders per request. */ -export interface FuturesV5CancelBatchOrdersReq { +/** Req for submitCoinMPerpTpslOrder. At least one of tp_trigger_price or sl_trigger_price required. Rate limit 5/s. */ +export interface FuturesCmPerpTpslOrderReq { contract_code: string; - /** Order IDs. One of order_id or client_order_id required */ - order_id?: string[]; - /** Client order IDs. One of order_id or client_order_id required */ - client_order_id?: string[]; + direction: FuturesDirection; + volume: number | string; + tp_trigger_price?: number | string; + tp_order_price?: number | string; + tp_order_price_type?: FuturesTriggerOrderPriceType; + sl_trigger_price?: number | string; + sl_order_price?: number | string; + sl_order_price_type?: FuturesTriggerOrderPriceType; + price_protect?: boolean; } ⋮---- -/** Order IDs. One of order_id or client_order_id required */ +/** Req for cancelCoinMPerpTpslOrder. Max 10 order_ids. Rate limit 5/s. */ +export interface FuturesCmPerpCancelTpslOrderReq { + contract_code: string; + order_id: string; +} ⋮---- -/** Client order IDs. One of order_id or client_order_id required */ +/** Req for cancelCoinMPerpAllTpslOrders. Optional direction filter. Rate limit 5/s. */ +export interface FuturesCmPerpCancelAllTpslOrdersReq { + contract_code: string; + direction?: FuturesDirection; +} ⋮---- -/** Req for POST /v5/trade/cancel_all_orders. Cancel all open orders. */ -export interface FuturesV5CancelAllOrdersReq { - contract_code?: string; - side?: FuturesDirection; - position_side?: FuturesPositionSide; +/** Req for getCoinMPerpTpslOpenOrders. */ +export interface FuturesCmPerpTpslOpenOrdersReq { + contract_code: string; + page_index?: number; + page_size?: number; + trade_type?: 0 | 3 | 4; } ⋮---- -/** Req for POST /v5/trade/position. Close all of a symbol at market price. */ -export interface FuturesV5ClosePositionReq { +/** Req for getCoinMPerpTpslHistoryOrders. create_date: days, max 90. */ +export interface FuturesCmPerpTpslHisOrdersReq { contract_code: string; - margin_mode: FuturesMarginMode; - position_side: FuturesPositionSide; - client_order_id?: string; + /** 0:all, 4:submitted, 5:failed, 6:cancelled, 11:expired. Comma-separated allowed */ + status: string; + create_date: number; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortBy; } ⋮---- -/** Req for GET /v5/trade/order/opens. Get unfilled orders. */ -export interface FuturesV5OpenOrdersReq { - contract_code?: string; - margin_mode?: FuturesMarginMode; - order_id?: string; - client_order_id?: string; - from?: number; - limit?: number; - direct?: FuturesDirect; +/** 0:all, 4:submitted, 5:failed, 6:cancelled, 11:expired. Comma-separated allowed */ +⋮---- +/** Req for getCoinMPerpRelationTpslOrder. order_id = open order id. */ +export interface FuturesCmPerpRelationTpslOrderReq { + contract_code: string; + order_id: number | string; } ⋮---- -/** Req for GET /v5/trade/order/details. Execution details (last 3 days). */ -export interface FuturesV5OrderDetailsReq { - contract_code?: string; - order_id?: string; - start_time?: string | number; - end_time?: string | number; - from?: number; - limit?: number; - direct?: FuturesDirect; +/** Req for submitCoinMPerpTrailingOrder. callback_rate min 0.001 (0.1%). Rate limit 5/s. */ +export interface FuturesCmPerpTrailingOrderReq { + contract_code: string; + direction: FuturesDirection; + offset: FuturesOffset; + volume: number | string; + callback_rate: number | string; + active_price: number | string; + order_price_type: FuturesTrailingOrderPriceType; + lever_rate?: number; } ⋮---- -/** Req for GET /v5/trade/order/history. Get order history. */ -export interface FuturesV5OrderHistoryReq { +/** Req for cancelCoinMPerpTrailingOrder. Max 10 order_ids. Rate limit 5/s. */ +export interface FuturesCmPerpCancelTrailingOrderReq { contract_code: string; - margin_mode: FuturesMarginMode; - state?: string; - type?: FuturesV5OrderType; - price_match?: string; - start_time?: string | number; - end_time?: string | number; - from?: number; - limit?: number; - direct?: FuturesDirect; + order_id: string; } ⋮---- -/** Req for GET /v5/trade/order. Get single order info. */ -export interface FuturesV5OrderInfoReq { +/** Req for cancelCoinMPerpAllTrailingOrders. Optional direction/offset filter. Rate limit 5/s. */ +export interface FuturesCmPerpCancelAllTrailingOrdersReq { contract_code: string; - margin_mode?: FuturesMarginMode; - order_id?: string; - client_order_id?: string; + direction?: FuturesDirection; + offset?: FuturesOffset; } ⋮---- -/** Req for POST /v5/trade/cancel-after. Automatic order cancellation (Dead Man's Switch). */ -export interface FuturesV5CancelAfterReq { - on_off: '0' | '1'; - time_out?: number | string; +/** Req for getCoinMPerpTrailingOpenOrders. */ +export interface FuturesCmPerpTrailingOpenOrdersReq { + contract_code: string; + trade_type?: 0 | 1 | 2 | 3 | 4; + page_index?: number; + page_size?: number; } ⋮---- -/** Req for POST /v5/trade/order. Place a single order. */ -export interface FuturesV5SubmitOrderReq { +/** Req for getCoinMPerpTrailingHistoryOrders. create_date: days, max 90. */ +export interface FuturesCmPerpTrailingHisOrdersReq { contract_code: string; - margin_mode: FuturesMarginMode; - side: FuturesDirection; - type: FuturesV5OrderType; - volume: string; - position_side?: FuturesPositionSide; - price_match?: FuturesPriceMatch; - client_order_id?: string; - price?: string | number; - reduce_only?: 0 | 1; - time_in_force?: FuturesTimeInForce; - tp_trigger_price?: string; - tp_order_price?: string; - tp_type?: FuturesTriggerOrderPriceType | 'market'; - tp_trigger_price_type?: FuturesTriggerPriceType; - sl_trigger_price?: string; - sl_order_price?: string; - sl_type?: FuturesTriggerOrderPriceType | 'market'; - sl_trigger_price_type?: FuturesTriggerPriceType; - price_protect?: boolean; - self_match_prevent?: FuturesSelfMatchPrevent; + /** 0:all, 4:success, 5:failed, 6:cancelled. Comma-separated allowed */ + status: string; + /** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long */ + trade_type: 0 | 1 | 2 | 3 | 4; + create_date: number; + page_index?: number; + page_size?: number; + sort_by?: FuturesSortByCmPerp; } ⋮---- -/** - * USDT Margined Futures Multi Asset - Positions (v5 API) - */ +/** 0:all, 4:success, 5:failed, 6:cancelled. Comma-separated allowed */ ⋮---- -/** Req for GET /v5/trade/position/opens. Get current positions. Inlined in getMultiAssetPositions - params?: { contract_code? } */ +/** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long */ ⋮---- -/** Req for GET /v5/position/lever. Get leverage list. */ -export interface FuturesV5LeverListReq { - contract_code?: string; - margin_mode?: FuturesMarginMode; - position_side?: FuturesPositionSide; +/** Req for POST /swap-api/v1/swap_master_sub_transfer */ +export interface FuturesCmPerpMasterSubTransferReq { + sub_uid: number; + contract_code: string; + amount: number | string; + type: FuturesTransferType; + client_order_id?: number; } ⋮---- -/** Req for POST /v5/position/lever. Set leverage. */ -export interface FuturesV5SetLeverageReq { +/** Req for getCoinMPerpMasterSubTransfers */ +export interface FuturesCmPerpMasterSubTransfersReq { contract_code: string; - margin_mode: FuturesMarginMode; - lever_rate: string | number; - /** Required when isolated margin in two-way position mode */ - position_side?: FuturesPositionSide; + transfer_type?: string; + create_date: number; + page_index?: number; + page_size?: number; } ⋮---- -/** Required when isolated margin in two-way position mode */ +/** Req for POST /swap-api/v3/swap_financial_record */ +export interface FuturesCmPerpFinancialRecordReq { + contract: string; + type?: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; +} ⋮---- -/** Req for POST /v5/position/mode. Set position mode. Inlined in updateMultiAssetPositionMode - params: { position_mode } */ +/** Req for POST /swap-api/v3/swap_financial_record_exact. Same params as swap_financial_record. */ +export type FuturesCmPerpFinancialRecordExactReq = + FuturesCmPerpFinancialRecordReq; ⋮---- -/** Req for GET /v5/position/risk/limit. Get current position risk limit. */ -export interface FuturesV5RiskLimitReq { - contract_code?: string; - margin_mode?: FuturesMarginMode; - position_side?: FuturesPositionSide; +/** Req for GET /swap-api/v1/swap_sub_auth_list */ +export interface FuturesCmPerpSubPermissionsReq { + sub_uid?: string; + start_time?: number; + end_time?: number; + direct?: FuturesDirect; + from_id?: number; } ⋮---- -/** Req for GET /v5/position/risk/limit_tier. Query risk limit tiers. Inlined in getMultiAssetRiskLimitTiers - params: { contract_code, margin_mode? } */ -⋮---- -/** Req for POST /v5/position/margin. Adjust margin for isolated positions. */ -export interface FuturesV5AdjustMarginReq { +/** Req for GET /index/market/history/swap_estimated_rate_kline */ +export interface FuturesCmPerpFundingRateKlinesReq { contract_code: string; - position_side: FuturesPositionSide; - type: FuturesMarginAdjustType; - amount: string; - currency?: string; + period: FuturesKlinePeriod; + size: number; } ⋮---- -/** V5 algo order type */ -export type FuturesV5AlgoOrderType = - | 'tp' - | 'sl' - | 'tp_sl' - | 'tpsl' - | 'trigger' - | 'trailing_stop'; -⋮---- -/** V5 algo trigger price type */ -export type FuturesV5AlgoTriggerPriceType = 'last' | 'mark' | 'index'; -⋮---- -/** V5 algo TP/SL order type */ -export type FuturesV5AlgoTpSlType = - | 'market' - | 'limit' - | 'optimal_5' - | 'optimal_10' - | 'optimal_20'; -⋮---- -/** Req for POST /v5/algo/order. Place an algo order. */ -export interface FuturesV5SubmitAlgoOrderReq { +/** Req for GET /index/market/history/swap_basis */ +export interface FuturesCmPerpBasisDataReq { contract_code: string; - type: FuturesV5AlgoOrderType; - position_side: FuturesPositionSide; - side: FuturesDirection; - margin_mode: FuturesMarginMode; - algo_client_order_id?: string; - volume?: string; - tp_trigger_price?: string; - tp_order_price?: string; - tp_type?: FuturesV5AlgoTpSlType; - tp_trigger_price_type?: FuturesV5AlgoTriggerPriceType; - sl_trigger_price?: string; - sl_order_price?: string; - sl_type?: FuturesV5AlgoTpSlType; - sl_trigger_price_type?: FuturesV5AlgoTriggerPriceType; - price?: string; - price_type?: 'optimal_5' | 'optimal_10' | 'optimal_20'; - trigger_price?: string; - trigger_price_type?: FuturesV5AlgoTriggerPriceType; - activation_price?: string; - active_price?: string; - order_price_type?: - | 'optimal_5' - | 'optimal_10' - | 'optimal_20' - | 'trailing_mark'; - callback_rate?: string; - reduce_only?: boolean; + period: FuturesKlinePeriod; + size: number; + basis_price_type?: FuturesBasisPriceType; } ⋮---- -/** Req for POST /v5/algo/cancel_orders. Cancel unfilled algo orders. Max 10 per request. */ -export interface FuturesV5CancelAlgoOrderReq { +/** Req for GET /index/market/history/swap_premium_index_kline */ +export interface FuturesCmPerpPremiumIndexKlinesReq { contract_code: string; - algo_id?: string; - algo_client_order_id?: string; + period: FuturesKlinePeriod; + size: number; } ⋮---- -/** Req for GET /v5/algo/order. Query one algo order. */ -export interface FuturesV5AlgoOrderInfoReq { - type: FuturesV5AlgoOrderType; - algo_id?: string; - algo_client_order_id?: string; -} -⋮---- -/** Req for GET /v5/algo/order/opens. Untriggered algo orders. */ -export interface FuturesV5AlgoOpenOrdersReq { - type: FuturesV5AlgoOrderType; - contract_code?: string; - algo_id?: string; - algo_client_order_id?: string; - from?: number | string; - limit?: number; - direct?: FuturesDirect; -} -⋮---- -/** Req for GET /v5/algo/order/history. Algo order history. */ -export interface FuturesV5AlgoOrderHistoryReq { - type: FuturesV5AlgoOrderType; - contract_code?: string; - margin_mode?: FuturesMarginMode; - states?: string; - start_time?: string | number; - end_time?: string | number; - from?: number | string; - limit?: number; - direct?: FuturesDirect; +/** Req for GET /index/market/history/swap_mark_price_kline */ +export interface FuturesCmPerpMarkPriceKlinesReq { + contract_code: string; + period: FuturesKlinePeriod; + size: number; } ⋮---- -/** - * USDT Margined Futures Multi Asset - Basic Information (v5 API) - */ -⋮---- -/** Req for GET /v5/market/funding_rate_history. Historical funding rates. No signature. */ -export interface FuturesV5FundingRateHistoryReq { - /** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ +/** Req for GET /swap-ex/market/history/kline. Either size or (from+to) required. */ +export interface FuturesCmPerpKlinesReq { contract_code: string; - /** Start time (ms). Default: now - 48h */ - start_time?: string | number; - /** End time (ms). Default: now */ - end_time?: string | number; - /** Query id. Default 0 */ - from?: string | number; - /** Page size. Default 10, max 100 */ - limit?: number; - /** prev | next */ - direct?: FuturesDirect; + period: FuturesKlinePeriod; + size?: number; + from?: number; + to?: number; } ⋮---- -/** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ -⋮---- -/** Start time (ms). Default: now - 48h */ -⋮---- -/** End time (ms). Default: now */ -⋮---- -/** Query id. Default 0 */ -⋮---- -/** Page size. Default 10, max 100 */ -⋮---- -/** prev | next */ -⋮---- -/** Req for GET /v5/market/risk/limit. Get futures risk limit table. */ -export interface FuturesV5MarketRiskLimitReq { - contract_code?: string; - margin_mode?: FuturesMarginMode; - tier?: string | number; +/** Req for GET /swap-api/v1/swap_historical_funding_rate */ +export interface FuturesCmPerpHistoricalFundingRateReq { + contract_code: string; + page_index?: number; + page_size?: number; } ⋮---- -/** - * Coin-M Delivery - Reference Data (FuturesCmDelivery) - */ -⋮---- -/** Req for GET /api/v1/contract_adjustfactor. Tiered adjustment factor. Inlined in getCoinMDeliveryAdjustFactor - params?: { symbol?: string } */ -/** Req for GET /api/v1/contract_ladder_margin. Tiered margin. Inlined in getCoinMDeliveryTieredMargin - params?: { symbol?: string } */ -⋮---- -/** Req for GET /api/v1/contract_his_open_interest. Historical open interest. */ -export interface FuturesCmDeliveryOpenInterestReq { - symbol: string; - contract_type: FuturesContractType; +/** Req for GET /swap-api/v1/swap_his_open_interest */ +export interface FuturesCmPerpGetOpenInterestReq { + contract_code: string; + /** 60min, 4hour, 12hour, 1day */ period: FuturesOpenInterestPeriod; + /** 1: cont, 2: cryptocurrency */ amount_type: 1 | 2; + /** Default 48, [1, 200] */ size?: number; } ⋮---- -/** Req for GET /api/v1/contract_elite_account_ratio. Top trader sentiment - account. Inlined in getCoinMDeliveryAccountRatio - params: { symbol, period } */ -/** Req for GET /api/v1/contract_elite_position_ratio. Top trader sentiment - position. Inlined in getCoinMDeliveryPositionRatio - params: { symbol, period } */ +/** 60min, 4hour, 12hour, 1day */ ⋮---- -/** Req for GET /api/v3/contract_liquidation_orders. Liquidation orders. */ -export interface FuturesCmDeliveryLiquidationOrdersReq { - symbol: string; +/** 1: cont, 2: cryptocurrency */ +⋮---- +/** Default 48, [1, 200] */ +⋮---- +/** Req for GET /swap-api/v3/swap_liquidation_orders. 0=fully filled, 5=liquidated close, 6=liquidated open. */ +export interface FuturesCmPerpLiquidationOrdersReq { + /** Contract code. Case-insensitive */ + contract: string; + /** 0: fully filled liquidated; 5: liquidated close; 6: liquidated open */ trade_type: 0 | 5 | 6; + /** Start time (ms). Window max 2h, within 90 days */ start_time?: number; + /** End time (ms). Default now. Within 90 days */ end_time?: number; + /** next=chronological, prev=reverse. Default prev */ direct?: FuturesDirect; + /** Pagination: min/max query_id from last result depending on direct */ from_id?: number; } ⋮---- -/** Req for GET /api/v1/contract_settlement_records. Historical settlement records. */ -export interface FuturesCmDeliverySettlementRecordsReq { - symbol: string; +/** Contract code. Case-insensitive */ +⋮---- +/** 0: fully filled liquidated; 5: liquidated close; 6: liquidated open */ +⋮---- +/** Start time (ms). Window max 2h, within 90 days */ +⋮---- +/** End time (ms). Default now. Within 90 days */ +⋮---- +/** next=chronological, prev=reverse. Default prev */ +⋮---- +/** Pagination: min/max query_id from last result depending on direct */ +⋮---- +/** Req for GET /swap-api/v1/swap_settlement_records */ +export interface FuturesCmPerpSettlementRecordsReq { + contract_code: string; + /** Start time (ms). Default: now - 90 days */ start_time?: number; + /** End time (ms). Default: now */ end_time?: number; page_index?: number; page_size?: number; } ⋮---- -/** Req for GET /v1/insurance_fund_history. Historical risk reserves. Aligned with getCoinMDeliveryRiskReserveHistory. */ -export interface FuturesCmDeliveryRiskReserveHistoryReq { - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; - limit?: number; -} +/** Start time (ms). Default: now - 90 days */ ⋮---- -/** Req for GET /api/v1/contract_price_limit. Contract price limits. Aligned with getCoinMDeliveryContractLimit. */ -export interface FuturesCmDeliveryContractLimitReq { - symbol?: string; - contract_type?: FuturesContractType; - contract_code?: string; -} +/** End time (ms). Default: now */ ⋮---- -/** Req for GET /api/v1/contract_open_interest. Current open interest. */ -export interface FuturesCmDeliveryContractOpenInterestReq { - symbol?: string; - contract_type?: FuturesContractType; - contract_code?: string; +/** + * Copy Trading + */ +⋮---- +/** Req for GET /api/v6/copyTrading/trader/instruments. Product type PERP or omit for all. */ +export interface FuturesCopyTraderInstrumentsReq { + /** Product type. PERP = Perpetual Swap. Omit to return all. */ + instType?: 'PERP'; } ⋮---- -/** Req for GET /api/v1/contract_delivery_price. Estimated delivery price. Inlined in getCoinMDeliveryDeliveryPrice - params: { symbol: string } */ -/** Req for GET /api/v1/contract_estimated_settlement_price. Estimated settlement price. Inlined in getCoinMDeliveryEstimatedSettlementPrice - params?: { symbol?: string } */ -/** Req for GET /api/v1/contract_api_state. System status. Inlined in getCoinMDeliverySystemStatus - params?: { symbol?: string } */ +/** Product type. PERP = Perpetual Swap. Omit to return all. */ ⋮---- -/** Req for GET /api/v1/contract_contract_info. Contract info. */ -export interface FuturesCmDeliveryContractInfoReq { - symbol?: string; - contract_type?: FuturesContractType; - contract_code?: string; +/** Req for GET /api/v6/copyTrading/trader/statistics. Product type required. */ +export interface FuturesCopyTraderStatisticsReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; } ⋮---- -/** Req for GET /market/depth. Inlined in getCoinMDeliveryMarketDepth - params: { symbol, type } (type: step0–15) */ -/** Req for GET /market/bbo. Inlined in getCoinMDeliveryMarketBbo - params?: { symbol?: string } */ +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** Req for GET /market/history/kline. Either size or (from+to) required. Aligned with getCoinMDeliveryKlines. */ -export interface FuturesCmDeliveryKlinesReq { - symbol: string; - period: FuturesKlinePeriod; - size?: number; - from?: number; - to?: number; +/** Req for GET /api/v6/copyTrading/trader/profit-sharing-history. Historical profit sharing details. */ +export interface FuturesCopyTraderProfitSharingHistoryReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; + /** Product ID e.g. BTC-USDT-PERP */ + instId?: string; + /** Filter start time (inclusive), Unix timestamp in microseconds */ + begin?: string; + /** Filter end time (inclusive), Unix timestamp in microseconds */ + end?: string; + /** Paginate content before (older data) this ID (exclusive) */ + after?: string; + /** Paginate content after (newer data) this ID (exclusive) */ + before?: string; + /** Number of results to return, max 100, default 100 */ + limit?: string; } ⋮---- -/** Req for GET /index/market/history/mark_price_kline. Aligned with getCoinMDeliveryMarkKlines. */ -export interface FuturesCmDeliveryMarkPriceKlinesReq { - symbol: string; - period: FuturesKlinePeriod; - size: number; -} +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** Req for GET /api/v1/contract_index. Index price. Inlined in getCoinMDeliveryIndexPrice - params?: { symbol?: string } */ -/** Req for GET /api/market/contract_constituents. Index constituents. Inlined in getCoinMDeliveryIndexConstituents - params: { symbol: string } */ -/** Req for GET /api/v1/contract_query_elements. Contract elements. Inlined in getCoinMDeliveryContractElements - params?: { contract_code?: string } */ +/** Product ID e.g. BTC-USDT-PERP */ ⋮---- -/** Req for GET /index/market/history/index. Index kline data. */ -export interface FuturesCmDeliveryIndexKlinesReq { - symbol: string; - period: FuturesKlinePeriod; - size: number; -} +/** Filter start time (inclusive), Unix timestamp in microseconds */ ⋮---- -/** Req for GET /api/v1/contract_sub_auth_list. getCoinMDeliverySubPermissions. */ -export interface FuturesCmDeliverySubPermissionsReq { - sub_uid?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +/** Filter end time (inclusive), Unix timestamp in microseconds */ ⋮---- -/** Req for POST /api/v3/contract_financial_record. Account financial records. */ -export interface FuturesCmDeliveryFinancialRecordReq { - symbol: string; - type?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +/** Paginate content before (older data) this ID (exclusive) */ ⋮---- -/** Req for POST /api/v3/contract_financial_record_exact. Same as contract_financial_record; from_id for pagination. */ -export type FuturesCmDeliveryFinancialRecordExactReq = - FuturesCmDeliveryFinancialRecordReq; +/** Paginate content after (newer data) this ID (exclusive) */ ⋮---- -/** Req for POST /api/v1/contract_user_settlement_records. User settlement records. */ -export interface FuturesCmDeliveryUserSettlementRecordsReq { - symbol: string; - start_time?: number; - end_time?: number; - page_index?: number; - page_size?: number; +/** Number of results to return, max 100, default 100 */ +⋮---- +/** Req for GET /api/v6/copyTrading/trader/profit-sharing-history-summary. Historical profit sharing summary. */ +export interface FuturesCopyTraderProfitSharingHistorySummaryReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; } ⋮---- -/** Req for POST /api/v1/contract_order_limit */ -export interface FuturesCmDeliveryOrderLimitReq { - order_price_type: FuturesCmDeliveryOrderLimitPriceType; - symbol?: string; -} +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** Req for POST /api/v1/contract_order. Place order. Delivery futures. One of contract_code or (symbol+contract_type). */ -export interface FuturesCmDeliverySubmitOrderReq { - /** Contract code (e.g. bch210326). Use if known. */ - contract_code?: string; - /** Symbol (e.g. BTC, ETH). Case-insensitive. Use with contract_type. */ - symbol?: string; - /** this_week, next_week, quarter, next_quarter. Use with symbol. */ - contract_type?: FuturesContractType; - /** Client order ID [1, 9223372036854775807] */ - client_order_id?: number; - /** Price. Required for limit, post_only, ioc, fok */ - price?: number | string; - /** Order quantity. Required */ - volume: number; - /** buy or sell. Required */ - direction: FuturesDirection; - /** open or close. Required */ - offset: FuturesOffset; - /** Leverage rate. Required */ - lever_rate: number; - /** Order price type. Required */ - order_price_type: FuturesCmDeliverySubmitOrderPriceType; - /** Take-profit trigger price */ - tp_trigger_price?: number | string; - /** Take-profit order price */ - tp_order_price?: number | string; - /** Take-profit order type: limit, optimal_5, optimal_10, optimal_20 */ - tp_order_price_type?: string; - /** Stop-loss trigger price */ - sl_trigger_price?: number | string; - /** Stop-loss order price */ - sl_order_price?: number | string; - /** Stop-loss order type: limit, optimal_5, optimal_10, optimal_20 */ - sl_order_price_type?: string; - /** Price protection when setting tp/sl. Default false. */ - price_protect?: boolean; - /** 0: allow self-trade, 1: prevent. Default 1 */ - self_match_prevent?: 0 | 1; +/** Req for GET /api/v6/copyTrading/trader/unrealized-profit-sharing-summary. Unrealized profit sharing summary. */ +export interface FuturesCopyTraderUnrealizedProfitSharingSummaryReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; + /** Profit sharing currency */ + ccy?: string; } ⋮---- -/** Contract code (e.g. bch210326). Use if known. */ -⋮---- -/** Symbol (e.g. BTC, ETH). Case-insensitive. Use with contract_type. */ +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** this_week, next_week, quarter, next_quarter. Use with symbol. */ +/** Profit sharing currency */ ⋮---- -/** Client order ID [1, 9223372036854775807] */ +/** Req for GET /api/v6/copyTrading/trader/followers. Trader query followers. */ +export interface FuturesCopyTraderFollowersReq { + /** Product type. PERP = Perpetual Swap. Omit to return all. */ + instType?: 'PERP'; + /** Filter start time (inclusive), Unix timestamp in microseconds */ + begin?: string; + /** Filter end time (inclusive), Unix timestamp in microseconds */ + end?: string; + /** Paginate content before (older data) this ID (exclusive) */ + after?: string; + /** Paginate content after (newer data) this ID (exclusive) */ + before?: string; + /** Number of results to return, max 100, default 100 */ + limit?: string; +} ⋮---- -/** Price. Required for limit, post_only, ioc, fok */ +/** Product type. PERP = Perpetual Swap. Omit to return all. */ ⋮---- -/** Order quantity. Required */ +/** Filter start time (inclusive), Unix timestamp in microseconds */ ⋮---- -/** buy or sell. Required */ +/** Filter end time (inclusive), Unix timestamp in microseconds */ ⋮---- -/** open or close. Required */ +/** Paginate content before (older data) this ID (exclusive) */ ⋮---- -/** Leverage rate. Required */ +/** Paginate content after (newer data) this ID (exclusive) */ ⋮---- -/** Order price type. Required */ +/** Number of results to return, max 100, default 100 */ ⋮---- -/** Take-profit trigger price */ +/** Req for POST /api/v6/copyTrading/trader/follower. Trader remove follower. Max 10 followers at once. */ +export interface FuturesCopyTraderFollowerRemoveReq { + /** Follower user IDs */ + followerUids: string[]; + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; +} ⋮---- -/** Take-profit order price */ +/** Follower user IDs */ ⋮---- -/** Take-profit order type: limit, optimal_5, optimal_10, optimal_20 */ +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** Stop-loss trigger price */ +/** Req for POST /api/v6/copyTrading/trader/transfer. Trader account transfer. */ +export interface FuturesCopyTraderTransferReq { + /** Amount to transfer */ + amt: string; + /** Source account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ + from: string; + /** Destination account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ + to: string; + /** Currency, default USDT */ + ccy?: string; +} ⋮---- -/** Stop-loss order price */ +/** Amount to transfer */ ⋮---- -/** Stop-loss order type: limit, optimal_5, optimal_10, optimal_20 */ +/** Source account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ ⋮---- -/** Price protection when setting tp/sl. Default false. */ +/** Destination account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ ⋮---- -/** 0: allow self-trade, 1: prevent. Default 1 */ +/** Currency, default USDT */ ⋮---- -/** Req for POST /api/v1/contract_batchorder. Max 25 orders. */ -export interface FuturesCmDeliverySubmitBatchOrderReq { - orders_data: FuturesCmDeliverySubmitOrderReq[]; +/** Req for POST /api/v6/copyTrading/trader/follower-settings. Trader set lead trading config. */ +export interface FuturesCopyTraderFollowerSettingsReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; + /** Enable or disable copy trading */ + enable: boolean; + /** Profit sharing ratio when enabling: 0.1|0.15|0.2|0.25 */ + profitSharingRatio?: string; + /** Max followers when enabling: 100|200|500|1000 */ + maxFollowers?: string; } ⋮---- -/** Req for POST /api/v1/contract_cancel. One of order_id or client_order_id. Max 10 IDs. Symbol required. */ -export interface FuturesCmDeliveryCancelOrderReq { - symbol: string; - /** Order IDs, comma-separated. Max 10 */ - order_id?: string; - /** Client order IDs, comma-separated. Max 10 */ - client_order_id?: string; -} +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** Order IDs, comma-separated. Max 10 */ +/** Enable or disable copy trading */ ⋮---- -/** Client order IDs, comma-separated. Max 10 */ +/** Profit sharing ratio when enabling: 0.1|0.15|0.2|0.25 */ ⋮---- -/** Req for POST /api/v1/contract_switch_lever_rate. Inlined in updateCoinMDeliveryLeverage - params: { symbol, lever_rate } */ +/** Max followers when enabling: 100|200|500|1000 */ ⋮---- -/** Req for POST /api/v1/contract_order_info. One of order_id or client_order_id. Max 50 IDs. Symbol required. */ -export interface FuturesCmDeliveryGetOrderInfoReq { - symbol: string; - /** Order IDs, comma-separated. Max 50 */ - order_id?: string; - /** Client order IDs, comma-separated. Max 50 */ - client_order_id?: string; +/** Req for POST /api/v6/copyTrading/trader/config. Trader view lead trading config. */ +export interface FuturesCopyTraderConfigReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; } ⋮---- -/** Order IDs, comma-separated. Max 50 */ -⋮---- -/** Client order IDs, comma-separated. Max 50 */ +/** Product type. PERP = Perpetual Swap */ ⋮---- -/** Req for POST /api/v1/contract_order_detail. created_at cannot be 0. */ -export interface FuturesCmDeliveryGetOrderDetailReq { - symbol: string; - order_id: number | string; - created_at: number; - order_type: number; - page_index?: number; - page_size?: number; +/** Req for POST /api/v6/copyTrading/trader/apikey. Trader create lead trading API key. */ +export interface FuturesCopyTraderApikeyReq { + /** Product type. PERP = Perpetual Swap */ + instType: 'PERP'; } ⋮---- -/** Req for POST /api/v1/contract_openorders. Omit symbol to query all. */ -export interface FuturesCmDeliveryGetOpenOrdersReq { - symbol?: string; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ - trade_type?: 0 | 1 | 2 | 3 | 4; -} +/** Product type. PERP = Perpetual Swap */ + +================ +File: src/types/websockets/ws-general.ts +================ +import { AxiosRequestConfig } from 'axios'; ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ +import { RestClientOptions } from '../../lib/requestUtils.js'; +import { HtxWSNetwork } from '../../lib/websocket/websocket-util.js'; +import { WSConnectionOptions } from './ws-portable.js'; ⋮---- -/** Req for POST /api/v3/contract_hisorders. Window max 48h, within 90 days. */ -export interface FuturesCmDeliveryGetHistoryOrdersReq { - symbol: string; - /** 0:all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 5: sell liq, 6: buy liq, 7: delivery long, 8: delivery short, 11: reduce close long, 12: reduce close short */ - trade_type: number; - /** 1: All Orders, 2: Order in Finished Status */ - type: 1 | 2; - /** 0: all, or comma-separated: 3,4,5,6,7 */ - status: string; - contract_code?: string; - order_type?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; - limit?: number; +/** General configuration for the WebsocketClient */ +export interface WSClientConfigurableOptions { + /** Your API key */ + apiKey?: string; + + /** Your API secret */ + apiSecret?: string; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds. */ + recvWindow?: number; + + /** + * How often to check if the connection is alive. + * Futures public WS closes a connection that has had no ping for 25s, without notice. Keep this under 25s. The SDK default is 10s. + */ + 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?: WSConnectionOptions; + + wsUrl?: string; + + /** + * Switch between the AWS and Standard WebSocket domains. The AWS domain has better connectivity from certain regions. If you have trouble maintaining a stable connection, try switching the domain. + * + * AWS is used by default. If this field isn't set, but you're setting the baseUrlKey in the embedded restOptions, the WS domain will automatically switch to match the REST domain. + */ + wsEnvironment?: HtxWSNetwork; + + /** + * 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; + + /** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ + reauthWSAPIOnReconnect?: boolean; + + /** + * Whether to use native WebSocket ping/pong frames for heartbeats. + */ + useNativeHeartbeats?: boolean; } ⋮---- -/** 0:all, 1: buy long, 2: sell short, 3: buy short, 4: sell long, 5: sell liq, 6: buy liq, 7: delivery long, 8: delivery short, 11: reduce close long, 12: reduce close short */ +/** Your API key */ ⋮---- -/** 1: All Orders, 2: Order in Finished Status */ +/** Your API secret */ ⋮---- -/** 0: all, or comma-separated: 3,4,5,6,7 */ +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds. */ ⋮---- -/** Req for POST /api/v3/contract_hisorders_exact. type filters by trade type. Window max 48h, within 90 days. */ -export interface FuturesCmDeliveryGetHistoryOrdersExactReq { - symbol: string; - /** Same as trade_type */ - trade_type: number; - /** Same values as trade_type (0-12) */ - type: number; - /** 0: all, or comma-separated: 3,4,5,6,7 */ - status: string; - contract_code?: string; - order_type?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +/** + * How often to check if the connection is alive. + * Futures public WS closes a connection that has had no ping for 25s, without notice. Keep this under 25s. The SDK default is 10s. + */ ⋮---- -/** Same as trade_type */ +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -/** Same values as trade_type (0-12) */ +/** Delay in milliseconds before respawning the connection */ ⋮---- -/** 0: all, or comma-separated: 3,4,5,6,7 */ +/** + * Switch between the AWS and Standard WebSocket domains. The AWS domain has better connectivity from certain regions. If you have trouble maintaining a stable connection, try switching the domain. + * + * AWS is used by default. If this field isn't set, but you're setting the baseUrlKey in the embedded restOptions, the WS domain will automatically switch to match the REST domain. + */ ⋮---- -/** Req for POST /api/v3/contract_matchresults. Window max 48h, within 90 days. */ -export interface FuturesCmDeliveryGetFillsReq { - symbol: string; - /** Contract code (e.g. BTC-USD) */ - contract: string; - /** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ - trade_type: number; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +/** + * 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. + */ ⋮---- -/** Contract code (e.g. BTC-USD) */ +/** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ ⋮---- -/** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ +/** + * Whether to use native WebSocket ping/pong frames for heartbeats. + */ ⋮---- -/** Req for POST /api/v3/contract_matchresults_exact. Within 90 days. */ -export interface FuturesCmDeliveryGetFillsExactReq { - symbol: string; - /** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ - trade_type: number; - contract_code?: string; - start_time?: number; - end_time?: number; - from_id?: number; - /** Default 20, max 50 */ - size?: number; - direct?: FuturesDirect; +/** + * 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 { + pingInterval: number; + pongTimeout: number; + reconnectTimeout: number; + recvWindow: number; + + /** + * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + */ + requireConnectionReadyConfirmation: boolean; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequests: boolean; + reauthWSAPIOnReconnect: boolean; + + /** + * Whether to use native WebSocket ping/pong frames for heartbeats + */ + useNativeHeartbeats: boolean; } ⋮---- -/** 0: all, 1: open long, 2: open short, 3: close short, 4: close long, 5: liq long, 6: liq short */ +/** + * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + */ ⋮---- -/** Default 20, max 50 */ +/** + * Whether to use native WebSocket ping/pong frames for heartbeats + */ ⋮---- -/** Req for POST /api/v1/lightning_close_position. One of contract_code or (symbol+contract_type). */ -export interface FuturesCmDeliverySubmitFlashCloseOrderReq { - volume: number; - direction: FuturesDirection; - contract_code?: string; - symbol?: string; - contract_type?: FuturesContractType; - client_order_id?: number; - /** lightning (default), lightning_fok, lightning_ioc */ - order_price_type?: FuturesLightningOrderPriceTypeCm; -} +export type WsMarket = 'spot' | 'futures'; ⋮---- -/** lightning (default), lightning_fok, lightning_ioc */ +export type WsEventInternalSrc = 'event' | 'function' | 'frame'; ⋮---- -/** Req for POST /api/v1/contract_trigger_order. One of contract_code or (symbol+contract_type). */ -export interface FuturesCmDeliverySubmitTriggerOrderReq { - trigger_type: FuturesTriggerType; - trigger_price: number | string; - volume: number; - direction: FuturesDirection; - offset: FuturesOffset; - lever_rate: number; - contract_code?: string; - symbol?: string; - contract_type?: FuturesContractType; - order_price?: number | string; - /** limit (default), optimal_5, optimal_10, optimal_20 */ - order_price_type?: FuturesTriggerOrderPriceType; +export interface WsSpotAuthParams { + authType: 'api'; + accessKey: string; + signatureMethod: 'HmacSHA256' | 'Ed25519'; + signatureVersion: '2.1'; + timestamp: string; + signature: string; } ⋮---- -/** limit (default), optimal_5, optimal_10, optimal_20 */ +export interface WsDerivativesAuthParams { + op: 'auth'; + type: 'api'; + AccessKeyId: string; + SignatureMethod: 'HmacSHA256' | 'Ed25519'; + SignatureVersion: '2'; + Timestamp: string; + Signature: string; +} ⋮---- -/** Req for POST /api/v1/contract_trigger_cancel. Max 10 order_ids. Inlined in cancelCoinMDeliveryTriggerOrder - params: { symbol, order_id } */ +/** Vague structure for JSON-parsed incoming msg */ +export type ParsedWsMessage = Record; + +================ +File: src/types/websockets/ws-subscriptions.ts +================ +/** + * HTX websocket topics are string templates, e.g.: + * + * - `market.btcusdt.kline.1min` + * - `market.btcusdt.mbp.150` + * - `orders#btcusdt` + * - `orders.btc-usdt` + * + * The exchange publishes a large and evolving topic surface, so the SDK keeps + * the topic type open while exporting common topic groups for discovery and + * private/public routing. + */ ⋮---- -/** Req for POST /api/v1/contract_trigger_cancelall. symbol required. */ -export interface FuturesCmDeliveryCancelAllTriggerOrdersReq { - symbol: string; - contract_code?: string; - contract_type?: FuturesContractType; - direction?: FuturesDirection; - offset?: FuturesOffset; -} +export type WSSpotPublicTopic = (typeof WS_SPOT_PUBLIC_TOPICS)[number]; +export type WSSpotPrivateTopic = (typeof WS_SPOT_PRIVATE_TOPICS)[number]; +export type WSDerivativesPublicTopic = + (typeof WS_DERIVATIVES_PUBLIC_TOPICS)[number]; +export type WSDerivativesPrivateTopic = + (typeof WS_DERIVATIVES_PRIVATE_TOPICS)[number]; ⋮---- -/** Req for POST /api/v1/contract_trigger_openorders. Symbol required. */ -export interface FuturesCmDeliveryGetTriggerOpenOrdersReq { - symbol: string; - contract_code?: string; - page_index?: number; - page_size?: number; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ - trade_type?: 0 | 1 | 2 | 3 | 4; -} +export type WSTopic = + | WSSpotPublicTopic + | WSSpotPrivateTopic + | WSDerivativesPublicTopic + | WSDerivativesPrivateTopic + | string; ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ +export function isPrivateTopic(topic: string): boolean + +================ +File: src/index.ts +================ + + +================ +File: src/lib/websocket/websocket-util.ts +================ +import { MessageEventLike } from '../../types/websockets/ws-events.js'; +import { + WebSocketBinaryData, + WebSocketLike, +} from '../../types/websockets/ws-portable.js'; +import { WSTopic } from '../../types/websockets/ws-subscriptions.js'; ⋮---- -/** Req for POST /api/v1/contract_trigger_hisorders. Days within 90. */ -export interface FuturesCmDeliveryGetTriggerHistoryOrdersReq { - symbol: string; - /** 0: all, 1: open long, 2: close short, 3: open short, 4: close long */ - trade_type: 0 | 1 | 2 | 3 | 4; - /** 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated for multiple */ - status: string; - /** Days to query. Within 90. */ - create_date: number; - contract_code?: string; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; -} +/** Spot Market Data */ ⋮---- -/** 0: all, 1: open long, 2: close short, 3: open short, 4: close long */ +/** Spot high-frequency market data */ ⋮---- -/** 0: all, 4: submitted, 5: failed, 6: cancelled. Comma-separated for multiple */ +/** Spot Account Events */ ⋮---- -/** Days to query. Within 90. */ +/** Spot WS API */ ⋮---- -/** Req for POST /api/v1/contract_tpsl_cancel. Max 10 order_ids. Inlined in cancelCoinMDeliveryTpslOrder - params: { symbol, order_id } */ +/** + * Linear futures public market data (`/linear-swap-ws`). + * 200 concurrent connections per IP per backend instance. No minute-level connect-rate limit. + * Over that cap the server returns error 4000. A connection with no ping for 25s is closed without notice. + */ ⋮---- -/** Req for POST /api/v1/contract_tpsl_cancelall. One of: symbol, contract_code, or (symbol+contract_type). */ -export interface FuturesCmDeliveryCancelAllTpslOrdersReq { - symbol?: string; - contract_code?: string; - contract_type?: FuturesContractType; - direction?: FuturesDirection; -} +/** Linear futures account events */ ⋮---- -/** Req for POST /api/v1/contract_tpsl_openorders. Symbol required. */ -export interface FuturesCmDeliveryGetTpslOpenOrdersReq { - symbol: string; - contract_code?: string; - page_index?: number; - page_size?: number; - /** 0: all, 3: buy short, 4: sell long */ - trade_type?: 0 | 3 | 4; -} +/** Linear futures WS API */ ⋮---- -/** 0: all, 3: buy short, 4: sell long */ +/** V5 unified derivatives account events */ ⋮---- -/** Req for POST /api/v1/contract_tpsl_hisorders. Days within 90. */ -export interface FuturesCmDeliveryGetTpslHistoryOrdersReq { - symbol: string; - contract_code: string; - /** 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated for multiple */ - status: string; - /** Days to query. Within 90. */ - create_date: number; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; -} +/** This is used to differentiate between each of the available websocket streams. */ +export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; ⋮---- -/** 0: all, 4: submitted, 5: failed, 6: cancelled, 11: expired. Comma-separated for multiple */ +export type WSOperation = 'subscribe' | 'unsubscribe'; ⋮---- -/** Days to query. Within 90. */ +export type HtxWSNetwork = 'standard' | 'aws'; ⋮---- -/** Req for POST /api/v1/contract_relation_tpsl_order. TPSL orders related to position-opening order. Inlined in getCoinMDeliveryRelationTpslOrder - params: { symbol, order_id } */ +/** + * Normalised internal format for a request on a topic, with optional parameters. + * + * - Topic: the exchange topic string. + * - Payload: optional exchange-specific fields to merge into the request. + */ +export interface WSTopicRequest< + TWSTopic extends WSTopic = WSTopic, + TWSPayload = Record, +> { + topic: TWSTopic; + payload?: TWSPayload; +} ⋮---- -/** Req for POST /api/v1/contract_track_cancel. Max 10 order_ids. Inlined in cancelCoinMDeliveryTrailingOrder - params: { symbol, order_id } */ +/** Conveniently allow users to request either string topics or topic objects. */ +export type WSTopicRequestOrStringTopic< + TWSTopic extends WSTopic, + TWSPayload = Record, +> = WSTopicRequest | string; ⋮---- -/** Req for POST /api/v1/contract_track_cancelall. symbol required. */ -export interface FuturesCmDeliveryCancelAllTrailingOrdersReq { - symbol: string; - contract_code?: string; - contract_type?: FuturesContractType; - direction?: FuturesDirection; - offset?: FuturesOffset; +export interface HTXSpotMarketWSRequest { + sub?: string | string[]; + unsub?: string | string[]; + req?: string; + id?: string | number; } ⋮---- -/** Req for POST /api/v1/contract_track_openorders. Symbol required. */ -export interface FuturesCmDeliveryGetTrailingOpenOrdersReq { - symbol: string; - contract_code?: string; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ - trade_type?: 0 | 1 | 2 | 3 | 4; - page_index?: number; - page_size?: number; +export interface HTXSpotPrivateWSRequest { + action: 'sub' | 'unsub' | 'req' | 'ping' | 'pong'; + ch?: string; + params?: Record; + data?: Record; } ⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ -⋮---- -/** Req for POST /api/v1/contract_track_hisorders. Days within 90. */ -export interface FuturesCmDeliveryGetTrailingHistoryOrdersReq { - symbol: string; - /** 0: all, 4: success, 5: failed, 6: cancelled. Comma-separated for multiple */ - status: string; - /** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ - trade_type: 0 | 1 | 2 | 3 | 4; - /** Days to query. Within 90. */ - create_date: number; - contract_code?: string; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; +export interface HTXDerivativesWSRequest { + op: 'sub' | 'unsub' | 'req' | 'ping' | 'pong' | 'auth' | string; + cid?: string; + topic?: string; + data?: Record | Record[]; + [key: string]: unknown; } ⋮---- -/** 0: all, 4: success, 5: failed, 6: cancelled. Comma-separated for multiple */ -⋮---- -/** 0: all, 1: buy long, 2: sell short, 3: buy short, 4: sell long */ +export type HTXWSRequest = + | HTXSpotMarketWSRequest + | HTXSpotPrivateWSRequest + | HTXDerivativesWSRequest; ⋮---- -/** Days to query. Within 90. */ +export interface HTXSpotWSAPIRawRequest< + TOperation extends string = string, + TParams = unknown, +> { + cid: string; + ch: TOperation; + params?: TParams; +} ⋮---- -/** Req for POST /api/v1/contract_track_order. One of contract_code or (symbol+contract_type). lever_rate required when offset=open. */ -export interface FuturesCmDeliverySubmitTrailingOrderReq { - direction: FuturesDirection; - offset: FuturesOffset; - volume: number; - callback_rate: number; - active_price: number | string; - /** optimal_5, optimal_10, optimal_20, formula_price */ - order_price_type: FuturesTrailingOrderPriceType; - contract_code?: string; - symbol?: string; - contract_type?: FuturesContractType; - lever_rate?: number; +export interface HTXDerivativesWSAPIRawRequest< + TOperation extends string = string, + TParams = unknown, +> { + op: TOperation; + cid: string; + data?: TParams; } ⋮---- -/** optimal_5, optimal_10, optimal_20, formula_price */ +export type HTXWSAPIRawRequest = + | HTXSpotWSAPIRawRequest + | HTXDerivativesWSAPIRawRequest; ⋮---- -/** Req for POST /api/v1/contract_tpsl_order. One of contract_code or (symbol+contract_type). At least one of tp or sl required. */ -export interface FuturesCmDeliverySubmitTpslOrderReq { - direction: FuturesDirection; - volume: number; - contract_code?: string; - symbol?: string; - contract_type?: FuturesContractType; - tp_trigger_price?: number | string; - tp_order_price?: number | string; - tp_order_price_type?: FuturesTriggerOrderPriceType; - sl_trigger_price?: number | string; - sl_order_price?: number | string; - sl_order_price_type?: FuturesTriggerOrderPriceType; - price_protect?: boolean; -} +/** + * ws.terminate() is undefined in browsers. + * This only works in node.js, not in browsers. + * Does nothing if `ws` is undefined. Does nothing in browsers. + */ +export function safeTerminateWs( + ws?: WebSocketLike | unknown, + fallbackToClose?: boolean, +): boolean ⋮---- -/** Req for POST /api/v1/contract_cancelall. One of: symbol, contract_code, or (symbol+contract_type). */ -export interface FuturesCmDeliveryCancelAllOrdersReq { - /** Symbol (e.g. BTC). Cancel all contracts of this symbol. */ - symbol?: string; - /** Contract code (e.g. btc200925). Cancel orders for this contract. */ - contract_code?: string; - /** this_week, next_week, quarter, next_quarter. Use with symbol. */ - contract_type?: FuturesContractType; - /** buy or sell. Omit for all */ - direction?: FuturesDirection; - /** open or close. Omit for all */ - offset?: FuturesOffset; -} +export function isSpotWsKey(wsKey: WsKey): boolean ⋮---- -/** Symbol (e.g. BTC). Cancel all contracts of this symbol. */ +export function isDerivativesWsKey(wsKey: WsKey): boolean ⋮---- -/** Contract code (e.g. btc200925). Cancel orders for this contract. */ +export function isPrivateWsKey(wsKey: WsKey): boolean ⋮---- -/** this_week, next_week, quarter, next_quarter. Use with symbol. */ +export function isTradeWsKey(wsKey: WsKey): boolean ⋮---- -/** buy or sell. Omit for all */ +export function isGzipWsKey(wsKey: WsKey): boolean ⋮---- -/** open or close. Omit for all */ +export function getWsBaseUrl(wsKey: WsKey, network: HtxWSNetwork): string ⋮---- -/** Req for POST /api/v1/contract_master_sub_transfer_record */ -export interface FuturesCmDeliveryMasterSubTransferRecordReq { - symbol: string; - transfer_type?: string; - create_date: number; - page_index?: number; - page_size?: number; -} +export function getWsUrl(wsKey: WsKey, network: HtxWSNetwork): string ⋮---- -/** Req for POST /api/v1/contract_master_sub_transfer */ -export interface FuturesCmDeliveryMasterSubTransferReq { - sub_uid: number; - symbol: string; - amount: number | string; - type: FuturesTransferType; - client_order_id?: number; -} +export function getPromiseRefForWSAPIRequest( + wsKey: WsKey, + requestEvent: HTXWSAPIRawRequest, +): string ⋮---- -/** Req for POST /api/v1/contract_sub_account_info_list. Batch of sub-account assets with pagination. */ -export interface FuturesCmDeliverySubAccountInfoListReq { - symbol?: string; - page_index?: number; - page_size?: number; -} +export function getPromiseRefPrefixForWSAPIRequest(wsKey: WsKey): string ⋮---- -/** Req for POST /api/v1/contract_sub_account_list. Sub-account assets. */ -export interface FuturesCmDeliverySubAccountListReq { - symbol?: string; - direct?: FuturesDirect; - from_id?: number; -} +export function isBufferMessageEvent( + msg: unknown, +): msg is MessageEventLike ⋮---- -/** Req for GET /index/market/history/basis. Basis (contract - index) data. */ -export interface FuturesCmDeliveryBasisDataReq { - symbol: string; - period: FuturesKlinePeriod; - size: number; - basis_price_type?: FuturesBasisPriceType; -} +export function isBinaryLike(data: unknown): data is WebSocketBinaryData ⋮---- -/** Req for GET /v1/insurance_fund_history (CMPerp). Historical risk reserves. */ -export interface FuturesCmPerpRiskReserveHistoryReq { - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; - limit?: number; -} +export function binaryDataToUint8Array( + data: WebSocketBinaryData, +): Uint8Array ⋮---- -/** Req for POST /swap-api/v1/swap_sub_account_list */ -export interface FuturesCmPerpSubAccountsReq { - contract_code?: string; - direct?: FuturesDirect; - from_id?: number; -} +export function bufferLooksLikeText( + data?: WebSocketBinaryData | null, +): boolean ⋮---- -/** Req for POST /swap-api/v1/swap_sub_account_info_list */ -export interface FuturesCmPerpSubAccountsAssetsReq { - contract_code?: string; - page_index?: number; - page_size?: number; -} +export async function decompressMessageEvent( + event: MessageEventLike, + format: WebSocketCompressionFormat = 'gzip', +): Promise> ⋮---- -/** Req for POST /swap-api/v1/swap_order_limit */ -export interface FuturesCmPerpOrderLimitReq { - contract_code?: string; - order_price_type: string; -} +start(controller) ⋮---- -/** Req for POST /swap-api/v1/swap_cancel_after. Dead Man's Switch: auto-cancel pending orders if not refreshed. Inlined in setCoinMPerpCancelAfter - params: { on_off: 0|1, time_out? } */ +export type WebSocketCompressionFormat = 'deflate' | 'deflate-raw' | 'gzip'; ⋮---- -/** Req for POST /swap-api/v1/swap_order. Place order (CMPerp). */ -export interface FuturesCmPerpSubmitOrderReq { - contract_code: string; - direction: FuturesDirection; - offset: FuturesOffset; - volume: number; - lever_rate: number; - order_price_type: FuturesCmPerpSubmitOrderPriceType; - price?: number | string; - client_order_id?: number; - tp_trigger_price?: number | string; - tp_order_price?: number | string; - tp_order_price_type?: string; - sl_trigger_price?: number | string; - sl_order_price?: number | string; - sl_order_price_type?: string; - price_protect?: boolean; - self_match_prevent?: 0 | 1; -} +function isNodeBuffer(data: unknown): data is Uint8Array ⋮---- -/** Req for POST /swap-api/v1/swap_batchorder. Max 25 orders (CMPerp). */ -export interface FuturesCmPerpSubmitBatchOrderReq { - orders_data: FuturesCmPerpSubmitOrderReq[]; -} +Buffer?: + +================ +File: src/lib/BaseWSClient.ts +================ +import WebSocketImplementation from 'isomorphic-ws'; ⋮---- -/** Req for cancelCoinMPerpOrder. One of order_id or client_order_id required. Max 10. */ -export interface FuturesCmPerpCancelOrderReq { - contract_code: string; - order_id?: string; - client_order_id?: string; -} +import { + isMessageEvent, + MessageEventLike, +} from '../types/websockets/ws-events.js'; +import { + WebsocketClientOptions, + WSClientConfigurableOptions, + WsEventInternalSrc, +} from '../types/websockets/ws-general.js'; +import { + EventListener, + WebSocketLike, + WSConnectionOptions, +} from '../types/websockets/ws-portable.js'; +import { WSTopic } from '../types/websockets/ws-subscriptions.js'; +import { EventEmitter } from './event-emitter.js'; +import { isObjectLike } from './misc-util.js'; +import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; +import { DefaultLogger } from './websocket/logger.js'; +import { + decompressMessageEvent, + isBufferMessageEvent, + safeTerminateWs, + WSOperation, + WSTopicRequest, + WSTopicRequestOrStringTopic, +} from './websocket/websocket-util.js'; +import { WsStore } from './websocket/WsStore.js'; +import { + DeferredPromise, + WSConnectedResult, + WsConnectionStateEnum, +} from './websocket/WsStore.types.js'; ⋮---- -/** Req for cancelCoinMPerpAllOrders. Optional direction/offset filter. */ -export interface FuturesCmPerpCancelAllOrdersReq { - contract_code: string; - direction?: FuturesDirection; - offset?: FuturesOffset; +interface WebSocketConstructor { + new ( + url: string, + protocols?: string | string[], + options?: Omit, + ): WebSocketLike; } ⋮---- -/** Req for updateCoinMPerpLeverage. Rate limit 1/3s. Inlined in updateCoinMPerpLeverage - params: { contract_code, lever_rate } */ -⋮---- -/** Req for getCoinMPerpOrderInfo. One of order_id or client_order_id required. Max 50. */ -export interface FuturesCmPerpOrderInfoReq { - contract_code: string; - order_id?: string; - client_order_id?: string; -} +function isNativeBrowserWebSocket(ws: WebSocketLike): boolean ⋮---- -/** Req for getCoinMPerpOrderDetail. created_at improves query performance, cannot be 0. */ -export interface FuturesCmPerpOrderDetailReq { - contract_code: string; - order_id: number | string; - created_at?: number; - order_type?: number; - page_index?: number; - page_size?: number; -} +type UseTheExceptionEventInstead = never; +type WSClientEventPayload = Record & { + wsKey: WsKey; +}; ⋮---- -/** Req for getCoinMPerpOpenOrders. Omit contract_code for all. */ -export interface FuturesCmPerpOpenOrdersReq { - contract_code?: string; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; - trade_type?: 0 | 1 | 2 | 3 | 4; -} +type WSClientEventPayloadOrArray = + | WSClientEventPayload + | WSClientEventPayload[]; ⋮---- -/** Req for getCoinMPerpHistoryOrders. contract required. Window max 48h, within 90d. Cancel info: last 2h. */ -export interface FuturesCmPerpHistoryOrdersReq { - contract: string; - /** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long, 5:sell liq, 6:buy liq, 7:Delivery long, 8:Delivery short, 11:reduce close long, 12:reduce close short */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 12; - /** 1:All Orders, 2:Order in Finished Status */ - type: 1 | 2; - /** 0:all, or comma-separated e.g. "3,4,5" */ - status: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; +interface WSClientEventMap { + /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ + open: (evt: { + wsKey: WsKey; + event: unknown; + wsUrl: string; + ws: WebSocketLike; + }) => void; + + /** Reconnecting a dropped connection */ + reconnecting: (evt: { wsKey: WsKey; event: unknown }) => void; + + /** Successfully reconnected a connection that dropped */ + reconnected: (evt: { + wsKey: WsKey; + event: unknown; + wsUrl: string; + ws: WebSocketLike; + }) => void; + + /** Connection closed */ + close: (evt: { wsKey: WsKey; event: unknown }) => void; + + /** Received reply to websocket command (e.g. after subscribing to topics) */ + response: (response: WSClientEventPayloadOrArray) => void; + + /** Received data for topic */ + message: (response: WSClientEventPayloadOrArray) => void; + + /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ + exception: (response: WSClientEventPayloadOrArray) => void; + + /** + * See for more information: https://github.com/tiagosiebler/bybit-api/issues/413 + * @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection. + */ + error: UseTheExceptionEventInstead; + + /** Confirmation that a connection successfully authenticated */ + authenticated: (event: WSClientEventPayload) => void; } ⋮---- -/** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long, 5:sell liq, 6:buy liq, 7:Delivery long, 8:Delivery short, 11:reduce close long, 12:reduce close short */ -⋮---- -/** 1:All Orders, 2:Order in Finished Status */ +/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ ⋮---- -/** 0:all, or comma-separated e.g. "3,4,5" */ +/** Reconnecting a dropped connection */ ⋮---- -/** Req for getCoinMPerpHistoryOrdersExact. Same as HistoryOrdersReq + price_type filter. */ -export interface FuturesCmPerpHistoryOrdersExactReq { - contract: string; - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 11 | 12; - type: 1 | 2; - status: string; - price_type?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +/** Successfully reconnected a connection that dropped */ ⋮---- -/** Req for getCoinMPerpFills. Window max 48h, within 90d. */ -export interface FuturesCmPerpFillsReq { - contract: string; - /** 0:All, 1:Open long, 2:Open short, 3:Close short, 4:Close long, 5:Liquidate long, 6:Liquidate short */ - trade_type: 0 | 1 | 2 | 3 | 4 | 5 | 6; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +/** Connection closed */ ⋮---- -/** 0:All, 1:Open long, 2:Open short, 3:Close short, 4:Close long, 5:Liquidate long, 6:Liquidate short */ +/** Received reply to websocket command (e.g. after subscribing to topics) */ ⋮---- -/** Req for getCoinMPerpFillsExact. Same params as FillsReq. */ -export type FuturesCmPerpFillsExactReq = FuturesCmPerpFillsReq; +/** Received data for topic */ ⋮---- -/** Req for submitCoinMPerpLightningClose. Lightning close = rival price + optimal 30 levels; unfilled becomes limit. */ -export interface FuturesCmPerpLightningCloseReq { - contract_code: string; - volume: number; - direction: FuturesDirection; - client_order_id?: number; - order_price_type?: FuturesLightningOrderPriceTypeCm; -} +/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ ⋮---- -/** Req for submitCoinMPerpTriggerOrder. Rate limit 5/s. */ -export interface FuturesCmPerpTriggerOrderReq { - contract_code: string; - trigger_type: FuturesTriggerType; - trigger_price: number | string; - order_price?: number | string; - order_price_type?: FuturesTriggerOrderPriceType; - volume: number; - direction: FuturesDirection; - offset: FuturesOffset; - lever_rate?: number; -} +/** + * See for more information: https://github.com/tiagosiebler/bybit-api/issues/413 + * @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection. + */ ⋮---- -/** Req for cancelCoinMPerpTriggerOrder. Max 10 order_ids. Rate limit 5/s. Inlined in cancelCoinMPerpTriggerOrder - params: { contract_code, order_id } */ +/** Confirmation that a connection successfully authenticated */ ⋮---- -/** Req for cancelCoinMPerpAllTriggerOrders. Optional direction/offset filter. Rate limit 5/s. */ -export interface FuturesCmPerpCancelAllTriggerOrdersReq { - contract_code: string; - direction?: FuturesDirection; - offset?: FuturesOffset; +export interface EmittableEvent< + TEventType extends keyof WSClientEventMap = + keyof WSClientEventMap, +> { + eventType: + | TEventType + | 'pong' + | 'connectionReady' // tied to "requireConnectionReadyConfirmation"; + | 'connectionReadyForAuth'; // tied to specific events we need to wait for, before we can begin post-connect auth + event: Parameters[TEventType]>[0]; + isWSAPIResponse?: boolean; } ⋮---- -/** Req for getCoinMPerpTriggerOpenOrders. */ -export interface FuturesCmPerpTriggerOpenOrdersReq { - contract_code: string; - page_index?: number; - page_size?: number; - trade_type?: 0 | 1 | 2 | 3 | 4; -} +| 'connectionReady' // tied to "requireConnectionReadyConfirmation"; +| 'connectionReadyForAuth'; // tied to specific events we need to wait for, before we can begin post-connect auth ⋮---- -/** Req for getCoinMPerpTriggerHistoryOrders. create_date: days, max 90. Default query completed (status 4,5,6). */ -export interface FuturesCmPerpTriggerHistoryOrdersReq { - contract_code: string; - /** 0:All, 1:Open Long, 2:Close Short, 3:Open Short, 4:Close Long */ - trade_type: 0 | 1 | 2 | 3 | 4; - /** 0:all, 4:submitted, 5:failed, 6:cancelled. Comma-separated allowed */ - status: string; - create_date: number; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; +// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 +export interface BaseWebsocketClient< + TWSKey extends string, + TWSRequestEvent extends object, +> { + /** @internal preserves the request-event generic on the merged class type. */ + readonly __requestEventType?: TWSRequestEvent; + + on>( + event: U, + listener: WSClientEventMap[U], + ): this; + + addListener>( + event: U, + listener: WSClientEventMap[U], + ): this; + + once>( + event: U, + listener: WSClientEventMap[U], + ): this; + + prependListener>( + event: U, + listener: WSClientEventMap[U], + ): this; + + prependOnceListener>( + event: U, + listener: WSClientEventMap[U], + ): this; + + off>( + event: U, + listener: WSClientEventMap[U], + ): this; + + removeListener>( + event: U, + listener: WSClientEventMap[U], + ): this; + + removeAllListeners(event?: keyof WSClientEventMap): this; + + listeners(event: keyof WSClientEventMap): EventListener[]; + + listenerCount( + event: keyof WSClientEventMap, + listener?: WSClientEventMap[keyof WSClientEventMap], + ): number; + + emit>( + event: U, + ...args: Parameters[U]> + ): boolean; } ⋮---- -/** 0:All, 1:Open Long, 2:Close Short, 3:Open Short, 4:Close Long */ +/** @internal preserves the request-event generic on the merged class type. */ ⋮---- -/** 0:all, 4:submitted, 5:failed, 6:cancelled. Comma-separated allowed */ +on>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Req for submitCoinMPerpTpslOrder. At least one of tp_trigger_price or sl_trigger_price required. Rate limit 5/s. */ -export interface FuturesCmPerpTpslOrderReq { - contract_code: string; - direction: FuturesDirection; - volume: number | string; - tp_trigger_price?: number | string; - tp_order_price?: number | string; - tp_order_price_type?: FuturesTriggerOrderPriceType; - sl_trigger_price?: number | string; - sl_order_price?: number | string; - sl_order_price_type?: FuturesTriggerOrderPriceType; - price_protect?: boolean; -} +addListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Req for cancelCoinMPerpTpslOrder. Max 10 order_ids. Rate limit 5/s. */ -export interface FuturesCmPerpCancelTpslOrderReq { - contract_code: string; - order_id: string; -} +once>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Req for cancelCoinMPerpAllTpslOrders. Optional direction filter. Rate limit 5/s. */ -export interface FuturesCmPerpCancelAllTpslOrdersReq { - contract_code: string; - direction?: FuturesDirection; -} +prependListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Req for getCoinMPerpTpslOpenOrders. */ -export interface FuturesCmPerpTpslOpenOrdersReq { - contract_code: string; - page_index?: number; - page_size?: number; - trade_type?: 0 | 3 | 4; -} +prependOnceListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Req for getCoinMPerpTpslHistoryOrders. create_date: days, max 90. */ -export interface FuturesCmPerpTpslHisOrdersReq { - contract_code: string; - /** 0:all, 4:submitted, 5:failed, 6:cancelled, 11:expired. Comma-separated allowed */ - status: string; - create_date: number; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortBy; -} +off>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** 0:all, 4:submitted, 5:failed, 6:cancelled, 11:expired. Comma-separated allowed */ +removeListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Req for getCoinMPerpRelationTpslOrder. order_id = open order id. */ -export interface FuturesCmPerpRelationTpslOrderReq { - contract_code: string; - order_id: number | string; -} +removeAllListeners(event?: keyof WSClientEventMap): this; ⋮---- -/** Req for submitCoinMPerpTrailingOrder. callback_rate min 0.001 (0.1%). Rate limit 5/s. */ -export interface FuturesCmPerpTrailingOrderReq { - contract_code: string; - direction: FuturesDirection; - offset: FuturesOffset; - volume: number | string; - callback_rate: number | string; - active_price: number | string; - order_price_type: FuturesTrailingOrderPriceType; - lever_rate?: number; -} +listeners(event: keyof WSClientEventMap): EventListener[]; ⋮---- -/** Req for cancelCoinMPerpTrailingOrder. Max 10 order_ids. Rate limit 5/s. */ -export interface FuturesCmPerpCancelTrailingOrderReq { - contract_code: string; - order_id: string; -} +listenerCount( + event: keyof WSClientEventMap, + listener?: WSClientEventMap[keyof WSClientEventMap], + ): number; ⋮---- -/** Req for cancelCoinMPerpAllTrailingOrders. Optional direction/offset filter. Rate limit 5/s. */ -export interface FuturesCmPerpCancelAllTrailingOrdersReq { - contract_code: string; - direction?: FuturesDirection; - offset?: FuturesOffset; -} +emit>( + event: U, + ...args: Parameters[U]> + ): boolean; ⋮---- -/** Req for getCoinMPerpTrailingOpenOrders. */ -export interface FuturesCmPerpTrailingOpenOrdersReq { - contract_code: string; - trade_type?: 0 | 1 | 2 | 3 | 4; - page_index?: number; - page_size?: number; +/** + * A midflight WS request event (e.g. subscribe to these topics). + * + * - requestKey: unique identifier for this request, if available. Can be anything as a string. + * - requestEvent: the raw request, as an object, that will be sent on the ws connection. This may contain multiple topics/requests in one object, if the exchange supports it. + */ +export interface MidflightWsRequestEvent { + requestKey: string | number; + requestEvent: TEvent; } ⋮---- -/** Req for getCoinMPerpTrailingHistoryOrders. create_date: days, max 90. */ -export interface FuturesCmPerpTrailingHisOrdersReq { - contract_code: string; - /** 0:all, 4:success, 5:failed, 6:cancelled. Comma-separated allowed */ - status: string; - /** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long */ - trade_type: 0 | 1 | 2 | 3 | 4; - create_date: number; - page_index?: number; - page_size?: number; - sort_by?: FuturesSortByCmPerp; -} +/** + * Appends wsKey and isWSAPIResponse to all events. + * Some events are arrays, this handles that nested scenario too. + */ +function getFinalEmittable( + emittable: EmittableEvent, + wsKey: TWSKey, + isWSAPIResponse?: boolean, +): WSClientEventPayload; +function getFinalEmittable( + emittable: EmittableEvent[], + wsKey: TWSKey, + isWSAPIResponse?: boolean, +): WSClientEventPayload[]; +function getFinalEmittable( + emittable: EmittableEvent | EmittableEvent[], + wsKey: TWSKey, + isWSAPIResponse?: boolean, +): WSClientEventPayload | WSClientEventPayload[] ⋮---- -/** 0:all, 4:success, 5:failed, 6:cancelled. Comma-separated allowed */ +// Some topics just emit an array. +// This is consistent with how it was before the WS API upgrade: ⋮---- -/** 0:all, 1:buy long, 2:sell short, 3:buy short, 4:sell long */ +// const { event, ...others } = emittable; +// return { +// ...others, +// event: event.map((subEvent) => +// getFinalEmittable(subEvent, wsKey, isWSAPIResponse), +// ), +// }; ⋮---- -/** Req for POST /swap-api/v1/swap_master_sub_transfer */ -export interface FuturesCmPerpMasterSubTransferReq { - sub_uid: number; - contract_code: string; - amount: number | string; - type: FuturesTransferType; - client_order_id?: number; -} +/** + * Users can conveniently pass topics as strings or objects (object has topic name + optional params). + * + * This method normalises topics into objects (object has topic name + optional params). + */ +function getNormalisedTopicRequests( + wsTopicRequests: WSTopicRequestOrStringTopic[], +): WSTopicRequest[] ⋮---- -/** Req for getCoinMPerpMasterSubTransfers */ -export interface FuturesCmPerpMasterSubTransfersReq { - contract_code: string; - transfer_type?: string; - create_date: number; - page_index?: number; - page_size?: number; -} +// passed as string, convert to object ⋮---- -/** Req for POST /swap-api/v3/swap_financial_record */ -export interface FuturesCmPerpFinancialRecordReq { - contract: string; - type?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +// already a normalised object, thanks to user ⋮---- -/** Req for POST /swap-api/v3/swap_financial_record_exact. Same params as swap_financial_record. */ -export type FuturesCmPerpFinancialRecordExactReq = - FuturesCmPerpFinancialRecordReq; +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging +export abstract class BaseWebsocketClient< +TWSKey extends string, ⋮---- -/** Req for GET /swap-api/v1/swap_sub_auth_list */ -export interface FuturesCmPerpSubPermissionsReq { - sub_uid?: string; - start_time?: number; - end_time?: number; - direct?: FuturesDirect; - from_id?: number; -} +constructor( + options?: WSClientConfigurableOptions & { wsLoggerCategory: string }, + logger?: DefaultLogger, +) ⋮---- -/** Req for GET /index/market/history/swap_estimated_rate_kline */ -export interface FuturesCmPerpFundingRateKlinesReq { - contract_code: string; - period: FuturesKlinePeriod; - size: number; -} +// Futures public WS closes a socket with no ping for 25s. Default 10s stays under that. ⋮---- -/** Req for GET /index/market/history/swap_basis */ -export interface FuturesCmPerpBasisDataReq { - contract_code: string; - period: FuturesKlinePeriod; - size: number; - basis_price_type?: FuturesBasisPriceType; -} +// Requires a confirmation "response" from the ws connection before assuming it is ready ⋮---- -/** Req for GET /index/market/history/swap_premium_index_kline */ -export interface FuturesCmPerpPremiumIndexKlinesReq { - contract_code: string; - period: FuturesKlinePeriod; - size: number; -} +// Automatically auth after opening a connection? ⋮---- -/** Req for GET /index/market/history/swap_mark_price_kline */ -export interface FuturesCmPerpMarkPriceKlinesReq { - contract_code: string; - period: FuturesKlinePeriod; - size: number; -} +// Automatically include auth/sign/token with every WS request. +// Automatically handled during getWsRequestEvents. ⋮---- -/** Req for GET /swap-ex/market/history/kline. Either size or (from+to) required. */ -export interface FuturesCmPerpKlinesReq { - contract_code: string; - period: FuturesKlinePeriod; - size?: number; - from?: number; - to?: number; -} +// Automatically re-auth WS API, if we were auth'd before and get reconnected ⋮---- -/** Req for GET /swap-api/v1/swap_historical_funding_rate */ -export interface FuturesCmPerpHistoricalFundingRateReq { - contract_code: string; - page_index?: number; - page_size?: number; -} +// Whether to use native heartbeats (depends on the exchange) ⋮---- -/** Req for GET /swap-api/v1/swap_his_open_interest */ -export interface FuturesCmPerpGetOpenInterestReq { - contract_code: string; - /** 60min, 4hour, 12hour, 1day */ - period: FuturesOpenInterestPeriod; - /** 1: cont, 2: cryptocurrency */ - amount_type: 1 | 2; - /** Default 48, [1, 200] */ - size?: number; -} +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -/** 60min, 4hour, 12hour, 1day */ +/** + * Return true if this wsKey connection should automatically authenticate immediately after connecting + */ +protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; ⋮---- -/** 1: cont, 2: cryptocurrency */ +protected abstract isCustomReconnectionNeeded(wsKey: TWSKey): boolean; ⋮---- -/** Default 48, [1, 200] */ +protected abstract triggerCustomReconnectionWorkflow( + wsKey: TWSKey, + ): Promise; ⋮---- -/** Req for GET /swap-api/v3/swap_liquidation_orders. 0=fully filled, 5=liquidated close, 6=liquidated open. */ -export interface FuturesCmPerpLiquidationOrdersReq { - /** Contract code. Case-insensitive */ - contract: string; - /** 0: fully filled liquidated; 5: liquidated close; 6: liquidated open */ - trade_type: 0 | 5 | 6; - /** Start time (ms). Window max 2h, within 90 days */ - start_time?: number; - /** End time (ms). Default now. Within 90 days */ - end_time?: number; - /** next=chronological, prev=reverse. Default prev */ - direct?: FuturesDirect; - /** Pagination: min/max query_id from last result depending on direct */ - from_id?: number; -} +protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocketLike): boolean; ⋮---- -/** Contract code. Case-insensitive */ +protected abstract sendPongEvent( + wsKey: TWSKey, + ws: WebSocketLike, + event?: unknown, + ): void; ⋮---- -/** 0: fully filled liquidated; 5: liquidated close; 6: liquidated open */ +protected abstract isWsPing(data: unknown): boolean; ⋮---- -/** Start time (ms). Window max 2h, within 90 days */ +protected abstract isWsPong(data: unknown): boolean; ⋮---- -/** End time (ms). Default now. Within 90 days */ +protected abstract authPrivateConnectionsOnConnect(_wsKey: TWSKey): boolean; ⋮---- -/** next=chronological, prev=reverse. Default prev */ +/** + * Return the event sent to the server to trigger authentication. If the event requires waiting for another event first (e.g. a challenge), return 'waitForEvent' and the library will wait for that event before calling this method again. + * + * Usually only called once per connection, unless the connection drops/is reset. + */ +protected abstract getWsAuthRequestEvent( + wsKey: TWSKey, + eventToAuth?: object, + ): Promise; ⋮---- -/** Pagination: min/max query_id from last result depending on direct */ +protected abstract isPrivateTopicRequest( + request: WSTopicRequest, + wsKey: TWSKey, + ): boolean; ⋮---- -/** Req for GET /swap-api/v1/swap_settlement_records */ -export interface FuturesCmPerpSettlementRecordsReq { - contract_code: string; - /** Start time (ms). Default: now - 90 days */ - start_time?: number; - /** End time (ms). Default: now */ - end_time?: number; - page_index?: number; - page_size?: number; -} +protected abstract getPrivateWSKeys(): TWSKey[]; ⋮---- -/** Start time (ms). Default: now - 90 days */ +protected abstract getWsUrl(wsKey: TWSKey): Promise; ⋮---- -/** End time (ms). Default: now */ +protected abstract getMaxTopicsPerSubscribeEvent( + wsKey: TWSKey, + ): number | null; ⋮---- /** - * Copy Trading - */ + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + */ +protected abstract getWsRequestEvents( + wsKey: TWSKey, + operation: WSOperation, + requests: WSTopicRequest[], + ): Promise[]>; ⋮---- -/** Req for GET /api/v6/copyTrading/trader/instruments. Product type PERP or omit for all. */ -export interface FuturesCopyTraderInstrumentsReq { - /** Product type. PERP = Perpetual Swap. Omit to return all. */ - instType?: 'PERP'; -} +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected abstract resolveEmittableEvents( + wsKey: TWSKey, + event: MessageEventLike, + ): EmittableEvent[]; ⋮---- -/** Product type. PERP = Perpetual Swap. Omit to return all. */ +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +protected abstract connectAll(): Promise[]; ⋮---- -/** Req for GET /api/v6/copyTrading/trader/statistics. Product type required. */ -export interface FuturesCopyTraderStatisticsReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; -} +protected isPrivateWsKey(wsKey: TWSKey): boolean ⋮---- -/** Product type. PERP = Perpetual Swap */ +/** Returns auto-incrementing request ID, used to track promise references for async requests */ +protected getNewRequestId(): number ⋮---- -/** Req for GET /api/v6/copyTrading/trader/profit-sharing-history. Historical profit sharing details. */ -export interface FuturesCopyTraderProfitSharingHistoryReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; - /** Product ID e.g. BTC-USDT-PERP */ - instId?: string; - /** Filter start time (inclusive), Unix timestamp in microseconds */ - begin?: string; - /** Filter end time (inclusive), Unix timestamp in microseconds */ - end?: string; - /** Paginate content before (older data) this ID (exclusive) */ - after?: string; - /** Paginate content after (newer data) this ID (exclusive) */ - before?: string; - /** Number of results to return, max 100, default 100 */ - limit?: string; -} +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + operation: string, + params?: unknown, + ): Promise; ⋮---- -/** Product type. PERP = Perpetual Swap */ +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + channel: string, + params: unknown, + ): Promise; ⋮---- -/** Product ID e.g. BTC-USDT-PERP */ +public getTimeOffsetMs() ⋮---- -/** Filter start time (inclusive), Unix timestamp in microseconds */ +public setTimeOffsetMs(newOffset: number) ⋮---- -/** Filter end time (inclusive), Unix timestamp in microseconds */ +/** + * Don't call directly! Use subscribe() instead! + * + * Subscribe to one or more topics on a WS connection (identified by WS Key). + * + * - Topics are automatically cached + * - Connections are automatically opened, if not yet connected + * - Authentication is automatically handled + * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). + * + * @param wsTopicRequests array of topics to subscribe to + * @param wsKey ws key referring to the ws connection these topics should be subscribed on + */ +protected async subscribeTopicsForWsKey( + wsTopicRequests: WSTopicRequestOrStringTopic[], + wsKey: TWSKey, +) ⋮---- -/** Paginate content before (older data) this ID (exclusive) */ +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- -/** Paginate content after (newer data) this ID (exclusive) */ +// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect ⋮---- -/** Number of results to return, max 100, default 100 */ +// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. ⋮---- -/** Req for GET /api/v6/copyTrading/trader/profit-sharing-history-summary. Historical profit sharing summary. */ -export interface FuturesCopyTraderProfitSharingHistorySummaryReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; -} +/** + * Are we in the process of connection? Nothing to send yet. + */ ⋮---- -/** Product type. PERP = Perpetual Swap */ +// We're connected. Check if auth is needed and if already authenticated ⋮---- -/** Req for GET /api/v6/copyTrading/trader/unrealized-profit-sharing-summary. Unrealized profit sharing summary. */ -export interface FuturesCopyTraderUnrealizedProfitSharingSummaryReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; - /** Profit sharing currency */ - ccy?: string; -} +/** + * If not authenticated yet and auth is required, don't request topics yet. + * + * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. + */ ⋮---- -/** Product type. PERP = Perpetual Swap */ +// Finally, request subscription to topics if the connection is healthy and ready ⋮---- -/** Profit sharing currency */ +protected async unsubscribeTopicsForWsKey( + wsTopicRequests: WSTopicRequestOrStringTopic[], + wsKey: TWSKey, +): Promise ⋮---- -/** Req for GET /api/v6/copyTrading/trader/followers. Trader query followers. */ -export interface FuturesCopyTraderFollowersReq { - /** Product type. PERP = Perpetual Swap. Omit to return all. */ - instType?: 'PERP'; - /** Filter start time (inclusive), Unix timestamp in microseconds */ - begin?: string; - /** Filter end time (inclusive), Unix timestamp in microseconds */ - end?: string; - /** Paginate content before (older data) this ID (exclusive) */ - after?: string; - /** Paginate content after (newer data) this ID (exclusive) */ - before?: string; - /** Number of results to return, max 100, default 100 */ - limit?: string; -} +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- -/** Product type. PERP = Perpetual Swap. Omit to return all. */ +// If not connected, don't need to do anything. +// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. ⋮---- -/** Filter start time (inclusive), Unix timestamp in microseconds */ +// We're connected. Check if auth is needed and if already authenticated ⋮---- -/** Filter end time (inclusive), Unix timestamp in microseconds */ +/** + * If not authenticated yet and auth is required, don't need to do anything. + * We don't subscribe to topics until auth is complete anyway. + */ ⋮---- -/** Paginate content before (older data) this ID (exclusive) */ +// Finally, request subscription to topics if the connection is healthy and ready ⋮---- -/** Paginate content after (newer data) this ID (exclusive) */ +/** + * Splits topic requests into two groups, public & private topic requests + */ +private sortTopicRequestsIntoPublicPrivate( + wsTopicRequests: WSTopicRequest[], + wsKey: TWSKey, +): ⋮---- -/** Number of results to return, max 100, default 100 */ +/** Get the WsStore that tracks websockets & topics */ +public getWsStore(): WsStore> ⋮---- -/** Req for POST /api/v6/copyTrading/trader/follower. Trader remove follower. Max 10 followers at once. */ -export interface FuturesCopyTraderFollowerRemoveReq { - /** Follower user IDs */ - followerUids: string[]; - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; -} +public close(wsKey: TWSKey, force?: boolean) ⋮---- -/** Follower user IDs */ +public closeAll(force?: boolean) ⋮---- -/** Product type. PERP = Perpetual Swap */ +public isConnected(wsKey: TWSKey): boolean ⋮---- -/** Req for POST /api/v6/copyTrading/trader/transfer. Trader account transfer. */ -export interface FuturesCopyTraderTransferReq { - /** Amount to transfer */ - amt: string; - /** Source account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ - from: string; - /** Destination account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ - to: string; - /** Currency, default USDT */ - ccy?: string; -} +/** + * Request connection to a specific websocket, instead of waiting for automatic connection. + */ +public async connect( + wsKey: TWSKey, + customUrl?: string | undefined, + throwOnError?: boolean, +): Promise ⋮---- -/** Amount to transfer */ +// Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()! ⋮---- -/** Source account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ +private connectToWsUrl(url: string, wsKey: TWSKey): WebSocketLike ⋮---- -/** Destination account: 1=Spot, 2=USDT-Margined Contract, 4=Contract Copy Trading */ +// Event handlers for native heartbeats / ping/pong frames ⋮---- -/** Currency, default USDT */ +private parseWsError( + context: string, + error: unknown, + wsKey: TWSKey, +): boolean ⋮---- -/** Req for POST /api/v6/copyTrading/trader/follower-settings. Trader set lead trading config. */ -export interface FuturesCopyTraderFollowerSettingsReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; - /** Enable or disable copy trading */ - enable: boolean; - /** Profit sharing ratio when enabling: 0.1|0.15|0.2|0.25 */ - profitSharingRatio?: string; - /** Max followers when enabling: 100|200|500|1000 */ - maxFollowers?: string; -} +// Allow retry by default (in some places that call this). Prevent deadloop in hard failure (401) ⋮---- -/** Product type. PERP = Perpetual Swap */ +/** Get a signature, build the auth request and send it */ +private async sendAuthRequest( + wsKey: TWSKey, + eventToAuth?: object, +): Promise ⋮---- -/** Enable or disable copy trading */ +private async advanceAuthRequest( + wsKey: TWSKey, + authPromise: DeferredPromise, + eventToAuth?: object, +): Promise ⋮---- -/** Profit sharing ratio when enabling: 0.1|0.15|0.2|0.25 */ +// If not required, this won't return anything ⋮---- -/** Max followers when enabling: 100|200|500|1000 */ +// Short-circuit this for the next time it's called ⋮---- -/** Req for POST /api/v6/copyTrading/trader/config. Trader view lead trading config. */ -export interface FuturesCopyTraderConfigReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; -} +private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) ⋮---- -/** Product type. PERP = Perpetual Swap */ +// Some streams need a specialist reconnection workflow. +// E.g. the user data stream can't just be reconnected as is. ⋮---- -/** Req for POST /api/v6/copyTrading/trader/apikey. Trader create lead trading API key. */ -export interface FuturesCopyTraderApikeyReq { - /** Product type. PERP = Perpetual Swap */ - instType: 'PERP'; -} +private ping(wsKey: TWSKey) ⋮---- -/** Product type. PERP = Perpetual Swap */ - -================ -File: .gitignore -================ -!.gitkeep -.DS_Store -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json -pids -*.pid -*.seed -*.pid.lock -node_modules/ -.npm -.eslintcache -.node_repl_history -*.tgz -.yarn-integrity -.env -.env.test -.cache -dist -bundleReport.html -.history/ -examples/ignoreme -localtest.sh -repomix.sh -doc -.cursor/ -futuresOrder2.ts -.vscode/ -WSWIP.md -.tmp-packed* - -================ -File: src/types/response/futures.types.ts -================ /** - * Reference - */ + * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. + * If closed, trigger a reconnect immediately + */ +protected executeReconnectableClose(wsKey: TWSKey, reason: string) ⋮---- -/** Paginated response base. Use FuturesPaginatedData or FuturesPaginatedSettlement for specific data keys. */ -export interface FuturesPaginatedBase { - total_page: number; - current_page: number; - total_size: number; -} +private clearTimers(wsKey: TWSKey) ⋮---- -/** Paginated response with `data` array (e.g. historical funding rate, liquidation orders). */ -export type FuturesPaginatedData = FuturesPaginatedBase & { data: T[] }; +// Send a ping at intervals +private clearPingTimer(wsKey: TWSKey) ⋮---- -/** Paginated response with `settlement_record` array. */ -export type FuturesPaginatedSettlement = FuturesPaginatedBase & { - settlement_record: T[]; -}; +// Expect a pong within a time limit +private clearPongTimer(wsKey: TWSKey) ⋮---- -/** Paginated response with `sub_list` array (sub-account info list). */ -export type FuturesPaginatedSubList = FuturesPaginatedBase & { - sub_list: T[]; -}; +// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); ⋮---- -/** Paginated response with `transfer_record` array (master-sub transfers). */ -export type FuturesPaginatedTransferRecord = FuturesPaginatedBase & { - transfer_record: T[]; -}; +// this.logger.trace(`No active pong timer for "${wsKey}"`); ⋮---- -/** Paginated response with `orders` array (open orders, trigger orders, etc.). */ -export type FuturesPaginatedOrders = FuturesPaginatedBase & { orders: T[] }; +private clearReconnectTimer(wsKey: TWSKey) ⋮---- -/** Funding rate from swap_funding_rate and swap_batch_funding_rate */ -export interface FuturesFundingRate { - funding_rate: string; - contract_code: string; - symbol: string; - fee_asset: string; - funding_time: string; - /** Deprecated, default null */ - estimated_rate?: string | null; - /** Deprecated, default null */ - next_funding_time?: string | null; -} +/** + * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics + * + * If events are an object, these should be stringified (`return JSON.stringify(event);`) + * Each event returned by this will be sent one at a time + * + * Events are automatically split into smaller batches, by this method, if needed. + */ +protected async getWsOperationEventsForTopics( + topics: WSTopicRequest[], + wsKey: TWSKey, + operation: WSOperation, +): Promise[]> ⋮---- -/** Deprecated, default null */ +// Events that are ready to send (usually stringified JSON) ⋮---- -/** Deprecated, default null */ +/** + * Simply builds and sends subscribe events for a list of topics for a ws key + * + * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. + */ +private async requestSubscribeTopics( + wsKey: TWSKey, + wsTopicRequests: WSTopicRequest[], +) ⋮---- -/** Historical funding rate item from swap_historical_funding_rate */ -export interface FuturesHistoricalFundingRate { - avg_premium_index: string; - funding_rate: string; - funding_time: string; - /** Deprecated, default null */ - realized_rate?: string | null; - contract_code: string; - symbol: string; - fee_asset: string; -} +// Automatically splits requests into smaller batches, if needed ⋮---- -/** Deprecated, default null */ +`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" ⋮---- -/** Paginated wrapper for swap_historical_funding_rate data */ -export type FuturesHistoricalFundingRatePage = - FuturesPaginatedData; +/** + * Simply builds and sends unsubscribe events for a list of topics for a ws key + * + * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. + */ +private async requestUnsubscribeTopics( + wsKey: TWSKey, + wsTopicRequests: WSTopicRequest[], +) ⋮---- -/** Liquidation order item from swap_liquidation_orders */ -export interface FuturesLiquidationOrder { - query_id: number; - symbol: string; - contract_code: string; - created_at: number; - direction: string; - offset: string; - volume: number; - amount: number; - price: number; - trade_turnover: number; - pair: string; - business_type: string; -} +/** + * Try sending a string event on a WS connection (identified by the WS Key) + */ +private tryWsSendWithResult( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, +): boolean ⋮---- -/** Settlement record item from swap_settlement_records */ -export interface FuturesSettlementRecord { - symbol: string; - contract_code: string; - settlement_time: number; - clawback_ratio: number; - settlement_price: number; - settlement_type: string; - business_type: string; - pair: string; -} +public tryWsSend( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, +): void ⋮---- -/** Paginated settlement records from swap_settlement_records */ -export type FuturesSettlementRecordsPage = - FuturesPaginatedSettlement; +/** Send a message while reporting whether it reached the socket API. */ +protected tryWsSendWithStatus( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, +): boolean ⋮---- -/** Elite ratio list item (account and position) */ -export interface FuturesEliteRatioList { - buy_ratio: number; - sell_ratio: number; - /** Account ratio only */ - locked_ratio?: number; - ts: number; -} +private async onWsOpen( + event: unknown, + wsKey: TWSKey, + url: string, + ws: WebSocketLike, +) ⋮---- -/** Account ratio only */ +private resolveConnectionInProgressPromise(wsKey: TWSKey) ⋮---- -/** Elite account/position ratio data from swap_elite_account_ratio and swap_elite_position_ratio */ -export interface FuturesEliteRatio { - symbol: string; - contract_code: string; - pair: string; - business_type: string; - list: FuturesEliteRatioList[]; -} +// Resolve & cleanup deferred "connection attempt in progress" promise ⋮---- -/** System status item from swap_api_state. 1=available, 0=unavailable */ -export interface FuturesApiState { - symbol: string; - contract_code: string; - margin_mode: string; - margin_account: string; - open: number; - close: number; - cancel: number; - transfer_in: number; - transfer_out: number; - master_transfer_sub: number; - sub_transfer_master: number; - master_transfer_sub_inner_in: number; - master_transfer_sub_inner_out: number; - sub_transfer_master_inner_in: number; - sub_transfer_master_inner_out: number; - transfer_inner_in: number; - transfer_inner_out: number; -} +/** + * Called automatically once a connection is ready. + * - Some exchanges are ready immediately after the connections open. + * - Some exchanges send an event to confirm the connection is ready for us. + * + * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called. + */ +private async onWsReadyForEvents(wsKey: TWSKey) ⋮---- -/** Cross ladder margin tier from swap_cross_ladder_margin */ -export interface FuturesLadderMarginTier { - min_margin_balance: number | null; - max_margin_balance: number | null; - min_margin_available: number | null; - max_margin_available: number | null; -} +// Some websockets require an auth packet to be sent after opening the connection ⋮---- -/** Cross ladder margin list item */ -export interface FuturesCrossLadderMarginList { - lever_rate: number; - ladders: FuturesLadderMarginTier[]; -} +// Reconnect to topics known before it connected ⋮---- -/** Cross tiered margin item from swap_cross_ladder_margin. Isolated (swap_ladder_margin) omits business_type, pair, contract_type. */ -export interface FuturesCrossLadderMargin { - margin_account: string; - symbol: string; - contract_code: string; - margin_mode: string; - list: FuturesCrossLadderMarginList[]; - business_type?: string; - pair?: string; - contract_type?: string; -} +// Request sub to public topics, if any ⋮---- -/** Estimated settlement price item from swap_estimated_settlement_price. Empty around settlement/delivery. */ -export interface FuturesEstimatedSettlementPrice { - contract_code: string; - estimated_settlement_price: number | null; - settlement_type: string; - contract_type: string; - pair: string; - business_type: string; -} +// Request sub to private topics, if auth on connect isn't needed ⋮---- -/** Tiered adjustment factor ladder from swap_adjustfactor and swap_cross_adjustfactor */ -export interface FuturesAdjustFactorLadder { - ladder: number; - min_size: number; - max_size: number | null; - adjust_factor: number; -} +/** + * Handle subscription to private topics _after_ authentication successfully completes asynchronously. + * + * Only used for exchanges that require auth before sending private topic subscription requests + */ +private onWsAuthenticated(wsKey: TWSKey, event: unknown) ⋮---- -/** Adjust factor list item */ -export interface FuturesAdjustFactorList { - lever_rate: number; - ladders: FuturesAdjustFactorLadder[]; -} +// Resolve & cleanup deferred "auth attempt in progress" promise ⋮---- -/** Tiered adjustment factor item from swap_adjustfactor and swap_cross_adjustfactor. Cross includes business_type, pair, contract_type. */ -export interface FuturesAdjustFactor { - symbol: string; - contract_code: string; - margin_mode: string; - list: FuturesAdjustFactorList[]; - business_type?: string; - pair?: string; - contract_type?: string; -} +// Remove before continuing, in case there's more requests queued ⋮---- -/** Risk reserve balance from /v1/insurance_fund_info */ -export interface FuturesInsuranceFundInfo { - insurance_fund: string; - quote_currency?: string; -} +private onWsPing( + event: unknown, + wsKey: TWSKey, + ws: WebSocketLike, + source: WsEventInternalSrc, +) ⋮---- -/** Historical risk reserve item from /v1/insurance_fund_history */ -export interface FuturesInsuranceFundHistory { - query_id: number; - insurance_fund: string; - date: string; -} +private onWsPong(event: unknown, wsKey: TWSKey, source: WsEventInternalSrc) ⋮---- -/** Price limit item from swap_price_limit. business_type, pair, contract_type optional for CM products. */ -export interface FuturesPriceLimit { - symbol: string; - contract_code: string; - high_limit: number; - low_limit: number; - business_type?: string; - pair?: string; - contract_type?: string; -} +// Necessary when native heartbeats are used ⋮---- -/** Open interest item from swap_open_interest */ -export interface FuturesOpenInterest { - symbol: string; - volume: number; - amount: number; - contract_code: string; - value: number; - trade_amount: number; - trade_volume: number; - trade_turnover: number; - contract_type: string; - pair: string; - business_type: string; -} +private async onWsMessage( + event: unknown, + wsKey: TWSKey, + ws: WebSocketLike, + didDecompress = false, +): Promise ⋮---- -/** Contract info item from swap_contract_info */ -export interface FuturesContractInfo { - symbol: string; - contract_code: string; - contract_size: number; - price_tick: number; - settlement_date: string; - settlement_period: string; - create_date: string; - delivery_time: string; - contract_status: number; - support_margin_mode?: string; - contract_type: string; - pair: string; - business_type: string; - delivery_date: string; - adjust?: unknown[]; - price_estimated?: unknown[]; - open_type?: number; - trade_partition?: string; - labels?: string[]; - tradfi_labels?: string[]; -} +// console.log('onMessageRaw: ', (event as any).data); +// any message can clear the pong timer - wouldn't get a message if the ws wasn't working ⋮---- -/** Index price item from swap_index. symbol optional (CM Delivery uses symbol). */ -export interface FuturesIndexPrice { - contract_code?: string; - symbol?: string; - index_price: number; - index_ts: number; -} +// console.log(`raw event: `, { data, dataType, emittableEvents }); ⋮---- -/** Index constituent component from swap_contract_constituents */ -export interface FuturesIndexConstituentComponent { - exchange: string; - symbol: string; - /** Price as string. -1 means HTX masked proprietary third-party index pricing. */ - symbol_price: string; - weights: string; -} +// Other event types are automatically emitted here ⋮---- -/** Price as string. -1 means HTX masked proprietary third-party index pricing. */ +// this.logger.trace( +// `onWsMessage().emit(${emittable.eventType}).done()`, +// emittableFinalEvent, +// ); ⋮---- -/** Index constituents data from swap_contract_constituents. contract_code or symbol per product. */ -export interface FuturesIndexConstituents { - contract_code?: string; - symbol?: string; - index_price: string; - ts: number; - components: FuturesIndexConstituentComponent[]; -} +// this.logger.trace('Decompressed message event from buffer', { +// ...this.WS_LOGGER_CATEGORY, +// wsKey, +// decompressed, +// }); ⋮---- -/** Contract elements price tick / value item */ -export interface FuturesContractElementsPrice { - business_type: number; - price: string; -} +private onWsClose(event: unknown, wsKey: TWSKey) ⋮---- -/** Contract elements order limit item */ -export interface FuturesContractElementsOrderLimit { - instrument_type: number; - open: string; - close: string; - order_type?: number; - open_after_closing?: string; -} +// unintentional close, attempt recovery ⋮---- -/** Contract elements contract info item */ -export interface FuturesContractElementsContractInfo { - contract_code: string; - instrument_type: number; - settlement_date: string; - delivery_time: string; - create_date: string; - contract_status: number; - delivery_date: string; - trigger_protect?: number; -} +// clean up any pending promises for this connection ⋮---- -/** Timestamp response from /api/v1/timestamp. No data field. */ -export interface FuturesTimestamp { - status: string; - ts: number; -} +// this.clearTopicsPendingSubscriptions(wsKey, true, 'WS Closed'); ⋮---- -/** Heartbeat data from /heartbeat/ - system availability */ -export interface FuturesHeartbeat { - heartbeat?: number; - swap_heartbeat?: number; - estimated_recovery_time?: number | null; - swap_estimated_recovery_time?: number | null; - linear_swap_heartbeat?: number; - linear_swap_estimated_recovery_time?: number | null; -} +// intentional close - clean up +// clean up any pending promises for this connection ⋮---- -/** Contract elements item from swap_query_elements */ -export interface FuturesContractElements { - contract_code: string; - mode_type: number; - swap_delivery_type: number; - instrument_index_code: string; - real_time_settlement: number; - transfer_profit_ratio: number; - cross_transfer_profit_ratio: number; - instrument_type: number[]; - trade_partition: string; - min_level: string; - max_level: string; - settle_period: number; - funding_rate_cap: string; - funding_rate_floor: string; - trigger_protect?: number; - long_position_limit?: string; - offset_order_limit?: string; - open_order_limit?: string; - short_position_limit?: string; - price_tick?: string; - instrument_value?: string; - price_ticks?: FuturesContractElementsPrice[]; - instrument_values?: FuturesContractElementsPrice[]; - order_limits?: FuturesContractElementsOrderLimit[]; - normal_limits?: { - instrument_type: number; - open: string; - close: string; - }[]; - open_limits?: { instrument_type: number; open: string; close: string }[]; - trade_limits?: { - instrument_type: number; - open: string; - close: string; - }[]; - contract_infos?: FuturesContractElementsContractInfo[]; -} +// This was an intentional close, delete all state for this connection, as if it never existed: +⋮---- +private getWs(wsKey: TWSKey) +⋮---- +private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) ⋮---- /** - * Market + * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) + */ +protected async assertIsConnected(wsKey: TWSKey): Promise +⋮---- +// Already in progress? Await shared promise and retry +⋮---- +// Start connection, it should automatically store/return a promise. +⋮---- +/** + * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) + */ +public async assertIsAuthenticated(wsKey: TWSKey): Promise +⋮---- +// Already in progress? Await shared promise and retry +⋮---- +// Start authentication, it should automatically store/return a promise. + +================ +File: src/types/response/spot.types.ts +================ +/** + * Reference Data */ ⋮---- -/** Market depth tick from market/depth. ch, id, mrid, version optional per product. Payload in "tick". */ -export interface FuturesMarketDepthTick { - asks: [number, number][]; - bids: [number, number][]; - ch?: string; - id?: number; - mrid?: number; - ts: number; - version?: number; +/** Status page response from status.huobigroup.com */ +export interface SpotSystemStatusPage { + page: { + id: string; + name: string; + url: string; + time_zone: string; + updated_at: string; + }; + components: { + id: string; + name: string; + status: string; + created_at: string; + updated_at: string; + [key: string]: unknown; + }[]; + incidents: + | { + id: string; + name: string; + status: string; + created_at: string; + updated_at: string; + [key: string]: unknown; + }[] + | null; + scheduled_maintenances: + | { + id: string; + name: string; + status: string; + created_at: string; + updated_at: string; + scheduled_for: string; + scheduled_until: string; + [key: string]: unknown; + }[] + | null; + status: { + indicator: 'none' | 'minor' | 'major' | 'critical' | 'maintenance'; + description: string; + }; } ⋮---- -/** BBO tick from market/bbo. contract_code or symbol per product. ask/bid: [price, qty]. */ -export interface FuturesBboTick { - contract_code?: string; - symbol?: string; - business_type?: string; - mrid: number; - ask: [number, number]; - bid: [number, number]; - ts: number; -} +/** Market status: 1=normal, 2=halted, 3=cancel-only */ +export type SpotMarketStatus = 1 | 2 | 3; ⋮---- -/** Kline item from market/history/kline. trade_turnover optional per product. */ -export interface FuturesKline { - id: number; - vol: number; - count: number; - open: number; - close: number; - low: number; - high: number; - amount: number; - trade_turnover?: number; +/** Halt reason: 2=emergency-maintenance, 3=scheduled-maintenance */ +export type SpotHaltReason = 2 | 3; +⋮---- +export interface SpotMarketStatusData { + marketStatus: SpotMarketStatus; + haltStartTime?: number; + haltEndTime?: number; + haltReason?: SpotHaltReason; + affectedSymbols?: string; } ⋮---- -/** Basis data item from /index/market/history/linear_swap_basis and /index/market/history/basis */ -export interface FuturesBasis { - id: number; - contract_price: string; - index_price: string; - basis: string; - basis_rate: string; +export interface SpotMarketStatusResponse { + code: number; + message: string; + data: SpotMarketStatusData; } ⋮---- -/** Mark price kline item. Also used for premium index and estimated rate kline. trade_turnover optional. */ -export interface FuturesMarkPriceKline { - id: number; - vol: string; - count: string; - open: string; - close: string; - low: string; - high: string; - amount: string; - trade_turnover?: string; -} -⋮---- -/** 24h ticker from market detail/merged. contract_code, symbol, business_type optional per product. */ -export interface FuturesTicker { - id: number; - ts: number; - amount: string; - count: number; - vol: string; - open: string; - close: string; - low: string; - high: string; - trade_turnover?: string; - ask: [number, number]; - bid: [number, number]; - contract_code?: string; - symbol?: string; - business_type?: string; - number_of?: string; -} -⋮---- -/** Trade item from last trade and history trade. symbol, contract_code, business_type, trade_turnover optional per product. */ -export interface FuturesTrade { - id: number; - price: string | number; - amount: string | number; - direction: string; - ts: number; - quantity?: string | number; - contract_code?: string; - business_type?: string; - trade_turnover?: string | number; - symbol?: string; - /** Whether the trade involved an RPI order. USDT-M uses snake_case. */ - is_rpi_trade?: boolean | number | string; - /** Whether the trade is an RPI trade. Coin-M uses the hyphenated name. */ - 'is-rpi-trade'?: boolean | number | string; +/** Trading symbol from /v2/settings/common/symbols */ +export interface SpotTradingSymbol { + sc: string; + si?: string; + scr?: string; + dn: string; + bc: string; + bcdn: string; + qc: string; + qcdn: string; + state: string; + whe?: boolean; + cd?: boolean; + te?: boolean; + toa?: number; + sp?: string; + w?: number; + ttp?: number; + tap?: number; + tpp?: number; + fp?: number; + suspend_desc?: string; + transfer_board_desc?: string; + tags?: string; + lr?: number | null; + smlr?: number | null; + flr?: string | null; + wr?: string | null; + d?: number | null; + elr?: string | null; + /** Whether the symbol supports RPI trading */ + enable_rpi?: boolean | number | string; + p?: { id?: number; name?: string; weight?: number }[]; } ⋮---- -/** Whether the trade involved an RPI order. USDT-M uses snake_case. */ -⋮---- -/** Whether the trade is an RPI trade. Coin-M uses the hyphenated name. */ +/** Whether the symbol supports RPI trading */ ⋮---- -/** Last trade tick from market/trade. Payload in "tick". */ -export interface FuturesLastTrade { - id: number; - ts: number; - data: FuturesTrade[]; +export interface SpotCurrency { + cc: string; + dn: string; + fn: string; + at?: number; + wp?: number; + ft?: string; + dma?: string; + wma?: string; + sp?: string; + w?: number; + qc?: boolean; + state?: string; + v?: boolean; + whe?: boolean; + cd?: boolean; + de?: boolean; + wed?: boolean; + cawt?: boolean; + fc?: number; + sc?: number; + swd?: string | null; + wd?: string | null; + sdd?: string | null; + dd?: string | null; + svd?: string | null; + tags?: string; } ⋮---- -/** Trade history group from market/history/trade. Each group has trades by timestamp. */ -export interface FuturesTradeHistory { - id: number; - ts: number; - data: FuturesTrade[]; +/** Currency settings item from /v1/settings/common/currencys */ +export interface SpotV1CurrencySettings { + name: string; + dn?: string; + vat?: number; + det?: number; + wet?: number; + wp?: number; + ct?: string; + cp?: string; + ss?: string[]; + oe?: number; + dma?: string; + wma?: string; + sp?: string; + w?: number | string; + qc?: boolean; + state?: string; + v?: boolean; + whe?: boolean; + cd?: boolean; + de?: boolean; + we?: boolean; + cawt?: boolean; + cao?: boolean; + fc?: number; + sc?: number; + swd?: string | null; + wd?: string | null; + sdd?: string | null; + dd?: string | null; + svd?: string | null; + tags?: string; + fn?: string; + bc?: string; + iqc?: boolean; } ⋮---- -/** Open interest tick item from swap_his_open_interest */ -export interface FuturesOpenInterestTick { - volume: number; - amount_type: number; - ts: number; - value: number; +/** Symbol settings item from /v1/settings/common/symbols */ +export interface SpotV1SymbolSettings { + symbol: string; + sn?: string; + bc?: string; + qc?: string; + state?: string; + ve?: boolean; + we?: boolean; + dl?: boolean; + cd?: boolean; + te?: boolean; + ce?: boolean; + tet?: number; + toa?: number; + tca?: number; + voa?: number; + vca?: number; + sp?: string; + tm?: string; + w?: number | string; + ttp?: number; + tap?: number; + tpp?: number; + fp?: number; + tags?: string; + d?: unknown; + bcdn?: string; + qcdn?: string; + elr?: string | null; + castate?: string; + ca1oa?: number; + ca1ca?: number; + ca2oa?: number; + ca2ca?: number; } ⋮---- -/** Open interest data from swap_his_open_interest. data is object with tick array. */ -export interface FuturesHistoricalOpenInterest { +/** Market symbol settings item from /v1/settings/common/market-symbols */ +export interface SpotV1MarketSymbolSettings { symbol: string; - contract_code: string; - contract_type: string; - pair: string; - business_type: string; - tick: FuturesOpenInterestTick[]; + bc?: string; + qc?: string; + state?: string; + sp?: string; + tags?: string; + lr?: number; + smlr?: number; + pp?: number; + ap?: number; + vp?: number; + /** @deprecated No longer valid. */ + minoa?: number | string; + maxoa?: number | string; + minov?: number | string; + /** @deprecated No longer valid. */ + lominoa?: number | string; + lomaxoa?: number | string; + lomaxba?: number | string; + lomaxsa?: number | string; + /** @deprecated No longer valid. */ + smminoa?: number | string; + smmaxoa?: number | string; + bmmaxov?: number | string; + blmlt?: number | string; + slmgt?: number | string; + msormlt?: number | string; + mbormlt?: number | string; + at?: string; + u?: string; + mfr?: number | string; + ct?: string; + rt?: string; + rthr?: number | string; + in?: number | string; + maxov?: number | string; + flr?: number | string; + castate?: string; } ⋮---- -/** - * Account - */ +/** @deprecated No longer valid. */ ⋮---- -/** Asset valuation item from swap_balance_valuation */ -export interface FuturesBalanceValuation { - valuation_asset: string; - balance: string; -} +/** @deprecated No longer valid. */ ⋮---- -/** Isolated account info item from swap_account_info */ -export interface FuturesIsolatedAccountInfo { - symbol: string; - contract_code: string; - margin_asset: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real?: number; - profit_unreal: number; - risk_rate: number | null; - new_risk_rate?: string | null; - trade_partition?: string; - withdraw_available: number; - liquidation_price: number | null; - lever_rate: number; - adjust_factor: number; - margin_static: number; - margin_mode: string; - margin_account: string; - position_mode: string; +/** @deprecated No longer valid. */ +⋮---- +/** Chain info item from /v1/settings/common/chains */ +export interface SpotV1ChainInfo { + chain?: string; + currency?: string; + code?: string; + ct?: string; + ac?: string; + default?: number; + dma?: string; + wma?: string; + de?: boolean; + we?: boolean; + wp?: number; + ft?: string; + dn?: string; + fn?: string; + awt?: boolean; + adt?: boolean; + ao?: boolean; + fc?: number; + sc?: number; + v?: boolean; + sda?: string | null; + swa?: string | null; + 'deposit-desc'?: string; + 'deposit-tips-desc'?: string; + 'withdraw-desc'?: string; + 'suspend-deposit-desc'?: string; + 'suspend-withdraw-desc'?: string; + 'replace-chain-info-desc'?: string; + 'replace-chain-notification-desc'?: string; + 'replace-chain-popup-desc'?: string; + ca?: string; + cct?: number; + 'withdraw-tips-desc'?: string; + 'suspend-visible-desc'?: string; } ⋮---- -/** Cross account contract detail (swap + futures) from swap_cross_account_info */ -export interface FuturesCrossAccountContractDetail { +/** Chain reference from /v2/reference/currencies */ +export interface SpotV2ChainReference { + chain?: string; + displayName?: string; + baseChain?: string; + baseChainProtocol?: string; + isDynamic?: boolean; + numOfConfirmations?: number; + numOfFastConfirmations?: number; + minDepositAmt?: string; + depositStatus?: string; + minWithdrawAmt?: string; + maxWithdrawAmt?: string; + withdrawQuotaPerDay?: string; + withdrawQuotaPerYear?: string; + withdrawQuotaTotal?: string; + withdrawPrecision?: number; + withdrawFeeType?: string; + transactFeeWithdraw?: string; + minTransactFeeWithdraw?: string; + maxTransactFeeWithdraw?: string; + transactFeeRateWithdraw?: string; + withdrawStatus?: string; +} +⋮---- +/** Fee rate from GET /v2/reference/transact-fee-rate */ +export interface SpotV2TransactFeeRate { symbol: string; - contract_code: string; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_unreal: number; - liquidation_price: number | null; - lever_rate: number; - adjust_factor: number; - contract_type: string; - cross_max_available?: string; - trade_partition?: string; - pair: string; - business_type: string; + makerFeeRate: string; + takerFeeRate: string; + actualMakerRate: string; + actualTakerRate: string; + /** RPI order fee rate */ + rpiFeeRate?: string; } ⋮---- -/** Cross account info item from swap_cross_account_info */ -export interface FuturesCrossAccountInfo { - margin_mode: string; - margin_account: string; - margin_asset: string; - margin_balance: number; - margin_static: number; - margin_position: number; - margin_frozen: number; - profit_unreal: number; - withdraw_available: number; - risk_rate: number | null; - money_in?: string; - money_out?: string; - new_risk_rate?: string | null; - position_mode: string; - contract_detail: FuturesCrossAccountContractDetail[]; - futures_contract_detail: FuturesCrossAccountContractDetail[]; +/** RPI order fee rate */ +⋮---- +/** Currency reference item from /v2/reference/currencies */ +export interface SpotV2CurrencyReference { + currency?: string; + instStatus?: string; + chains?: SpotV2ChainReference[]; + /** Whether the currency supports direct transfers to Poloniex */ + externalTransferEnabled?: boolean | string | number; } ⋮---- -/** Position info item from swap_position_info and swap_cross_position_info */ -export interface FuturesPositionInfo { - symbol: string; - contract_code: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - margin_asset: string; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - margin_mode: string; - margin_account: string; - position_mode: string; - withdraw_available?: number; - risk_rate?: number | null; - liquidation_price?: number | null; - adl_risk_percent?: string | number; - contract_type?: string; - pair?: string; - business_type?: string; - margin?: number | string; +/** Whether the currency supports direct transfers to Poloniex */ +⋮---- +/** + * Market Data + */ +⋮---- +/** Kline/candlestick item from /market/history/kline */ +export interface SpotKline { + id: number; + open: number; + close: number; + low: number; + high: number; + amount: number; + vol: number; + count: number; } ⋮---- -/** Nested position in swap_account_position_info */ -export interface FuturesAccountPosition { - symbol: string; - contract_code: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - margin_asset: string; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - margin_mode: string; - margin_account: string; - position_mode: string; - adl_risk_percent?: string | number; - new_risk_rate?: string | null; - trade_partition?: string; +/** Merged ticker from /market/detail/merged (payload is in "tick" not "data"). */ +export interface SpotMergedTicker { + id: number; + version?: number; + open: number; + close: number; + low: number; + high: number; + amount: number; + vol: number; + count: number; + /** [price, size] */ + bid: [number, number]; + /** [price, size] */ + ask: [number, number]; } ⋮---- -/** Account + positions from swap_account_position_info (Isolated) */ -export interface FuturesIsolatedAccountPosition { +/** [price, size] */ +⋮---- +/** [price, size] */ +⋮---- +/** Ticker from /market/tickers */ +export interface SpotTicker { symbol: string; - contract_code: string; - margin_asset: string; - margin_balance: number; - margin_static: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real?: number; - profit_unreal: number; - risk_rate: number | null; - new_risk_rate?: string | null; - trade_partition?: string; - liquidation_price: number | null; - withdraw_available: number; - lever_rate: number; - adjust_factor: number; - margin_mode: string; - margin_account: string; - position_mode: string; - positions: FuturesAccountPosition[]; - adl_risk_percent?: string | number; + open: number; + high: number; + low: number; + close: number; + amount: number; + vol: number; + count: number; + bid: number; + bidSize: number; + ask: number; + askSize: number; } ⋮---- -/** Cross position item (in positions array) from swap_cross_account_position_info */ -export interface FuturesCrossAccountPositionItem { - symbol: string; - contract_code: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - margin_asset: string; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - margin_mode: string; - margin_account: string; - contract_type: string; - pair: string; - business_type: string; - position_mode: string; - new_risk_rate?: string | null; - trade_partition?: string; +/** Depth tick from /market/depth and /market/fullMbp (payload is in "tick" not "data"). */ +export interface SpotDepth { + ts: number; + version: number; + bids: [number, number][]; + asks: [number, number][]; } ⋮---- -/** Cross account + positions from swap_cross_account_position_info. data is object, not array. */ -export interface FuturesCrossAccountPosition { - margin_mode: string; - margin_account: string; - margin_asset: string; - margin_balance: number; - margin_static: number; - margin_position: number; - margin_frozen: number; - profit_real?: number; - profit_unreal: number; - withdraw_available: number; - risk_rate: number | null; - money_in?: string; - money_out?: string; - new_risk_rate?: string | null; - position_mode: string; - contract_detail: FuturesCrossAccountContractDetail[]; - futures_contract_detail: FuturesCrossAccountContractDetail[]; - positions: FuturesCrossAccountPositionItem[]; - adl_risk_percent?: string | number; +/** 24h market summary tick from /market/detail (payload is in "tick" not "data"). */ +export interface SpotDetailTick { + id: number; + low: number; + high: number; + open: number; + close: number; + vol: number; + amount: number; + version: number; + count: number; } ⋮---- -/** Sub auth error from swap_sub_auth and swap_sub_auth_list */ -export interface FuturesSubAuthError { - sub_uid: string; - err_code: number | string; - err_msg: string; +/** Trade (shared by /market/trade and /market/history/trade) */ +export interface SpotTrade { + id: number; + ts: number; + 'trade-id': number; + amount: number; + price: number; + direction: string; } ⋮---- -/** Sub auth response data from swap_sub_auth */ -export interface FuturesSubAuth { - errors: FuturesSubAuthError[]; - successes: string; +/** Trade tick from /market/trade (payload is in "tick" not "data"). */ +export interface SpotLastTrade { + id: number; + ts: number; + data: SpotTrade[]; } ⋮---- -/** Sub auth success item from swap_sub_auth_list */ -export interface FuturesSubAuthSuccess { - query_id?: number; - sub_uid: string; - sub_auth: number | string; +/** Timestamp group from /market/history/trade. Each element in data array. */ +export interface SpotTradeTimestampGroup { + id: number; + ts: number; + data: SpotTrade[]; } ⋮---- -/** Sub permissions response from getSubPermissions */ -export interface FuturesSubPermissions { - errors: FuturesSubAuthError[]; - successes: FuturesSubAuthSuccess[]; -} +/** + * Account + */ ⋮---- -/** Isolated sub-account list item from swap_sub_account_list */ -export interface FuturesIsolatedSubAccountList { - symbol: string; - contract_code: string; - margin_asset: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | string | null; - margin_mode: string; - margin_account: string; - /** Used as from_id for next/prev pagination */ - query_id?: number; +/** Account from /v1/account/accounts */ +export interface SpotAccount { + id: number; + type: string; + subtype?: string; + state: string; } ⋮---- -/** Used as from_id for next/prev pagination */ +/** Balance row from /v1/account/accounts/{account-id}/balance list */ +export interface SpotBalance { + currency: string; + type: string; + balance: string; + debt?: string; + available?: string; + 'seq-num'?: string; +} ⋮---- -/** Isolated sub-account entry from swap_sub_account_list (data array element) */ -export interface FuturesIsolatedSubAccountListEntry { - sub_uid: number; - list: FuturesIsolatedSubAccountList[]; +/** Account balance from /v1/account/accounts/{account-id}/balance */ +export interface SpotAccountBalance { + id: number; + type: string; + state: string; + list: SpotBalance[]; } ⋮---- -/** Cross sub-account list item from swap_cross_sub_account_list */ -export interface FuturesCrossSubAccountList { - margin_mode: string; - margin_account: string; - margin_asset: string; - margin_balance: number; - risk_rate: number | string | null; - trade_partition?: string; +/** Profit account balance item from /v2/account/valuation */ +export interface SpotV2ProfitAccountBalance { + distributionType: string; + balance: number; + success: boolean; + accountBalance: string; } ⋮---- -/** Asset multi-sub object from swap_cross_sub_account_list. Can be null. */ -export interface FuturesCrossSubAccountAssetMultiSub { - state: string; - equity: string; - initial_margin: string; - maintenance_margin: string; - maintenance_margin_rate: string; - profit_unreal: string; - available_margin: string; - created_time: number | string; - updated_time: number | string; - details: unknown[]; +/** Updated info from /v2/account/valuation */ +export interface SpotV2ValuationUpdated { + success: boolean; + time: number; } ⋮---- -/** Cross sub-account entry from swap_cross_sub_account_list (data array element) */ -export interface FuturesCrossSubAccountListEntry { - query_id: number; - sub_uid: number; - list: FuturesCrossSubAccountList[]; - asset_multi_sub: FuturesCrossSubAccountAssetMultiSub | null; +/** Response from /v2/account/valuation */ +export interface SpotV2AccountValuation { + totalBalance?: string; + todayProfit?: string; + todayProfitRate?: string; + profitAccountBalanceList?: SpotV2ProfitAccountBalance[]; + updated?: SpotV2ValuationUpdated; } ⋮---- -/** Account info item from swap_sub_account_info_list */ -export interface FuturesSubAccountInfoAccount { - symbol: string; - contract_code: string; - margin_account: string; - margin_mode: string; - margin_asset: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | string | null; +/** Response from /v2/account/asset-valuation */ +export interface SpotV2AssetValuation { + balance: string; + timestamp: number; } ⋮---- -/** Sub-account item in swap_sub_account_info_list data.sub_list */ -export interface FuturesSubAccountInfoSub { - sub_uid: number; - account_info_list: FuturesSubAccountInfoAccount[]; +/** Transfer result from POST /v1/account/transfer */ +export interface SpotAccountTransferResult { + 'transact-id': number; + 'transact-time': number; } ⋮---- -/** object from swap_sub_account_info_list */ -export type FuturesSubAccountInfoList = - FuturesPaginatedSubList; +export interface SpotV2PointAccountGroupId { + groupId: number; + expiryDate: number | null; + remainAmt: string; +} ⋮---- -/** Cross sub-account info list: account_info_list item (no symbol/contract_code) */ -export interface FuturesCrossSubAccountInfoListAccount { - margin_mode: string; - margin_account: string; - margin_asset: string; - margin_balance: number; - risk_rate: number | string | null; - trade_partition?: string; +/** Point balance from GET /v2/point/account */ +export interface SpotV2PointAccount { + accountId: string; + accountStatus: string; + acctBalance: string; + groupIds: SpotV2PointAccountGroupId[]; } ⋮---- -/** Cross sub-account info list: sub_list item */ -export interface FuturesCrossSubAccountInfoListSub { - sub_uid: number; - account_info_list: FuturesCrossSubAccountInfoListAccount[]; +/** Point transfer result from POST /v2/point/transfer */ +export interface SpotV2PointTransfer { + transactId: string; + transactTime: number; } ⋮---- -/** Cross sub-account info list: unite_sub_list item */ -export interface FuturesCrossSubAccountInfoListUnite { - sub_uid: number; - asset_multi_sub: FuturesCrossSubAccountAssetMultiSub; +/** Deduction info from GET /v1/account/switch/user/info */ +export interface SpotV1AccountSwitchUserInfo { + /** 1=point card deduction, 0=no */ + pointSwitch: number; + /** 1=HTX deduction, 0=no. Choose one of point card and HTX deduction. */ + currencySwitch: number; + deductionCurrency: string; + /** 1: limited, 0: unlimited */ + deductionType: number; + /** Total deductible (USDT). Only when deductionType=1 */ + totalDeductionLimit?: string; + /** Remaining deductible (USDT). Only when deductionType=1 */ + remainingDeductionLimit?: string; } ⋮---- -/** object from swap_cross_sub_account_info_list */ -export type FuturesCrossSubAccountInfoList = - FuturesPaginatedSubList & { - unite_sub_list: FuturesCrossSubAccountInfoListUnite[]; - }; +/** 1=point card deduction, 0=no */ ⋮---- -/** Isolated sub-account info item from swap_sub_account_info (single sub, data array element) */ -export interface FuturesIsolatedSubAccountInfo { - symbol: string; - contract_code: string; - margin_asset: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real?: number; - profit_unreal: number; - risk_rate: number | string | null; - new_risk_rate?: string | null; - trade_partition?: string; - liquidation_price: number | null; - withdraw_available: number; - lever_rate: number; - adjust_factor: number; - margin_static: number; - margin_mode: string; - margin_account: string; - position_mode: string; -} +/** 1=HTX deduction, 0=no. Choose one of point card and HTX deduction. */ ⋮---- -/** Cross sub-account info item from swap_cross_sub_account_info (single sub, data array element) */ -export interface FuturesCrossSubAccountInfo { - margin_mode: string; - margin_account: string; - margin_asset: string; - margin_balance: number; - margin_static: number; - margin_position: number; - margin_frozen: number; - profit_real?: number; - profit_unreal: number; - withdraw_available: number; - risk_rate: number | string | null; - money_in?: string; - money_out?: string; - new_risk_rate?: string | null; - position_mode: string; - contract_detail: FuturesCrossAccountContractDetail[]; - futures_contract_detail: FuturesCrossAccountContractDetail[]; -} +/** 1: limited, 0: unlimited */ ⋮---- -/** Financial record item from swap_financial_record and swap_financial_record_exact */ -export interface FuturesFinancialRecord { - query_id: number; - id: number; - ts: number; - asset: string; - contract_code: string; - margin_account: string; - face_margin_account: string; - type: number; - amount: number | string; -} +/** Total deductible (USDT). Only when deductionType=1 */ ⋮---- -/** Available leverage item from swap_available_level_rate */ -export interface FuturesAvailableLevelRate { - contract_code: string; - margin_mode: string; - available_level_rate: string; -} +/** Remaining deductible (USDT). Only when deductionType=1 */ ⋮---- -/** Available leverage item from swap_cross_available_level_rate */ -export interface FuturesCrossAvailableLevelRate { - contract_code: string; - margin_mode: string; - available_level_rate: string; - contract_type: string; - pair: string; - business_type: string; +/** Deductible currency info from GET /v1/account/overview/info */ +export interface SpotV1AccountOverviewInfo { + currency: string; } ⋮---- -/** Order limit list item from swap_order_limit */ -export interface FuturesOrderLimitList { - symbol: string; - contract_code: string; - open_limit: number; - close_limit: number; - contract_type: string; - pair: string; - business_type: string; +/** Account history row from GET /v1/account/history */ +export interface SpotAccountHistory { + 'account-id': number; + currency: string; + 'record-id': number; + 'transact-amt': string; + /** Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ + 'transact-type': string; + 'avail-balance': string; + 'acct-balance': string; + 'transact-time': number; } ⋮---- -/** from swap_order_limit */ -export interface FuturesOrderLimit { - order_price_type: string; - list: FuturesOrderLimitList[]; -} +/** Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ ⋮---- -/** Fee item from swap_fee */ -export interface FuturesFee { - symbol: string; - contract_code: string; - open_maker_fee: string; - open_taker_fee: string; - close_maker_fee: string; - close_taker_fee: string; - fee_asset: string; - contract_type: string; - pair: string; - business_type: string; - delivery_fee: string; +/** Ledger row from GET /v2/account/ledger */ +export interface SpotV2AccountLedger { + accountId: number; + currency: string; + transactAmt: number; + transactType: string; + transferType?: string; + transactId: number; + transactTime: number; + transferer: number; + transferee: number; } ⋮---- -/** Transfer limit item from swap_transfer_limit */ -export interface FuturesTransferLimit { - symbol: string; - contract_code: string; - margin_mode: string; - margin_account: string; - transfer_in_max_each: number; - transfer_in_min_each: number; - transfer_out_max_each: number; - transfer_out_min_each: number; - transfer_in_max_daily: number; - transfer_out_max_daily: number; - net_transfer_in_max_daily: number; - net_transfer_out_max_daily: number; +/** Batch order placement result. Success: order-id, client-order-id. Error: err-code, err-msg. */ +export interface SpotV1OrderBatchPlaceResult { + 'order-id'?: number; + 'client-order-id'?: string; + 'err-code'?: string; + 'err-msg'?: string; } ⋮---- -/** Transfer limit item from swap_cross_transfer_limit */ -export interface FuturesCrossTransferLimit { - margin_mode: string; - margin_account: string; - transfer_in_max_each: number; - transfer_in_min_each: number; - transfer_out_max_each: number; - transfer_out_min_each: number; - transfer_in_max_daily: number; - transfer_out_max_daily: number; - net_transfer_in_max_daily: number; - net_transfer_out_max_daily: number; +/** Margin order result from POST /v1/order/auto/place */ +export interface SpotV1OrderAutoPlaceResult { + 'order-id': number; } ⋮---- -/** Position limit item from swap_position_limit */ -export interface FuturesPositionLimit { - symbol: string; - contract_code: string; - margin_mode: string; - buy_limit: number; - sell_limit: number; - lever_rate: number; - buy_limit_value: number; - sell_limit_value: number; - mark_price: number; -} +/** Canceled order id from POST /v1/order/orders/{order-id}/submitcancel */ +export type SpotV1OrderCancelResult = string; ⋮---- -/** Position limit item from swap_cross_position_limit */ -export interface FuturesCrossPositionLimit { - symbol: string; - contract_code: string; - margin_mode: string; - buy_limit: number; - sell_limit: number; - lever_rate: number; - buy_limit_value: number; - sell_limit_value: number; - mark_price: number; - contract_type: string; - pair: string; - business_type: string; -} +/** Order status from POST /v1/order/orders/submitCancelClientOrder. 1:ready, 2:created, 3:submitted, 4:partial-filled, 5:partial-canceled, 6:filled, 7:canceled, 10:canceling */ +export type SpotV1OrderCancelByClientOrderIdResult = number; ⋮---- -/** Lever position limit list item (per leverage) from swap_lever_position_limit */ -export interface FuturesLeverPositionLimitList { - lever_rate: number; - buy_limit_value: number; - sell_limit_value: number; +/** Result from POST /v1/order/orders/batchCancelOpenOrders */ +export interface SpotV1OrderBatchCancelOpenOrdersResult { + 'success-count': number; + 'failed-count': number; + /** Next order id to cancel, -1 = none */ + 'next-id': number; } ⋮---- -/** Lever position limit item from swap_lever_position_limit */ -export interface FuturesLeverPositionLimit { - symbol: string; - contract_code: string; - margin_mode: string; - list: FuturesLeverPositionLimitList[]; -} +/** Next order id to cancel, -1 = none */ ⋮---- -/** Lever position limit item from swap_cross_lever_position_limit */ -export interface FuturesCrossLeverPositionLimit { - symbol: string; - contract_code: string; - margin_mode: string; - business_type: string; - contract_type: string; - pair: string; - list: FuturesLeverPositionLimitList[]; +/** Failed cancel from POST /v1/order/orders/batchcancel */ +export interface SpotV1OrderBatchCancelFailed { + 'order-id'?: string; + 'client-order-id'?: string; + 'err-code'?: string; + 'err-msg'?: string; + 'order-state'?: string; } ⋮---- -/** Master-sub transfer response from transfer*MasterSub */ -export interface FuturesMasterSubTransfer { - order_id: string; - client_order_id?: number; +/** Result from POST /v2/algo-orders/cancel-all-after (Dead man's switch) */ +export interface SpotV2AlgoOrdersCancelAllAfterResult { + currentTime: number; + triggerTime: number; } ⋮---- -/** Transfer record item from master_sub_transfer_record. asset, margin_account, symbol, contract_code optional per product. */ -export interface FuturesMasterSubTransferRecordItem { - id: number; - ts: number; - sub_uid: string; - sub_account_name: string; - transfer_type: number; - amount: number | string; - asset?: string; - margin_account?: string; - from_margin_account?: string; - to_margin_account?: string; - symbol?: string; - contract_code?: string; +/** + * Conditional Order + */ +⋮---- +/** Result from POST /v2/algo-orders (Place a conditional order) */ +export interface SpotV2AlgoOrdersPlaceResult { + clientOrderId: string; } ⋮---- -/** Master-sub transfer records from swap_master_sub_transfer_record */ -export type FuturesMasterSubTransferRecords = - FuturesPaginatedTransferRecord; +/** Result from POST /v2/algo-orders/cancellation (Cancel conditional orders before triggering) */ +export interface SpotV2AlgoOrdersCancellationResult { + accepted: string[]; + rejected: string[]; +} ⋮---- -/** Cancel-after response data from linear-cancel-after */ -export interface FuturesCancelAfter { - current_time: number; - trigger_time: number; +/** Conditional order item from GET /v2/algo-orders/opening (orderStatus=created) and /history and /specific */ +export interface SpotV2AlgoOrder { + accountId: number; + source: string; + clientOrderId: string; + symbol?: string; + orderPrice?: string; + orderSize?: string; + orderValue?: string; + orderSide: string; + orderType: string; + timeInForce?: string; + stopPrice?: string; + trailingRate?: string; + orderOrigTime: number; + lastActTime: number; + orderStatus: string; + /** Only for orderStatus=triggered */ + orderId?: string; + /** Order trigger time. Only for orderStatus=triggered */ + orderCreateTime?: number; + /** Only for orderStatus=rejected */ + errCode?: number; + /** Only for orderStatus=rejected */ + errMessage?: string; } ⋮---- -/** Submit order response data from swap_order and swap_cross_order. order_id may exceed JS safe integer - use order_id_str. */ -export interface FuturesSubmitOrder { - order_id: number | string; - order_id_str: string; - client_order_id?: number; +/** Only for orderStatus=triggered */ +⋮---- +/** Order trigger time. Only for orderStatus=triggered */ +⋮---- +/** Only for orderStatus=rejected */ +⋮---- +/** Only for orderStatus=rejected */ +⋮---- +/** + * Margin Loan (Cross/Isolated) + */ +⋮---- +/** Repayment result from POST /v2/account/repayment. Check transaction record to confirm status. */ +export interface SpotMarginRepaymentResult { + repayId: string | number; + repayTime: number; } ⋮---- -/** Batch order error item from swap_batchorder and swap_cross_batchorder */ -export interface FuturesBatchOrderError { - index: number; - err_code: number; - err_msg: string; +/** Transact ID detail from GET /v2/account/repayment (Repayment Record Reference) */ +export interface SpotRepaymentRecordTransactId { + transactId: number; + repaidPrincipal?: string; + repaidInterest?: string; + paidHt?: string; + paidPoint?: string; } ⋮---- -/** Batch order success item from swap_batchorder and swap_cross_batchorder */ -export interface FuturesBatchOrderSuccess { - index: number; - order_id: number | string; - order_id_str: string; - client_order_id?: number; +/** Repayment record from GET /v2/account/repayment (Repayment Record Reference) */ +export interface SpotRepaymentRecord { + repayId: string | number; + repayTime: number; + accountId: string; + currency: string; + repaidAmount: string; + transactIds?: SpotRepaymentRecordTransactId | SpotRepaymentRecordTransactId[]; } ⋮---- -/** Cancel order error item from swap_cancel and swap_cross_cancel */ -export interface FuturesCancelOrderError { - order_id: string; - err_code: number; - err_msg: string; +/** Currency from GET /v1/margin/loan-info */ +export interface SpotMarginLoanInfoCurrency { + currency: string; + 'interest-rate': string; + 'min-loan-amt': string; + 'max-loan-amt': string; + 'loanable-amt': string; + 'actual-rate': string; } ⋮---- -/** Cancel order response data from swap_cancel, swap_cross_cancel, swap_cancelall, swap_cross_cancelall */ -export interface FuturesCancelOrder { - errors: FuturesCancelOrderError[]; - /** Comma-separated list of successfully cancelled order_id or client_order_id */ - successes: string; +/** Symbol from GET /v1/margin/loan-info */ +export interface SpotMarginLoanInfo { + symbol: string; + currencies: SpotMarginLoanInfoCurrency[]; } ⋮---- -/** Comma-separated list of successfully cancelled order_id or client_order_id */ +/** Loan order item from GET /v1/margin/loan-orders */ +export interface SpotMarginLoanOrder { + id: number; + 'account-id': number; + 'user-id': number; + symbol: string; + currency: string; + 'created-at': string; + 'accrued-at'?: string; + 'loan-amount': string; + 'loan-balance': string; + 'interest-rate': string; + 'interest-amount'?: string; + 'interest-balance'?: string; + state: string; + 'paid-point'?: string; + 'paid-coin'?: string; + 'deduct-rate'?: string; + 'deduct-currency'?: string; + 'deduct-amount'?: string; + 'updated-at'?: number; + 'hour-interest-rate'?: string; + 'day-interest-rate'?: string; +} ⋮---- -/** Switch leverage response data from swap_switch_lever_rate */ -export interface FuturesSwitchLeverRate { - contract_code: string; - margin_mode: string; - lever_rate: number; +/** Balance row from GET /v1/margin/accounts/balance */ +export interface SpotMarginBalance { + currency: string; + type: string; + balance: string; } ⋮---- -/** Switch leverage response data from swap_cross_switch_lever_rate */ -export interface FuturesCrossSwitchLeverRate { - contract_code: string; - margin_mode: string; - lever_rate: number; - contract_type: string; - pair: string; - business_type: string; +/** Account item from GET /v1/margin/accounts/balance */ +export interface SpotMarginAccountBalance { + id: number; + type: string; + symbol: string; + state: string; + 'risk-rate'?: string; + 'fl-type'?: string; + 'fl-price'?: string; + list: SpotMarginBalance[]; } ⋮---- -/** - * Batch order response data from swap_batchorder and swap_cross_batchorder. - * A successful request can contain both accepted and rejected orders. - */ -export interface FuturesBatchOrder { - errors: FuturesBatchOrderError[]; - success: FuturesBatchOrderSuccess[]; +/** Account balance from GET /v1/cross-margin/accounts/balance. Single object (unlike isolated which returns array). */ +export interface SpotCrossMarginAccountBalance { + id: number; + type: string; + state: string; + 'risk-rate'?: string; + 'acct-balance-sum'?: string; + 'debt-balance-sum'?: string; + list: SpotMarginBalance[]; } ⋮---- -/** Position mode item from swap_switch_position_mode and swap_cross_switch_position_mode */ -export interface FuturesSwitchPositionMode { - margin_account: string; - position_mode: string; +/** Loan order item from GET /v1/cross-margin/loan-orders */ +export interface SpotCrossMarginLoanOrder { + id: number; + 'account-id': number; + 'user-id': number; + currency: string; + 'filled-points'?: string; + 'filled-ht'?: string; + 'created-at': string | number; + 'accrued-at'?: string | number; + 'loan-amount': string; + 'loan-balance': string; + 'interest-amount'?: string; + 'interest-balance'?: string; + state: string; } ⋮---- -/** Order info item from getOrderInfo, getCoinMDeliveryOrderInfo, getCoinMPerpOrderInfo. Product-specific fields optional. */ -export interface FuturesOrderInfo { - symbol: string; - contract_code: string; - volume: number; - price: number; - order_price_type: string; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - client_order_id: number | string | null; - created_at: number; - canceled_at: number | null; - trade_volume: number; - trade_turnover: number; - fee: number; - trade_avg_price: number | null; - margin_frozen: number; - profit: number; - status: number; - order_source: string; - fee_asset: string; - liquidation_type: string | null; - is_tpsl: number; - real_profit: number; - update_time?: number; - /** USDM only */ - margin_asset?: string; - margin_mode?: string; - margin_account?: string; - reduce_only?: number; - fee_amount?: number; - fee_quote_amount?: number; - self_match_prevent_new?: string; - /** CM Delivery: required; USDM/CM Perp: optional */ - contract_type?: string; - pair?: string; - business_type?: string; - canceled_source?: string; - self_match_prevent?: number; +/** Position limit from GET /v2/margin/limit */ +export interface SpotMarginLimit { + currency: string; + 'max-holdings': string; } ⋮---- -/** USDM only */ +/** Result from POST /v1/order/orders/batchcancel */ +export interface SpotV1OrderBatchCancelResult { + /** Successfully canceled order ids or client-order-ids */ + success: string[]; + /** Failed cancel requests */ + failed: SpotV1OrderBatchCancelFailed[]; +} ⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ +/** Successfully canceled order ids or client-order-ids */ ⋮---- -/** Order detail trade item (trades array) from getOrderDetail, getCoinMDeliveryOrderDetail, getCoinMPerpOrderDetail */ -export interface FuturesOrderDetailTrade { - id: string; - trade_id: number | string; - trade_price: number; - trade_volume: number; - trade_turnover: number; - trade_fee: number; - role: string; - created_at: number; - profit: number; - real_profit: number; - fee_asse?: string; - price?: string; - fee_asset?: string; - canceled_source?: string; - self_match_prevent?: string | number; +/** Failed cancel requests */ +⋮---- +/** Match result item from GET /v1/order/orders/{order-id}/matchresults */ +export interface SpotV1OrderMatchResult { + id: number; + symbol: string; + 'order-id': number; + 'match-id': number; + 'trade-id': number; + price: string; + 'created-at': number; + type: string; + 'filled-amount': string; + 'filled-fees': string; + 'fee-currency'?: string; + source?: string; + role?: string; + 'filled-points'?: string; + 'fee-deduct-currency'?: string; + 'fee-deduct-state'?: string; } ⋮---- -/** Order detail from getOrderDetail, getCoinMDeliveryOrderDetail, getCoinMPerpOrderDetail. Product-specific fields optional. */ -export interface FuturesOrderDetail { +/** Historical order from GET /v1/order/orders (search past orders) */ +export interface SpotV1OrderHistory { + id: number; + 'client-order-id'?: string; + 'account-id'?: number; + amount?: string; symbol: string; - contract_code: string; - lever_rate: number; - direction: string; - offset: string; - volume: number; - price: number; - created_at: number; - canceled_at: number; - order_source: string; - order_price_type: string; - margin_frozen: number; - profit: number; - order_id: number | string; - order_id_str: string; - client_order_id: number | string | null; - order_type: number | string; - status: number; - trade_volume: number; - trade_turnover: number; - trade_avg_price: number; - total_page: number; - current_page: number; - total_size: number; - instrument_price: number; - final_interest: number; - adjust_value: number; - fee_asset: string; - fee: number; - liquidation_type: string; - is_tpsl: number; - real_profit: number; - trades: FuturesOrderDetailTrade[]; - /** USDM only */ - margin_asset?: string; - margin_mode?: string; - margin_account?: string; - reduce_only?: number; - self_match_prevent_new?: string; - /** CM Delivery: required; USDM/CM Perp: optional */ - contract_type?: string; - pair?: string; - business_type?: string; - canceled_source?: string; - self_match_prevent?: number; + price?: string; + 'created-at': number; + 'canceled-at'?: number; + 'finished-at'?: number; + type?: string; + 'field-amount'?: string; + 'field-cash-amount'?: string; + 'field-fees'?: string; + source?: string; + state: string; + 'stop-price'?: string; + operator?: string; + role?: string; + 'canceled-source'?: number | string; + 'canceled-source-desc'?: string; + 'market-amount'?: string; + 'ice-amount'?: string; + 'is-ice'?: boolean; + 'updated-at'?: number; } ⋮---- -/** USDM only */ +/** Historical order from GET /v1/order/history (48h). Includes next-time when more results exist. */ +export interface SpotV1OrderHistory48h extends SpotV1OrderHistory { + /** Next start-time or end-time for pagination. Only when results exceed size. */ + 'next-time'?: number; +} ⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ +/** Next start-time or end-time for pagination. Only when results exceed size. */ ⋮---- -/** Open order item from swap_openorders and swap_cross_openorders */ -export interface FuturesOpenOrder { +/** Order detail from GET /v1/order/orders/{order-id} and getClientOrder */ +export interface SpotV1OrderDetail { + id: number; + 'client-order-id': string; symbol: string; - contract_code: string; - volume: number; - price: number; - order_price_type: string; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - client_order_id: number | string | null; - created_at: number; - trade_volume: number; - trade_turnover: number; - fee: number; - trade_avg_price: number | null; - margin_frozen: number; - margin_asset: string; - profit: number; - status: number; - order_source: string; - fee_asset: string; - liquidation_type: string | null; - canceled_at: number | null; - margin_mode: string; - margin_account: string; - is_tpsl: number; - real_profit: number; - update_time: number; - reduce_only: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; + 'account-id': number; + amount: string; + price: string; + 'created-at': number; + 'finished-at': number; + 'canceled-at': number; + type: string; + 'field-amount': string; + 'field-cash-amount': string; + 'field-fees': string; + source: string; + 'canceled-source'?: string; + state: string; + 'stop-price'?: string; + operator?: string; } ⋮---- -/** Cross margin only */ -⋮---- -/** Open orders response from swap_openorders and swap_cross_openorders */ -export type FuturesOpenOrders = FuturesPaginatedOrders & { - self_match_prevent_new: string; - self_match_prevent?: number; - canceled_source?: string; -}; +/** Deposit address item from GET /v2/account/deposit/address */ +export interface SpotDepositAddress { + userId: number; + currency: string; + address: string; + addressTag: string; + chain: string; +} ⋮---- -/** History order from getHistoryOrders, getCoinMDeliveryHistoryOrders, getCoinMPerpHistoryOrders. Product-specific optional. */ -export interface FuturesHistoryOrder { - query_id: number; - order_id: number | string; - order_id_str: string; - symbol: string; - contract_code: string; - lever_rate: number; - direction: string; - offset: string; - volume: number; - price: number; - create_date: number; - update_time: number; - order_source: string; - order_price_type: string | number; - order_type: number; - margin_frozen: number; - profit: number; - trade_volume: number; - trade_turnover: number; - fee: number; - trade_avg_price: number; - status: number; - fee_asset: string; - liquidation_type: string; - is_tpsl: number; - real_profit: number; - /** USDM only */ - margin_mode?: string; - margin_account?: string; - margin_asset?: string; - reduce_only?: number; - self_match_prevent_new?: string; - /** CM Delivery: required; USDM/CM Perp: optional */ - contract_type?: string; - pair?: string; - business_type?: string; - canceled_source?: string; - self_match_prevent?: number; +/** Withdraw quota chain from GET /v2/account/withdraw/quota */ +export interface SpotWithdrawQuotaChain { + chain: string; + maxWithdrawAmt: string; + withdrawQuotaPerDay: string; + remainWithdrawQuotaPerDay: string; + withdrawQuotaPerYear: string; + remainWithdrawQuotaPerYear: string; + withdrawQuotaTotal: string; + remainWithdrawQuotaTotal: string; } ⋮---- -/** USDM only */ +/** Withdraw quota from GET /v2/account/withdraw/quota */ +export interface SpotWithdrawQuota { + currency: string; + chains: SpotWithdrawQuotaChain[]; +} ⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ +/** + * Withdraw address status from GET /v2/account/withdraw/address. + * `normal`: common address. + * `white`: whitelist in effect. + * `white-delaying`: whitelist waiting out its delay. + * `processing`: pending 2FA or risk-control checks. + */ +export type SpotWithdrawAddressStatus = + | 'normal' + | 'white' + | 'white-delaying' + | 'processing'; ⋮---- -/** Fill / match result from getFills, getCoinMDeliveryFills, getCoinMPerpFills. Product-specific optional. */ -export interface FuturesMatchResult { - id: string; - query_id: number; - match_id: number | string; - order_id: number | string; - order_id_str: string; - symbol: string; - contract_code: string; - direction: string; - offset: string; - trade_volume: number; - trade_price: number; - trade_turnover: number; - create_date: number; - offset_profitloss: number; - trade_fee: number; - role: string; - real_profit: number; - fee_asset: string; - order_source: string; - /** USDM only */ - margin_mode?: string; - margin_account?: string; - reduce_only?: number; - /** CM Delivery: required; USDM/CM Perp: optional */ - contract_type?: string; - pair?: string; - business_type?: string; - /** getFillsExact only */ - ht_price?: string; +/** Withdraw address item from GET /v2/account/withdraw/address */ +export interface SpotWithdrawAddress { + currency: string; + chain: string; + note: string; + addressTag?: string; + address: string; + /** See {@link SpotWithdrawAddressStatus}. */ + status: SpotWithdrawAddressStatus; } ⋮---- -/** USDM only */ -⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ -⋮---- -/** getFillsExact only */ -⋮---- -/** Position mode item from swap_position_side and swap_cross_position_side */ -export interface FuturesPositionSideInfo { - margin_account: string; - position_mode: 'single_side' | 'dual_side'; -} +/** See {@link SpotWithdrawAddressStatus}. */ ⋮---- -/** Transfer state item from swap_cross_transfer_state */ -export interface FuturesCrossTransferState { - margin_mode: string; - margin_account: string; - /** 1: available, 0: unavailable */ - transfer_in: number; - /** 1: available, 0: unavailable */ - transfer_out: number; - /** 1: available, 0: unavailable */ - master_transfer_sub: number; - /** 1: available, 0: unavailable */ - sub_transfer_master: number; - master_transfer_sub_inner_in: number; - master_transfer_sub_inner_out: number; - sub_transfer_master_inner_in: number; - sub_transfer_master_inner_out: number; - transfer_inner_in: number; - transfer_inner_out: number; +/** Deposit/withdraw record from GET /v1/query/deposit-withdraw or GET /v1/query/withdraw/client-order-id */ +export interface SpotDepositWithdrawRecord { + id: number; + type: string; + 'sub-type'?: string; + currency: string; + /** Chain name. Poloniex rapid transfer defaults to t397342. */ + chain: string; + 'tx-hash': string; + amount: number; + 'from-addr-tag'?: string; + /** On-chain address, or UID:XXXX for Poloniex→HTX rapid transfers. */ + address: string; + 'address-tag'?: string; + fee: number; + state: string; + 'created-at': number; + 'updated-at': number; + 'error-code'?: string; + 'error-msg'?: string; } ⋮---- -/** 1: available, 0: unavailable */ -⋮---- -/** 1: available, 0: unavailable */ -⋮---- -/** 1: available, 0: unavailable */ +/** Chain name. Poloniex rapid transfer defaults to t397342. */ ⋮---- -/** 1: available, 0: unavailable */ +/** On-chain address, or UID:XXXX for Poloniex→HTX rapid transfers. */ ⋮---- -/** Trade state item from swap_cross_trade_state */ -export interface FuturesCrossTradeState { - symbol: string; - contract_code: string; - margin_mode: string; - margin_account: string; - contract_type: string; - pair: string; - business_type: string; - /** 1=available, 0=unavailable */ - open: number; - /** 1=available, 0=unavailable */ - close: number; - /** 1=available, 0=unavailable */ - cancel: number; +/** VASP exchange from GET /v1/query/vasp-list */ +export interface SpotVaspExchange { + 'vasp-id': string; + 'vasp-name': string; + 'legal-name': string; } ⋮---- -/** 1=available, 0=unavailable */ +/** User rebate status from GET /broker/v1/user_rebate_status */ +export interface SpotBrokerUserRebateStatus { + spotRebateStatus: boolean; + contractRebateStatus: boolean; + spotIsNewUser: boolean; + contractIsNewUser?: boolean; +} ⋮---- -/** 1=available, 0=unavailable */ +/** Sub-user fee rate from GET /broker/v1/sub-user/fee_rate */ +export interface SpotBrokerSubUserFeeRate { + userId: number; + subUserId: number; + bizType: number; + taker: string; + maker: string; + type: number; + addTaker: string; + addMaker: string; + updatedAt: number; + effectAt: number; +} ⋮---- -/** 1=available, 0=unavailable */ +/** Fee rate add result from POST /broker/v1/sub-user/fee_rate/add */ +export interface SpotBrokerFeeRateAddResult { + subUserIds: number[]; + effectAt: string; +} ⋮---- -/** Trigger order open order item from swap_trigger_openorders and swap_cross_trigger_openorders */ -export interface FuturesTriggerOrderOpenOrder { - symbol: string; - contract_code: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_price: number | string; - order_price: number | string; - created_at: number; - order_price_type: string; - status: number; - margin_mode: string; - margin_account: string; - reduce_only: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; +/** Account capital snapshot item from POST /broker/v1/account_capital_snapshot_everyday */ +export interface SpotBrokerAccountCapitalSnapshot { + accountId: number; + accountType: string; + snapshotTime: string; + convertBalance: string; + dataList: unknown[]; } ⋮---- -/** Cross margin only */ +/** Deduct mode result item from POST /v2/sub-user/deduct-mode */ +export interface SpotSubUserDeductModeResult { + subUid: string; + deductMode: string | null; + errCode?: string; + errMessage?: string; +} ⋮---- -/** Trigger open orders response from swap_trigger_openorders and swap_cross_trigger_openorders */ -export type FuturesTriggerOpenOrders = - FuturesPaginatedOrders; +/** API key from getSubUserApiKey */ +export interface SpotSubUserApiKey { + accessKey: string; + status: string; + note: string; + permission: string; + ipAddresses: string; + validDays: number; + createTime: number; + updateTime: number; +} ⋮---- -/** Trigger order history item from swap_trigger_hisorders and swap_cross_trigger_hisorders */ -export interface FuturesTriggerOrderHisOrder { - symbol: string; - contract_code: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - relation_order_id: string; - order_price_type: string; - status: number; - order_source: string; - trigger_price: number | string; - triggered_price: number | string | null; - order_price: number | string; - created_at: number; - triggered_at: number | null; - order_insert_at: number; - canceled_at: number | null; - update_time: number; - fail_code: number | null; - fail_reason: string | null; - margin_mode: string; - margin_account: string; - reduce_only?: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; +/** Sub user creation result item from POST /v2/sub-user/creation */ +export interface SpotSubUserCreationResult { + userName: string; + note?: string; + uid?: number; + /** Spot account id for spot order transactions */ + spotAccountId?: number; + errCode?: string; + errMessage?: string; } ⋮---- -/** Cross margin only */ +/** Spot account id for spot order transactions */ ⋮---- -/** Trigger history orders response from getTriggerHistoryOrders, getCrossTriggerHistoryOrders */ -export type FuturesTriggerHistoryOrders = - FuturesPaginatedOrders; +/** Sub user from GET /v2/sub-user/user-list */ +export interface SpotSubUserList { + uid: number; + userState: string; + subUserName: string; + note: string; +} ⋮---- -/** TP/SL order result; when only TP or only SL is set, the other is empty */ -export interface FuturesTpslOrderResult { - order_id: number | string; - order_id_str: string; +/** Result from updateSubUserLockStatus */ +export interface SpotSubUserLockStatusResult { + subUid: number; + userState: string; } ⋮---- -/** TPSL order response data from swap_tpsl_order and swap_cross_tpsl_order. tp_order or sl_order empty when only the other is set */ -export interface FuturesTpslOrder { - tp_order?: FuturesTpslOrderResult; - sl_order?: FuturesTpslOrderResult; +/** Result from getSubUserStatus */ +export interface SpotSubUserStatusResult { + uid: number; + userState: string; } ⋮---- -/** TPSL open order item from swap_tpsl_openorders and swap_cross_tpsl_openorders */ -export interface FuturesTpslOpenOrder { - symbol: string; - contract_code: string; - margin_mode: string; - margin_account: string; - volume: number; - order_type: number; - tpsl_order_type: string; - direction: string; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_type: string; - trigger_price: number | string; - price_protect?: boolean; - created_at: number; - order_price_type: string; - order_price: number | string; - status: number; - source_order_id: string | null; - relation_tpsl_order_id: string; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; +/** Tradable market result item from POST /v2/sub-user/tradable-market */ +export interface SpotSubUserTradableMarketResult { + subUid: string; + accountType: string; + activation: string; + errCode?: number; + errMessage?: string; } ⋮---- -/** Cross margin only */ -⋮---- -/** TPSL open orders response from swap_tpsl_openorders and swap_cross_tpsl_openorders */ -export type FuturesTpslOpenOrders = - FuturesPaginatedOrders; +/** Result item from setSubUserTransferPermissions */ +export interface SpotSubUserTransferPermissionsResult { + subUid: number; + accountType: string; + transferrable: boolean; + errCode?: number; + errMessage?: string; +} ⋮---- -/** TPSL history order item from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ -export interface FuturesTpslHisOrder { - symbol: string; - contract_code: string; - margin_mode: string; - margin_account: string; - volume: number; - order_type: number; - tpsl_order_type: string; - direction: string; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_type: string; - trigger_price: number | string; - price_protect?: boolean; - created_at: number; - order_price_type: string; - order_price: number | string; - status: number; - source_order_id: string | null; - relation_tpsl_order_id: string; - canceled_at: number | null; - fail_code: number | null; - fail_reason: string | null; - triggered_price: number | string | null; - relation_order_id: string; - update_time: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; +/** Account ID from sub user account list */ +export interface SpotSubUserAccountId { + accountId: number; + subType?: string; + accountStatus?: string; } ⋮---- -/** Cross margin only */ +/** Account from sub user account list */ +export interface SpotSubUserAccount { + accountType: string; + activation: string; + transferrable?: boolean; + accountIds?: SpotSubUserAccountId[]; +} ⋮---- -/** TPSL history orders response from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ -export type FuturesTpslHisOrders = FuturesPaginatedOrders; +/** Result from getSubUserAccounts */ +export interface SpotSubUserAccountsResult { + uid: number; + deductMode: string; + list: SpotSubUserAccount[]; +} ⋮---- -/** TPSL order info item within relation_tpsl_order response. getRelationTpslOrder, getCoinMDeliveryRelationTpslOrder, getCoinMPerpRelationTpslOrder. */ -export interface FuturesRelationTpslOrderTpslInfo { - volume: number; - tpsl_order_type: string; - direction: string; - order_id: number | string; - order_id_str: string; - trigger_type: string; - trigger_price: number | string; - created_at: number; - order_price: number | string; - status: number; - relation_tpsl_order_id: string; - relation_order_id: string; - order_price_type?: string; - price_protect?: boolean; - canceled_at: number | null; - fail_code: number | null; - fail_reason: string | null; - triggered_price: number | string | null; +/** Result from createSubUserApiKey */ +export interface SpotSubUserApiKeyCreationResult { + accessKey: string; + secretKey: string; + note: string; + permission: string; + ipAddresses: string; } ⋮---- -/** Relation TPSL order from getRelationTpslOrder, getCoinMDeliveryRelationTpslOrder, getCoinMPerpRelationTpslOrder. Product-specific optional. */ -export interface FuturesRelationTpslOrder { - symbol: string; - contract_code: string; - volume: number; - price: number | string; - order_price_type: string; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - client_order_id: number | string | null; - created_at: number; - trade_volume: number; - trade_turnover: number | string; - fee: number | string; - trade_avg_price: number | string; - margin_frozen: number | string; - profit: number | string; - status: number; - order_type: number | null; - order_source: string; - fee_asset: string; - canceled_at: number; - tpsl_order_info: FuturesRelationTpslOrderTpslInfo[]; - /** USDM only */ - margin_mode?: string; - margin_account?: string; - /** CM Delivery: required; USDM/CM Perp: optional */ - contract_type?: string; - pair?: string; - business_type?: string; +/** Result from updateSubUserApiKey */ +export interface SpotSubUserApiKeyUpdateResult { + note: string; + permission: string; + ipAddresses: string; } ⋮---- -/** USDM only */ +/** Record from getSubUserDepositHistory */ +export interface SpotSubUserDepositHistoryRecord { + id: number; + currency: string; + txHash: string; + chain: string; + amount: number; + address: string; + addressTag: string; + state: string; + createTime: number; + updateTime: number; +} ⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ +/** Balance from getSubUsersAggregatedBalance */ +export interface SpotSubUsersAggregatedBalance { + currency: string; + type: string; + balance: string; +} ⋮---- -/** Trailing order open order item from swap_track_openorders and swap_cross_track_openorders */ -export interface FuturesTrackOpenOrder { - symbol: string; - contract_code: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - created_at: number; - order_price_type: string; - status: number; - callback_rate: number | string; - active_price: number | string; - is_active: number; - margin_mode: string; - margin_account: string; - reduce_only: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; +/** Result from getSubUserBalance */ +export interface SpotSubUserBalanceResult { + id: number; + type: string; + state: string; + list: SpotBalance[]; + symbol?: string; } ⋮---- -/** Cross margin only */ +/** Custody sub-account from GET /v2/sub-user/entrust-user-list */ +export interface SpotSubUserEntrustUser { + uid: number; + subUserName: string; +} ⋮---- -/** Trailing open orders response data from swap_track_openorders and swap_cross_track_openorders */ -export type FuturesTrackOpenOrders = - FuturesPaginatedOrders; +/** Managed transfer record from GET /v2/sub-user/managed-transfer-history */ +export interface SpotSubUserManagedTransferRecord { + currency: string; + type: string; + amount: number; + uid: number; + subUserName: string; + query_id?: string; +} ⋮---- -/** Trailing order history item from swap_track_hisorders and swap_cross_track_hisorders */ -export interface FuturesTrackHisOrder { - symbol: string; - contract_code: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - created_at: number; - update_time: number; - order_price_type: string; - status: number; - canceled_at: number | null; - fail_code: number | null; - fail_reason: string | null; - callback_rate: number | string; - active_price: number | string; - is_active: number; - market_limit_price: number | string | null; - formula_price: number | string | null; - real_volume: number | string; - triggered_price: number | string | null; - relation_order_id: string; - margin_mode: string; - margin_account: string; - reduce_only: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; -} -⋮---- -/** Cross margin only */ -⋮---- -/** Trailing history orders response from swap_track_hisorders and swap_cross_track_hisorders */ -export type FuturesTrackHisOrders = - FuturesPaginatedOrders; -⋮---- -/** Cross swap item within unified_account_info */ -export interface FuturesUnifiedAccountCrossSwap { - symbol: string; - contract_code: string; - margin_mode: string; - margin_available: number | string; - cross_max_available?: number | string; - lever_rate: number | string; - contract_type: string; - business_type: string; +/** Referral rebate detail from GET /v2/invitee/rebate/detail */ +export interface SpotReferralRebateDetail { + invitee_type: string; + invitee_rebate_rate_spot_m2: string; + invitee_rebate_rate_contract_m2: string; + invitee_rebate_rate_partner_spot?: string; + invitee_rebate_rate_partner_contract?: string; + join_time_m2: string; + join_time_partner?: string; + invitee_total_commission_usdt: string; + invitee_total_commission_trx: string; + invitee_total_commission_htx: string; + partner_total_commission_usdt: string; + partner_total_commission_trx: string; + partner_total_commission_htx: string; } ⋮---- -/** Cross futures item within unified_account_info */ -export interface FuturesUnifiedAccountCrossFuture { - symbol: string; - contract_code: string; - margin_mode: string; - margin_available: number | string; - cross_max_available?: number | string; - lever_rate: number | string; - contract_type: string; - business_type: string; +/** Referral rebate history record from GET /v2/invitee/rebate/history */ +export interface SpotReferralRebateHistoryRecord { + date: number; + invitee_total_commission_usdt: string; + invitee_total_commission_trx: string; + invitee_total_commission_htx: string; + partner_total_commission_usdt: string; + partner_total_commission_trx: string; + partner_total_commission_htx: string; } ⋮---- -/** Isolated swap item within unified_account_info */ -export interface FuturesUnifiedAccountIsolatedSwap { - symbol: string; - contract_code: string; - margin_mode: string; - margin_available: number | string; - withdraw_available?: number | string; - lever_rate: number | string; - position_mode?: string; +/** Referral rebate detail from all_rebate/detail or batcher_rebate/detail */ +export interface SpotReferralAllRebateDetail { + invitee_uid: number; + invitee_type: string; + invitee_rebate_rate_spot_m2: string | null; + invitee_rebate_rate_contract_m2: string | null; + invitee_rebate_rate_partner_spot?: string | null; + invitee_rebate_rate_partner_contract?: string | null; + join_time_m2: string; + join_time_partner?: string | null; + invitee_total_commission_usdt: string; + invitee_total_commission_trx: string; + invitee_total_commission_htx: string; + partner_total_commission_usdt: string; + partner_total_commission_trx: string; + partner_total_commission_htx: string; } ⋮---- -/** Unified account info item from unified_account_info */ -export interface FuturesUnifiedAccountInfo { - margin_balance: number | string; - margin_static: number | string; - cross_profit_unreal: number | string; - cross_margin_static: number | string; - margin_asset: string; - margin_frozen: number | string; - withdraw_available: number | string; - cross_risk_rate: number | string | null; - cross_swap: FuturesUnifiedAccountCrossSwap[]; - cross_future: FuturesUnifiedAccountCrossFuture[]; - isolated_swap: FuturesUnifiedAccountIsolatedSwap[]; - userId?: string | null; +/** P2P order from GET /v1/api/c2c/order/history */ +export interface SpotP2POrderHistory { + orderNo: string; + role: string; + side: string; + counterpartNickName: string; + fiatCurrency: string; + asset: string; + amount: string; + unitPrice: string; + totalPrice: string; + fee: string; + orderStatus: string; + createTime: string; + queryId?: number; } ⋮---- -/** Linear swap overview account info item from linear_swap_overview_account_info */ -export interface FuturesLinearSwapOverviewAccountInfo { - margin_asset: string; - margin_balance: number | string; - margin_available: number | string; +/** Tiered rate from Earn project */ +export interface SpotEarnTieredRate { + amountStart: string; + amountEnd: string; + rate: string; } ⋮---- -/** Fix position margin change record item from fix_position_margin_change_record */ -export interface FuturesFixPositionMarginChangeRecord { - query_id: number; - order_id: string; - amount: number | string; - asset: string; - symbol: string; +/** Earn project from GET /v1/earn/project/queryEarnProjectList */ +export interface SpotEarnProject { + projectId: number; + productId: number; + calculationType: number; type: number; - direction: number; + viewYearRate: string; + finishAmount: string; + projectStatus: number; + totalAmount: string; + currency: string; + startAmount: string; + apyType: number; + tieredRates?: SpotEarnTieredRate[]; + marketPerkUpLimit?: string; + marketTimeApy?: string; + marketPerkApy?: string; } ⋮---- -/** Fix position margin change response data from fix_position_margin_change */ -export interface FuturesFixPositionMarginChange { - amount: number | string; - asset: string; - contract_code: string; - type: number; - direction: number; - order_id: string; - client_order_id: number | string | null; +/** Result from POST /v1/earn/order/demand/add */ +export interface SpotEarnSubscribeResult { + currency: string; + amount: string; + orderId: number; + status: number; } ⋮---- -/** - * USDT Margined Futures Multi Asset - Account (v5 API) - */ -⋮---- -/** Currency detail from /v5/account/balance */ -export interface FuturesV5AccountBalanceDetail { +/** Result from POST /v1/earn/order/demand/redeem-order */ +export interface SpotEarnRedeemResult { currency: string; - equity: string; - isolated_equity: string; - available: string; - isolated_available?: string; - withdraw_available: string; - profit_unreal: string; - isolated_profit_unreal: string; - initial_margin: string; - maintenance_margin: string; - maintenance_margin_rate: string; - initial_margin_rate: string; - voucher: string; - voucher_value: string; - created_time: number; - updated_time: number; + amount: string; + orderId: number; + status: number; } ⋮---- -/** Account balance data from /v5/account/balance */ -export interface FuturesV5AccountBalance { - /** "normal" | "liquidating" | "adl" | "open_limit" */ - state: string; - equity: string; - initial_margin: string; - maintenance_margin: string; - maintenance_margin_rate: string; - profit_unreal: string; - available_margin: string; - voucher_value: string; - created_time: number; - updated_time: number; - details: FuturesV5AccountBalanceDetail[]; +/** Earn user asset from GET /v1/earn/order/user/assets/list */ +export interface SpotEarnUserAsset { + projectId: number; + orderId: number; + projectType: number; + currency: string; + yesterdayIncome: string; + totalIncomeAmount: string; + totalAmount: string; + miningYearRate: string; + apyType: number; } ⋮---- -/** "normal" | "liquidating" | "adl" | "open_limit" */ -⋮---- -/** Set asset mode response data from POST /v5/account/asset_mode */ -export interface FuturesV5AssetMode { - /** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ - assets_mode: 0 | 1 | 2; +/** Referral invited user from GET /v2/invitee/rebate/referrals */ +export interface SpotReferralReferral { + id: number; + invitee_uid: number; + remark: string; + referral_code: string; + invitee_type: string; + invitee_rebate_rate_spot_m2: string; + invitee_rebate_rate_contract_m2: string; + invitee_rebate_rate_partner_spot?: string | null; + invitee_rebate_rate_partner_contract?: string | null; + join_time_m2: number; + join_time_partner?: number | null; + /** Whether advanced KYC was completed */ + completed_kyc?: boolean | number | string; + /** Invitee email */ + mail?: string | null; } ⋮---- -/** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ +/** Whether advanced KYC was completed */ ⋮---- -/** Get asset mode response data from GET /v5/account/asset_mode */ -export interface FuturesV5AssetModeGet { - /** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ - asset_mode: 0 | 1 | 2; -} -⋮---- -/** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ +/** Invitee email */ ⋮---- -/** Fee deduction crypto from /v5/account/fee_deduction_currency */ -export interface FuturesV5FeeDeductionCurrency { - /** 1: Yes; 0: No */ - fee_option: 0 | 1; - /** Deduction currency (e.g. htx, trx). Not returned when fee_option = 0 */ - deduction_currency?: string; +/** Open order from GET /v1/order/openOrders */ +export interface SpotV1OpenOrder { + id: number; + 'client-order-id'?: string; + symbol: string; + 'account-id'?: number; + price?: string; + amount?: string; + 'created-at': number; + type: string; + 'filled-amount': string; + 'filled-cash-amount': string; + 'filled-fees': string; + source?: string; + state: string; + 'stop-price'?: string; + operator?: string; } ⋮---- -/** 1: Yes; 0: No */ -⋮---- -/** Deduction currency (e.g. htx, trx). Not returned when fee_option = 0 */ +/** Result from POST /v5/account/universal_transfer */ +export interface SpotUniversalTransferResult { + transfer_id: number; +} ⋮---- -/** Financial record item from /v5/account/bills */ -export interface FuturesV5Bill { - id: string; - contract_code: string; - margin_mode: string; - /** - * Financial type code. - * 160: dividend settlement income. 161: dividend settlement expense. - */ - type: string; - currency: string; +/** Record from GET /v5/account/universal_transfer_records */ +export interface SpotUniversalTransferRecord { + id: number; + transfer_id: number | string; amount: string; - created_time: string; + currency?: string; + status?: string; + from_account_type: string; + to_account_type: string; + from_account_asset?: string; + to_account_asset?: string; + from_asset_type?: string; + to_asset_type?: string; + transfer_time?: number; } + +================ +File: src/WebsocketClient.ts +================ +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './lib/BaseWSClient.js'; +import { + getStringOrUndefined, + isRecord, + omitKeys, + removeInternalParamFields, +} from './lib/misc-util.js'; +import { + APIIDMain, + generateNewOrderID, + getOrderIdPrefix, + logInvalidOrderId, + REST_CLIENT_TYPE_ENUM, + serializeParams, + validateWSAPICustomOrderID, + validateWSAPIDerivativesChannelKey, +} from './lib/requestUtils.js'; +import { + getSignKeyType, + SignAlgorithm, + SignEncodeMethod, + signMessage as signRawMessage, +} from './lib/webCryptoAPI.js'; +import { DefaultLogger } from './lib/websocket/logger.js'; +import { + getPromiseRefForWSAPIRequest, + getPromiseRefPrefixForWSAPIRequest, + getWsUrl as getHtxWsUrl, + HTXDerivativesWSAPIRawRequest, + HTXDerivativesWSRequest, + HTXSpotPrivateWSRequest, + HTXSpotWSAPIRawRequest, + HTXWSAPIRawRequest, + HtxWSNetwork, + HTXWSRequest, + isPrivateWsKey, + PRIVATE_WS_KEYS, + TRADE_WS_KEYS, + WS_KEY_MAP, + WS_KEY_PATH_MAP, + WsKey, + WSOperation, + WSTopicRequest, +} from './lib/websocket/websocket-util.js'; +import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; +import { + SpotV1OrderAutoPlaceReq, + SpotV1OrderPlaceReq, +} from './types/request/spot.types.js'; +import { OrderIdProperty } from './types/response/shared.types.js'; +import { + Exact, + WS_API_Operations, + WSAPIDerivativesOperation, + WSAPIOperation, + WSAPISpotOperation, + WSAPITopicRequestParamMap, + WSAPITopicResponseMap, + WSAPIWsKey, + WSAPIWsKeyTopicMap, +} from './types/websockets/ws-api.js'; +import { MessageEventLike } from './types/websockets/ws-events.js'; +import { + ParsedWsMessage, + WSClientConfigurableOptions, + WsDerivativesAuthParams, + WsSpotAuthParams, +} from './types/websockets/ws-general.js'; +import { + WebSocketLike, + WebSocketReadyState, +} from './types/websockets/ws-portable.js'; +import { + isPrivateTopic, + WSTopic, +} from './types/websockets/ws-subscriptions.js'; ⋮---- -/** - * Financial type code. - * 160: dividend settlement income. 161: dividend settlement expense. - */ +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for this WS API request. */ + authIsOptional?: boolean | undefined; + /** Optional caller-supplied correlation id. Generated automatically when omitted. */ + cid?: string; +} ⋮---- -/** - * USDT Margined Futures Multi Asset - Orders (v5 API) - */ +/** If true, will skip auth requirement for this WS API request. */ ⋮---- -/** Place order response from POST /v5/trade/order */ -export interface FuturesV5PlaceOrderResp { - order_id: string; - client_order_id?: string; -} +/** Optional caller-supplied correlation id. Generated automatically when omitted. */ ⋮---- -/** Batch place order item from POST /v5/trade/batch_orders */ -export interface FuturesV5PlaceBatchOrderRespItem { - order_id: string; - client_order_id?: string; - code: number; - message: string; +interface WsEndpointParts { + url: string; + host: string; + path: string; } ⋮---- -/** Close position response from POST /v5/trade/position */ -export interface FuturesV5ClosePositionResp { - order_id: string | number; - client_order_id?: string; +interface WSAPIInflightRequestRef { + wsKey: WSAPIWsKey; + operation: WSAPIOperation; + cid: string; } ⋮---- -/** Open order / order info / order history item from v5 trade endpoints */ -export interface FuturesV5Order { - id: string; - contract_code: string; - contract_type?: string; - side: string; - position_side: string; - type: string; - price_match?: string | null; - order_id: string; - client_order_id: string; - margin_mode: string; - price?: string; - volume: string; - lever_rate?: number; - state: string | number; - order_source: string; - reduce_only?: boolean | string; - time_in_force: string; - tp_trigger_price?: string; - tp_order_price?: string; - tp_type?: string | null; - tp_trigger_price_type?: string | null; - sl_trigger_price?: string; - sl_order_price?: string; - sl_type?: string | null; - sl_trigger_price_type?: string | null; - trade_avg_price?: string; - trade_volume?: string; - trade_turnover?: string; - fee_currency?: string; - fee?: string; - profit?: string | null; - price_protect?: boolean | string; - cancel_reason?: string | null; - created_time?: string; - updated_time?: string; - self_match_prevent?: string; - cancel_volume?: string; -} +export class WebsocketClient extends BaseWebsocketClient< ⋮---- -/** Execution/trade detail from GET /v5/trade/order/details */ -export interface FuturesV5OrderExecutionDetail { - id?: string; - contract_code?: string; - order_id?: string; - trade_id?: string; - side?: string; - position_side?: string; - order_type?: string; - margin_mode?: string; - type?: string; - client_order_id?: string; - role?: string; - trade_price?: string; - trade_volume?: string; - trade_turnover?: string; - created_time?: string; - updated_time?: string; - order_source?: string; - fee_currency?: string; - trade_fee?: string; - deduction_price?: string; - profit?: string; - contract_type?: string; -} +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- -/** Cancel-after response from POST /v5/trade/cancel-after */ -export interface FuturesV5CancelAfterResp { - current_time: string; - trigger_time?: string; -} +// For most connections, heartbeats are messages for HTX, not WS-level frames ⋮---- -/** Place algo order item from POST /v5/algo/order */ -export interface FuturesV5PlaceAlgoOrderResp { - algo_id: string; - algo_client_order_id?: string; -} +/** + * Request connection of all market/private sockets that are useful for subscriptions. + * Trade-command sockets are intentionally opened lazily by sendWSAPIRequest(). + */ +public connectAll(): Promise[] ⋮---- -/** Cancel algo order item from POST /v5/algo/cancel_orders */ -export interface FuturesV5CancelAlgoOrderResp { - algo_id: string; - algo_client_order_id?: string; - code?: number; - message?: string; -} +/** + * Ensures a WS API connection is active and, unless skipped, authenticated. + */ +public connectWSAPI( + wsKey: WSAPIWsKey = WS_KEY_MAP.spotTrade, + skipAuth?: boolean, +): Promise ⋮---- -/** Algo order from GET /v5/algo/order, /opens, /history */ -export interface FuturesV5AlgoOrder { - id?: string | number; - algo_id: string; - algo_client_order_id?: string; - contract_code: string; - volume?: string; - type: string; - state: string; - position_side: string; - margin_mode: string; - side: string; - tp_trigger_price?: string; - tp_order_price?: string; - tp_type?: string; - tp_trigger_price_type?: string; - sl_trigger_price?: string; - sl_order_price?: string; - sl_type?: string; - sl_trigger_price_type?: string; - price?: string; - price_match?: string; - trigger_price?: string; - trigger_price_type?: string; - active_price?: string; - order_price_type?: string; - callback_rate?: string; - reduce_only?: boolean | string; - actual_volume?: string; - actual_price?: string; - actual_time?: string; - relation_order_id?: string; - created_time?: string; - updated_time?: string; - order_source?: string; -} +public subscribe( + requests: + | (WSTopicRequest | WSTopic) + | (WSTopicRequest | WSTopic)[], + wsKey: WsKey, +) +⋮---- +public unsubscribe( + requests: + | (WSTopicRequest | WSTopic) + | (WSTopicRequest | WSTopic)[], + wsKey: WsKey, +) ⋮---- /** - * USDT Margined Futures Multi Asset - Positions (v5 API) - */ + * WS API Methods - similar to the REST API, but via WebSockets + */ ⋮---- -/** Position from GET /v5/trade/position/opens */ -export interface FuturesV5Position { - contract_code: string; - position_side: string; - direction: string; - margin_mode: string; - open_avg_price: string; - volume: string; - available: string; - lever_rate: string | number; - adl_risk_percent?: number | null; - liquidation_price: string; - initial_margin: string; - maintenance_margin: string; - profit_unreal: string; - profit_rate: string; - margin_rate: string; - margin_currency: string; - last_price?: string; - mark_price?: string; - contract_type: string; - created_time: string; - updated_time: string; -} +/** + * Send a Websocket API event on a connection. Returns a promise that resolves on reply. + * + * 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). + * + * After a fresh connection, you should always send a login request first. + * + * If you authenticated once and you're reconnected later (e.g. connection temporarily lost), the SDK will by default automatically: + * - Detect you were authenticated to the WS API before + * - Try to re-authenticate (up to 5 times, in case something (bad timestamp) goes wrong) + * - If it succeeds, it will emit the 'authenticated' event. + * - If it fails and gives up, it will emit an 'exception' event (type: 'wsapi.auth', reason: detailed text). + * + * You can turn off the automatic re-auth WS API logic using `reauthWSAPIOnReconnect: false` in the WSClient config. + * + * @param wsKey - The connection this event is for. + * @param channel - The channel this event is for (e.g. "spot.login" to authenticate) + * @param params - Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs. + * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response + */ +async sendWSAPIRequest< + TWSKey extends keyof WSAPIWsKeyTopicMap, + TWSOperation extends keyof WSAPITopicRequestParamMap & + WSAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact, + TWSAPIResponse extends WSAPITopicResponseMap[TWSOperation] | object = + WSAPITopicResponseMap[TWSOperation], + >( + wsKey: TWSKey, + operation: TWSOperation, + params?: TWSParams, + requestFlags?: WSAPIRequestFlags, + ): Promise; ⋮---- -/** Leverage list entry from GET /v5/position/lever */ -export interface FuturesV5LeverListEntry { - contract_code: string; - contract_type: string; - margin_mode: string; - position_side: string; - lever_rate: number; - available_lever: string | string[]; -} +async sendWSAPIRequest< + TWSKey extends keyof WSAPIWsKeyTopicMap, + TWSOperation extends keyof WSAPITopicRequestParamMap & + WSAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact, + TWSAPIResponse extends WSAPITopicResponseMap[TWSOperation] | object = + WSAPITopicResponseMap[TWSOperation], + >( + wsKey: TWSKey, + operation: TWSOperation, + params: TWSParams & { signRequest?: boolean }, + requestFlags?: WSAPIRequestFlags, +): Promise ⋮---- -/** Set leverage response from POST /v5/position/lever */ -export interface FuturesV5SetLeverageResp { - contract_code: string; - margin_mode: string; - position_side?: string; - lever_rate: number; -} +// Used by other exchanges for commands that don't require authentication. ⋮---- -/** Position mode from GET/POST /v5/position/mode */ -export interface FuturesV5PositionModeResp { - position_mode: 'single_side' | 'dual_side'; -} +protected isCustomReconnectionNeeded(): boolean ⋮---- -/** Risk limit entry from GET /v5/position/risk/limit */ -export interface FuturesV5RiskLimitEntry { - contract_code: string; - contract_type?: string; - margin_mode: string; - position_side: string; - max_lever: string; - maintenance_margin_rate: string; - max_volume: string; - min_volume: string; - volume_unit: string; -} +public generateNewOrderID(): string ⋮---- -/** Risk limit tier entry from GET /v5/position/risk/limit_tier */ -export interface FuturesV5RiskLimitTierEntry { - contract_code: string; - margin_mode: string; - tier: number; - max_lever: string; - maintenance_margin_rate: string; - max_volume: string; - min_volume: string; - volume_unit: string; -} +public getOrderIdPrefix(): string ⋮---- -/** - * USDT Margined Futures Multi Asset - Basic Information (v5 API) - */ +protected async triggerCustomReconnectionWorkflow(): Promise ⋮---- -/** Funding fee type on GET /v5/market/funding_rate_history */ -export type FuturesV5FundingFeeType = 'normal' | 'dividend_settlement'; +protected async getWsUrl(wsKey: WsKey): Promise ⋮---- -/** Historical funding rate item from GET /v5/market/funding_rate_history */ -export interface FuturesV5FundingRateHistory { - id: string; - /** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ - contract_code: string; - funding_rate: string; - /** Funding time, unix ms */ - funding_time: string; - /** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ - funding_fee_type: FuturesV5FundingFeeType; -} +protected sendPingEvent(wsKey: WsKey, ws: WebSocketLike): boolean ⋮---- -/** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ +// These WS Keys use native ping frames, since the JSON ping is not supported for these websocket endpoints (confirmed by HTX) ⋮---- -/** Funding time, unix ms */ +protected sendPongEvent(wsKey: WsKey, _ws: WebSocketLike, event?: unknown) ⋮---- -/** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ +protected isWsPing(event: unknown): boolean ⋮---- -/** Risk limit entry from GET /v5/market/risk/limit */ -export interface FuturesV5MarketRiskLimitEntry { - contract_code: string; - margin_mode: string; - tier: number; - max_lever: string; - maintenance_margin_rate: string; - max_volume: string; - min_volume: string; - volume_unit?: string; -} +protected isWsPong(event: unknown): boolean ⋮---- -/** Assets deduction currency from GET /v5/market/assets_deduction_currency */ -export interface FuturesV5AssetsDeductionCurrencyResp { - currency: string[]; -} +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] ⋮---- -/** Multi-assets margin from GET /v5/market/multi_assets_margin */ -export interface FuturesV5MultiAssetsMarginResp { - multi_assets: string[]; -} +protected isPrivateTopicRequest( + request: WSTopicRequest, + wsKey: WsKey, +): boolean ⋮---- -/** - * Coin-M Delivery - Reference Data (FuturesCmDelivery) - */ +protected getPrivateWSKeys(): WsKey[] ⋮---- -/** Ladder item from contract_adjustfactor */ -export interface FuturesCmDeliveryAdjustFactorLadder { - ladder: number; - min_size: number; - max_size: number | null; - adjust_factor: number; -} +protected authPrivateConnectionsOnConnect(wsKey: WsKey): boolean ⋮---- -/** Lever item in adjust factor list */ -export interface FuturesCmDeliveryAdjustFactorLeverItem { - lever_rate: number; - ladders: FuturesCmDeliveryAdjustFactorLadder[]; -} +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -/** GET /api/v1/contract_adjustfactor */ -export interface FuturesCmDeliveryAdjustFactor { - symbol: string; - list: FuturesCmDeliveryAdjustFactorLeverItem[]; -} +protected getMaxTopicsPerSubscribeEvent(): number | null ⋮---- -/** Tick from contract_his_open_interest */ -export interface FuturesCmDeliveryOpenInterestTick { - volume: string; - amount_type: number; - ts: number; -} +protected async getWsRequestEvents( + wsKey: WsKey, + operation: WSOperation, + requests: WSTopicRequest[], +): Promise[]> ⋮---- -/** GET /api/v1/contract_his_open_interest */ -export interface FuturesCmDeliveryOpenInterest { - symbol: string; - contract_type: string; - tick: FuturesCmDeliveryOpenInterestTick[]; -} +protected async getWsAuthRequestEvent( + wsKey: WsKey, +): Promise ⋮---- -/** Ladder item from contract_ladder_margin */ -export interface FuturesCmDeliveryLadderMarginLadder { - min_margin_balance: number; - max_margin_balance: number | null; - min_margin_available: number; - max_margin_available: number | null; -} +private getWsApiRequestEvent< + TWSKey extends keyof WSAPIWsKeyTopicMap, + TWSOperation extends keyof WSAPITopicRequestParamMap & + WSAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact, + >( + wsKey: TWSKey, + operation: TWSOperation, + params: TWSParams | undefined, + cid: string, +): HTXWSAPIRawRequest ⋮---- -/** Lever item in ladder margin list */ -export interface FuturesCmDeliveryLadderMarginLeverItem { - lever_rate: number; - ladders: FuturesCmDeliveryLadderMarginLadder[]; -} +private resolveWSAPIResponse( + wsKey: WsKey, + parsed: ParsedWsMessage, +): EmittableEvent[] ⋮---- -/** GET /api/v1/contract_ladder_margin */ -export interface FuturesCmDeliveryLadderMargin { - symbol: string; - list: FuturesCmDeliveryLadderMarginLeverItem[]; -} +private async getSpotAuthParams(wsKey: WsKey): Promise ⋮---- -/** Ladder from GET /swap-api/v1/swap_adjustfactor */ -export interface FuturesCmPerpAdjustFactorLadder { - ladder: number; - min_size: number; - max_size: number | null; - adjust_factor: number; -} +private async getDerivativesAuthParams( + wsKey: WsKey, +): Promise ⋮---- -/** Lever item from swap_adjustfactor list */ -export interface FuturesCmPerpAdjustFactorLeverItem { - lever_rate: number; - ladders: FuturesCmPerpAdjustFactorLadder[]; -} +private async signHtxParams( + host: string, + path: string, + params: Record, +): Promise ⋮---- -/** GET /swap-api/v1/swap_adjustfactor */ -export interface FuturesCmPerpAdjustFactor { - symbol: string; - contract_code: string; - list: FuturesCmPerpAdjustFactorLeverItem[]; -} +private async signMessage( + paramsStr: string, + secret: string, + method: SignEncodeMethod, + algorithm: SignAlgorithm, +): Promise ⋮---- -/** Tick from GET /swap-api/v1/swap_his_open_interest */ -export interface FuturesCmPerpOpenInterestTick { - volume: number; - amount_type: number; - ts: number; -} +private getSignatureMethod(): 'HmacSHA256' | 'Ed25519' ⋮---- -/** GET /swap-api/v1/swap_his_open_interest */ -export interface FuturesCmPerpOpenInterest { - symbol: string; - contract_code: string; - tick: FuturesCmPerpOpenInterestTick[]; -} +private getTimestampForSignature(): string ⋮---- -/** Ladder from GET /swap-api/v1/swap_ladder_margin */ -export interface FuturesCmPerpTieredMarginLadder { - min_margin_balance: number; - max_margin_balance: number | null; - min_margin_available: number; - max_margin_available: number | null; -} +private async getWsEndpointParts(wsKey: WsKey): Promise ⋮---- -/** Lever item from swap_ladder_margin list */ -export interface FuturesCmPerpTieredMarginLeverItem { - lever_rate: number; - ladders: FuturesCmPerpTieredMarginLadder[]; -} +private getWsNetwork(): HtxWSNetwork ⋮---- -/** GET /swap-api/v1/swap_ladder_margin */ -export interface FuturesCmPerpTieredMargin { - symbol: string; - contract_code: string; - list: FuturesCmPerpTieredMarginLeverItem[]; -} +private isMarketProtocolWsKey(wsKey: WsKey): boolean ⋮---- -/** List item from GET /swap-api/v1/swap_elite_account_ratio */ -export interface FuturesCmPerpAccountRatioItem { - buy_ratio: number; - sell_ratio: number; - locked_ratio: number; - ts: number; -} +private isSpotPrivateProtocolWsKey(wsKey: WsKey): boolean ⋮---- -/** GET /swap-api/v1/swap_elite_account_ratio */ -export interface FuturesCmPerpAccountRatio { - symbol: string; - contract_code: string; - list: FuturesCmPerpAccountRatioItem[]; -} +private isDerivativesTopicProtocolWsKey(wsKey: WsKey): boolean ⋮---- -/** List item from GET /swap-api/v1/swap_elite_position_ratio */ -export interface FuturesCmPerpPositionRatioItem { - buy_ratio: number; - sell_ratio: number; - ts: number; -} +private isDerivativesOperationProtocolWsKey(wsKey: WsKey): boolean ⋮---- -/** GET /swap-api/v1/swap_elite_position_ratio */ -export interface FuturesCmPerpPositionRatio { - symbol: string; - contract_code: string; - list: FuturesCmPerpPositionRatioItem[]; -} +private parseWsMessage(event: unknown): ParsedWsMessage | undefined ⋮---- -/** Item from GET /swap-api/v1/swap_estimated_settlement_price data[] */ -export interface FuturesCmPerpEstimatedSettlementPrice { - contract_code: string; - estimated_settlement_price: number | null; - settlement_type: 'delivery' | 'settlement'; -} +private getHeartbeatTimestamp(parsed?: ParsedWsMessage): string | number ⋮---- -/** GET /swap-api/v1/swap_api_state */ -export interface FuturesCmPerpSystemStatus { - symbol: string; - contract_code: string; - open: number; - close: number; - cancel: number; - transfer_in: number; - transfer_out: number; - master_transfer_sub: number; - sub_transfer_master: number; -} +private getPayloadRecord(payload: unknown): Record ⋮---- -/** GET /swap-api/v1/swap_funding_rate */ -export interface FuturesCmPerpFundingRate { - symbol: string; - contract_code: string; - fee_asset: string; - funding_time: string; - funding_rate: string; - estimated_rate: string | null; - next_funding_time: string | null; -} +private getPayloadStringOrNumber( + payload: Record, + key: string, +): string | number | undefined ⋮---- -/** Item from GET /swap-api/v1/swap_historical_funding_rate data[] */ -export interface FuturesCmPerpHistoricalFundingRate { - symbol: string; - contract_code: string; - fee_asset: string; - funding_time: string; - funding_rate: string; - /** Deprecated, default null */ - realized_rate?: string | null; - avg_premium_index: string; -} +private isAuthResponse(parsed: ParsedWsMessage): boolean ⋮---- -/** Deprecated, default null */ +private isWSAPIResponse(wsKey: WsKey, parsed: ParsedWsMessage): boolean ⋮---- -/** Paginated wrapper for GET /swap-api/v1/swap_historical_funding_rate */ -export type FuturesCmPerpHistoricalFundingRatePage = - FuturesPaginatedData; +private isSubscriptionResponse(parsed: ParsedWsMessage): boolean ⋮---- -/** Item from GET /swap-api/v3/swap_liquidation_orders data[] */ -export interface FuturesCmPerpLiquidationOrder { - query_id?: number; - contract_code: string; - symbol: string; - direction: string; - offset: string; - volume: number; - price: number; - created_at: number; - amount: number; -} +private isRequestResponse(parsed: ParsedWsMessage): boolean ⋮---- -/** Item from GET /swap-api/v1/swap_settlement_records settlement_record[] */ -export interface FuturesCmPerpSettlementRecord { - symbol: string; - contract_code: string; - settlement_time: number; - clawback_ratio: number; - settlement_price: number; - settlement_type: string; -} +private isErrorEvent(parsed: ParsedWsMessage): boolean ⋮---- -/** Paginated wrapper for GET /swap-api/v1/swap_settlement_records */ -export type FuturesCmPerpSettlementRecordsPage = - FuturesPaginatedSettlement; +private getEventOperation(parsed: ParsedWsMessage): string | undefined ⋮---- -/** Index constituents from GET /swap-api/market/swap_constituents. data is object. */ -export interface FuturesCmPerpIndexConstituents { - contract_code: string; - ts: number; - index_price: string; - components: FuturesIndexConstituentComponent[]; -} +private trackWSAPIRequestRef( + promiseRef: string, + wsKey: WSAPIWsKey, + operation: WSAPIOperation, + cid: string, +): void ⋮---- -/** Item from GET /swap-api/v1/swap_contract_info data[] */ -export interface FuturesCmPerpContractInfo { - symbol: string; - contract_code: string; - contract_size: number; - price_tick: number; - settlement_date: string; - settlement_period: string; - create_date: string; - delivery_time: string; - contract_status: number; - labels?: string[]; +private getPromiseRefForWSAPIResponse( + wsKey: WsKey, + parsed: ParsedWsMessage, +): string | undefined +⋮---- +/** + * + * Misc Utility Methods + * + */ +⋮---- +/** + * Validate syntax meets requirements set by HTX. + * Log warning if not. + */ +public validateOrderId( + params: SpotV1OrderPlaceReq | SpotV1OrderAutoPlaceReq, + orderIdProperty: OrderIdProperty, +): void + +================ +File: src/types/request/spot.types.ts +================ +/** + * Reference Data + */ +⋮---- +export interface SpotGetChainsReq { + /** Show desc: 0=no, 1=all, 2=suspend deposit/withdrawal and chain exchange */ + 'show-desc'?: string; + /** Currency filter */ + currency?: string; + /** Timestamp for incremental data. Returns updates from ts to now. If no update, data is []. */ + ts?: number; } ⋮---- -/** Item from GET /swap-api/v1/swap_open_interest data[] */ -export interface FuturesCmPerpOpenInterestCurrent { +/** Show desc: 0=no, 1=all, 2=suspend deposit/withdrawal and chain exchange */ +⋮---- +/** Currency filter */ +⋮---- +/** Timestamp for incremental data. Returns updates from ts to now. If no update, data is []. */ +⋮---- +/** + * Market Data + */ +⋮---- +/** Req for /market/history/kline */ +export interface SpotGetKlineReq { + /** Trading symbol (e.g. btcusdt, btc3lusdtnav for ETP NAV) */ symbol: string; - contract_code: string; - volume: number; - amount: number; - trade_amount: number; - trade_volume: number; - trade_turnover: number; + /** Candle period. Default 1day. */ + period?: string; + /** Number of data points [1-2000]. Default 150. */ + size?: number; } ⋮---- -/** contract_infos[] item from GET /swap-api/v1/swap_query_elements */ -export interface FuturesCmPerpContractElementsContractInfo { - contract_code: string; - settlement_date: string; - /** Empty string when no delivery */ - delivery_time: string; - create_date: string; - contract_status: number; - instrument_type?: number; -} +/** Trading symbol (e.g. btcusdt, btc3lusdtnav for ETP NAV) */ ⋮---- -/** Empty string when no delivery */ +/** Candle period. Default 1day. */ ⋮---- -/** Market depth tick from GET /swap-ex/market/depth. Payload in "tick". */ -export interface FuturesCmPerpMarketDepth { - mrid: number; - id: number; - asks: [number, number][]; - bids: [number, number][]; - ts: number; - version: number; - ch: string; -} +/** Number of data points [1-2000]. Default 150. */ ⋮---- -/** BBO tick from GET /swap-ex/market/bbo. ask/bid: [price, qty]. Payload in "ticks". */ -export interface FuturesCmPerpMarketBbo { - contract_code: string; - mrid: number; - ask: [number, number]; - bid: [number, number]; - ts: number; +export interface SpotGetDepthReq { + /** Trading symbol (e.g. btcusdt) */ + symbol: string; + /** Depth levels per side. 5, 10, 20, 30. Default 20. step0 uses 150 if omitted. */ + depth?: number; + /** step0=no agg, step1-5=aggregation levels. Default step0. */ + type?: string; } ⋮---- -/** Kline item from GET /swap-ex/market/history/kline */ -export interface FuturesCmPerpKline { - id: number; - vol: number; - count: number; - open: number; - close: number; - low: number; - high: number; - amount: number; -} +/** Trading symbol (e.g. btcusdt) */ ⋮---- -/** Mark price kline item from GET /index/market/history/swap_mark_price_kline */ -export interface FuturesCmPerpMarkPriceKline { - id: number; - vol: string; - count: string; - open: string; - close: string; - low: string; - high: string; - amount: string; - trade_turnover: string; -} +/** Depth levels per side. 5, 10, 20, 30. Default 20. step0 uses 150 if omitted. */ ⋮---- -/** 24h ticker from GET /swap-ex/market/detail/merged. Payload in "tick". */ -export interface FuturesCmPerp24hTicker { - id: number; - ts: number; - vol: string; - count: number; - open: string; - close: string; - low: string; - high: string; - amount: string; - ask: [number, number]; - bid: [number, number]; -} +/** step0=no agg, step1-5=aggregation levels. Default step0. */ ⋮---- -/** 24h ticker item from GET /v2/swap-ex/market/detail/batch_merged */ -export interface FuturesCmPerp24hTickers { - contract_code: string; - id: number; - ts: number; - amount: string; - count: number; - vol: string; - number_of: string; - open: string; - close: string; - low: string; - high: string; - ask: [number, number]; - bid: [number, number]; -} +/** + * Account + */ export interface SpotGetAssetValuationReq { ⋮---- -/** Trade item from GET /swap-ex/market/trade and history/trade */ -export interface FuturesCmPerpTrade { - id: number; - price: string; - amount: string; - direction: string; - ts: number; - quantity: string; - contract_code?: string; +*/ export interface SpotGetAssetValuationReq { + /** Account type: spot, margin, otc, super-margin. Default spot. */ + accountType?: string; + /** Valuation currency: BTC, CNY, USD, JPY, etc. Case sensitive. Default BTC. */ + valuationCurrency?: string; + /** Sub user UID. Omit for API key owner. */ + subUid?: number; } ⋮---- -/** Last trade tick from GET /swap-ex/market/trade. Payload in "tick". */ -export interface FuturesCmPerpLastTrade { - id: number; - ts: number; - data: FuturesCmPerpTrade[]; -} +/** Account type: spot, margin, otc, super-margin. Default spot. */ ⋮---- -/** Trade history group from GET /swap-ex/market/history/trade. Each group has trades by timestamp. */ -export interface FuturesCmPerpTradeHistory { - id: number; - ts: number; - data: FuturesCmPerpTrade[]; -} +/** Valuation currency: BTC, CNY, USD, JPY, etc. Case sensitive. Default BTC. */ ⋮---- -/** Estimated funding rate kline item from GET /index/market/history/swap_estimated_rate_kline */ -export interface FuturesCmPerpFundingRateKline { - id: number; - vol: string; - count: string; - open: string; - close: string; - low: string; - high: string; +/** Sub user UID. Omit for API key owner. */ +⋮---- +/** Req for POST /v2/account/transfer - transfer between spot, linear-swap, otc, futures, swap */ +export interface SpotV2AccountTransferReq { + /** Source: spot, linear-swap, otc, futures, swap */ + from: string; + /** Destination: spot, linear-swap, otc, futures, swap */ + to: string; + /** Currency (e.g. usdt). Upper/lowercase supported. */ + currency: string; + /** Transfer amount */ amount: string; + /** Margin account (e.g. btc-usdt, eth-usdt, USDT) */ + 'margin-account': string; } ⋮---- -/** Premium index kline item from GET /index/market/history/swap_premium_index_kline */ -export interface FuturesCmPerpPremiumIndexKline { - id: number; - vol: string; - count: string; - open: string; - close: string; - low: string; - high: string; +/** Source: spot, linear-swap, otc, futures, swap */ +⋮---- +/** Destination: spot, linear-swap, otc, futures, swap */ +⋮---- +/** Currency (e.g. usdt). Upper/lowercase supported. */ +⋮---- +/** Transfer amount */ +⋮---- +/** Margin account (e.g. btc-usdt, eth-usdt, USDT) */ +⋮---- +/** Req for POST /v1/futures/transfer - transfer between spot and future contract account */ +export interface SpotV1FuturesTransferReq { + /** Currency name */ + currency: string; + /** Amount to transfer */ amount: string; + /** futures-to-pro (contract -> spot) or pro-to-futures (spot -> contract) */ + type: 'futures-to-pro' | 'pro-to-futures'; } ⋮---- -/** Basis data item from GET /index/market/history/swap_basis */ -export interface FuturesCmPerpBasisData { - id: number; - contract_price: string; - index_price: string; - basis: string; - basis_rate: string; -} +/** Currency name */ ⋮---- -/** Account info from POST /swap-api/v1/swap_account_info */ -export interface FuturesCmPerpAccountInfo { - symbol: string; - contract_code: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real?: number; - profit_unreal: number; - risk_rate: number | null; - new_risk_rate?: string | null; - trade_partition?: string; - withdraw_available: number; - liquidation_price: number | null; - lever_rate: number; - adjust_factor: number; - margin_static: number; -} +/** Amount to transfer */ ⋮---- -/** Position info from POST /swap-api/v1/swap_position_info */ -export interface FuturesCmPerpPositionInfo { - symbol: string; - contract_code: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - adl_risk_percent?: string | number; - liq_px: string; - new_risk_rate?: string | null; - trade_partition?: string; -} +/** futures-to-pro (contract -> spot) or pro-to-futures (spot -> contract) */ ⋮---- -/** Position item in getCoinMPerpAccountFull positions[] */ -export interface FuturesCmPerpAccountFullPosition { - symbol: string; - contract_code: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - adl_risk_percent?: string | number; +/** Req for POST /v1/account/transfer */ +export interface SpotAccountTransferReq { + /** Transfer out user uid */ + 'from-user': number; + /** Transfer out account type: spot, margin */ + 'from-account-type': string; + /** Transfer out account id */ + 'from-account': number; + /** Transfer in user uid */ + 'to-user': number; + /** Transfer in account type: spot, margin */ + 'to-account-type': string; + /** Transfer in account id */ + 'to-account': number; + /** Currency name */ + currency: string; + /** Amount to transfer */ + amount: string; } ⋮---- -/** Account + positions from getCoinMPerpAccountFull */ -/** Account + positions from getCoinMPerpAccountFull */ -export interface FuturesCmPerpAccountFull { - symbol: string; - contract_code: string; - margin_balance: number; - margin_static: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real?: number; - profit_unreal: number; - risk_rate: number | null; - withdraw_available: number; - liquidation_price: number | null; - lever_rate: number; - adjust_factor: number; - new_risk_rate?: string | null; - trade_partition?: string; - positions: FuturesCmPerpAccountFullPosition[]; -} +/** Transfer out user uid */ ⋮---- -/** Sub-auth error from swap_sub_auth and swap_sub_auth_list */ -export interface FuturesCmPerpSubPermissionsError { - sub_uid: string; - err_code: number | string; - err_msg: string; -} +/** Transfer out account type: spot, margin */ ⋮---- -/** Sub-auth response from updateCoinMPerpSubPermissions */ -export interface FuturesCmPerpUpdateSubPermissions { - errors: FuturesCmPerpSubPermissionsError[]; - successes: string; -} +/** Transfer out account id */ ⋮---- -/** Sub-auth success item from swap_sub_auth_list */ -export interface FuturesCmPerpSubPermissionsSuccess { - query_id?: number; - sub_uid: string; - sub_auth: number | string; -} +/** Transfer in user uid */ ⋮---- -/** Sub-auth list from getCoinMPerpSubPermissions */ -export interface FuturesCmPerpSubPermissions { - errors: FuturesCmPerpSubPermissionsError[]; - successes: FuturesCmPerpSubPermissionsSuccess[]; -} +/** Transfer in account type: spot, margin */ ⋮---- -/** Sub-account list item from getCoinMPerpSubAccounts list[] */ -export interface FuturesCmPerpSubAccountsItem { - symbol: string; - contract_code: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | null; - query_id?: number; -} +/** Transfer in account id */ ⋮---- -/** Sub-account entry from getCoinMPerpSubAccounts (data array element) */ -export interface FuturesCmPerpSubAccounts { - sub_uid: number; - list: FuturesCmPerpSubAccountsItem[]; -} +/** Currency name */ ⋮---- -/** Account info item from getCoinMPerpSubAccountsAssets account_info_list[] */ -export interface FuturesCmPerpSubAccountsAssetsAccount { - symbol: string; - contract_code: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | null; -} +/** Amount to transfer */ ⋮---- -/** Sub-list item from getCoinMPerpSubAccountsAssets sub_list[] */ -export interface FuturesCmPerpSubAccountsAssetsSub { - sub_uid: number; - account_info_list: FuturesCmPerpSubAccountsAssetsAccount[]; +/** Req for GET /v1/account/history */ +export interface SpotGetAccountHistoryReq { + /** Account ID from GET /v1/account/accounts */ + 'account-id': string | number; + /** Currency filter */ + currency?: string; + /** Amount change types, comma-separated. Default all. Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ + 'transact-types'?: string; + /** Start time (unix ms). Query window max 1 hour. */ + 'start-time'?: number; + /** End time (unix ms). Query window within 30 days. */ + 'end-time'?: number; + /** Sort order: asc, desc. Default asc. */ + sort?: string; + /** Max items [1-500]. Default 100. */ + size?: number; + /** First record ID for pagination (next page) */ + 'from-id'?: number; } ⋮---- -/** Response from getCoinMPerpSubAccounts */ -export type FuturesCmPerpSubAccountsAssets = - FuturesPaginatedSubList; +/** Account ID from GET /v1/account/accounts */ ⋮---- -/** Sub-account account info from getCoinMPerpSubAccountAssets (data array element) */ -export interface FuturesCmPerpSubAccountAssets { - symbol: string; - contract_code: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real?: number; - profit_unreal: number; - risk_rate: number | null; - liquidation_price: number | null; - withdraw_available: number; - lever_rate: number; - adjust_factor: number; - margin_static: number; - new_risk_rate?: string | null; - trade_partition?: string; -} +/** Currency filter */ ⋮---- -/** Sub-account position from getCoinMPerpSubPositions (data array element) */ -export interface FuturesCmPerpSubPositions { - symbol: string; - contract_code: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - adl_risk_percent?: string | number; - liq_px: string; - new_risk_rate?: string | null; - trade_partition?: string; -} +/** Amount change types, comma-separated. Default all. Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ ⋮---- -/** Financial record from POST /swap-api/v3/swap_financial_record and swap_financial_record_exact */ -export interface FuturesCmPerpFinancialRecord { - query_id: number; - id: number | string; - ts: number; - symbol: string; - contract_code: string; - type: number; - amount: number | string; -} +/** Start time (unix ms). Query window max 1 hour. */ ⋮---- -/** Available leverage from getCoinMPerpAvailableLeverage */ -export interface FuturesCmPerpAvailableLeverage { - contract_code: string; - available_level_rate: string; -} +/** End time (unix ms). Query window within 30 days. */ ⋮---- -/** Order limit list item from swap_order_limit list[] */ -export interface FuturesCmPerpOrderLimitList { - symbol: string; - contract_code: string; - open_limit: number; - close_limit: number; -} +/** Sort order: asc, desc. Default asc. */ ⋮---- -/** Order limit from POST /swap-api/v1/swap_order_limit */ -export interface FuturesCmPerpOrderLimit { - order_price_type: string; - list: FuturesCmPerpOrderLimitList[]; -} +/** Max items [1-500]. Default 100. */ ⋮---- -/** Fee from POST /swap-api/v1/swap_fee */ -export interface FuturesCmPerpFee { - symbol: string; - contract_code: string; - open_maker_fee: string; - open_taker_fee: string; - close_maker_fee: string; - close_taker_fee: string; - fee_asset: string; - delivery_fee?: string; -} +/** First record ID for pagination (next page) */ ⋮---- -/** Transfer limit from POST /swap-api/v1/swap_transfer_limit */ -export interface FuturesCmPerpTransferLimit { - symbol: string; - contract_code: string; - transfer_in_max_each: number; - transfer_in_min_each: number; - transfer_out_max_each: number; - transfer_out_min_each: number; - transfer_in_max_daily: number; - transfer_out_max_daily: number; - net_transfer_in_max_daily: number; - net_transfer_out_max_daily: number; +export interface SpotV2PointTransferReq { + /** Transferer UID */ + fromUid: string; + /** Transferee UID */ + toUid: string; + /** Group ID. 0 = termless points. For terminable points, query sub user balance first. */ + groupId: number; + /** Transfer amount (max 8 decimal places) */ + amount: string; } ⋮---- -/** Position limit from POST /swap-api/v1/swap_position_limit */ -export interface FuturesCmPerpPositionLimit { - symbol: string; - contract_code: string; - buy_limit: number; - sell_limit: number; -} +/** Transferer UID */ ⋮---- -/** API trading status COR from getCoinMPerpApiStatus */ -export interface FuturesCmPerpApiStatusCor { - orders_threshold: number; - orders: number; - invalid_cancel_orders: number; - cancel_ratio_threshold: number; - cancel_ratio: number; - is_trigger: number; - is_active: number; -} +/** Transferee UID */ ⋮---- -/** API trading status TDN from getCoinMPerpApiStatus */ -export interface FuturesCmPerpApiStatusTdn { - disables_threshold: number; - disables: number; - is_trigger: number; - is_active: number; -} +/** Group ID. 0 = termless points. For terminable points, query sub user balance first. */ ⋮---- -/** API trading status from getCoinMPerpApiStatus */ -export interface FuturesCmPerpApiStatus { - is_disable: number; - order_price_types: string; - disable_reason: string; - disable_interval: number; - recovery_time: number; - COR: FuturesCmPerpApiStatusCor; - TDN: FuturesCmPerpApiStatusTdn; -} +/** Transfer amount (max 8 decimal places) */ ⋮---- -/** Cancel-after response from setCoinMPerpCancelAfter */ -export interface FuturesCmPerpCancelAfter { - current_time: number; - trigger_time: number; -} +/** + * Trading + */ ⋮---- -/** Trigger open order item from getCoinMPerpTriggerOpenOrders */ -export interface FuturesCmPerpTriggerOpenOrder { - symbol: string; - contract_code: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_price: number | string; - order_price: number | string; - created_at: number; - order_price_type: string; - status: number; -} +/** Order type: direction-type. market=no price; limit=price+amount; limit-maker=maker only; ioc=immediately or cancel; limit-fok=fill or kill; stop-*=trigger price */ +export type SpotOrderType = + | 'buy-market' + | 'sell-market' + | 'buy-limit' + | 'sell-limit' + | 'buy-ioc' + | 'sell-ioc' + | 'buy-limit-maker' + | 'sell-limit-maker' + | 'buy-stop-limit' + | 'sell-stop-limit' + | 'buy-limit-fok' + | 'sell-limit-fok' + | 'buy-stop-limit-fok' + | 'sell-stop-limit-fok'; ⋮---- -/** Trigger open orders response from getCoinMPerpTriggerOpenOrders */ -export type FuturesCmPerpTriggerOpenOrders = - FuturesPaginatedOrders; +/** Order source: spot-api, margin-api, super-margin-api, c2c-margin-api */ +export type SpotOrderSource = + | 'spot-api' + | 'margin-api' + | 'super-margin-api' + | 'c2c-margin-api'; ⋮---- -/** Trigger history order item from getCoinMPerpTriggerHisOrders */ -export interface FuturesCmPerpTriggerHisOrder { +/** Req for POST /v1/order/orders/place */ +export interface SpotV1OrderPlaceReq { + /** Account ID from GET /v1/account/accounts. Required for trading. */ + 'account-id': string | number; + /** Trading symbol (e.g. ethusdt) */ symbol: string; - contract_code: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - relation_order_id: string; - order_price_type: string; - status: number; - order_source: string; - trigger_price: number | string; - triggered_price: number | string | null; - order_price: number | string; - created_at: number; - triggered_at: number | null; - order_insert_at: number; - canceled_at: number | null; - update_time: number; - fail_code: number | null; - fail_reason: string | null; + /** Order type (e.g. buy-limit, sell-market) */ + type: SpotOrderType; + /** Order size. For buy-market = order value in quote currency. */ + amount: string; + /** Order price. Not used for market orders. Required for limit types. */ + price?: string; + /** Order source. Default spot-api */ + source?: SpotOrderSource; + /** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ + 'client-order-id'?: string; + /** 0=allow self-trade, 1=prevent. Default 0 */ + 'self-match-prevent'?: 0 | 1; + /** Trigger price for stop-limit orders */ + 'stop-price'?: string; + /** Operator for stop price (lte, gte, etc) */ + operator?: string; + /** RPI order - type must be buy-limit or sell-limit */ + 'time-in-force'?: 'rpi'; } ⋮---- -/** Trigger history orders response from getCoinMPerpTriggerHistoryOrders */ -export type FuturesCmPerpTriggerHistoryOrders = - FuturesPaginatedOrders; +/** Account ID from GET /v1/account/accounts. Required for trading. */ ⋮---- -/** TPSL open order item from getCoinMPerpTpslOpenOrders */ -export interface FuturesCmPerpTpslOpenOrder { - symbol: string; - contract_code: string; - volume: number; - order_type: number; - tpsl_order_type: string; - direction: string; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_type: string; - trigger_price: number | string; - price_protect?: boolean; - created_at: number; - order_price_type: string; - order_price: number | string; - status: number; - source_order_id: string | null; - relation_tpsl_order_id: string; -} +/** Trading symbol (e.g. ethusdt) */ ⋮---- -/** TPSL open orders response from getCoinMPerpTpslOpenOrders */ -export type FuturesCmPerpTpslOpenOrders = - FuturesPaginatedOrders; +/** Order type (e.g. buy-limit, sell-market) */ ⋮---- -/** TPSL history order item from getCoinMPerpTpslHistoryOrders */ -export interface FuturesCmPerpTpslHisOrder { - symbol: string; - contract_code: string; - volume: number; - order_type: number; - tpsl_order_type: string; - direction: string; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_type: string; - trigger_price: number | string; - price_protect?: boolean; - created_at: number; - order_price_type: string; - order_price: number | string; - status: number; - source_order_id: string | null; - relation_tpsl_order_id: string; - canceled_at: number | null; - fail_code: number | null; - fail_reason: string | null; - triggered_price: number | string | null; - relation_order_id: string; - update_time: number; -} +/** Order size. For buy-market = order value in quote currency. */ ⋮---- -/** TPSL history orders response from getCoinMPerpTpslHistoryOrders */ -export type FuturesCmPerpTpslHisOrders = - FuturesPaginatedOrders; +/** Order price. Not used for market orders. Required for limit types. */ ⋮---- -/** Trailing open order item from getCoinMPerpTrailingOpenOrders */ -export interface FuturesCmPerpTrailingOpenOrder { - symbol: string; - contract_code: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - created_at: number; - order_price_type: string; - status: number; - callback_rate: number | string; - active_price: number | string; - is_active: number; -} +/** Order source. Default spot-api */ ⋮---- -/** Trailing open orders response from getCoinMPerpTrailingOpenOrders */ -export type FuturesCmPerpTrailingOpenOrders = - FuturesPaginatedOrders; +/** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ ⋮---- -/** Trailing history order item from getCoinMPerpTrailingHistoryOrders */ -export interface FuturesCmPerpTrailingHisOrder { - symbol: string; - contract_code: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - created_at: number; - update_time: number; - order_price_type: string; - status: number; - canceled_at: number | null; - fail_code: number | null; - fail_reason: string | null; - callback_rate: number | string; - active_price: number | string; - is_active: number; - market_limit_price: number | string | null; - formula_price: number | string | null; - real_volume: number | string; - triggered_price: number | string | null; - relation_order_id: string; -} +/** 0=allow self-trade, 1=prevent. Default 0 */ ⋮---- -/** Trailing history orders response from getCoinMPerpTrailingHistoryOrders */ -export type FuturesCmPerpTrailingHisOrders = - FuturesPaginatedOrders; +/** Trigger price for stop-limit orders */ ⋮---- -/** Update leverage response from updateCoinMPerpLeverage */ -export interface FuturesCmPerpUpdateLeverage { - contract_code: string; - lever_rate: number; -} +/** Operator for stop price (lte, gte, etc) */ ⋮---- -/** Open order item from getCoinMPerpOpenOrders */ -export interface FuturesCmPerpOpenOrder { +/** RPI order - type must be buy-limit or sell-limit */ +⋮---- +/** Margin order with auto borrow/repay for POST /v1/order/auto/place. Sub-accounts not supported. */ +export interface SpotV1OrderAutoPlaceReq { symbol: string; - contract_code: string; - volume: number; - price: number; - order_price_type: string; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - client_order_id: number | string | null; - created_at: number; - trade_volume: number; - trade_turnover: number; - fee: number; - trade_avg_price: number | null; - margin_frozen: number; - profit: number; - status: number; - order_source: string; - fee_asset: string; - liquidation_type: string | null; - canceled_at: number | null; - is_tpsl: number; - update_time: number; - real_profit: number; - canceled_source?: string; - self_match_prevent?: number; + 'account-id': string | number; + type: SpotOrderType; + /** 1: automatic loan, 2: automatic repayment */ + 'trade-purpose': '1' | '2'; + source: SpotOrderSource; + /** Order volume. For market buy = order value. Use amount or market-amount, not both. */ + amount?: string; + /** Market buy = order volume, market sell = order amount. Use amount or market-amount, not both. */ + 'market-amount'?: string; + /** Amount/quantity to borrow when trade-purpose=1. Max 3 decimal precision. */ + 'borrow-amount'?: string; + price?: string; + /** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ + 'client-order-id'?: string; + 'stop-price'?: string; + operator?: string; } ⋮---- -/** Open orders response from getCoinMPerpOpenOrders */ -export type FuturesCmPerpOpenOrders = - FuturesPaginatedOrders & { - canceled_source?: string; - self_match_prevent?: number; - }; +/** 1: automatic loan, 2: automatic repayment */ ⋮---- -/** Item from GET /swap-api/v1/swap_query_elements data[] */ -export interface FuturesCmPerpContractElements { - contract_code: string; - instrument_index_code: string; - real_time_settlement: number; - transfer_profit_ratio: number; - min_level: string; - max_level: string; - open_order_limit: string; - offset_order_limit: string; - long_position_limit: string; - short_position_limit: string; - price_tick: string; - instrument_value: string; - settle_period: number; - funding_rate_cap: string; - funding_rate_floor: string; - trigger_protect?: number; - hig_normal_limit: string; - min_normal_limit: string; - hig_open_limit: string; - min_open_limit: string; - hig_trade_limit: string; - min_trade_limit: string; - contract_infos: FuturesCmPerpContractElementsContractInfo[]; -} +/** Order volume. For market buy = order value. Use amount or market-amount, not both. */ ⋮---- -/** List item from contract_elite_account_ratio */ -export interface FuturesCmDeliveryEliteAccountRatioItem { - buy_ratio: number; - sell_ratio: number; - locked_ratio: number; - ts: number; -} +/** Market buy = order volume, market sell = order amount. Use amount or market-amount, not both. */ ⋮---- -/** GET /api/v1/contract_elite_account_ratio */ -export interface FuturesCmDeliveryEliteAccountRatio { - symbol: string; - list: FuturesCmDeliveryEliteAccountRatioItem[]; -} +/** Amount/quantity to borrow when trade-purpose=1. Max 3 decimal precision. */ ⋮---- -/** List item from contract_elite_position_ratio */ -export interface FuturesCmDeliveryElitePositionRatioItem { - buy_ratio: number; - sell_ratio: number; - ts: number; -} +/** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ ⋮---- -/** GET /api/v1/contract_elite_position_ratio */ -export interface FuturesCmDeliveryElitePositionRatio { - symbol: string; - list: FuturesCmDeliveryElitePositionRatioItem[]; +/** Req for POST /v1/order/orders/batchCancelOpenOrders */ +export interface SpotV1OrderBatchCancelOpenOrdersReq { + /** Account ID from GET /v1/account/accounts */ + 'account-id'?: string; + /** Comma-separated symbols (max 10). Default all */ + symbol?: string; + /** Order types comma-separated */ + types?: string; + /** Filter: buy, sell */ + side?: 'buy' | 'sell'; + /** Orders to cancel [1-100]. Default 100 */ + size?: number; } ⋮---- -/** BBO tick from GET /market/bbo. ask/bid: [price, qty]. Uses symbol (e.g. BTC_CW). */ -export interface FuturesCmDeliveryMarketBbo { - symbol: string; - mrid: number; - ask: [number, number]; - bid: [number, number]; - ts: number; -} +/** Account ID from GET /v1/account/accounts */ ⋮---- -/** Kline item from GET /market/history/kline */ -export interface FuturesCmDeliveryKline { - id: number; - vol: number; - count: number; - open: number; - close: number; - low: number; - high: number; - amount: number; -} +/** Comma-separated symbols (max 10). Default all */ ⋮---- -/** Mark price kline item from GET /index/market/history/mark_price_kline */ -export interface FuturesCmDeliveryMarkPriceKline { - id: number; - vol: string; - count: string; - open: string; - close: string; - low: string; - high: string; - amount: string; -} +/** Order types comma-separated */ ⋮---- -/** Ticker from GET /market/detail/merged. 24h summary + best bid/ask. Payload in "tick". Alias: getCoinMDeliveryTicker/getCoinMDeliveryTickers. */ -export interface FuturesCmDeliveryTicker { - id: number; - ts: number; - vol: string; - count: number; - open: string; - close: string; - low: string; - high: string; - amount: string; - ask: [number, number]; - bid: [number, number]; -} +/** Filter: buy, sell */ ⋮---- -export interface FuturesCmDeliveryTrade { - id: number; - price: string; - amount: string; - direction: string; - ts: number; - quantity: string; +/** Orders to cancel [1-100]. Default 100 */ +⋮---- +/** Req for GET /v1/order/orders (search past orders) */ +export interface SpotGetOrderHistoryReq { + /** Trading symbol (required) */ symbol: string; - /** Whether the trade is an RPI trade */ - 'is-rpi-trade'?: boolean | number | string; + /** Order types comma-separated */ + types?: string; + /** Start time (unix ms). Max 48h window. */ + 'start-time'?: number; + /** End time (unix ms). Max 48h window, within 180 days. */ + 'end-time'?: number; + /** States: filled, partial-canceled, canceled (comma-separated, required) */ + states: string; + /** Start order ID for pagination */ + from?: string; + /** next=desc, prev=asc. Default both */ + direct?: 'next' | 'prev'; + /** Orders to return [1-100]. Default 100 */ + size?: number; } ⋮---- -/** Whether the trade is an RPI trade */ +/** Trading symbol (required) */ ⋮---- -/** Last trade tick from GET /market/trade. Payload in "tick". */ -export interface FuturesCmDeliveryLastTrade { - id: number; - ts: number; - data: FuturesCmDeliveryTrade[]; -} +/** Order types comma-separated */ ⋮---- -/** Trade item from GET /market/history/trade data array. No symbol in response. */ -export interface FuturesCmDeliveryTradeHistoryItem { - id: number; - price: string | number; - amount: string | number; - direction: string; - ts: number; - quantity?: string | number; - /** Whether the trade is an RPI trade */ - 'is-rpi-trade'?: boolean | number | string; -} +/** Start time (unix ms). Max 48h window. */ ⋮---- -/** Whether the trade is an RPI trade */ +/** End time (unix ms). Max 48h window, within 180 days. */ ⋮---- -/** Trade history from GET /market/history/trade. Each group has trades by timestamp. Payload in "data". Alias: getCoinMDeliveryTradeHistory. */ -export interface FuturesCmDeliveryTradeHistory { - id: number; - ts: number; - data: FuturesCmDeliveryTradeHistoryItem[]; -} +/** States: filled, partial-canceled, canceled (comma-separated, required) */ ⋮---- -/** Index kline item from GET /index/market/history/index. vol/count/amount typically 0. Alias: getCoinMDeliveryIndexKlines. */ -export interface FuturesCmDeliveryIndexKline { - id: number; - vol: number; - count: number; - open: number; - close: number; - low: number; - high: number; - amount: number; -} +/** Start order ID for pagination */ ⋮---- -/** Account info from POST /api/v1/contract_account_info. Per-symbol margin account. */ -export interface FuturesCmDeliveryAccountInfo { - symbol: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real: number; - profit_unreal: number; - risk_rate: number | null; - new_risk_rate: string; - trade_partition: string; - liquidation_price: number | null; - withdraw_available: number; - lever_rate: number; - adjust_factor: number; - margin_static: number; -} +/** next=desc, prev=asc. Default both */ ⋮---- -/** Sub-account list item from POST /api/v1/contract_sub_account_list. Per-symbol margin info. */ -export interface FuturesCmDeliverySubAccountListItem { - symbol: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | string | null; - query_id: number; -} +/** Orders to return [1-100]. Default 100 */ ⋮---- -/** All sub-account from POST /api/v1/contract_sub_account_list. Alias: getCoinMDeliveryAllSubAccounts. */ -export interface FuturesCmDeliveryAllSubAccount { - sub_uid: number; - list: FuturesCmDeliverySubAccountListItem[]; +/** Req for GET /v1/order/history (48h historical orders) */ +export interface SpotGetOrderHistory48hReq { + /** Trading symbol */ + symbol?: string; + /** Start time (unix ms). Default 48h ago */ + 'start-time'?: number; + /** End time (unix ms). Default now */ + 'end-time'?: number; + /** prev=asc, next=desc. Default next */ + direct?: 'prev' | 'next'; + /** Items per response [10-1000]. Default 100 */ + size?: number; + /** created-at: order creation time. updated-at: last update time. */ + 'sort-by'?: 'created-at' | 'updated-at'; } ⋮---- -/** Account info item from POST /api/v1/contract_sub_account_info_list sub_list[].account_info_list */ -export interface FuturesCmDeliverySubAccountInfoListItem { - symbol: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | string | null; -} +/** Trading symbol */ ⋮---- -/** Sub-list item from POST /api/v1/contract_sub_account_info_list */ -export interface FuturesCmDeliverySubAccountInfoListSub { - sub_uid: number; - account_info_list: FuturesCmDeliverySubAccountInfoListItem[]; -} +/** Start time (unix ms). Default 48h ago */ ⋮---- -/** Sub-accounts assets from POST /api/v1/contract_sub_account_info_list. Alias: getCoinMDeliverySubAccounts. */ -export type FuturesCmDeliverySubAccountsAssets = - FuturesPaginatedSubList; +/** End time (unix ms). Default now */ ⋮---- -/** Sub-account assets from POST /api/v1/contract_sub_account_info. Alias: getCoinMDeliverySubAccountAssets. */ -export interface FuturesCmDeliverySubAccountAssets { - symbol: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real: number; - profit_unreal: number; - risk_rate: number | string | null; - liquidation_price: number | null; - withdraw_available: number; - lever_rate: number; - adjust_factor: number; - margin_static: number; - new_risk_rate: string; - trade_partition: string; -} +/** prev=asc, next=desc. Default next */ ⋮---- -/** Position info from POST /api/v1/contract_sub_position_info. Single sub-account positions, data array element. */ -export interface FuturesCmDeliverySubPositionInfo { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - adl_risk_percent?: string | number; - liq_px: string; - new_risk_rate: string; - trade_partition: string; -} +/** Items per response [10-1000]. Default 100 */ ⋮---- -/** Position info from POST /api/v1/contract_position_info. */ -export interface FuturesCmDeliveryPositionInfo { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - adl_risk_percent?: string | number; - liq_px: string; - new_risk_rate: string; - trade_partition: string; -} +/** created-at: order creation time. updated-at: last update time. */ ⋮---- -/** Liquidation order from GET /api/v3/contract_liquidation_orders */ -export interface FuturesCmDeliveryLiquidationOrder { - query_id: number; - symbol: string; - contract_code: string; - direction: string; - offset: string; - volume: number; - amount: number; - price: number; - created_at: number; +/** Req for GET /v1/order/matchresults (search match results) */ +export interface SpotGetMatchResultsReq { + /** Trading symbol */ + symbol?: string; + /** Order types comma-separated */ + types?: string; + /** Start time (unix ms). 48h window, 120 days range */ + 'start-time'?: number; + /** End time (unix ms). 48h window */ + 'end-time'?: number; + /** Internal id to begin pagination (use last id of prev page) */ + from?: string; + /** next or prev. Default next */ + direct?: 'next' | 'prev'; + /** Items to return [1-500]. Default 100 */ + size?: number; } ⋮---- -/** Settlement record list item from contract_settlement_records */ -export interface FuturesCmDeliverySettlementRecordItem { - contract_code: string; - settlement_price: number; - settlement_type: string; -} +/** Trading symbol */ ⋮---- -/** Settlement record from GET /api/v1/contract_settlement_records */ -export interface FuturesCmDeliverySettlementRecord { - symbol: string; - settlement_time: number; - clawback_ratio: number; - list: FuturesCmDeliverySettlementRecordItem[]; -} +/** Order types comma-separated */ ⋮---- -/** GET /api/v1/contract_settlement_records */ -export interface FuturesCmDeliverySettlementRecords { - total_page: number; - current_page: number; - total_size: number; - settlement_record: FuturesCmDeliverySettlementRecord[]; -} +/** Start time (unix ms). 48h window, 120 days range */ ⋮---- -/** Financial record from POST /api/v3/contract_financial_record and contract_financial_record_exact */ -export interface FuturesCmDeliveryFinancialRecord { - query_id?: number; - id: number; - ts: number; - symbol: string; - contract_code: string; - type: number; - amount: number | string; -} +/** End time (unix ms). 48h window */ ⋮---- -/** Position in user settlement record from POST /api/v1/contract_user_settlement_records */ -export interface FuturesCmDeliveryUserSettlementRecordPosition { - symbol: string; - contract_code: string; - direction: string; - volume: number; - cost_open: number; - cost_hold_pre: number; - cost_hold: number; - settlement_profit_unreal: number; - settlement_price: number; - settlement_type: string; -} +/** Internal id to begin pagination (use last id of prev page) */ ⋮---- -/** User settlement record from POST /api/v1/contract_user_settlement_records */ -export interface FuturesCmDeliveryUserSettlementRecord { - symbol: string; - margin_balance_init: number; - margin_balance: number; - settlement_profit_real: number; - settlement_time: number; - clawback: number; - delivery_fee: number; - offset_profitloss: number; - fee: number; - fee_asset: string; - positions: FuturesCmDeliveryUserSettlementRecordPosition[]; -} +/** next or prev. Default next */ ⋮---- -/** Response from POST /api/v1/contract_user_settlement_records */ -export interface FuturesCmDeliveryUserSettlementRecords { - total_page: number; - current_page: number; - total_size: number; - settlement_records: FuturesCmDeliveryUserSettlementRecord[]; +/** Items to return [1-500]. Default 100 */ +⋮---- +/** Req for GET /v1/order/openOrders */ +export interface SpotGetOpenOrdersReq { + /** Account ID from GET /v1/account/accounts */ + 'account-id'?: string; + /** Trading symbol (e.g. ethusdt) */ + symbol?: string; + /** Filter: buy, sell */ + side?: 'buy' | 'sell'; + /** Order types comma-separated */ + types?: string; + /** Start order ID for pagination */ + from?: string; + /** prev=asc from start, next=desc from start */ + direct?: 'prev' | 'next'; + /** Orders to return [1-500]. Default 100 */ + size?: number; } ⋮---- -/** Order limit type from POST /api/v1/contract_order_limit list[].types */ -export interface FuturesCmDeliveryOrderLimitType { - contract_type: string; - open_limit: number; - close_limit: number; -} +/** Account ID from GET /v1/account/accounts */ ⋮---- -/** Order limit list item from POST /api/v1/contract_order_limit */ -export interface FuturesCmDeliveryOrderLimitListItem { - symbol: string; - types: FuturesCmDeliveryOrderLimitType[]; -} +/** Trading symbol (e.g. ethusdt) */ ⋮---- -/** Response from POST /api/v1/contract_order_limit */ -export interface FuturesCmDeliveryOrderLimit { - order_price_type: string; - list: FuturesCmDeliveryOrderLimitListItem[]; -} +/** Filter: buy, sell */ ⋮---- -/** Response from POST /api/v1/contract_switch_lever_rate */ -export interface FuturesCmDeliverySwitchLeverRate { - symbol: string; - lever_rate: number; -} +/** Order types comma-separated */ ⋮---- -/** Open order item from POST /api/v1/contract_openorders data.orders[] */ -export interface FuturesCmDeliveryOpenOrder { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - price: number; - order_price_type: string; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - client_order_id: number | string | null; - created_at: number; - trade_volume: number; - trade_turnover: number; - fee: number; - trade_avg_price: number | null; - margin_frozen: number; - profit: number; - status: number; - order_source: string; - fee_asset: string; - is_tpsl: number; - update_time: number; - real_profit: number; - liquidation_type?: string | null; - canceled_at?: number | null; -} +/** Start order ID for pagination */ ⋮---- -/** Response from POST /api/v1/contract_openorders */ -export type FuturesCmDeliveryOpenOrders = - FuturesPaginatedOrders & { - self_match_prevent?: number; - canceled_source?: string; - }; +/** prev=asc from start, next=desc from start */ ⋮---- -/** Trigger open order item from POST /api/v1/contract_trigger_openorders data.orders[] */ -export interface FuturesCmDeliveryTriggerOpenOrder { - symbol: string; - contract_code: string; - contract_type: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_price: number; - order_price: number; - created_at: number; - order_price_type: string; - status: number; -} +/** Orders to return [1-500]. Default 100 */ ⋮---- -/** Response from POST /api/v1/contract_trigger_openorders */ -export type FuturesCmDeliveryTriggerOpenOrders = - FuturesPaginatedOrders; +/** + * Conditional Order + */ ⋮---- -/** Trigger history order item from POST /api/v1/contract_trigger_hisorders data.orders[] */ -export interface FuturesCmDeliveryTriggerHistoryOrder { - symbol: string; - contract_code: string; - contract_type: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - relation_order_id: string; - order_price_type: string; - status: number; - order_source: string; - trigger_price: number; - triggered_price: number; - order_price: number; - created_at: number; - triggered_at: number; - order_insert_at: number; - canceled_at: number; - fail_code: number | null; - fail_reason: string | null; - update_time?: number; +/** Req for POST /v2/algo-orders (Place a conditional order). Conditional orders only via this endpoint, not Trading section. */ +export interface SpotV2AlgoOrdersPlaceReq { + /** Account ID. Spot, margin, super-margin. C2C margin not supported. */ + accountId?: number; + /** Trading symbol */ + symbol?: string; + /** Order price (invalid for market order) */ + orderPrice?: string; + /** Order side: buy, sell */ + orderSide?: 'buy' | 'sell'; + /** Order size (invalid for market buy order) */ + orderSize?: string; + /** Order value (only valid for market buy order) */ + orderValue?: string; + /** Time in force: gtc, boc, ioc, fok. gtc=good till cancel, boc=book or cancel, ioc=immediate or cancel, fok=fill or kill. gtc for limit; ioc for market. */ + timeInForce?: 'gtc' | 'boc' | 'ioc' | 'fok'; + /** Order type: limit, market */ + orderType?: 'limit' | 'market'; + /** Client order ID (max 64 chars). Must be unique within 24h for same user. */ + clientOrderId?: string; + /** Stop price */ + stopPrice?: string; + /** Trailing rate [0.001-0.050]. Only valid for trailing stop order */ + trailingRate?: string; } ⋮---- -/** Response from POST /api/v1/contract_trigger_hisorders */ -export type FuturesCmDeliveryTriggerHistoryOrders = - FuturesPaginatedOrders; +/** Account ID. Spot, margin, super-margin. C2C margin not supported. */ ⋮---- -/** TPSL open order item from POST /api/v1/contract_tpsl_openorders data.orders[] */ -export interface FuturesCmDeliveryTpslOpenOrder { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - order_type: number; - tpsl_order_type: 'tp' | 'sl'; - direction: string; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_type: string; - trigger_price: number; - order_price: number; - created_at: number; - order_price_type: string; - status: number; - source_order_id: string | null; - relation_tpsl_order_id: string; - price_protect?: boolean; -} +/** Trading symbol */ ⋮---- -/** Response from POST /api/v1/contract_tpsl_openorders */ -export type FuturesCmDeliveryTpslOpenOrders = - FuturesPaginatedOrders; +/** Order price (invalid for market order) */ ⋮---- -/** TPSL history order item from POST /api/v1/contract_tpsl_hisorders data.orders[] */ -export interface FuturesCmDeliveryTpslHistoryOrder { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - order_type: number; - tpsl_order_type: 'tp' | 'sl'; - direction: string; - order_id: number | string; - order_id_str: string; - order_source: string; - trigger_type: string; - trigger_price: number; - order_price: number; - created_at: number; - order_price_type: string; - status: number; - source_order_id: string | null; - relation_tpsl_order_id: string; - canceled_at: number; - fail_code: number | null; - fail_reason: string | null; - triggered_price: number | null; - relation_order_id: string; - update_time: number; - price_protect?: boolean; -} +/** Order side: buy, sell */ ⋮---- -/** Response from POST /api/v1/contract_tpsl_hisorders */ -export type FuturesCmDeliveryTpslHistoryOrders = - FuturesPaginatedOrders; +/** Order size (invalid for market buy order) */ ⋮---- -/** Trailing open order item from POST /api/v1/contract_track_openorders data.orders[] */ -export interface FuturesCmDeliveryTrailingOpenOrder { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - created_at: number; - order_price_type: string; - status: number; - callback_rate: number; - active_price: number; - is_active: number; +/** Order value (only valid for market buy order) */ +⋮---- +/** Time in force: gtc, boc, ioc, fok. gtc=good till cancel, boc=book or cancel, ioc=immediate or cancel, fok=fill or kill. gtc for limit; ioc for market. */ +⋮---- +/** Order type: limit, market */ +⋮---- +/** Client order ID (max 64 chars). Must be unique within 24h for same user. */ +⋮---- +/** Stop price */ +⋮---- +/** Trailing rate [0.001-0.050]. Only valid for trailing stop order */ +⋮---- +export interface SpotV2AlgoOrdersOpeningReq { + /** Account ID */ + accountId?: number; + /** Trading symbol */ + symbol?: string; + /** Order side: buy, sell */ + orderSide?: 'buy' | 'sell'; + /** Order type: limit, market */ + orderType?: 'limit' | 'market'; + /** Sort: asc, desc. Default desc */ + sort?: 'asc' | 'desc'; + /** Max items [1-500]. Default 100 */ + limit?: number; + /** First record ID for next-page pagination */ + fromId?: number; } ⋮---- -/** Response from POST /api/v1/contract_track_openorders */ -export type FuturesCmDeliveryTrailingOpenOrders = - FuturesPaginatedOrders; +/** Account ID */ ⋮---- -/** Trailing history order item from POST /api/v1/contract_track_hisorders data.orders[] */ -export interface FuturesCmDeliveryTrailingHistoryOrder { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; - lever_rate: number; - order_id: number | string; - order_id_str: string; - order_source: string; - created_at: number; - update_time: number; - order_price_type: string; - status: number; - canceled_at: number; - fail_code: number | null; - fail_reason: string | null; - callback_rate: number; - active_price: number; - is_active: number; - market_limit_price: number | null; - formula_price: number | null; - real_volume: number; - triggered_price: number | null; - relation_order_id: string; -} +/** Trading symbol */ ⋮---- -/** Response from POST /api/v1/contract_track_hisorders */ -export type FuturesCmDeliveryTrailingHistoryOrders = - FuturesPaginatedOrders; +/** Order side: buy, sell */ ⋮---- -/** Fee from POST /api/v1/contract_fee */ -export interface FuturesCmDeliveryFee { - symbol: string; - open_maker_fee: string; - open_taker_fee: string; - close_maker_fee: string; - close_taker_fee: string; - delivery_fee: string; - fee_asset: string; -} +/** Order type: limit, market */ ⋮---- -/** Transfer limit from POST /api/v1/contract_transfer_limit */ -export interface FuturesCmDeliveryTransferLimit { - symbol: string; - transfer_in_max_each: number; - transfer_in_min_each: number; - transfer_out_max_each: number; - transfer_out_min_each: number; - transfer_in_max_daily: number; - transfer_out_max_daily: number; - net_transfer_in_max_daily: number; - net_transfer_out_max_daily: number; -} +/** Sort: asc, desc. Default desc */ ⋮---- -/** Position limit list item from POST /api/v1/contract_position_limit data[].list */ -export interface FuturesCmDeliveryPositionLimitListItem { - contract_type: string; - buy_limit: number; - sell_limit: number; -} +/** Max items [1-500]. Default 100 */ ⋮---- -/** Position limit from POST /api/v1/contract_position_limit */ -export interface FuturesCmDeliveryPositionLimit { - symbol: string; - list: FuturesCmDeliveryPositionLimitListItem[]; -} +/** First record ID for next-page pagination */ ⋮---- -/** Position in asset_position_info from POST /api/v1/contract_account_position_info */ -export interface FuturesCmDeliveryAssetPositionInfoPosition { - symbol: string; - contract_code: string; - contract_type: string; - volume: number; - available: number; - frozen: number; - cost_open: number; - cost_hold: number; - profit_unreal: number; - profit_rate: number; - profit: number; - position_margin: number; - lever_rate: number; - direction: string; - last_price: number; - adl_risk_percent?: string | number; +/** Req for GET /v2/algo-orders/history (Query conditional order history). orderStatus: canceled, rejected, triggered. */ +export interface SpotV2AlgoOrdersHistoryReq { + /** Account ID */ + accountId?: number; + /** Trading symbol */ + symbol?: string; + /** Order side: buy, sell */ + orderSide?: 'buy' | 'sell'; + /** Order type: limit, market */ + orderType?: 'limit' | 'market'; + /** Order status: canceled, rejected, triggered */ + orderStatus?: 'canceled' | 'rejected' | 'triggered'; + /** Start time (unix ms) */ + startTime?: number; + /** End time (unix ms) */ + endTime?: number; + /** Sort: asc, desc */ + sort?: 'asc' | 'desc'; + /** Max items [1-500] */ + limit?: number; + /** First record ID for next-page pagination */ + fromId?: number; } ⋮---- -/** Asset + positions from POST /api/v1/contract_account_position_info. Alias: getCoinMDeliveryAssetPositionInfo. */ -export interface FuturesCmDeliveryAssetPositionInfo { - symbol: string; - margin_balance: number; - margin_position: number; - margin_frozen: number; - margin_available: number; - profit_real: number; - profit_unreal: number; - risk_rate: number | string | null; - withdraw_available: number; - liquidation_price: number | null; - lever_rate: number; - adjust_factor: number; - margin_static: number; - new_risk_rate: string; - trade_partition: string; - positions: FuturesCmDeliveryAssetPositionInfoPosition[]; -} +/** Account ID */ ⋮---- -/** API trading status item from GET /api/v1/contract_api_trading_status */ -export interface FuturesCmDeliveryApiTradingStatusCor { - orders_threshold: number; - orders: number; - invalid_cancel_orders: number; - cancel_ratio_threshold: number; - cancel_ratio: number; - is_trigger: number; - is_active: number; -} +/** Trading symbol */ ⋮---- -/** API trading status TDN from GET /api/v1/contract_api_trading_status */ -export interface FuturesCmDeliveryApiTradingStatusTdn { - disables_threshold: number; - disables: number; - is_trigger: number; - is_active: number; -} +/** Order side: buy, sell */ ⋮---- -/** API trading status from GET /api/v1/contract_api_trading_status */ -export interface FuturesCmDeliveryApiTradingStatus { - is_disable: number; - order_price_types: string; - disable_reason: string; - disable_interval: number; - recovery_time: number; - COR: FuturesCmDeliveryApiTradingStatusCor; - TDN: FuturesCmDeliveryApiTradingStatusTdn; -} +/** Order type: limit, market */ ⋮---- -/** Leverage rate from POST /api/v1/contract_available_level_rate. Alias: getCoinMDeliveryLeverageRate. */ -export interface FuturesCmDeliveryLeverageRate { - symbol: string; - available_level_rate: string; -} +/** Order status: canceled, rejected, triggered */ ⋮---- -/** GET /api/v1/contract_open_interest */ -export interface FuturesCmDeliveryContractOpenInterest { - symbol: string; - contract_type: string; - contract_code: string; - volume: number; - amount: number; - trade_amount: number; - trade_volume: number; - trade_turnover: number; -} +/** Start time (unix ms) */ ⋮---- -/** Delivery price from GET /api/v1/contract_delivery_price */ -export interface FuturesCmDeliveryDeliveryPrice { - delivery_price: number; -} +/** End time (unix ms) */ ⋮---- -/** Estimated settlement price list item */ -export interface FuturesCmDeliveryEstimatedSettlementPriceItem { - contract_type: string; - contract_code: string; - estimated_settlement_price: number | null; - settlement_type: string; -} +/** Sort: asc, desc */ ⋮---- -/** GET /api/v1/contract_estimated_settlement_price */ -export interface FuturesCmDeliveryEstimatedSettlementPrice { - symbol: string; - list: FuturesCmDeliveryEstimatedSettlementPriceItem[]; -} +/** Max items [1-500] */ ⋮---- -/** GET /api/v1/contract_api_state */ -export interface FuturesCmDeliveryApiState { - symbol: string; - open: number; - close: number; - cancel: number; - transfer_in: number; - transfer_out: number; - master_transfer_sub: number; - sub_transfer_master: number; -} +/** First record ID for next-page pagination */ ⋮---- -/** GET /api/v1/contract_contract_info */ -export interface FuturesCmDeliveryContractInfo { - symbol: string; - contract_code: string; - contract_type: string; - contract_size: number; - price_tick: number; - delivery_date: string; - create_date: string; - settlement_time: string; - delivery_time: string; - contract_status: number; - labels?: string[]; -} +/** + * Margin Loan (Cross/Isolated) + */ ⋮---- -/** GET /api/market/contract_constituents */ -export interface FuturesCmDeliveryConstituents { - symbol: string; - ts: number; - index_price: string; - components: FuturesIndexConstituentComponent[]; +/** Req for GET /v2/account/repayment (Repayment Record Reference). Sorted by repayTime. */ +export interface SpotRepaymentRecordReq { + /** Repayment transaction ID */ + repayId?: string; + /** Account ID. Default all accounts */ + accountId?: string; + /** Borrowing/lending currency. Default all currencies */ + currency?: string; + /** Start time (unix ms). Range: [(endTime – x D), endTime] */ + startTime?: number; + /** End time (unix ms). Range: [(now – y D), now]. Default now */ + endTime?: number; + /** Sort: asc, desc. Default desc */ + sort?: 'asc' | 'desc'; + /** Max items [1-100]. Default 50 */ + limit?: number; + /** Search ID for next-page pagination */ + fromId?: number; } ⋮---- -/** Contract info sub-item in query elements */ -export interface FuturesCmDeliveryQueryElementsContractInfo { - contract_code: string; - instrument_type: number | number[]; - create_date: string; - contract_status: number; - delivery_time: string; - delivery_date: string; -} +/** Repayment transaction ID */ ⋮---- -/** Order limit in query elements */ -export interface FuturesCmDeliveryQueryElementsOrderLimit { - instrument_type: number; - open: string; - close: string; - trigger_protect?: number; -} +/** Account ID. Default all accounts */ ⋮---- -/** GET /api/v1/contract_query_elements */ -export interface FuturesCmDeliveryQueryElements { - contract_code: string; - instrument_index_code: string; - real_time_settlement?: number; - price_tick?: string; - instrument_value?: string; - transfer_profit_ratio?: number; - min_level?: string; - max_level?: string; - open_order_limit?: string; - offset_order_limit?: string; - long_position_limit?: string; - short_position_limit?: string; - week_hig_normal_limit?: number; - week_min_normal_limit?: number; - week_hig_open_limit?: number; - week_min_open_limit?: number; - week_hig_trade_limit?: number; - week_min_trade_limit?: number; - biweek_hig_normal_limit?: number; - biweek_min_normal_limit?: number; - biweek_hig_open_limit?: number; - biweek_min_open_limit?: number; - biweek_hig_trade_limit?: number; - biweek_min_trade_limit?: number; - quarter_hig_normal_limit?: number; - quarter_min_normal_limit?: number; - quarter_hig_open_limit?: number; - quarter_min_open_limit?: number; - quarter_hig_trade_limit?: number; - quarter_min_trade_limit?: number; - biquarter_hig_normal_limit?: number; - biquarter_min_normal_limit?: number; - biquarter_hig_open_limit?: number; - biquarter_min_open_limit?: number; - biquarter_hig_trade_limit?: number; - biquarter_min_trade_limit?: number; - instrument_type?: number[]; - contract_infos?: FuturesCmDeliveryQueryElementsContractInfo[]; - order_limits?: FuturesCmDeliveryQueryElementsOrderLimit[]; -} +/** Borrowing/lending currency. Default all currencies */ ⋮---- -/** - * Copy Trading - */ +/** Start time (unix ms). Range: [(endTime – x D), endTime] */ ⋮---- -/** Lead trading instrument from GET /api/v6/copyTrading/trader/instruments */ -export interface FuturesCopyTraderInstrument { - instId: string; - instType: string; -} +/** End time (unix ms). Range: [(now – y D), now]. Default now */ ⋮---- -/** Profit detail item in trader statistics */ -export interface FuturesCopyTraderProfitDetail { - pnlRate: string; - pnl: string; - ts: string; -} +/** Sort: asc, desc. Default desc */ ⋮---- -/** Trader lead trading metrics from GET /api/v6/copyTrading/trader/statistics */ -export interface FuturesCopyTraderStatistics { - instType: string; - totalFollowerNum: string; - curFollowerNum: string; - totalPnl: string; - followerTotalPnl: string; - winRate: string; - winNum: string; - lossNum: string; - profitDetails24h?: FuturesCopyTraderProfitDetail[]; - profitDetails90d: FuturesCopyTraderProfitDetail[]; -} +/** Max items [1-100]. Default 50 */ ⋮---- -/** Profit sharing history item from GET /api/v6/copyTrading/trader/profit-sharing-history */ -export interface FuturesCopyTraderProfitSharingHistory { - id: string; - instType: string; - followerName: string; - ccy: string; - profitSharingAmt: string; - ts: string; -} +/** Search ID for next-page pagination */ ⋮---- -/** Profit sharing summary from GET /api/v6/copyTrading/trader/profit-sharing-history-summary or unrealized-profit-sharing-summary */ -export interface FuturesCopyTraderProfitSharingSummary { - instType: string; - ccy: string; - totalAmt: string; +/** Req for POST /v2/account/repayment (Repay Margin Loan). Loan interest paid first if no transactId. */ +export interface SpotMarginRepaymentReq { + /** Repayment account ID */ + accountId?: string; + /** Repayment currency */ + currency?: string; + /** Repayment amount */ + amount?: string; + /** Loan transaction ID. When specified, repay that loan; otherwise interest paid first. */ + transactId?: string; } ⋮---- -/** Follower info from GET /api/v6/copyTrading/trader/followers */ -export interface FuturesCopyTraderFollower { - id: string; - instType: string; - followerAvatarLink: string; - followerName: string; - followerUid: string; - followTime: string; - followerAssetAmt: string; - followerProfitSharingAmt: string; - followerTradeAmt: string; - totalProfitSharingAmt: string; -} +/** Repayment account ID */ ⋮---- -/** Remove follower result item from POST /api/v6/copyTrading/trader/follower */ -export interface FuturesCopyTraderFollowerRemoveResult { - followerUid: string; - scode: string; - smsg: string; -} +/** Repayment currency */ ⋮---- -/** Lead trading config from GET /api/v6/copyTrading/trader/config or POST follower-settings */ -export interface FuturesCopyTraderConfig { - instType: string; - enable: boolean; - profitSharingRatio: string; - maxFollowers: string; -} +/** Repayment amount */ ⋮---- -/** Lead trading API key from POST /api/v6/copyTrading/trader/apikey */ -export interface FuturesCopyTraderApikey { - label: string; - accessKey: string; - secretKey: string; - perm: string[]; - ts: string; -} - -================ -File: src/types/response/spot.types.ts -================ -/** - * Reference Data - */ +/** Loan transaction ID. When specified, repay that loan; otherwise interest paid first. */ ⋮---- -/** Status page response from status.huobigroup.com */ -export interface SpotSystemStatusPage { - page: { - id: string; - name: string; - url: string; - time_zone: string; - updated_at: string; - }; - components: { - id: string; - name: string; - status: string; - created_at: string; - updated_at: string; - [key: string]: unknown; - }[]; - incidents: - | { - id: string; - name: string; - status: string; - created_at: string; - updated_at: string; - [key: string]: unknown; - }[] - | null; - scheduled_maintenances: - | { - id: string; - name: string; - status: string; - created_at: string; - updated_at: string; - scheduled_for: string; - scheduled_until: string; - [key: string]: unknown; - }[] - | null; - status: { - indicator: 'none' | 'minor' | 'major' | 'critical' | 'maintenance'; - description: string; - }; +/** Req for POST /v1/dw/transfer-in/margin (Transfer Spot -> Isolated Margin). */ +export interface SpotMarginTransferInIsolatedReq { + /** Trading symbol (e.g. btcusdt, ethusdt) */ + symbol?: string; + /** Currency to transfer */ + currency?: string; + /** Amount to transfer */ + amount?: string; } ⋮---- -/** Market status: 1=normal, 2=halted, 3=cancel-only */ -export type SpotMarketStatus = 1 | 2 | 3; +/** Trading symbol (e.g. btcusdt, ethusdt) */ ⋮---- -/** Halt reason: 2=emergency-maintenance, 3=scheduled-maintenance */ -export type SpotHaltReason = 2 | 3; +/** Currency to transfer */ ⋮---- -export interface SpotMarketStatusData { - marketStatus: SpotMarketStatus; - haltStartTime?: number; - haltEndTime?: number; - haltReason?: SpotHaltReason; - affectedSymbols?: string; +/** Amount to transfer */ +⋮---- +/** Req for POST /v1/dw/transfer-out/margin (Transfer Isolated Margin -> Spot). */ +export interface SpotMarginTransferOutIsolatedReq { + /** Trading symbol (e.g. btcusdt, ethusdt) */ + symbol?: string; + /** Currency to transfer */ + currency?: string; + /** Amount to transfer */ + amount?: string; } ⋮---- -export interface SpotMarketStatusResponse { - code: number; - message: string; - data: SpotMarketStatusData; +/** Trading symbol (e.g. btcusdt, ethusdt) */ +⋮---- +/** Currency to transfer */ +⋮---- +/** Amount to transfer */ +⋮---- +/** Req for POST /v1/margin/orders (Request a Margin Loan, Isolated) */ +export interface SpotMarginLoanOrderReq { + /** Trading symbol to borrow margin (e.g. btcusdt, ethusdt) */ + symbol?: string; + /** Currency to borrow */ + currency?: string; + /** Amount to borrow (max 3 decimal places) */ + amount?: string; } ⋮---- -/** Trading symbol from /v2/settings/common/symbols */ -export interface SpotTradingSymbol { - sc: string; - si?: string; - scr?: string; - dn: string; - bc: string; - bcdn: string; - qc: string; - qcdn: string; - state: string; - whe?: boolean; - cd?: boolean; - te?: boolean; - toa?: number; - sp?: string; - w?: number; - ttp?: number; - tap?: number; - tpp?: number; - fp?: number; - suspend_desc?: string; - transfer_board_desc?: string; - tags?: string; - lr?: number | null; - smlr?: number | null; - flr?: string | null; - wr?: string | null; - d?: number | null; - elr?: string | null; - /** Whether the symbol supports RPI trading */ - enable_rpi?: boolean | number | string; - p?: { id?: number; name?: string; weight?: number }[]; -} +/** Trading symbol to borrow margin (e.g. btcusdt, ethusdt) */ ⋮---- -/** Whether the symbol supports RPI trading */ +/** Currency to borrow */ ⋮---- -export interface SpotCurrency { - cc: string; - dn: string; - fn: string; - at?: number; - wp?: number; - ft?: string; - dma?: string; - wma?: string; - sp?: string; - w?: number; - qc?: boolean; - state?: string; - v?: boolean; - whe?: boolean; - cd?: boolean; - de?: boolean; - wed?: boolean; - cawt?: boolean; - fc?: number; - sc?: number; - swd?: string | null; - wd?: string | null; - sdd?: string | null; - dd?: string | null; - svd?: string | null; - tags?: string; -} +/** Amount to borrow (max 3 decimal places) */ ⋮---- -/** Currency settings item from /v1/settings/common/currencys */ -export interface SpotV1CurrencySettings { - name: string; - dn?: string; - vat?: number; - det?: number; - wet?: number; - wp?: number; - ct?: string; - cp?: string; - ss?: string[]; - oe?: number; - dma?: string; - wma?: string; - sp?: string; - w?: number | string; - qc?: boolean; - state?: string; - v?: boolean; - whe?: boolean; - cd?: boolean; - de?: boolean; - we?: boolean; - cawt?: boolean; - cao?: boolean; - fc?: number; - sc?: number; - swd?: string | null; - wd?: string | null; - sdd?: string | null; - dd?: string | null; - svd?: string | null; - tags?: string; - fn?: string; - bc?: string; - iqc?: boolean; +/** Req for GET /v1/margin/loan-orders (Search Past Margin Orders, Isolated) */ +export interface SpotMarginLoanOrdersReq { + /** Trading symbol (e.g. btcusdt) */ + symbol?: string; + /** Order states comma-separated: created, accrual, cleared, invalid, failed */ + states?: string; + /** Start date yyyy-mm-dd. Default -61d */ + 'start-date'?: string; + /** End date yyyy-mm-dd. Default today */ + 'end-date'?: string; + /** Search order id to begin with */ + from?: string; + /** Search direction when from is used: next, prev */ + direct?: 'next' | 'prev'; + /** Orders to return [1-100]. Default 100 */ + size?: number; + /** Sub user ID (required when parent queries sub user's orders) */ + 'sub-uid'?: number; } ⋮---- -/** Symbol settings item from /v1/settings/common/symbols */ -export interface SpotV1SymbolSettings { - symbol: string; - sn?: string; - bc?: string; - qc?: string; - state?: string; - ve?: boolean; - we?: boolean; - dl?: boolean; - cd?: boolean; - te?: boolean; - ce?: boolean; - tet?: number; - toa?: number; - tca?: number; - voa?: number; - vca?: number; - sp?: string; - tm?: string; - w?: number | string; - ttp?: number; - tap?: number; - tpp?: number; - fp?: number; - tags?: string; - d?: unknown; - bcdn?: string; - qcdn?: string; - elr?: string | null; - castate?: string; - ca1oa?: number; - ca1ca?: number; - ca2oa?: number; - ca2ca?: number; -} +/** Trading symbol (e.g. btcusdt) */ ⋮---- -/** Market symbol settings item from /v1/settings/common/market-symbols */ -export interface SpotV1MarketSymbolSettings { - symbol: string; - bc?: string; - qc?: string; - state?: string; - sp?: string; - tags?: string; - lr?: number; - smlr?: number; - pp?: number; - ap?: number; - vp?: number; - /** @deprecated No longer valid. */ - minoa?: number | string; - maxoa?: number | string; - minov?: number | string; - /** @deprecated No longer valid. */ - lominoa?: number | string; - lomaxoa?: number | string; - lomaxba?: number | string; - lomaxsa?: number | string; - /** @deprecated No longer valid. */ - smminoa?: number | string; - smmaxoa?: number | string; - bmmaxov?: number | string; - blmlt?: number | string; - slmgt?: number | string; - msormlt?: number | string; - mbormlt?: number | string; - at?: string; - u?: string; - mfr?: number | string; - ct?: string; - rt?: string; - rthr?: number | string; - in?: number | string; - maxov?: number | string; - flr?: number | string; - castate?: string; -} +/** Order states comma-separated: created, accrual, cleared, invalid, failed */ ⋮---- -/** @deprecated No longer valid. */ +/** Start date yyyy-mm-dd. Default -61d */ ⋮---- -/** @deprecated No longer valid. */ +/** End date yyyy-mm-dd. Default today */ ⋮---- -/** @deprecated No longer valid. */ +/** Search order id to begin with */ ⋮---- -/** Chain info item from /v1/settings/common/chains */ -export interface SpotV1ChainInfo { - chain?: string; +/** Search direction when from is used: next, prev */ +⋮---- +/** Orders to return [1-100]. Default 100 */ +⋮---- +/** Sub user ID (required when parent queries sub user's orders) */ +⋮---- +/** Req for GET /v1/cross-margin/loan-orders (Search Past Margin Orders, Cross) */ +export interface SpotCrossMarginLoanOrdersReq { + /** Start date yyyy-mm-dd. Default -61d */ + 'start-date'?: string; + /** End date yyyy-mm-dd. Default today */ + 'end-date'?: string; + /** Currency filter */ currency?: string; - code?: string; - ct?: string; - ac?: string; - default?: number; - dma?: string; - wma?: string; - de?: boolean; - we?: boolean; - wp?: number; - ft?: string; - dn?: string; - fn?: string; - awt?: boolean; - adt?: boolean; - ao?: boolean; - fc?: number; - sc?: number; - v?: boolean; - sda?: string | null; - swa?: string | null; - 'deposit-desc'?: string; - 'deposit-tips-desc'?: string; - 'withdraw-desc'?: string; - 'suspend-deposit-desc'?: string; - 'suspend-withdraw-desc'?: string; - 'replace-chain-info-desc'?: string; - 'replace-chain-notification-desc'?: string; - 'replace-chain-popup-desc'?: string; - ca?: string; - cct?: number; - 'withdraw-tips-desc'?: string; - 'suspend-visible-desc'?: string; + /** Order state: created, accrual, cleared, invalid. Default all */ + state?: string; + /** Search order id to begin with. Default 0 */ + from?: string; + /** Search direction when from is used: next, prev. Default next */ + direct?: 'next' | 'prev'; + /** Orders to return [10-100]. Default 10 */ + size?: number; + /** Sub user UID */ + 'sub-uid'?: number; } ⋮---- -/** Chain reference from /v2/reference/currencies */ -export interface SpotV2ChainReference { +/** Start date yyyy-mm-dd. Default -61d */ +⋮---- +/** End date yyyy-mm-dd. Default today */ +⋮---- +/** Currency filter */ +⋮---- +/** Order state: created, accrual, cleared, invalid. Default all */ +⋮---- +/** Search order id to begin with. Default 0 */ +⋮---- +/** Search direction when from is used: next, prev. Default next */ +⋮---- +/** Orders to return [10-100]. Default 10 */ +⋮---- +/** Sub user UID */ +⋮---- +/** Req for POST /v1/dw/withdraw/api/create. Create withdraw request. */ +export interface SpotWithdrawCreateReq { + /** + * Destination address. + * On-chain: chain address. + * Internal: UID:1234567, PHONE:xxx, MAIL:xxx. + * Poloniex zero-fee cross-exchange: POLOUSER:{UUID} (linked on HTX first). + */ + address: string; + /** Crypto currency */ + currency: string; + /** Amount to withdraw */ + amount: string; + /** Fee. Use 0 for UID withdraw and Poloniex cross-exchange transfers. */ + fee?: number; + /** + * Chain. Required for multi-chain coins. + * For internal withdraw or Poloniex cross-exchange transfer, use t397342. + */ chain?: string; - displayName?: string; - baseChain?: string; - baseChainProtocol?: string; - isDynamic?: boolean; - numOfConfirmations?: number; - numOfFastConfirmations?: number; - minDepositAmt?: string; - depositStatus?: string; - minWithdrawAmt?: string; - maxWithdrawAmt?: string; - withdrawQuotaPerDay?: string; - withdrawQuotaPerYear?: string; - withdrawQuotaTotal?: string; - withdrawPrecision?: number; - withdrawFeeType?: string; - transactFeeWithdraw?: string; - minTransactFeeWithdraw?: string; - maxTransactFeeWithdraw?: string; - transactFeeRateWithdraw?: string; - withdrawStatus?: string; + /** Address tag. For UID withdraw, use recipient UID. */ + 'addr-tag'?: string; + /** Client order id for idempotency (max 32 char) */ + 'client-order-id'?: string; + /** Exchange VASP id from /v1/query/vasp-list */ + 'exchange-vasp'?: string; + /** Recipient name for Korean/English: "SURNAME##FIRSTNAME" */ + 'user-name-vasp'?: string; } ⋮---- -/** Fee rate from GET /v2/reference/transact-fee-rate */ -export interface SpotV2TransactFeeRate { - symbol: string; - makerFeeRate: string; - takerFeeRate: string; - actualMakerRate: string; - actualTakerRate: string; - /** RPI order fee rate */ - rpiFeeRate?: string; -} +/** + * Destination address. + * On-chain: chain address. + * Internal: UID:1234567, PHONE:xxx, MAIL:xxx. + * Poloniex zero-fee cross-exchange: POLOUSER:{UUID} (linked on HTX first). + */ ⋮---- -/** RPI order fee rate */ +/** Crypto currency */ ⋮---- -/** Currency reference item from /v2/reference/currencies */ -export interface SpotV2CurrencyReference { - currency?: string; - instStatus?: string; - chains?: SpotV2ChainReference[]; - /** Whether the currency supports direct transfers to Poloniex */ - externalTransferEnabled?: boolean | string | number; -} +/** Amount to withdraw */ ⋮---- -/** Whether the currency supports direct transfers to Poloniex */ +/** Fee. Use 0 for UID withdraw and Poloniex cross-exchange transfers. */ ⋮---- /** - * Market Data - */ + * Chain. Required for multi-chain coins. + * For internal withdraw or Poloniex cross-exchange transfer, use t397342. + */ ⋮---- -/** Kline/candlestick item from /market/history/kline */ -export interface SpotKline { - id: number; - open: number; - close: number; - low: number; - high: number; - amount: number; - vol: number; - count: number; -} +/** Address tag. For UID withdraw, use recipient UID. */ ⋮---- -/** Merged ticker from /market/detail/merged (payload is in "tick" not "data"). */ -export interface SpotMergedTicker { - id: number; - version?: number; - open: number; - close: number; - low: number; - high: number; - amount: number; - vol: number; - count: number; - /** [price, size] */ - bid: [number, number]; - /** [price, size] */ - ask: [number, number]; -} +/** Client order id for idempotency (max 32 char) */ ⋮---- -/** [price, size] */ +/** Exchange VASP id from /v1/query/vasp-list */ ⋮---- -/** [price, size] */ +/** Recipient name for Korean/English: "SURNAME##FIRSTNAME" */ ⋮---- -/** Ticker from /market/tickers */ -export interface SpotTicker { - symbol: string; - open: number; - high: number; - low: number; - close: number; - amount: number; - vol: number; - count: number; - bid: number; - bidSize: number; - ask: number; - askSize: number; +/** Req for GET /v1/query/deposit-withdraw. Search deposit/withdraw records. */ +export interface SpotDepositWithdrawQueryReq { + /** Crypto currency. Omit for all. */ + currency?: string; + /** deposit or withdraw */ + type: 'deposit' | 'withdraw'; + /** Transfer id to begin search */ + from?: string; + /** Items to return [1-50]. Default 50. */ + size?: string; + /** prev (asc) or next (desc). Default next. */ + direct?: 'prev' | 'next'; } ⋮---- -/** Depth tick from /market/depth and /market/fullMbp (payload is in "tick" not "data"). */ -export interface SpotDepth { - ts: number; - version: number; - bids: [number, number][]; - asks: [number, number][]; -} +/** Crypto currency. Omit for all. */ ⋮---- -/** 24h market summary tick from /market/detail (payload is in "tick" not "data"). */ -export interface SpotDetailTick { - id: number; - low: number; - high: number; - open: number; - close: number; - vol: number; - amount: number; - version: number; - count: number; -} +/** deposit or withdraw */ ⋮---- -/** Trade (shared by /market/trade and /market/history/trade) */ -export interface SpotTrade { - id: number; - ts: number; - 'trade-id': number; - amount: number; - price: number; - direction: string; -} +/** Transfer id to begin search */ ⋮---- -/** Trade tick from /market/trade (payload is in "tick" not "data"). */ -export interface SpotLastTrade { - id: number; - ts: number; - data: SpotTrade[]; -} +/** Items to return [1-50]. Default 50. */ ⋮---- -/** Timestamp group from /market/history/trade. Each element in data array. */ -export interface SpotTradeTimestampGroup { - id: number; - ts: number; - data: SpotTrade[]; +/** prev (asc) or next (desc). Default next. */ +⋮---- +/** Req for GET /v2/account/withdraw/address. Query withdraw address. */ +export interface SpotWithdrawAddressReq { + /** + * Crypto currency. + * Use "t247117" for universal address. + * Use "t397342" to query Poloniex UID withdraw addresses added on platform. + */ + currency?: string; + /** Block chain name. Omit for all chains. */ + chain?: string; + /** Note of withdraw address. Omit for all. */ + note?: string; + /** Items to return [1-500]. Default 100. */ + limit?: number; + /** First record ID for next page. */ + fromId?: number; } ⋮---- /** - * Account - */ + * Crypto currency. + * Use "t247117" for universal address. + * Use "t397342" to query Poloniex UID withdraw addresses added on platform. + */ ⋮---- -/** Account from /v1/account/accounts */ -export interface SpotAccount { - id: number; - type: string; - subtype?: string; - state: string; -} +/** Block chain name. Omit for all chains. */ ⋮---- -/** Balance row from /v1/account/accounts/{account-id}/balance list */ -export interface SpotBalance { - currency: string; - type: string; - balance: string; - debt?: string; - available?: string; - 'seq-num'?: string; -} +/** Note of withdraw address. Omit for all. */ ⋮---- -/** Account balance from /v1/account/accounts/{account-id}/balance */ -export interface SpotAccountBalance { - id: number; - type: string; - state: string; - list: SpotBalance[]; -} +/** Items to return [1-500]. Default 100. */ ⋮---- -/** Profit account balance item from /v2/account/valuation */ -export interface SpotV2ProfitAccountBalance { - distributionType: string; - balance: number; - success: boolean; - accountBalance: string; -} +/** First record ID for next page. */ ⋮---- -/** Updated info from /v2/account/valuation */ -export interface SpotV2ValuationUpdated { - success: boolean; - time: number; +/** Req for POST /broker/v1/sub-user/fee_rate/add. Set sub-user trading fee rate. */ +export interface SpotBrokerSubUserFeeRateAddReq { + /** Sub-account ids, max 10 */ + subUids: number[]; + /** 0 all, 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ + bizType: number; + /** Type: 1 fixed (0.001-0.5), 2 percent (1-1000) */ + type: number; + /** Additional taker fee. Either taker or maker required. */ + taker?: string; + /** Additional maker fee. Either taker or maker required. */ + maker?: string; + /** YYYYMMDD effect date. Omit for T+1. */ + effectAt?: string; } ⋮---- -/** Response from /v2/account/valuation */ -export interface SpotV2AccountValuation { - totalBalance?: string; - todayProfit?: string; - todayProfitRate?: string; - profitAccountBalanceList?: SpotV2ProfitAccountBalance[]; - updated?: SpotV2ValuationUpdated; -} +/** Sub-account ids, max 10 */ ⋮---- -/** Response from /v2/account/asset-valuation */ -export interface SpotV2AssetValuation { - balance: string; - timestamp: number; -} +/** 0 all, 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ ⋮---- -/** Transfer result from POST /v1/account/transfer */ -export interface SpotAccountTransferResult { - 'transact-id': number; - 'transact-time': number; -} +/** Type: 1 fixed (0.001-0.5), 2 percent (1-1000) */ ⋮---- -export interface SpotV2PointAccountGroupId { - groupId: number; - expiryDate: number | null; - remainAmt: string; -} +/** Additional taker fee. Either taker or maker required. */ ⋮---- -/** Point balance from GET /v2/point/account */ -export interface SpotV2PointAccount { - accountId: string; - accountStatus: string; - acctBalance: string; - groupIds: SpotV2PointAccountGroupId[]; -} +/** Additional maker fee. Either taker or maker required. */ ⋮---- -/** Point transfer result from POST /v2/point/transfer */ -export interface SpotV2PointTransfer { - transactId: string; - transactTime: number; -} +/** YYYYMMDD effect date. Omit for T+1. */ ⋮---- -/** Deduction info from GET /v1/account/switch/user/info */ -export interface SpotV1AccountSwitchUserInfo { - /** 1=point card deduction, 0=no */ - pointSwitch: number; - /** 1=HTX deduction, 0=no. Choose one of point card and HTX deduction. */ - currencySwitch: number; - deductionCurrency: string; - /** 1: limited, 0: unlimited */ - deductionType: number; - /** Total deductible (USDT). Only when deductionType=1 */ - totalDeductionLimit?: string; - /** Remaining deductible (USDT). Only when deductionType=1 */ - remainingDeductionLimit?: string; +/** Req for POST /broker/v1/account_capital_snapshot_everyday. Account asset snapshot. */ +export interface SpotBrokerAccountCapitalSnapshotReq { + /** Account type: spot, margin-api, super-margin-api, delivery, swap, linear */ + account_type: string; + /** Start time (ms). Omit with end_time for last 7 days. */ + start_time?: number; + /** End time (ms). Max 30 days from start. */ + end_time?: number; } ⋮---- -/** 1=point card deduction, 0=no */ -⋮---- -/** 1=HTX deduction, 0=no. Choose one of point card and HTX deduction. */ -⋮---- -/** 1: limited, 0: unlimited */ +/** Account type: spot, margin-api, super-margin-api, delivery, swap, linear */ ⋮---- -/** Total deductible (USDT). Only when deductionType=1 */ +/** Start time (ms). Omit with end_time for last 7 days. */ ⋮---- -/** Remaining deductible (USDT). Only when deductionType=1 */ +/** End time (ms). Max 30 days from start. */ ⋮---- -/** Deductible currency info from GET /v1/account/overview/info */ -export interface SpotV1AccountOverviewInfo { - currency: string; +/** Req for POST /v2/sub-user/tradable-market. Set tradable market for sub users. */ +export interface SpotSubUserTradableMarketReq { + /** Sub user UIDs, comma-separated, max 50 */ + subUids: string; + /** isolated-margin or cross-margin */ + accountType: 'isolated-margin' | 'cross-margin'; + /** activated or deactivated */ + activation: 'activated' | 'deactivated'; } ⋮---- -/** Account history row from GET /v1/account/history */ -export interface SpotAccountHistory { - 'account-id': number; - currency: string; - 'record-id': number; - 'transact-amt': string; - /** Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ - 'transact-type': string; - 'avail-balance': string; - 'acct-balance': string; - 'transact-time': number; -} +/** Sub user UIDs, comma-separated, max 50 */ ⋮---- -/** Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ +/** isolated-margin or cross-margin */ ⋮---- -/** Ledger row from GET /v2/account/ledger */ -export interface SpotV2AccountLedger { - accountId: number; - currency: string; - transactAmt: number; - transactType: string; - transferType?: string; - transactId: number; - transactTime: number; - transferer: number; - transferee: number; -} +/** activated or deactivated */ ⋮---- -/** Batch order placement result. Success: order-id, client-order-id. Error: err-code, err-msg. */ -export interface SpotV1OrderBatchPlaceResult { - 'order-id'?: number; - 'client-order-id'?: string; - 'err-code'?: string; - 'err-msg'?: string; +/** Req for setSubUserTransferPermissions. Set asset transfer permission. */ +export interface SpotSubUserTransferPermissionsReq { + /** Sub user UIDs, comma-separated, max 50 */ + subUids: string; + /** true or false */ + transferrable: boolean; + /** Account type. Default spot. */ + accountType?: 'spot'; } ⋮---- -/** Margin order result from POST /v1/order/auto/place */ -export interface SpotV1OrderAutoPlaceResult { - 'order-id': number; -} +/** Sub user UIDs, comma-separated, max 50 */ ⋮---- -/** Canceled order id from POST /v1/order/orders/{order-id}/submitcancel */ -export type SpotV1OrderCancelResult = string; +/** true or false */ ⋮---- -/** Order status from POST /v1/order/orders/submitCancelClientOrder. 1:ready, 2:created, 3:submitted, 4:partial-filled, 5:partial-canceled, 6:filled, 7:canceled, 10:canceling */ -export type SpotV1OrderCancelByClientOrderIdResult = number; +/** Account type. Default spot. */ ⋮---- -/** Result from POST /v1/order/orders/batchCancelOpenOrders */ -export interface SpotV1OrderBatchCancelOpenOrdersResult { - 'success-count': number; - 'failed-count': number; - /** Next order id to cancel, -1 = none */ - 'next-id': number; +/** Req for POST /v1/subuser/transfer. Transfer asset between parent and sub account. */ +export interface SpotSubUserTransferReq { + /** Sub account UID */ + 'sub-uid': number; + /** Currency e.g. btc, usdt */ + currency: string; + /** Amount to transfer */ + amount: string; + /** master-transfer-in, master-transfer-out, master-point-transfer-in, master-point-transfer-out */ + type: + | 'master-transfer-in' + | 'master-transfer-out' + | 'master-point-transfer-in' + | 'master-point-transfer-out'; + /** Client order id for idempotency */ + 'client-order-id'?: string; } ⋮---- -/** Next order id to cancel, -1 = none */ +/** Sub account UID */ ⋮---- -/** Failed cancel from POST /v1/order/orders/batchcancel */ -export interface SpotV1OrderBatchCancelFailed { - 'order-id'?: string; - 'client-order-id'?: string; - 'err-code'?: string; - 'err-msg'?: string; - 'order-state'?: string; -} +/** Currency e.g. btc, usdt */ ⋮---- -/** Result from POST /v2/algo-orders/cancel-all-after (Dead man's switch) */ -export interface SpotV2AlgoOrdersCancelAllAfterResult { - currentTime: number; - triggerTime: number; -} +/** Amount to transfer */ ⋮---- -/** - * Conditional Order - */ +/** master-transfer-in, master-transfer-out, master-point-transfer-in, master-point-transfer-out */ ⋮---- -/** Result from POST /v2/algo-orders (Place a conditional order) */ -export interface SpotV2AlgoOrdersPlaceResult { - clientOrderId: string; -} +/** Client order id for idempotency */ ⋮---- -/** Result from POST /v2/algo-orders/cancellation (Cancel conditional orders before triggering) */ -export interface SpotV2AlgoOrdersCancellationResult { - accepted: string[]; - rejected: string[]; +/** Req for getSubUserDepositHistory. Query sub user deposit history. */ +export interface SpotSubUserDepositHistoryReq { + /** Sub user UID */ + subUid: number; + /** Crypto currency. Omit for all. */ + currency?: string; + /** Start time (ms). Default endTime - 30 days. */ + startTime?: number; + /** End time (ms). Default now. */ + endTime?: number; + /** asc or desc */ + sort?: 'asc' | 'desc'; + /** Items per page [1-500]. Default 100. */ + limit?: number; + /** First record ID for next page. */ + fromId?: number; } ⋮---- -/** Conditional order item from GET /v2/algo-orders/opening (orderStatus=created) and /history and /specific */ -export interface SpotV2AlgoOrder { - accountId: number; - source: string; - clientOrderId: string; - symbol?: string; - orderPrice?: string; - orderSize?: string; - orderValue?: string; - orderSide: string; - orderType: string; - timeInForce?: string; - stopPrice?: string; - trailingRate?: string; - orderOrigTime: number; - lastActTime: number; - orderStatus: string; - /** Only for orderStatus=triggered */ - orderId?: string; - /** Order trigger time. Only for orderStatus=triggered */ - orderCreateTime?: number; - /** Only for orderStatus=rejected */ - errCode?: number; - /** Only for orderStatus=rejected */ - errMessage?: string; -} +/** Sub user UID */ ⋮---- -/** Only for orderStatus=triggered */ +/** Crypto currency. Omit for all. */ ⋮---- -/** Order trigger time. Only for orderStatus=triggered */ +/** Start time (ms). Default endTime - 30 days. */ ⋮---- -/** Only for orderStatus=rejected */ +/** End time (ms). Default now. */ ⋮---- -/** Only for orderStatus=rejected */ +/** asc or desc */ ⋮---- -/** - * Margin Loan (Cross/Isolated) - */ +/** Items per page [1-500]. Default 100. */ ⋮---- -/** Repayment result from POST /v2/account/repayment. Check transaction record to confirm status. */ -export interface SpotMarginRepaymentResult { - repayId: string | number; - repayTime: number; -} +/** First record ID for next page. */ ⋮---- -/** Transact ID detail from GET /v2/account/repayment (Repayment Record Reference) */ -export interface SpotRepaymentRecordTransactId { - transactId: number; - repaidPrincipal?: string; - repaidInterest?: string; - paidHt?: string; - paidPoint?: string; +/** Req for GET /v2/sub-user/managed-transfer-history. Managed sub-account transfer history. */ +export interface SpotSubUserManagedTransferHistoryReq { + /** Sub user UID. Omit for all managed sub-accounts. */ + uid?: number; + /** Currency filter */ + currency?: string; + /** 0: master to sub, 1: sub to master */ + type?: string; + /** Start time (ms). Max 48h window, within 120 days. */ + startTime?: number; + /** End time (ms). */ + endTime?: number; + /** Search id to begin with. */ + from?: string; + /** next or prev. Default next. */ + direct?: 'next' | 'prev'; + /** Items to return [1-100]. Default 100. */ + size?: string; } ⋮---- -/** Repayment record from GET /v2/account/repayment (Repayment Record Reference) */ -export interface SpotRepaymentRecord { - repayId: string | number; - repayTime: number; - accountId: string; - currency: string; - repaidAmount: string; - transactIds?: SpotRepaymentRecordTransactId | SpotRepaymentRecordTransactId[]; -} +/** Sub user UID. Omit for all managed sub-accounts. */ ⋮---- -/** Currency from GET /v1/margin/loan-info */ -export interface SpotMarginLoanInfoCurrency { - currency: string; - 'interest-rate': string; - 'min-loan-amt': string; - 'max-loan-amt': string; - 'loanable-amt': string; - 'actual-rate': string; -} +/** Currency filter */ ⋮---- -/** Symbol from GET /v1/margin/loan-info */ -export interface SpotMarginLoanInfo { - symbol: string; - currencies: SpotMarginLoanInfoCurrency[]; -} +/** 0: master to sub, 1: sub to master */ ⋮---- -/** Loan order item from GET /v1/margin/loan-orders */ -export interface SpotMarginLoanOrder { - id: number; - 'account-id': number; - 'user-id': number; - symbol: string; - currency: string; - 'created-at': string; - 'accrued-at'?: string; - 'loan-amount': string; - 'loan-balance': string; - 'interest-rate': string; - 'interest-amount'?: string; - 'interest-balance'?: string; - state: string; - 'paid-point'?: string; - 'paid-coin'?: string; - 'deduct-rate'?: string; - 'deduct-currency'?: string; - 'deduct-amount'?: string; - 'updated-at'?: number; - 'hour-interest-rate'?: string; - 'day-interest-rate'?: string; -} +/** Start time (ms). Max 48h window, within 120 days. */ ⋮---- -/** Balance row from GET /v1/margin/accounts/balance */ -export interface SpotMarginBalance { - currency: string; - type: string; - balance: string; -} +/** End time (ms). */ ⋮---- -/** Account item from GET /v1/margin/accounts/balance */ -export interface SpotMarginAccountBalance { - id: number; - type: string; - symbol: string; - state: string; - 'risk-rate'?: string; - 'fl-type'?: string; - 'fl-price'?: string; - list: SpotMarginBalance[]; -} +/** Search id to begin with. */ ⋮---- -/** Account balance from GET /v1/cross-margin/accounts/balance. Single object (unlike isolated which returns array). */ -export interface SpotCrossMarginAccountBalance { - id: number; - type: string; - state: string; - 'risk-rate'?: string; - 'acct-balance-sum'?: string; - 'debt-balance-sum'?: string; - list: SpotMarginBalance[]; -} +/** next or prev. Default next. */ ⋮---- -/** Loan order item from GET /v1/cross-margin/loan-orders */ -export interface SpotCrossMarginLoanOrder { - id: number; - 'account-id': number; - 'user-id': number; - currency: string; - 'filled-points'?: string; - 'filled-ht'?: string; - 'created-at': string | number; - 'accrued-at'?: string | number; - 'loan-amount': string; - 'loan-balance': string; - 'interest-amount'?: string; - 'interest-balance'?: string; - state: string; -} +/** Items to return [1-100]. Default 100. */ ⋮---- -/** Position limit from GET /v2/margin/limit */ -export interface SpotMarginLimit { - currency: string; - 'max-holdings': string; +/** Req for createSubUserApiKey. Create sub user API key. */ +export interface SpotSubUserApiKeyCreationReq { + /** Sub user UID */ + subUid: number; + /** Google OTP (6 digits) if parent has 2FA */ + otpToken?: string; + /** API key note, max 255 chars */ + note?: string; + /** readOnly, trade. readOnly required. Comma-separated. */ + permission?: string; + /** IP addresses, comma-separated, max 20 */ + ipAddresses?: string; } ⋮---- -/** Result from POST /v1/order/orders/batchcancel */ -export interface SpotV1OrderBatchCancelResult { - /** Successfully canceled order ids or client-order-ids */ - success: string[]; - /** Failed cancel requests */ - failed: SpotV1OrderBatchCancelFailed[]; -} +/** Sub user UID */ ⋮---- -/** Successfully canceled order ids or client-order-ids */ +/** Google OTP (6 digits) if parent has 2FA */ ⋮---- -/** Failed cancel requests */ +/** API key note, max 255 chars */ ⋮---- -/** Match result item from GET /v1/order/orders/{order-id}/matchresults */ -export interface SpotV1OrderMatchResult { - id: number; - symbol: string; - 'order-id': number; - 'match-id': number; - 'trade-id': number; - price: string; - 'created-at': number; - type: string; - 'filled-amount': string; - 'filled-fees': string; - 'fee-currency'?: string; - source?: string; - role?: string; - 'filled-points'?: string; - 'fee-deduct-currency'?: string; - 'fee-deduct-state'?: string; -} +/** readOnly, trade. readOnly required. Comma-separated. */ ⋮---- -/** Historical order from GET /v1/order/orders (search past orders) */ -export interface SpotV1OrderHistory { - id: number; - 'client-order-id'?: string; - 'account-id'?: number; - amount?: string; - symbol: string; - price?: string; - 'created-at': number; - 'canceled-at'?: number; - 'finished-at'?: number; - type?: string; - 'field-amount'?: string; - 'field-cash-amount'?: string; - 'field-fees'?: string; - source?: string; - state: string; - 'stop-price'?: string; - operator?: string; - role?: string; - 'canceled-source'?: number | string; - 'canceled-source-desc'?: string; - 'market-amount'?: string; - 'ice-amount'?: string; - 'is-ice'?: boolean; - 'updated-at'?: number; -} +/** IP addresses, comma-separated, max 20 */ ⋮---- -/** Historical order from GET /v1/order/history (48h). Includes next-time when more results exist. */ -export interface SpotV1OrderHistory48h extends SpotV1OrderHistory { - /** Next start-time or end-time for pagination. Only when results exceed size. */ - 'next-time'?: number; +/** Req for updateSubUserApiKey. Modify sub user API key. */ +export interface SpotSubUserApiKeyUpdateReq { + /** Sub user UID */ + subUid: number; + /** Access key to modify */ + accessKey: string; + /** API key note, max 255 chars */ + note?: string; + /** readOnly, trade. Comma-separated. */ + permission?: string; + /** IP addresses, comma-separated, max 20 */ + ipAddresses?: string; } ⋮---- -/** Next start-time or end-time for pagination. Only when results exceed size. */ +/** Sub user UID */ ⋮---- -/** Order detail from GET /v1/order/orders/{order-id} and getClientOrder */ -export interface SpotV1OrderDetail { - id: number; - 'client-order-id': string; - symbol: string; - 'account-id': number; - amount: string; - price: string; - 'created-at': number; - 'finished-at': number; - 'canceled-at': number; - type: string; - 'field-amount': string; - 'field-cash-amount': string; - 'field-fees': string; - source: string; - 'canceled-source'?: string; - state: string; - 'stop-price'?: string; - operator?: string; -} +/** Access key to modify */ ⋮---- -/** Deposit address item from GET /v2/account/deposit/address */ -export interface SpotDepositAddress { - userId: number; - currency: string; - address: string; - addressTag: string; - chain: string; -} +/** API key note, max 255 chars */ ⋮---- -/** Withdraw quota chain from GET /v2/account/withdraw/quota */ -export interface SpotWithdrawQuotaChain { - chain: string; - maxWithdrawAmt: string; - withdrawQuotaPerDay: string; - remainWithdrawQuotaPerDay: string; - withdrawQuotaPerYear: string; - remainWithdrawQuotaPerYear: string; - withdrawQuotaTotal: string; - remainWithdrawQuotaTotal: string; -} +/** readOnly, trade. Comma-separated. */ ⋮---- -/** Withdraw quota from GET /v2/account/withdraw/quota */ -export interface SpotWithdrawQuota { - currency: string; - chains: SpotWithdrawQuotaChain[]; +/** IP addresses, comma-separated, max 20 */ +⋮---- +/** Req for GET /v2/account/ledger */ +export interface SpotGetAccountLedgerReq { + /** Account ID */ + accountId: string; + /** Currency. Default all. */ + currency?: string; + /** Transaction types, comma-separated. Phase 1: transfer only. */ + transactTypes?: string; + /** Start time (unix ms). Max 10-day window, within 180 days. */ + startTime?: number; + /** End time (unix ms). */ + endTime?: number; + /** Sort order: asc, desc. Deprecated. */ + sort?: string; + /** Max items [1-500]. Default 100. */ + limit?: number; + /** First record ID for pagination (next page) */ + fromId?: number; } ⋮---- -/** - * Withdraw address status from GET /v2/account/withdraw/address. - * `normal`: common address. - * `white`: whitelist in effect. - * `white-delaying`: whitelist waiting out its delay. - * `processing`: pending 2FA or risk-control checks. - */ -export type SpotWithdrawAddressStatus = - | 'normal' - | 'white' - | 'white-delaying' - | 'processing'; +/** Account ID */ ⋮---- -/** Withdraw address item from GET /v2/account/withdraw/address */ -export interface SpotWithdrawAddress { - currency: string; - chain: string; - note: string; - addressTag?: string; - address: string; - /** See {@link SpotWithdrawAddressStatus}. */ - status: SpotWithdrawAddressStatus; -} +/** Currency. Default all. */ ⋮---- -/** See {@link SpotWithdrawAddressStatus}. */ +/** Transaction types, comma-separated. Phase 1: transfer only. */ ⋮---- -/** Deposit/withdraw record from GET /v1/query/deposit-withdraw or GET /v1/query/withdraw/client-order-id */ -export interface SpotDepositWithdrawRecord { - id: number; - type: string; - 'sub-type'?: string; - currency: string; - /** Chain name. Poloniex rapid transfer defaults to t397342. */ - chain: string; - 'tx-hash': string; - amount: number; - 'from-addr-tag'?: string; - /** On-chain address, or UID:XXXX for Poloniex→HTX rapid transfers. */ - address: string; - 'address-tag'?: string; - fee: number; - state: string; - 'created-at': number; - 'updated-at': number; - 'error-code'?: string; - 'error-msg'?: string; -} +/** Start time (unix ms). Max 10-day window, within 180 days. */ ⋮---- -/** Chain name. Poloniex rapid transfer defaults to t397342. */ +/** End time (unix ms). */ ⋮---- -/** On-chain address, or UID:XXXX for Poloniex→HTX rapid transfers. */ +/** Sort order: asc, desc. Deprecated. */ ⋮---- -/** VASP exchange from GET /v1/query/vasp-list */ -export interface SpotVaspExchange { - 'vasp-id': string; - 'vasp-name': string; - 'legal-name': string; -} +/** Max items [1-500]. Default 100. */ ⋮---- -/** User rebate status from GET /broker/v1/user_rebate_status */ -export interface SpotBrokerUserRebateStatus { - spotRebateStatus: boolean; - contractRebateStatus: boolean; - spotIsNewUser: boolean; - contractIsNewUser?: boolean; -} +/** First record ID for pagination (next page) */ ⋮---- -/** Sub-user fee rate from GET /broker/v1/sub-user/fee_rate */ -export interface SpotBrokerSubUserFeeRate { - userId: number; - subUserId: number; - bizType: number; - taker: string; - maker: string; - type: number; - addTaker: string; - addMaker: string; - updatedAt: number; - effectAt: number; +/** Req for GET /v2/invitee/rebate/history. Referral rebate history. */ +export interface SpotReferralRebateHistoryReq { + /** Invitee UID */ + inviteeUid: number; + /** Start date yyyy-MM-dd. Last 90 days. */ + startTime?: string; + /** End date yyyy-MM-dd. Last 90 days. */ + endTime?: string; + /** next or prev. Default prev. */ + direct?: 'next' | 'prev'; + /** Pagination cursor. Min query_id for prev, max for next. */ + fromId?: string; + /** Items per page, max 100. Default 100. */ + limit?: number; } ⋮---- -/** Fee rate add result from POST /broker/v1/sub-user/fee_rate/add */ -export interface SpotBrokerFeeRateAddResult { - subUserIds: number[]; - effectAt: string; -} +/** Invitee UID */ ⋮---- -/** Account capital snapshot item from POST /broker/v1/account_capital_snapshot_everyday */ -export interface SpotBrokerAccountCapitalSnapshot { - accountId: number; - accountType: string; - snapshotTime: string; - convertBalance: string; - dataList: unknown[]; -} +/** Start date yyyy-MM-dd. Last 90 days. */ ⋮---- -/** Deduct mode result item from POST /v2/sub-user/deduct-mode */ -export interface SpotSubUserDeductModeResult { - subUid: string; - deductMode: string | null; - errCode?: string; - errMessage?: string; -} +/** End date yyyy-MM-dd. Last 90 days. */ ⋮---- -/** API key from getSubUserApiKey */ -export interface SpotSubUserApiKey { - accessKey: string; - status: string; - note: string; - permission: string; - ipAddresses: string; - validDays: number; - createTime: number; - updateTime: number; -} +/** next or prev. Default prev. */ ⋮---- -/** Sub user creation result item from POST /v2/sub-user/creation */ -export interface SpotSubUserCreationResult { - userName: string; - note?: string; - uid?: number; - /** Spot account id for spot order transactions */ - spotAccountId?: number; - errCode?: string; - errMessage?: string; -} +/** Pagination cursor. Min query_id for prev, max for next. */ ⋮---- -/** Spot account id for spot order transactions */ +/** Items per page, max 100. Default 100. */ ⋮---- -/** Sub user from GET /v2/sub-user/user-list */ -export interface SpotSubUserList { - uid: number; - userState: string; - subUserName: string; - note: string; +/** Req for GET /v2/invitee/rebate/all_rebate/detail. All rebate detail. */ +export interface SpotReferralAllRebateDetailReq { + /** next or prev. Default prev. */ + direct?: 'next' | 'prev'; + /** Pagination cursor. */ + fromId?: string; + /** Items per page, max 100. Default 100. */ + limit?: number; } ⋮---- -/** Result from updateSubUserLockStatus */ -export interface SpotSubUserLockStatusResult { - subUid: number; - userState: string; -} +/** next or prev. Default prev. */ ⋮---- -/** Result from getSubUserStatus */ -export interface SpotSubUserStatusResult { - uid: number; - userState: string; -} +/** Pagination cursor. */ ⋮---- -/** Tradable market result item from POST /v2/sub-user/tradable-market */ -export interface SpotSubUserTradableMarketResult { - subUid: string; - accountType: string; - activation: string; - errCode?: number; - errMessage?: string; -} +/** Items per page, max 100. Default 100. */ ⋮---- -/** Result item from setSubUserTransferPermissions */ -export interface SpotSubUserTransferPermissionsResult { - subUid: number; - accountType: string; - transferrable: boolean; - errCode?: number; - errMessage?: string; +/** Req for GET /v2/invitee/rebate/referrals. Invited user list. */ +export interface SpotReferralReferralsReq { + /** Invitee UIDs, comma-separated, max 50. */ + inviteeUidList?: string; + /** Referral code used at registration. */ + referralCode?: string; + /** Start date yyyy-MM-dd. Last 14 days. */ + startTime?: string; + /** End date yyyy-MM-dd. Last 14 days. */ + endTime?: string; + /** prev or next. Default next. */ + direct?: 'prev' | 'next'; + /** Pagination cursor. */ + fromId?: string; + /** Items per page, max 100. Default 30. */ + limit?: number; } ⋮---- -/** Account ID from sub user account list */ -export interface SpotSubUserAccountId { - accountId: number; - subType?: string; - accountStatus?: string; -} +/** Invitee UIDs, comma-separated, max 50. */ ⋮---- -/** Account from sub user account list */ -export interface SpotSubUserAccount { - accountType: string; - activation: string; - transferrable?: boolean; - accountIds?: SpotSubUserAccountId[]; -} +/** Referral code used at registration. */ ⋮---- -/** Result from getSubUserAccounts */ -export interface SpotSubUserAccountsResult { - uid: number; - deductMode: string; - list: SpotSubUserAccount[]; -} +/** Start date yyyy-MM-dd. Last 14 days. */ ⋮---- -/** Result from createSubUserApiKey */ -export interface SpotSubUserApiKeyCreationResult { - accessKey: string; - secretKey: string; - note: string; - permission: string; - ipAddresses: string; -} +/** End date yyyy-MM-dd. Last 14 days. */ ⋮---- -/** Result from updateSubUserApiKey */ -export interface SpotSubUserApiKeyUpdateResult { - note: string; - permission: string; - ipAddresses: string; -} +/** prev or next. Default next. */ ⋮---- -/** Record from getSubUserDepositHistory */ -export interface SpotSubUserDepositHistoryRecord { - id: number; - currency: string; - txHash: string; - chain: string; - amount: number; - address: string; - addressTag: string; - state: string; - createTime: number; - updateTime: number; -} +/** Pagination cursor. */ ⋮---- -/** Balance from getSubUsersAggregatedBalance */ -export interface SpotSubUsersAggregatedBalance { - currency: string; - type: string; - balance: string; -} +/** Items per page, max 100. Default 30. */ ⋮---- -/** Result from getSubUserBalance */ -export interface SpotSubUserBalanceResult { - id: number; - type: string; - state: string; - list: SpotBalance[]; - symbol?: string; +/** Req for GET /v1/api/c2c/order/history. P2P order history. */ +export interface SpotP2POrderHistoryReq { + /** 0: buy, 1: sell */ + side?: string; + /** Start time (ms). Last 90 days. */ + startTime?: number; + /** End time (ms). Last 90 days. */ + endTime?: number; + /** next or prev. Default prev. */ + direct?: 'next' | 'prev'; + /** Pagination cursor. Min query_id for prev, max for next. */ + fromId?: number; + /** Items per page, max 100. Default 100. */ + limit?: number; } ⋮---- -/** Custody sub-account from GET /v2/sub-user/entrust-user-list */ -export interface SpotSubUserEntrustUser { - uid: number; - subUserName: string; -} +/** 0: buy, 1: sell */ ⋮---- -/** Managed transfer record from GET /v2/sub-user/managed-transfer-history */ -export interface SpotSubUserManagedTransferRecord { - currency: string; - type: string; - amount: number; - uid: number; - subUserName: string; - query_id?: string; -} +/** Start time (ms). Last 90 days. */ ⋮---- -/** Referral rebate detail from GET /v2/invitee/rebate/detail */ -export interface SpotReferralRebateDetail { - invitee_type: string; - invitee_rebate_rate_spot_m2: string; - invitee_rebate_rate_contract_m2: string; - invitee_rebate_rate_partner_spot?: string; - invitee_rebate_rate_partner_contract?: string; - join_time_m2: string; - join_time_partner?: string; - invitee_total_commission_usdt: string; - invitee_total_commission_trx: string; - invitee_total_commission_htx: string; - partner_total_commission_usdt: string; - partner_total_commission_trx: string; - partner_total_commission_htx: string; -} +/** End time (ms). Last 90 days. */ ⋮---- -/** Referral rebate history record from GET /v2/invitee/rebate/history */ -export interface SpotReferralRebateHistoryRecord { - date: number; - invitee_total_commission_usdt: string; - invitee_total_commission_trx: string; - invitee_total_commission_htx: string; - partner_total_commission_usdt: string; - partner_total_commission_trx: string; - partner_total_commission_htx: string; -} +/** next or prev. Default prev. */ ⋮---- -/** Referral rebate detail from all_rebate/detail or batcher_rebate/detail */ -export interface SpotReferralAllRebateDetail { - invitee_uid: number; - invitee_type: string; - invitee_rebate_rate_spot_m2: string | null; - invitee_rebate_rate_contract_m2: string | null; - invitee_rebate_rate_partner_spot?: string | null; - invitee_rebate_rate_partner_contract?: string | null; - join_time_m2: string; - join_time_partner?: string | null; - invitee_total_commission_usdt: string; - invitee_total_commission_trx: string; - invitee_total_commission_htx: string; - partner_total_commission_usdt: string; - partner_total_commission_trx: string; - partner_total_commission_htx: string; -} +/** Pagination cursor. Min query_id for prev, max for next. */ ⋮---- -/** P2P order from GET /v1/api/c2c/order/history */ -export interface SpotP2POrderHistory { - orderNo: string; - role: string; - side: string; - counterpartNickName: string; - fiatCurrency: string; - asset: string; - amount: string; - unitPrice: string; - totalPrice: string; - fee: string; - orderStatus: string; - createTime: string; - queryId?: number; -} +/** Items per page, max 100. Default 100. */ ⋮---- -/** Tiered rate from Earn project */ -export interface SpotEarnTieredRate { - amountStart: string; - amountEnd: string; - rate: string; +/** Req for GET /v1/earn/project/queryEarnProjectList. Earn product query. */ +export interface SpotEarnProjectListReq { + /** Crypto currency filter */ + currency?: string; + /** Page number. Default 1. */ + pageNum: number; + /** Items per page, max 100. Default 10. */ + pageSize: number; } ⋮---- -/** Earn project from GET /v1/earn/project/queryEarnProjectList */ -export interface SpotEarnProject { - projectId: number; - productId: number; - calculationType: number; - type: number; - viewYearRate: string; - finishAmount: string; - projectStatus: number; - totalAmount: string; - currency: string; - startAmount: string; - apyType: number; - tieredRates?: SpotEarnTieredRate[]; - marketPerkUpLimit?: string; - marketTimeApy?: string; - marketPerkApy?: string; -} +/** Crypto currency filter */ ⋮---- -/** Result from POST /v1/earn/order/demand/add */ -export interface SpotEarnSubscribeResult { - currency: string; - amount: string; - orderId: number; - status: number; -} +/** Page number. Default 1. */ ⋮---- -/** Result from POST /v1/earn/order/demand/redeem-order */ -export interface SpotEarnRedeemResult { - currency: string; +/** Items per page, max 100. Default 10. */ +⋮---- +/** Req for POST /v1/earn/order/demand/add. Earn subscription. */ +export interface SpotEarnSubscribeReq { + /** Project ID */ + id: number; + /** Subscription amount */ amount: string; - orderId: number; - status: number; + /** Idempotent ID (e.g. Snowflake). */ + requestId: string; } ⋮---- -/** Earn user asset from GET /v1/earn/order/user/assets/list */ -export interface SpotEarnUserAsset { - projectId: number; +/** Project ID */ +⋮---- +/** Subscription amount */ +⋮---- +/** Idempotent ID (e.g. Snowflake). */ +⋮---- +/** Req for POST /v1/earn/order/demand/redeem-order. Earn redemption. */ +export interface SpotEarnRedeemReq { + /** Order ID */ orderId: number; - projectType: number; - currency: string; - yesterdayIncome: string; - totalIncomeAmount: string; - totalAmount: string; - miningYearRate: string; - apyType: number; + /** Redemption amount */ + amount: string; + /** Idempotent ID (e.g. Snowflake). */ + requestId?: string; } ⋮---- -/** Referral invited user from GET /v2/invitee/rebate/referrals */ -export interface SpotReferralReferral { - id: number; - invitee_uid: number; - remark: string; - referral_code: string; - invitee_type: string; - invitee_rebate_rate_spot_m2: string; - invitee_rebate_rate_contract_m2: string; - invitee_rebate_rate_partner_spot?: string | null; - invitee_rebate_rate_partner_contract?: string | null; - join_time_m2: number; - join_time_partner?: number | null; - /** Whether advanced KYC was completed */ - completed_kyc?: boolean | number | string; - /** Invitee email */ - mail?: string | null; -} +/** Order ID */ ⋮---- -/** Whether advanced KYC was completed */ +/** Redemption amount */ ⋮---- -/** Invitee email */ +/** Idempotent ID (e.g. Snowflake). */ ⋮---- -/** Open order from GET /v1/order/openOrders */ -export interface SpotV1OpenOrder { - id: number; - 'client-order-id'?: string; - symbol: string; - 'account-id'?: number; - price?: string; - amount?: string; - 'created-at': number; - type: string; - 'filled-amount': string; - 'filled-cash-amount': string; - 'filled-fees': string; - source?: string; - state: string; - 'stop-price'?: string; - operator?: string; +/** Req for GET /v1/earn/order/user/assets/list. Earn position query. */ +export interface SpotEarnUserAssetsReq { + /** Project type: 0 = Flexible */ + projectType?: number; + /** Crypto currency filter */ + currency?: string; + /** Page number. Default 1. */ + pageNum: number; + /** Items per page, max 100. Default 10. */ + pageSize: number; } ⋮---- -/** Result from POST /v5/account/universal_transfer */ -export interface SpotUniversalTransferResult { - transfer_id: number; -} +/** Project type: 0 = Flexible */ ⋮---- -/** Record from GET /v5/account/universal_transfer_records */ -export interface SpotUniversalTransferRecord { - id: number; - transfer_id: number | string; - amount: string; - currency?: string; - status?: string; - from_account_type: string; - to_account_type: string; - from_account_asset?: string; - to_account_asset?: string; +/** Crypto currency filter */ +⋮---- +/** Page number. Default 1. */ +⋮---- +/** Items per page, max 100. Default 10. */ +⋮---- +/** Account type for POST /v5/account/universal_transfer */ +export type SpotUniversalTransferAccountType = + | 'otc' + | 'spot' + | 'linear-swap' + | 'futures' + | 'swap' + | 'margin' + | 'super-margin' + | 'otc-options'; +⋮---- +/** Req for POST /v5/account/universal_transfer. Create universal transfer. */ +export interface SpotUniversalTransferReq { + amount: number | string; + currency: string; + from_account_type: SpotUniversalTransferAccountType; + to_account_type: SpotUniversalTransferAccountType; from_asset_type?: string; to_asset_type?: string; - transfer_time?: number; +} +⋮---- +/** Req for GET /v5/account/universal_transfer_records. Universal transfer history. */ +export interface SpotUniversalTransferRecordsReq { + transfer_id?: number | string; + currency?: string; + status?: 'success' | 'pending' | 'failed'; + start_time?: number; + end_time?: number; + from?: number; + limit?: number; + direct?: 'prev' | 'next'; } ================ -File: src/types/request/spot.types.ts +File: .gitignore +================ +!.gitkeep +.DS_Store +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json +pids +*.pid +*.seed +*.pid.lock +node_modules/ +.npm +.eslintcache +.node_repl_history +*.tgz +.yarn-integrity +.env +.env.test +.cache +dist +bundleReport.html +.history/ +examples/ignoreme +localtest.sh +repomix.sh +doc +.cursor/ +futuresOrder2.ts +.vscode/ +WSWIP.md +.tmp-packed* + +================ +File: src/types/response/futures.types.ts ================ /** - * Reference Data + * Reference */ ⋮---- -export interface SpotGetChainsReq { - /** Show desc: 0=no, 1=all, 2=suspend deposit/withdrawal and chain exchange */ - 'show-desc'?: string; - /** Currency filter */ - currency?: string; - /** Timestamp for incremental data. Returns updates from ts to now. If no update, data is []. */ - ts?: number; +/** Paginated response base. Use FuturesPaginatedData or FuturesPaginatedSettlement for specific data keys. */ +export interface FuturesPaginatedBase { + total_page: number; + current_page: number; + total_size: number; } ⋮---- -/** Show desc: 0=no, 1=all, 2=suspend deposit/withdrawal and chain exchange */ +/** Paginated response with `data` array (e.g. historical funding rate, liquidation orders). */ +export type FuturesPaginatedData = FuturesPaginatedBase & { data: T[] }; ⋮---- -/** Currency filter */ +/** Paginated response with `settlement_record` array. */ +export type FuturesPaginatedSettlement = FuturesPaginatedBase & { + settlement_record: T[]; +}; ⋮---- -/** Timestamp for incremental data. Returns updates from ts to now. If no update, data is []. */ +/** Paginated response with `sub_list` array (sub-account info list). */ +export type FuturesPaginatedSubList = FuturesPaginatedBase & { + sub_list: T[]; +}; ⋮---- -/** - * Market Data - */ +/** Paginated response with `transfer_record` array (master-sub transfers). */ +export type FuturesPaginatedTransferRecord = FuturesPaginatedBase & { + transfer_record: T[]; +}; ⋮---- -/** Req for /market/history/kline */ -export interface SpotGetKlineReq { - /** Trading symbol (e.g. btcusdt, btc3lusdtnav for ETP NAV) */ +/** Paginated response with `orders` array (open orders, trigger orders, etc.). */ +export type FuturesPaginatedOrders = FuturesPaginatedBase & { orders: T[] }; +⋮---- +/** Funding rate from swap_funding_rate and swap_batch_funding_rate */ +export interface FuturesFundingRate { + funding_rate: string; + contract_code: string; symbol: string; - /** Candle period. Default 1day. */ - period?: string; - /** Number of data points [1-2000]. Default 150. */ - size?: number; + fee_asset: string; + funding_time: string; + /** Deprecated, default null */ + estimated_rate?: string | null; + /** Deprecated, default null */ + next_funding_time?: string | null; } ⋮---- -/** Trading symbol (e.g. btcusdt, btc3lusdtnav for ETP NAV) */ -⋮---- -/** Candle period. Default 1day. */ +/** Deprecated, default null */ ⋮---- -/** Number of data points [1-2000]. Default 150. */ +/** Deprecated, default null */ ⋮---- -export interface SpotGetDepthReq { - /** Trading symbol (e.g. btcusdt) */ +/** Historical funding rate item from swap_historical_funding_rate */ +export interface FuturesHistoricalFundingRate { + avg_premium_index: string; + funding_rate: string; + funding_time: string; + /** Deprecated, default null */ + realized_rate?: string | null; + contract_code: string; symbol: string; - /** Depth levels per side. 5, 10, 20, 30. Default 20. step0 uses 150 if omitted. */ - depth?: number; - /** step0=no agg, step1-5=aggregation levels. Default step0. */ - type?: string; + fee_asset: string; } ⋮---- -/** Trading symbol (e.g. btcusdt) */ -⋮---- -/** Depth levels per side. 5, 10, 20, 30. Default 20. step0 uses 150 if omitted. */ -⋮---- -/** step0=no agg, step1-5=aggregation levels. Default step0. */ +/** Deprecated, default null */ ⋮---- -/** - * Account - */ export interface SpotGetAssetValuationReq { +/** Paginated wrapper for swap_historical_funding_rate data */ +export type FuturesHistoricalFundingRatePage = + FuturesPaginatedData; ⋮---- -*/ export interface SpotGetAssetValuationReq { - /** Account type: spot, margin, otc, super-margin. Default spot. */ - accountType?: string; - /** Valuation currency: BTC, CNY, USD, JPY, etc. Case sensitive. Default BTC. */ - valuationCurrency?: string; - /** Sub user UID. Omit for API key owner. */ - subUid?: number; +/** Liquidation order item from swap_liquidation_orders */ +export interface FuturesLiquidationOrder { + query_id: number; + symbol: string; + contract_code: string; + created_at: number; + direction: string; + offset: string; + volume: number; + amount: number; + price: number; + trade_turnover: number; + pair: string; + business_type: string; } ⋮---- -/** Account type: spot, margin, otc, super-margin. Default spot. */ -⋮---- -/** Valuation currency: BTC, CNY, USD, JPY, etc. Case sensitive. Default BTC. */ -⋮---- -/** Sub user UID. Omit for API key owner. */ -⋮---- -/** Req for POST /v2/account/transfer - transfer between spot, linear-swap, otc, futures, swap */ -export interface SpotV2AccountTransferReq { - /** Source: spot, linear-swap, otc, futures, swap */ - from: string; - /** Destination: spot, linear-swap, otc, futures, swap */ - to: string; - /** Currency (e.g. usdt). Upper/lowercase supported. */ - currency: string; - /** Transfer amount */ - amount: string; - /** Margin account (e.g. btc-usdt, eth-usdt, USDT) */ - 'margin-account': string; +/** Settlement record item from swap_settlement_records */ +export interface FuturesSettlementRecord { + symbol: string; + contract_code: string; + settlement_time: number; + clawback_ratio: number; + settlement_price: number; + settlement_type: string; + business_type: string; + pair: string; } ⋮---- -/** Source: spot, linear-swap, otc, futures, swap */ +/** Paginated settlement records from swap_settlement_records */ +export type FuturesSettlementRecordsPage = + FuturesPaginatedSettlement; ⋮---- -/** Destination: spot, linear-swap, otc, futures, swap */ +/** Elite ratio list item (account and position) */ +export interface FuturesEliteRatioList { + buy_ratio: number; + sell_ratio: number; + /** Account ratio only */ + locked_ratio?: number; + ts: number; +} ⋮---- -/** Currency (e.g. usdt). Upper/lowercase supported. */ +/** Account ratio only */ ⋮---- -/** Transfer amount */ -⋮---- -/** Margin account (e.g. btc-usdt, eth-usdt, USDT) */ +/** Elite account/position ratio data from swap_elite_account_ratio and swap_elite_position_ratio */ +export interface FuturesEliteRatio { + symbol: string; + contract_code: string; + pair: string; + business_type: string; + list: FuturesEliteRatioList[]; +} ⋮---- -/** Req for POST /v1/futures/transfer - transfer between spot and future contract account */ -export interface SpotV1FuturesTransferReq { - /** Currency name */ - currency: string; - /** Amount to transfer */ - amount: string; - /** futures-to-pro (contract -> spot) or pro-to-futures (spot -> contract) */ - type: 'futures-to-pro' | 'pro-to-futures'; +/** System status item from swap_api_state. 1=available, 0=unavailable */ +export interface FuturesApiState { + symbol: string; + contract_code: string; + margin_mode: string; + margin_account: string; + open: number; + close: number; + cancel: number; + transfer_in: number; + transfer_out: number; + master_transfer_sub: number; + sub_transfer_master: number; + master_transfer_sub_inner_in: number; + master_transfer_sub_inner_out: number; + sub_transfer_master_inner_in: number; + sub_transfer_master_inner_out: number; + transfer_inner_in: number; + transfer_inner_out: number; } ⋮---- -/** Currency name */ +/** Cross ladder margin tier from swap_cross_ladder_margin */ +export interface FuturesLadderMarginTier { + min_margin_balance: number | null; + max_margin_balance: number | null; + min_margin_available: number | null; + max_margin_available: number | null; +} ⋮---- -/** Amount to transfer */ +/** Cross ladder margin list item */ +export interface FuturesCrossLadderMarginList { + lever_rate: number; + ladders: FuturesLadderMarginTier[]; +} ⋮---- -/** futures-to-pro (contract -> spot) or pro-to-futures (spot -> contract) */ +/** Cross tiered margin item from swap_cross_ladder_margin. Isolated (swap_ladder_margin) omits business_type, pair, contract_type. */ +export interface FuturesCrossLadderMargin { + margin_account: string; + symbol: string; + contract_code: string; + margin_mode: string; + list: FuturesCrossLadderMarginList[]; + business_type?: string; + pair?: string; + contract_type?: string; +} ⋮---- -/** Req for POST /v1/account/transfer */ -export interface SpotAccountTransferReq { - /** Transfer out user uid */ - 'from-user': number; - /** Transfer out account type: spot, margin */ - 'from-account-type': string; - /** Transfer out account id */ - 'from-account': number; - /** Transfer in user uid */ - 'to-user': number; - /** Transfer in account type: spot, margin */ - 'to-account-type': string; - /** Transfer in account id */ - 'to-account': number; - /** Currency name */ - currency: string; - /** Amount to transfer */ - amount: string; +/** Estimated settlement price item from swap_estimated_settlement_price. Empty around settlement/delivery. */ +export interface FuturesEstimatedSettlementPrice { + contract_code: string; + estimated_settlement_price: number | null; + settlement_type: string; + contract_type: string; + pair: string; + business_type: string; } ⋮---- -/** Transfer out user uid */ +/** Tiered adjustment factor ladder from swap_adjustfactor and swap_cross_adjustfactor */ +export interface FuturesAdjustFactorLadder { + ladder: number; + min_size: number; + max_size: number | null; + adjust_factor: number; +} ⋮---- -/** Transfer out account type: spot, margin */ +/** Adjust factor list item */ +export interface FuturesAdjustFactorList { + lever_rate: number; + ladders: FuturesAdjustFactorLadder[]; +} ⋮---- -/** Transfer out account id */ +/** Tiered adjustment factor item from swap_adjustfactor and swap_cross_adjustfactor. Cross includes business_type, pair, contract_type. */ +export interface FuturesAdjustFactor { + symbol: string; + contract_code: string; + margin_mode: string; + list: FuturesAdjustFactorList[]; + business_type?: string; + pair?: string; + contract_type?: string; +} ⋮---- -/** Transfer in user uid */ +/** Risk reserve balance from /v1/insurance_fund_info */ +export interface FuturesInsuranceFundInfo { + insurance_fund: string; + quote_currency?: string; +} ⋮---- -/** Transfer in account type: spot, margin */ +/** Historical risk reserve item from /v1/insurance_fund_history */ +export interface FuturesInsuranceFundHistory { + query_id: number; + insurance_fund: string; + date: string; +} ⋮---- -/** Transfer in account id */ +/** Price limit item from swap_price_limit. business_type, pair, contract_type optional for CM products. */ +export interface FuturesPriceLimit { + symbol: string; + contract_code: string; + high_limit: number; + low_limit: number; + business_type?: string; + pair?: string; + contract_type?: string; +} ⋮---- -/** Currency name */ +/** Open interest item from swap_open_interest */ +export interface FuturesOpenInterest { + symbol: string; + volume: number; + amount: number; + contract_code: string; + value: number; + trade_amount: number; + trade_volume: number; + trade_turnover: number; + contract_type: string; + pair: string; + business_type: string; +} ⋮---- -/** Amount to transfer */ +/** Contract info item from swap_contract_info */ +export interface FuturesContractInfo { + symbol: string; + contract_code: string; + contract_size: number; + price_tick: number; + settlement_date: string; + settlement_period: string; + create_date: string; + delivery_time: string; + contract_status: number; + support_margin_mode?: string; + contract_type: string; + pair: string; + business_type: string; + delivery_date: string; + adjust?: unknown[]; + price_estimated?: unknown[]; + open_type?: number; + trade_partition?: string; + labels?: string[]; + tradfi_labels?: string[]; +} ⋮---- -/** Req for GET /v1/account/history */ -export interface SpotGetAccountHistoryReq { - /** Account ID from GET /v1/account/accounts */ - 'account-id': string | number; - /** Currency filter */ - currency?: string; - /** Amount change types, comma-separated. Default all. Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ - 'transact-types'?: string; - /** Start time (unix ms). Query window max 1 hour. */ - 'start-time'?: number; - /** End time (unix ms). Query window within 30 days. */ - 'end-time'?: number; - /** Sort order: asc, desc. Default asc. */ - sort?: string; - /** Max items [1-500]. Default 100. */ - size?: number; - /** First record ID for pagination (next page) */ - 'from-id'?: number; +/** Index price item from swap_index. symbol optional (CM Delivery uses symbol). */ +export interface FuturesIndexPrice { + contract_code?: string; + symbol?: string; + index_price: number; + index_ts: number; } ⋮---- -/** Account ID from GET /v1/account/accounts */ +/** Index constituent component from swap_contract_constituents */ +export interface FuturesIndexConstituentComponent { + exchange: string; + symbol: string; + /** Price as string. -1 means HTX masked proprietary third-party index pricing. */ + symbol_price: string; + weights: string; +} ⋮---- -/** Currency filter */ +/** Price as string. -1 means HTX masked proprietary third-party index pricing. */ ⋮---- -/** Amount change types, comma-separated. Default all. Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ +/** Index constituents data from swap_contract_constituents. contract_code or symbol per product. */ +export interface FuturesIndexConstituents { + contract_code?: string; + symbol?: string; + index_price: string; + ts: number; + components: FuturesIndexConstituentComponent[]; +} ⋮---- -/** Start time (unix ms). Query window max 1 hour. */ +/** Contract elements price tick / value item */ +export interface FuturesContractElementsPrice { + business_type: number; + price: string; +} ⋮---- -/** End time (unix ms). Query window within 30 days. */ +/** Contract elements order limit item */ +export interface FuturesContractElementsOrderLimit { + instrument_type: number; + open: string; + close: string; + order_type?: number; + open_after_closing?: string; +} ⋮---- -/** Sort order: asc, desc. Default asc. */ +/** Contract elements contract info item */ +export interface FuturesContractElementsContractInfo { + contract_code: string; + instrument_type: number; + settlement_date: string; + delivery_time: string; + create_date: string; + contract_status: number; + delivery_date: string; + trigger_protect?: number; +} ⋮---- -/** Max items [1-500]. Default 100. */ +/** Timestamp response from /api/v1/timestamp. No data field. */ +export interface FuturesTimestamp { + status: string; + ts: number; +} ⋮---- -/** First record ID for pagination (next page) */ -⋮---- -export interface SpotV2PointTransferReq { - /** Transferer UID */ - fromUid: string; - /** Transferee UID */ - toUid: string; - /** Group ID. 0 = termless points. For terminable points, query sub user balance first. */ - groupId: number; - /** Transfer amount (max 8 decimal places) */ - amount: string; +/** Heartbeat data from /heartbeat/ - system availability */ +export interface FuturesHeartbeat { + heartbeat?: number; + swap_heartbeat?: number; + estimated_recovery_time?: number | null; + swap_estimated_recovery_time?: number | null; + linear_swap_heartbeat?: number; + linear_swap_estimated_recovery_time?: number | null; } ⋮---- -/** Transferer UID */ -⋮---- -/** Transferee UID */ -⋮---- -/** Group ID. 0 = termless points. For terminable points, query sub user balance first. */ -⋮---- -/** Transfer amount (max 8 decimal places) */ +/** Contract elements item from swap_query_elements */ +export interface FuturesContractElements { + contract_code: string; + mode_type: number; + swap_delivery_type: number; + instrument_index_code: string; + real_time_settlement: number; + transfer_profit_ratio: number; + cross_transfer_profit_ratio: number; + instrument_type: number[]; + trade_partition: string; + min_level: string; + max_level: string; + settle_period: number; + funding_rate_cap: string; + funding_rate_floor: string; + trigger_protect?: number; + long_position_limit?: string; + offset_order_limit?: string; + open_order_limit?: string; + short_position_limit?: string; + price_tick?: string; + instrument_value?: string; + price_ticks?: FuturesContractElementsPrice[]; + instrument_values?: FuturesContractElementsPrice[]; + order_limits?: FuturesContractElementsOrderLimit[]; + normal_limits?: { + instrument_type: number; + open: string; + close: string; + }[]; + open_limits?: { instrument_type: number; open: string; close: string }[]; + trade_limits?: { + instrument_type: number; + open: string; + close: string; + }[]; + contract_infos?: FuturesContractElementsContractInfo[]; +} ⋮---- /** - * Trading + * Market */ ⋮---- -/** Order type: direction-type. market=no price; limit=price+amount; limit-maker=maker only; ioc=immediately or cancel; limit-fok=fill or kill; stop-*=trigger price */ -export type SpotOrderType = - | 'buy-market' - | 'sell-market' - | 'buy-limit' - | 'sell-limit' - | 'buy-ioc' - | 'sell-ioc' - | 'buy-limit-maker' - | 'sell-limit-maker' - | 'buy-stop-limit' - | 'sell-stop-limit' - | 'buy-limit-fok' - | 'sell-limit-fok' - | 'buy-stop-limit-fok' - | 'sell-stop-limit-fok'; +/** Market depth tick from market/depth. ch, id, mrid, version optional per product. Payload in "tick". */ +export interface FuturesMarketDepthTick { + asks: [number, number][]; + bids: [number, number][]; + ch?: string; + id?: number; + mrid?: number; + ts: number; + version?: number; +} ⋮---- -/** Order source: spot-api, margin-api, super-margin-api, c2c-margin-api */ -export type SpotOrderSource = - | 'spot-api' - | 'margin-api' - | 'super-margin-api' - | 'c2c-margin-api'; +/** BBO tick from market/bbo. contract_code or symbol per product. ask/bid: [price, qty]. */ +export interface FuturesBboTick { + contract_code?: string; + symbol?: string; + business_type?: string; + mrid: number; + ask: [number, number]; + bid: [number, number]; + ts: number; +} ⋮---- -/** Req for POST /v1/order/orders/place */ -export interface SpotV1OrderPlaceReq { - /** Account ID from GET /v1/account/accounts. Required for trading. */ - 'account-id': string | number; - /** Trading symbol (e.g. ethusdt) */ - symbol: string; - /** Order type (e.g. buy-limit, sell-market) */ - type: SpotOrderType; - /** Order size. For buy-market = order value in quote currency. */ - amount: string; - /** Order price. Not used for market orders. Required for limit types. */ - price?: string; - /** Order source. Default spot-api */ - source?: SpotOrderSource; - /** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ - 'client-order-id'?: string; - /** 0=allow self-trade, 1=prevent. Default 0 */ - 'self-match-prevent'?: 0 | 1; - /** Trigger price for stop-limit orders */ - 'stop-price'?: string; - /** Operator for stop price (lte, gte, etc) */ - operator?: string; - /** RPI order - type must be buy-limit or sell-limit */ - 'time-in-force'?: 'rpi'; +/** Kline item from market/history/kline. trade_turnover optional per product. */ +export interface FuturesKline { + id: number; + vol: number; + count: number; + open: number; + close: number; + low: number; + high: number; + amount: number; + trade_turnover?: number; } ⋮---- -/** Account ID from GET /v1/account/accounts. Required for trading. */ +/** Basis data item from /index/market/history/linear_swap_basis and /index/market/history/basis */ +export interface FuturesBasis { + id: number; + contract_price: string; + index_price: string; + basis: string; + basis_rate: string; +} ⋮---- -/** Trading symbol (e.g. ethusdt) */ +/** Mark price kline item. Also used for premium index and estimated rate kline. trade_turnover optional. */ +export interface FuturesMarkPriceKline { + id: number; + vol: string; + count: string; + open: string; + close: string; + low: string; + high: string; + amount: string; + trade_turnover?: string; +} ⋮---- -/** Order type (e.g. buy-limit, sell-market) */ +/** 24h ticker from market detail/merged. contract_code, symbol, business_type optional per product. */ +export interface FuturesTicker { + id: number; + ts: number; + amount: string; + count: number; + vol: string; + open: string; + close: string; + low: string; + high: string; + trade_turnover?: string; + ask: [number, number]; + bid: [number, number]; + contract_code?: string; + symbol?: string; + business_type?: string; + number_of?: string; +} ⋮---- -/** Order size. For buy-market = order value in quote currency. */ +/** Trade item from last trade and history trade. symbol, contract_code, business_type, trade_turnover optional per product. */ +export interface FuturesTrade { + id: number; + price: string | number; + amount: string | number; + direction: string; + ts: number; + quantity?: string | number; + contract_code?: string; + business_type?: string; + trade_turnover?: string | number; + symbol?: string; + /** Whether the trade involved an RPI order. USDT-M uses snake_case. */ + is_rpi_trade?: boolean | number | string; + /** Whether the trade is an RPI trade. Coin-M uses the hyphenated name. */ + 'is-rpi-trade'?: boolean | number | string; +} ⋮---- -/** Order price. Not used for market orders. Required for limit types. */ +/** Whether the trade involved an RPI order. USDT-M uses snake_case. */ ⋮---- -/** Order source. Default spot-api */ +/** Whether the trade is an RPI trade. Coin-M uses the hyphenated name. */ ⋮---- -/** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ +/** Last trade tick from market/trade. Payload in "tick". */ +export interface FuturesLastTrade { + id: number; + ts: number; + data: FuturesTrade[]; +} ⋮---- -/** 0=allow self-trade, 1=prevent. Default 0 */ +/** Trade history group from market/history/trade. Each group has trades by timestamp. */ +export interface FuturesTradeHistory { + id: number; + ts: number; + data: FuturesTrade[]; +} ⋮---- -/** Trigger price for stop-limit orders */ +/** Open interest tick item from swap_his_open_interest */ +export interface FuturesOpenInterestTick { + volume: number; + amount_type: number; + ts: number; + value: number; +} ⋮---- -/** Operator for stop price (lte, gte, etc) */ +/** Open interest data from swap_his_open_interest. data is object with tick array. */ +export interface FuturesHistoricalOpenInterest { + symbol: string; + contract_code: string; + contract_type: string; + pair: string; + business_type: string; + tick: FuturesOpenInterestTick[]; +} ⋮---- -/** RPI order - type must be buy-limit or sell-limit */ +/** + * Account + */ ⋮---- -/** Margin order with auto borrow/repay for POST /v1/order/auto/place. Sub-accounts not supported. */ -export interface SpotV1OrderAutoPlaceReq { +/** Asset valuation item from swap_balance_valuation */ +export interface FuturesBalanceValuation { + valuation_asset: string; + balance: string; +} +⋮---- +/** Isolated account info item from swap_account_info */ +export interface FuturesIsolatedAccountInfo { symbol: string; - 'account-id': string | number; - type: SpotOrderType; - /** 1: automatic loan, 2: automatic repayment */ - 'trade-purpose': '1' | '2'; - source: SpotOrderSource; - /** Order volume. For market buy = order value. Use amount or market-amount, not both. */ - amount?: string; - /** Market buy = order volume, market sell = order amount. Use amount or market-amount, not both. */ - 'market-amount'?: string; - /** Amount/quantity to borrow when trade-purpose=1. Max 3 decimal precision. */ - 'borrow-amount'?: string; - price?: string; - /** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ - 'client-order-id'?: string; - 'stop-price'?: string; - operator?: string; + contract_code: string; + margin_asset: string; + margin_balance: number; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_real?: number; + profit_unreal: number; + risk_rate: number | null; + new_risk_rate?: string | null; + trade_partition?: string; + withdraw_available: number; + liquidation_price: number | null; + lever_rate: number; + adjust_factor: number; + margin_static: number; + margin_mode: string; + margin_account: string; + position_mode: string; } ⋮---- -/** 1: automatic loan, 2: automatic repayment */ -⋮---- -/** Order volume. For market buy = order value. Use amount or market-amount, not both. */ +/** Cross account contract detail (swap + futures) from swap_cross_account_info */ +export interface FuturesCrossAccountContractDetail { + symbol: string; + contract_code: string; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_unreal: number; + liquidation_price: number | null; + lever_rate: number; + adjust_factor: number; + contract_type: string; + cross_max_available?: string; + trade_partition?: string; + pair: string; + business_type: string; +} ⋮---- -/** Market buy = order volume, market sell = order amount. Use amount or market-amount, not both. */ +/** Cross account info item from swap_cross_account_info */ +export interface FuturesCrossAccountInfo { + margin_mode: string; + margin_account: string; + margin_asset: string; + margin_balance: number; + margin_static: number; + margin_position: number; + margin_frozen: number; + profit_unreal: number; + withdraw_available: number; + risk_rate: number | null; + money_in?: string; + money_out?: string; + new_risk_rate?: string | null; + position_mode: string; + contract_detail: FuturesCrossAccountContractDetail[]; + futures_contract_detail: FuturesCrossAccountContractDetail[]; +} ⋮---- -/** Amount/quantity to borrow when trade-purpose=1. Max 3 decimal precision. */ +/** Position info item from swap_position_info and swap_cross_position_info */ +export interface FuturesPositionInfo { + symbol: string; + contract_code: string; + volume: number; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; + profit: number; + margin_asset: string; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; + margin_mode: string; + margin_account: string; + position_mode: string; + withdraw_available?: number; + risk_rate?: number | null; + liquidation_price?: number | null; + adl_risk_percent?: string | number; + contract_type?: string; + pair?: string; + business_type?: string; + margin?: number | string; +} ⋮---- -/** Client order ID. Max 64 chars. Valid 8h for open, 2h for completed. */ +/** Nested position in swap_account_position_info */ +export interface FuturesAccountPosition { + symbol: string; + contract_code: string; + volume: number; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; + profit: number; + margin_asset: string; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; + margin_mode: string; + margin_account: string; + position_mode: string; + adl_risk_percent?: string | number; + new_risk_rate?: string | null; + trade_partition?: string; +} ⋮---- -/** Req for POST /v1/order/orders/batchCancelOpenOrders */ -export interface SpotV1OrderBatchCancelOpenOrdersReq { - /** Account ID from GET /v1/account/accounts */ - 'account-id'?: string; - /** Comma-separated symbols (max 10). Default all */ - symbol?: string; - /** Order types comma-separated */ - types?: string; - /** Filter: buy, sell */ - side?: 'buy' | 'sell'; - /** Orders to cancel [1-100]. Default 100 */ - size?: number; +/** Account + positions from swap_account_position_info (Isolated) */ +export interface FuturesIsolatedAccountPosition { + symbol: string; + contract_code: string; + margin_asset: string; + margin_balance: number; + margin_static: number; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_real?: number; + profit_unreal: number; + risk_rate: number | null; + new_risk_rate?: string | null; + trade_partition?: string; + liquidation_price: number | null; + withdraw_available: number; + lever_rate: number; + adjust_factor: number; + margin_mode: string; + margin_account: string; + position_mode: string; + positions: FuturesAccountPosition[]; + adl_risk_percent?: string | number; } ⋮---- -/** Account ID from GET /v1/account/accounts */ +/** Cross position item (in positions array) from swap_cross_account_position_info */ +export interface FuturesCrossAccountPositionItem { + symbol: string; + contract_code: string; + volume: number; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; + profit: number; + margin_asset: string; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; + margin_mode: string; + margin_account: string; + contract_type: string; + pair: string; + business_type: string; + position_mode: string; + new_risk_rate?: string | null; + trade_partition?: string; +} ⋮---- -/** Comma-separated symbols (max 10). Default all */ +/** Cross account + positions from swap_cross_account_position_info. data is object, not array. */ +export interface FuturesCrossAccountPosition { + margin_mode: string; + margin_account: string; + margin_asset: string; + margin_balance: number; + margin_static: number; + margin_position: number; + margin_frozen: number; + profit_real?: number; + profit_unreal: number; + withdraw_available: number; + risk_rate: number | null; + money_in?: string; + money_out?: string; + new_risk_rate?: string | null; + position_mode: string; + contract_detail: FuturesCrossAccountContractDetail[]; + futures_contract_detail: FuturesCrossAccountContractDetail[]; + positions: FuturesCrossAccountPositionItem[]; + adl_risk_percent?: string | number; +} ⋮---- -/** Order types comma-separated */ +/** Sub auth error from swap_sub_auth and swap_sub_auth_list */ +export interface FuturesSubAuthError { + sub_uid: string; + err_code: number | string; + err_msg: string; +} ⋮---- -/** Filter: buy, sell */ +/** Sub auth response data from swap_sub_auth */ +export interface FuturesSubAuth { + errors: FuturesSubAuthError[]; + successes: string; +} ⋮---- -/** Orders to cancel [1-100]. Default 100 */ +/** Sub auth success item from swap_sub_auth_list */ +export interface FuturesSubAuthSuccess { + query_id?: number; + sub_uid: string; + sub_auth: number | string; +} ⋮---- -/** Req for GET /v1/order/orders (search past orders) */ -export interface SpotGetOrderHistoryReq { - /** Trading symbol (required) */ - symbol: string; - /** Order types comma-separated */ - types?: string; - /** Start time (unix ms). Max 48h window. */ - 'start-time'?: number; - /** End time (unix ms). Max 48h window, within 180 days. */ - 'end-time'?: number; - /** States: filled, partial-canceled, canceled (comma-separated, required) */ - states: string; - /** Start order ID for pagination */ - from?: string; - /** next=desc, prev=asc. Default both */ - direct?: 'next' | 'prev'; - /** Orders to return [1-100]. Default 100 */ - size?: number; +/** Sub permissions response from getSubPermissions */ +export interface FuturesSubPermissions { + errors: FuturesSubAuthError[]; + successes: FuturesSubAuthSuccess[]; } ⋮---- -/** Trading symbol (required) */ -⋮---- -/** Order types comma-separated */ -⋮---- -/** Start time (unix ms). Max 48h window. */ +/** Isolated sub-account list item from swap_sub_account_list */ +export interface FuturesIsolatedSubAccountList { + symbol: string; + contract_code: string; + margin_asset: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | string | null; + margin_mode: string; + margin_account: string; + /** Used as from_id for next/prev pagination */ + query_id?: number; +} ⋮---- -/** End time (unix ms). Max 48h window, within 180 days. */ +/** Used as from_id for next/prev pagination */ ⋮---- -/** States: filled, partial-canceled, canceled (comma-separated, required) */ +/** Isolated sub-account entry from swap_sub_account_list (data array element) */ +export interface FuturesIsolatedSubAccountListEntry { + sub_uid: number; + list: FuturesIsolatedSubAccountList[]; +} ⋮---- -/** Start order ID for pagination */ +/** Cross sub-account list item from swap_cross_sub_account_list */ +export interface FuturesCrossSubAccountList { + margin_mode: string; + margin_account: string; + margin_asset: string; + margin_balance: number; + risk_rate: number | string | null; + trade_partition?: string; +} ⋮---- -/** next=desc, prev=asc. Default both */ +/** Asset multi-sub object from swap_cross_sub_account_list. Can be null. */ +export interface FuturesCrossSubAccountAssetMultiSub { + state: string; + equity: string; + initial_margin: string; + maintenance_margin: string; + maintenance_margin_rate: string; + profit_unreal: string; + available_margin: string; + created_time: number | string; + updated_time: number | string; + details: unknown[]; +} ⋮---- -/** Orders to return [1-100]. Default 100 */ +/** Cross sub-account entry from swap_cross_sub_account_list (data array element) */ +export interface FuturesCrossSubAccountListEntry { + query_id: number; + sub_uid: number; + list: FuturesCrossSubAccountList[]; + asset_multi_sub: FuturesCrossSubAccountAssetMultiSub | null; +} ⋮---- -/** Req for GET /v1/order/history (48h historical orders) */ -export interface SpotGetOrderHistory48hReq { - /** Trading symbol */ - symbol?: string; - /** Start time (unix ms). Default 48h ago */ - 'start-time'?: number; - /** End time (unix ms). Default now */ - 'end-time'?: number; - /** prev=asc, next=desc. Default next */ - direct?: 'prev' | 'next'; - /** Items per response [10-1000]. Default 100 */ - size?: number; - /** created-at: order creation time. updated-at: last update time. */ - 'sort-by'?: 'created-at' | 'updated-at'; +/** Account info item from swap_sub_account_info_list */ +export interface FuturesSubAccountInfoAccount { + symbol: string; + contract_code: string; + margin_account: string; + margin_mode: string; + margin_asset: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | string | null; } ⋮---- -/** Trading symbol */ +/** Sub-account item in swap_sub_account_info_list data.sub_list */ +export interface FuturesSubAccountInfoSub { + sub_uid: number; + account_info_list: FuturesSubAccountInfoAccount[]; +} ⋮---- -/** Start time (unix ms). Default 48h ago */ +/** object from swap_sub_account_info_list */ +export type FuturesSubAccountInfoList = + FuturesPaginatedSubList; ⋮---- -/** End time (unix ms). Default now */ +/** Cross sub-account info list: account_info_list item (no symbol/contract_code) */ +export interface FuturesCrossSubAccountInfoListAccount { + margin_mode: string; + margin_account: string; + margin_asset: string; + margin_balance: number; + risk_rate: number | string | null; + trade_partition?: string; +} ⋮---- -/** prev=asc, next=desc. Default next */ +/** Cross sub-account info list: sub_list item */ +export interface FuturesCrossSubAccountInfoListSub { + sub_uid: number; + account_info_list: FuturesCrossSubAccountInfoListAccount[]; +} ⋮---- -/** Items per response [10-1000]. Default 100 */ +/** Cross sub-account info list: unite_sub_list item */ +export interface FuturesCrossSubAccountInfoListUnite { + sub_uid: number; + asset_multi_sub: FuturesCrossSubAccountAssetMultiSub; +} ⋮---- -/** created-at: order creation time. updated-at: last update time. */ +/** object from swap_cross_sub_account_info_list */ +export type FuturesCrossSubAccountInfoList = + FuturesPaginatedSubList & { + unite_sub_list: FuturesCrossSubAccountInfoListUnite[]; + }; ⋮---- -/** Req for GET /v1/order/matchresults (search match results) */ -export interface SpotGetMatchResultsReq { - /** Trading symbol */ - symbol?: string; - /** Order types comma-separated */ - types?: string; - /** Start time (unix ms). 48h window, 120 days range */ - 'start-time'?: number; - /** End time (unix ms). 48h window */ - 'end-time'?: number; - /** Internal id to begin pagination (use last id of prev page) */ - from?: string; - /** next or prev. Default next */ - direct?: 'next' | 'prev'; - /** Items to return [1-500]. Default 100 */ - size?: number; +/** Isolated sub-account info item from swap_sub_account_info (single sub, data array element) */ +export interface FuturesIsolatedSubAccountInfo { + symbol: string; + contract_code: string; + margin_asset: string; + margin_balance: number; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_real?: number; + profit_unreal: number; + risk_rate: number | string | null; + new_risk_rate?: string | null; + trade_partition?: string; + liquidation_price: number | null; + withdraw_available: number; + lever_rate: number; + adjust_factor: number; + margin_static: number; + margin_mode: string; + margin_account: string; + position_mode: string; } ⋮---- -/** Trading symbol */ -⋮---- -/** Order types comma-separated */ +/** Cross sub-account info item from swap_cross_sub_account_info (single sub, data array element) */ +export interface FuturesCrossSubAccountInfo { + margin_mode: string; + margin_account: string; + margin_asset: string; + margin_balance: number; + margin_static: number; + margin_position: number; + margin_frozen: number; + profit_real?: number; + profit_unreal: number; + withdraw_available: number; + risk_rate: number | string | null; + money_in?: string; + money_out?: string; + new_risk_rate?: string | null; + position_mode: string; + contract_detail: FuturesCrossAccountContractDetail[]; + futures_contract_detail: FuturesCrossAccountContractDetail[]; +} ⋮---- -/** Start time (unix ms). 48h window, 120 days range */ +/** Financial record item from swap_financial_record and swap_financial_record_exact */ +export interface FuturesFinancialRecord { + query_id: number; + id: number; + ts: number; + asset: string; + contract_code: string; + margin_account: string; + face_margin_account: string; + type: number; + amount: number | string; +} ⋮---- -/** End time (unix ms). 48h window */ +/** Available leverage item from swap_available_level_rate */ +export interface FuturesAvailableLevelRate { + contract_code: string; + margin_mode: string; + available_level_rate: string; +} ⋮---- -/** Internal id to begin pagination (use last id of prev page) */ +/** Available leverage item from swap_cross_available_level_rate */ +export interface FuturesCrossAvailableLevelRate { + contract_code: string; + margin_mode: string; + available_level_rate: string; + contract_type: string; + pair: string; + business_type: string; +} ⋮---- -/** next or prev. Default next */ +/** Order limit list item from swap_order_limit */ +export interface FuturesOrderLimitList { + symbol: string; + contract_code: string; + open_limit: number; + close_limit: number; + contract_type: string; + pair: string; + business_type: string; +} ⋮---- -/** Items to return [1-500]. Default 100 */ +/** from swap_order_limit */ +export interface FuturesOrderLimit { + order_price_type: string; + list: FuturesOrderLimitList[]; +} ⋮---- -/** Req for GET /v1/order/openOrders */ -export interface SpotGetOpenOrdersReq { - /** Account ID from GET /v1/account/accounts */ - 'account-id'?: string; - /** Trading symbol (e.g. ethusdt) */ - symbol?: string; - /** Filter: buy, sell */ - side?: 'buy' | 'sell'; - /** Order types comma-separated */ - types?: string; - /** Start order ID for pagination */ - from?: string; - /** prev=asc from start, next=desc from start */ - direct?: 'prev' | 'next'; - /** Orders to return [1-500]. Default 100 */ - size?: number; +/** Fee item from swap_fee */ +export interface FuturesFee { + symbol: string; + contract_code: string; + open_maker_fee: string; + open_taker_fee: string; + close_maker_fee: string; + close_taker_fee: string; + fee_asset: string; + contract_type: string; + pair: string; + business_type: string; + delivery_fee: string; } ⋮---- -/** Account ID from GET /v1/account/accounts */ +/** Transfer limit item from swap_transfer_limit */ +export interface FuturesTransferLimit { + symbol: string; + contract_code: string; + margin_mode: string; + margin_account: string; + transfer_in_max_each: number; + transfer_in_min_each: number; + transfer_out_max_each: number; + transfer_out_min_each: number; + transfer_in_max_daily: number; + transfer_out_max_daily: number; + net_transfer_in_max_daily: number; + net_transfer_out_max_daily: number; +} ⋮---- -/** Trading symbol (e.g. ethusdt) */ +/** Transfer limit item from swap_cross_transfer_limit */ +export interface FuturesCrossTransferLimit { + margin_mode: string; + margin_account: string; + transfer_in_max_each: number; + transfer_in_min_each: number; + transfer_out_max_each: number; + transfer_out_min_each: number; + transfer_in_max_daily: number; + transfer_out_max_daily: number; + net_transfer_in_max_daily: number; + net_transfer_out_max_daily: number; +} ⋮---- -/** Filter: buy, sell */ +/** Position limit item from swap_position_limit */ +export interface FuturesPositionLimit { + symbol: string; + contract_code: string; + margin_mode: string; + buy_limit: number; + sell_limit: number; + lever_rate: number; + buy_limit_value: number; + sell_limit_value: number; + mark_price: number; +} ⋮---- -/** Order types comma-separated */ +/** Position limit item from swap_cross_position_limit */ +export interface FuturesCrossPositionLimit { + symbol: string; + contract_code: string; + margin_mode: string; + buy_limit: number; + sell_limit: number; + lever_rate: number; + buy_limit_value: number; + sell_limit_value: number; + mark_price: number; + contract_type: string; + pair: string; + business_type: string; +} ⋮---- -/** Start order ID for pagination */ +/** Lever position limit list item (per leverage) from swap_lever_position_limit */ +export interface FuturesLeverPositionLimitList { + lever_rate: number; + buy_limit_value: number; + sell_limit_value: number; +} ⋮---- -/** prev=asc from start, next=desc from start */ +/** Lever position limit item from swap_lever_position_limit */ +export interface FuturesLeverPositionLimit { + symbol: string; + contract_code: string; + margin_mode: string; + list: FuturesLeverPositionLimitList[]; +} ⋮---- -/** Orders to return [1-500]. Default 100 */ +/** Lever position limit item from swap_cross_lever_position_limit */ +export interface FuturesCrossLeverPositionLimit { + symbol: string; + contract_code: string; + margin_mode: string; + business_type: string; + contract_type: string; + pair: string; + list: FuturesLeverPositionLimitList[]; +} ⋮---- -/** - * Conditional Order - */ +/** Master-sub transfer response from transfer*MasterSub */ +export interface FuturesMasterSubTransfer { + order_id: string; + client_order_id?: number; +} ⋮---- -/** Req for POST /v2/algo-orders (Place a conditional order). Conditional orders only via this endpoint, not Trading section. */ -export interface SpotV2AlgoOrdersPlaceReq { - /** Account ID. Spot, margin, super-margin. C2C margin not supported. */ - accountId?: number; - /** Trading symbol */ +/** Transfer record item from master_sub_transfer_record. asset, margin_account, symbol, contract_code optional per product. */ +export interface FuturesMasterSubTransferRecordItem { + id: number; + ts: number; + sub_uid: string; + sub_account_name: string; + transfer_type: number; + amount: number | string; + asset?: string; + margin_account?: string; + from_margin_account?: string; + to_margin_account?: string; symbol?: string; - /** Order price (invalid for market order) */ - orderPrice?: string; - /** Order side: buy, sell */ - orderSide?: 'buy' | 'sell'; - /** Order size (invalid for market buy order) */ - orderSize?: string; - /** Order value (only valid for market buy order) */ - orderValue?: string; - /** Time in force: gtc, boc, ioc, fok. gtc=good till cancel, boc=book or cancel, ioc=immediate or cancel, fok=fill or kill. gtc for limit; ioc for market. */ - timeInForce?: 'gtc' | 'boc' | 'ioc' | 'fok'; - /** Order type: limit, market */ - orderType?: 'limit' | 'market'; - /** Client order ID (max 64 chars). Must be unique within 24h for same user. */ - clientOrderId?: string; - /** Stop price */ - stopPrice?: string; - /** Trailing rate [0.001-0.050]. Only valid for trailing stop order */ - trailingRate?: string; + contract_code?: string; } ⋮---- -/** Account ID. Spot, margin, super-margin. C2C margin not supported. */ -⋮---- -/** Trading symbol */ -⋮---- -/** Order price (invalid for market order) */ -⋮---- -/** Order side: buy, sell */ -⋮---- -/** Order size (invalid for market buy order) */ -⋮---- -/** Order value (only valid for market buy order) */ -⋮---- -/** Time in force: gtc, boc, ioc, fok. gtc=good till cancel, boc=book or cancel, ioc=immediate or cancel, fok=fill or kill. gtc for limit; ioc for market. */ -⋮---- -/** Order type: limit, market */ -⋮---- -/** Client order ID (max 64 chars). Must be unique within 24h for same user. */ -⋮---- -/** Stop price */ -⋮---- -/** Trailing rate [0.001-0.050]. Only valid for trailing stop order */ +/** Master-sub transfer records from swap_master_sub_transfer_record */ +export type FuturesMasterSubTransferRecords = + FuturesPaginatedTransferRecord; ⋮---- -export interface SpotV2AlgoOrdersOpeningReq { - /** Account ID */ - accountId?: number; - /** Trading symbol */ - symbol?: string; - /** Order side: buy, sell */ - orderSide?: 'buy' | 'sell'; - /** Order type: limit, market */ - orderType?: 'limit' | 'market'; - /** Sort: asc, desc. Default desc */ - sort?: 'asc' | 'desc'; - /** Max items [1-500]. Default 100 */ - limit?: number; - /** First record ID for next-page pagination */ - fromId?: number; +/** Cancel-after response data from linear-cancel-after */ +export interface FuturesCancelAfter { + current_time: number; + trigger_time: number; } ⋮---- -/** Account ID */ +/** Submit order response data from swap_order and swap_cross_order. order_id may exceed JS safe integer - use order_id_str. */ +export interface FuturesSubmitOrder { + order_id: number | string; + order_id_str: string; + client_order_id?: number; +} ⋮---- -/** Trading symbol */ +/** Batch order error item from swap_batchorder and swap_cross_batchorder */ +export interface FuturesBatchOrderError { + index: number; + err_code: number; + err_msg: string; +} ⋮---- -/** Order side: buy, sell */ +/** Batch order success item from swap_batchorder and swap_cross_batchorder */ +export interface FuturesBatchOrderSuccess { + index: number; + order_id: number | string; + order_id_str: string; + client_order_id?: number; +} ⋮---- -/** Order type: limit, market */ +/** Cancel order error item from swap_cancel and swap_cross_cancel */ +export interface FuturesCancelOrderError { + order_id: string; + err_code: number; + err_msg: string; +} ⋮---- -/** Sort: asc, desc. Default desc */ +/** Cancel order response data from swap_cancel, swap_cross_cancel, swap_cancelall, swap_cross_cancelall */ +export interface FuturesCancelOrder { + errors: FuturesCancelOrderError[]; + /** Comma-separated list of successfully cancelled order_id or client_order_id */ + successes: string; +} ⋮---- -/** Max items [1-500]. Default 100 */ +/** Comma-separated list of successfully cancelled order_id or client_order_id */ ⋮---- -/** First record ID for next-page pagination */ +/** Switch leverage response data from swap_switch_lever_rate */ +export interface FuturesSwitchLeverRate { + contract_code: string; + margin_mode: string; + lever_rate: number; +} ⋮---- -/** Req for GET /v2/algo-orders/history (Query conditional order history). orderStatus: canceled, rejected, triggered. */ -export interface SpotV2AlgoOrdersHistoryReq { - /** Account ID */ - accountId?: number; - /** Trading symbol */ - symbol?: string; - /** Order side: buy, sell */ - orderSide?: 'buy' | 'sell'; - /** Order type: limit, market */ - orderType?: 'limit' | 'market'; - /** Order status: canceled, rejected, triggered */ - orderStatus?: 'canceled' | 'rejected' | 'triggered'; - /** Start time (unix ms) */ - startTime?: number; - /** End time (unix ms) */ - endTime?: number; - /** Sort: asc, desc */ - sort?: 'asc' | 'desc'; - /** Max items [1-500] */ - limit?: number; - /** First record ID for next-page pagination */ - fromId?: number; +/** Switch leverage response data from swap_cross_switch_lever_rate */ +export interface FuturesCrossSwitchLeverRate { + contract_code: string; + margin_mode: string; + lever_rate: number; + contract_type: string; + pair: string; + business_type: string; } ⋮---- -/** Account ID */ +/** + * Batch order response data from swap_batchorder and swap_cross_batchorder. + * A successful request can contain both accepted and rejected orders. + */ +export interface FuturesBatchOrder { + errors: FuturesBatchOrderError[]; + success: FuturesBatchOrderSuccess[]; +} ⋮---- -/** Trading symbol */ -⋮---- -/** Order side: buy, sell */ -⋮---- -/** Order type: limit, market */ -⋮---- -/** Order status: canceled, rejected, triggered */ -⋮---- -/** Start time (unix ms) */ -⋮---- -/** End time (unix ms) */ -⋮---- -/** Sort: asc, desc */ -⋮---- -/** Max items [1-500] */ -⋮---- -/** First record ID for next-page pagination */ -⋮---- -/** - * Margin Loan (Cross/Isolated) - */ -⋮---- -/** Req for GET /v2/account/repayment (Repayment Record Reference). Sorted by repayTime. */ -export interface SpotRepaymentRecordReq { - /** Repayment transaction ID */ - repayId?: string; - /** Account ID. Default all accounts */ - accountId?: string; - /** Borrowing/lending currency. Default all currencies */ - currency?: string; - /** Start time (unix ms). Range: [(endTime – x D), endTime] */ - startTime?: number; - /** End time (unix ms). Range: [(now – y D), now]. Default now */ - endTime?: number; - /** Sort: asc, desc. Default desc */ - sort?: 'asc' | 'desc'; - /** Max items [1-100]. Default 50 */ - limit?: number; - /** Search ID for next-page pagination */ - fromId?: number; +/** Position mode item from swap_switch_position_mode and swap_cross_switch_position_mode */ +export interface FuturesSwitchPositionMode { + margin_account: string; + position_mode: string; } ⋮---- -/** Repayment transaction ID */ -⋮---- -/** Account ID. Default all accounts */ -⋮---- -/** Borrowing/lending currency. Default all currencies */ -⋮---- -/** Start time (unix ms). Range: [(endTime – x D), endTime] */ -⋮---- -/** End time (unix ms). Range: [(now – y D), now]. Default now */ -⋮---- -/** Sort: asc, desc. Default desc */ -⋮---- -/** Max items [1-100]. Default 50 */ -⋮---- -/** Search ID for next-page pagination */ -⋮---- -/** Req for POST /v2/account/repayment (Repay Margin Loan). Loan interest paid first if no transactId. */ -export interface SpotMarginRepaymentReq { - /** Repayment account ID */ - accountId?: string; - /** Repayment currency */ - currency?: string; - /** Repayment amount */ - amount?: string; - /** Loan transaction ID. When specified, repay that loan; otherwise interest paid first. */ - transactId?: string; +/** Order info item from getOrderInfo, getCoinMDeliveryOrderInfo, getCoinMPerpOrderInfo. Product-specific fields optional. */ +export interface FuturesOrderInfo { + symbol: string; + contract_code: string; + volume: number; + price: number; + order_price_type: string; + order_type: number; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + client_order_id: number | string | null; + created_at: number; + canceled_at: number | null; + trade_volume: number; + trade_turnover: number; + fee: number; + trade_avg_price: number | null; + margin_frozen: number; + profit: number; + status: number; + order_source: string; + fee_asset: string; + liquidation_type: string | null; + is_tpsl: number; + real_profit: number; + update_time?: number; + /** USDM only */ + margin_asset?: string; + margin_mode?: string; + margin_account?: string; + reduce_only?: number; + fee_amount?: number; + fee_quote_amount?: number; + self_match_prevent_new?: string; + /** CM Delivery: required; USDM/CM Perp: optional */ + contract_type?: string; + pair?: string; + business_type?: string; + canceled_source?: string; + self_match_prevent?: number; } ⋮---- -/** Repayment account ID */ -⋮---- -/** Repayment currency */ -⋮---- -/** Repayment amount */ +/** USDM only */ ⋮---- -/** Loan transaction ID. When specified, repay that loan; otherwise interest paid first. */ +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Req for POST /v1/dw/transfer-in/margin (Transfer Spot -> Isolated Margin). */ -export interface SpotMarginTransferInIsolatedReq { - /** Trading symbol (e.g. btcusdt, ethusdt) */ - symbol?: string; - /** Currency to transfer */ - currency?: string; - /** Amount to transfer */ - amount?: string; +/** Order detail trade item (trades array) from getOrderDetail, getCoinMDeliveryOrderDetail, getCoinMPerpOrderDetail */ +export interface FuturesOrderDetailTrade { + id: string; + trade_id: number | string; + trade_price: number; + trade_volume: number; + trade_turnover: number; + trade_fee: number; + role: string; + created_at: number; + profit: number; + real_profit: number; + fee_asse?: string; + price?: string; + fee_asset?: string; + canceled_source?: string; + self_match_prevent?: string | number; } ⋮---- -/** Trading symbol (e.g. btcusdt, ethusdt) */ +/** Order detail from getOrderDetail, getCoinMDeliveryOrderDetail, getCoinMPerpOrderDetail. Product-specific fields optional. */ +export interface FuturesOrderDetail { + symbol: string; + contract_code: string; + lever_rate: number; + direction: string; + offset: string; + volume: number; + price: number; + created_at: number; + canceled_at: number; + order_source: string; + order_price_type: string; + margin_frozen: number; + profit: number; + order_id: number | string; + order_id_str: string; + client_order_id: number | string | null; + order_type: number | string; + status: number; + trade_volume: number; + trade_turnover: number; + trade_avg_price: number; + total_page: number; + current_page: number; + total_size: number; + instrument_price: number; + final_interest: number; + adjust_value: number; + fee_asset: string; + fee: number; + liquidation_type: string; + is_tpsl: number; + real_profit: number; + trades: FuturesOrderDetailTrade[]; + /** USDM only */ + margin_asset?: string; + margin_mode?: string; + margin_account?: string; + reduce_only?: number; + self_match_prevent_new?: string; + /** CM Delivery: required; USDM/CM Perp: optional */ + contract_type?: string; + pair?: string; + business_type?: string; + canceled_source?: string; + self_match_prevent?: number; +} ⋮---- -/** Currency to transfer */ +/** USDM only */ ⋮---- -/** Amount to transfer */ +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Req for POST /v1/dw/transfer-out/margin (Transfer Isolated Margin -> Spot). */ -export interface SpotMarginTransferOutIsolatedReq { - /** Trading symbol (e.g. btcusdt, ethusdt) */ - symbol?: string; - /** Currency to transfer */ - currency?: string; - /** Amount to transfer */ - amount?: string; +/** Open order item from swap_openorders and swap_cross_openorders */ +export interface FuturesOpenOrder { + symbol: string; + contract_code: string; + volume: number; + price: number; + order_price_type: string; + order_type: number; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + client_order_id: number | string | null; + created_at: number; + trade_volume: number; + trade_turnover: number; + fee: number; + trade_avg_price: number | null; + margin_frozen: number; + margin_asset: string; + profit: number; + status: number; + order_source: string; + fee_asset: string; + liquidation_type: string | null; + canceled_at: number | null; + margin_mode: string; + margin_account: string; + is_tpsl: number; + real_profit: number; + update_time: number; + reduce_only: number; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; } ⋮---- -/** Trading symbol (e.g. btcusdt, ethusdt) */ -⋮---- -/** Currency to transfer */ +/** Cross margin only */ ⋮---- -/** Amount to transfer */ +/** Open orders response from swap_openorders and swap_cross_openorders */ +export type FuturesOpenOrders = FuturesPaginatedOrders & { + self_match_prevent_new: string; + self_match_prevent?: number; + canceled_source?: string; +}; ⋮---- -/** Req for POST /v1/margin/orders (Request a Margin Loan, Isolated) */ -export interface SpotMarginLoanOrderReq { - /** Trading symbol to borrow margin (e.g. btcusdt, ethusdt) */ - symbol?: string; - /** Currency to borrow */ - currency?: string; - /** Amount to borrow (max 3 decimal places) */ - amount?: string; +/** History order from getHistoryOrders, getCoinMDeliveryHistoryOrders, getCoinMPerpHistoryOrders. Product-specific optional. */ +export interface FuturesHistoryOrder { + query_id: number; + order_id: number | string; + order_id_str: string; + symbol: string; + contract_code: string; + lever_rate: number; + direction: string; + offset: string; + volume: number; + price: number; + create_date: number; + update_time: number; + order_source: string; + order_price_type: string | number; + order_type: number; + margin_frozen: number; + profit: number; + trade_volume: number; + trade_turnover: number; + fee: number; + trade_avg_price: number; + status: number; + fee_asset: string; + liquidation_type: string; + is_tpsl: number; + real_profit: number; + /** USDM only */ + margin_mode?: string; + margin_account?: string; + margin_asset?: string; + reduce_only?: number; + self_match_prevent_new?: string; + /** CM Delivery: required; USDM/CM Perp: optional */ + contract_type?: string; + pair?: string; + business_type?: string; + canceled_source?: string; + self_match_prevent?: number; } ⋮---- -/** Trading symbol to borrow margin (e.g. btcusdt, ethusdt) */ -⋮---- -/** Currency to borrow */ +/** USDM only */ ⋮---- -/** Amount to borrow (max 3 decimal places) */ +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Req for GET /v1/margin/loan-orders (Search Past Margin Orders, Isolated) */ -export interface SpotMarginLoanOrdersReq { - /** Trading symbol (e.g. btcusdt) */ - symbol?: string; - /** Order states comma-separated: created, accrual, cleared, invalid, failed */ - states?: string; - /** Start date yyyy-mm-dd. Default -61d */ - 'start-date'?: string; - /** End date yyyy-mm-dd. Default today */ - 'end-date'?: string; - /** Search order id to begin with */ - from?: string; - /** Search direction when from is used: next, prev */ - direct?: 'next' | 'prev'; - /** Orders to return [1-100]. Default 100 */ - size?: number; - /** Sub user ID (required when parent queries sub user's orders) */ - 'sub-uid'?: number; +/** Fill / match result from getFills, getCoinMDeliveryFills, getCoinMPerpFills. Product-specific optional. */ +export interface FuturesMatchResult { + id: string; + query_id: number; + match_id: number | string; + order_id: number | string; + order_id_str: string; + symbol: string; + contract_code: string; + direction: string; + offset: string; + trade_volume: number; + trade_price: number; + trade_turnover: number; + create_date: number; + offset_profitloss: number; + trade_fee: number; + role: string; + real_profit: number; + fee_asset: string; + order_source: string; + /** USDM only */ + margin_mode?: string; + margin_account?: string; + reduce_only?: number; + /** CM Delivery: required; USDM/CM Perp: optional */ + contract_type?: string; + pair?: string; + business_type?: string; + /** getFillsExact only */ + ht_price?: string; } ⋮---- -/** Trading symbol (e.g. btcusdt) */ -⋮---- -/** Order states comma-separated: created, accrual, cleared, invalid, failed */ -⋮---- -/** Start date yyyy-mm-dd. Default -61d */ -⋮---- -/** End date yyyy-mm-dd. Default today */ -⋮---- -/** Search order id to begin with */ +/** USDM only */ ⋮---- -/** Search direction when from is used: next, prev */ +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Orders to return [1-100]. Default 100 */ +/** getFillsExact only */ ⋮---- -/** Sub user ID (required when parent queries sub user's orders) */ +/** Position mode item from swap_position_side and swap_cross_position_side */ +export interface FuturesPositionSideInfo { + margin_account: string; + position_mode: 'single_side' | 'dual_side'; +} ⋮---- -/** Req for GET /v1/cross-margin/loan-orders (Search Past Margin Orders, Cross) */ -export interface SpotCrossMarginLoanOrdersReq { - /** Start date yyyy-mm-dd. Default -61d */ - 'start-date'?: string; - /** End date yyyy-mm-dd. Default today */ - 'end-date'?: string; - /** Currency filter */ - currency?: string; - /** Order state: created, accrual, cleared, invalid. Default all */ - state?: string; - /** Search order id to begin with. Default 0 */ - from?: string; - /** Search direction when from is used: next, prev. Default next */ - direct?: 'next' | 'prev'; - /** Orders to return [10-100]. Default 10 */ - size?: number; - /** Sub user UID */ - 'sub-uid'?: number; +/** Transfer state item from swap_cross_transfer_state */ +export interface FuturesCrossTransferState { + margin_mode: string; + margin_account: string; + /** 1: available, 0: unavailable */ + transfer_in: number; + /** 1: available, 0: unavailable */ + transfer_out: number; + /** 1: available, 0: unavailable */ + master_transfer_sub: number; + /** 1: available, 0: unavailable */ + sub_transfer_master: number; + master_transfer_sub_inner_in: number; + master_transfer_sub_inner_out: number; + sub_transfer_master_inner_in: number; + sub_transfer_master_inner_out: number; + transfer_inner_in: number; + transfer_inner_out: number; } ⋮---- -/** Start date yyyy-mm-dd. Default -61d */ +/** 1: available, 0: unavailable */ ⋮---- -/** End date yyyy-mm-dd. Default today */ +/** 1: available, 0: unavailable */ ⋮---- -/** Currency filter */ +/** 1: available, 0: unavailable */ ⋮---- -/** Order state: created, accrual, cleared, invalid. Default all */ +/** 1: available, 0: unavailable */ ⋮---- -/** Search order id to begin with. Default 0 */ +/** Trade state item from swap_cross_trade_state */ +export interface FuturesCrossTradeState { + symbol: string; + contract_code: string; + margin_mode: string; + margin_account: string; + contract_type: string; + pair: string; + business_type: string; + /** 1=available, 0=unavailable */ + open: number; + /** 1=available, 0=unavailable */ + close: number; + /** 1=available, 0=unavailable */ + cancel: number; +} ⋮---- -/** Search direction when from is used: next, prev. Default next */ +/** 1=available, 0=unavailable */ ⋮---- -/** Orders to return [10-100]. Default 10 */ +/** 1=available, 0=unavailable */ ⋮---- -/** Sub user UID */ +/** 1=available, 0=unavailable */ ⋮---- -/** Req for POST /v1/dw/withdraw/api/create. Create withdraw request. */ -export interface SpotWithdrawCreateReq { - /** - * Destination address. - * On-chain: chain address. - * Internal: UID:1234567, PHONE:xxx, MAIL:xxx. - * Poloniex zero-fee cross-exchange: POLOUSER:{UUID} (linked on HTX first). - */ - address: string; - /** Crypto currency */ - currency: string; - /** Amount to withdraw */ - amount: string; - /** Fee. Use 0 for UID withdraw and Poloniex cross-exchange transfers. */ - fee?: number; - /** - * Chain. Required for multi-chain coins. - * For internal withdraw or Poloniex cross-exchange transfer, use t397342. - */ - chain?: string; - /** Address tag. For UID withdraw, use recipient UID. */ - 'addr-tag'?: string; - /** Client order id for idempotency (max 32 char) */ - 'client-order-id'?: string; - /** Exchange VASP id from /v1/query/vasp-list */ - 'exchange-vasp'?: string; - /** Recipient name for Korean/English: "SURNAME##FIRSTNAME" */ - 'user-name-vasp'?: string; +/** Trigger order open order item from swap_trigger_openorders and swap_cross_trigger_openorders */ +export interface FuturesTriggerOrderOpenOrder { + symbol: string; + contract_code: string; + trigger_type: string; + volume: number; + order_type: number; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + order_source: string; + trigger_price: number | string; + order_price: number | string; + created_at: number; + order_price_type: string; + status: number; + margin_mode: string; + margin_account: string; + reduce_only: number; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; } ⋮---- -/** - * Destination address. - * On-chain: chain address. - * Internal: UID:1234567, PHONE:xxx, MAIL:xxx. - * Poloniex zero-fee cross-exchange: POLOUSER:{UUID} (linked on HTX first). - */ -⋮---- -/** Crypto currency */ +/** Cross margin only */ ⋮---- -/** Amount to withdraw */ +/** Trigger open orders response from swap_trigger_openorders and swap_cross_trigger_openorders */ +export type FuturesTriggerOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** Fee. Use 0 for UID withdraw and Poloniex cross-exchange transfers. */ -⋮---- -/** - * Chain. Required for multi-chain coins. - * For internal withdraw or Poloniex cross-exchange transfer, use t397342. - */ +/** Trigger order history item from swap_trigger_hisorders and swap_cross_trigger_hisorders */ +export interface FuturesTriggerOrderHisOrder { + symbol: string; + contract_code: string; + trigger_type: string; + volume: number; + order_type: number; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + relation_order_id: string; + order_price_type: string; + status: number; + order_source: string; + trigger_price: number | string; + triggered_price: number | string | null; + order_price: number | string; + created_at: number; + triggered_at: number | null; + order_insert_at: number; + canceled_at: number | null; + update_time: number; + fail_code: number | null; + fail_reason: string | null; + margin_mode: string; + margin_account: string; + reduce_only?: number; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; +} ⋮---- -/** Address tag. For UID withdraw, use recipient UID. */ +/** Cross margin only */ ⋮---- -/** Client order id for idempotency (max 32 char) */ +/** Trigger history orders response from getTriggerHistoryOrders, getCrossTriggerHistoryOrders */ +export type FuturesTriggerHistoryOrders = + FuturesPaginatedOrders; ⋮---- -/** Exchange VASP id from /v1/query/vasp-list */ +/** TP/SL order result; when only TP or only SL is set, the other is empty */ +export interface FuturesTpslOrderResult { + order_id: number | string; + order_id_str: string; +} ⋮---- -/** Recipient name for Korean/English: "SURNAME##FIRSTNAME" */ +/** TPSL order response data from swap_tpsl_order and swap_cross_tpsl_order. tp_order or sl_order empty when only the other is set */ +export interface FuturesTpslOrder { + tp_order?: FuturesTpslOrderResult; + sl_order?: FuturesTpslOrderResult; +} ⋮---- -/** Req for GET /v1/query/deposit-withdraw. Search deposit/withdraw records. */ -export interface SpotDepositWithdrawQueryReq { - /** Crypto currency. Omit for all. */ - currency?: string; - /** deposit or withdraw */ - type: 'deposit' | 'withdraw'; - /** Transfer id to begin search */ - from?: string; - /** Items to return [1-50]. Default 50. */ - size?: string; - /** prev (asc) or next (desc). Default next. */ - direct?: 'prev' | 'next'; +/** TPSL open order item from swap_tpsl_openorders and swap_cross_tpsl_openorders */ +export interface FuturesTpslOpenOrder { + symbol: string; + contract_code: string; + margin_mode: string; + margin_account: string; + volume: number; + order_type: number; + tpsl_order_type: string; + direction: string; + order_id: number | string; + order_id_str: string; + order_source: string; + trigger_type: string; + trigger_price: number | string; + price_protect?: boolean; + created_at: number; + order_price_type: string; + order_price: number | string; + status: number; + source_order_id: string | null; + relation_tpsl_order_id: string; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; } ⋮---- -/** Crypto currency. Omit for all. */ +/** Cross margin only */ ⋮---- -/** deposit or withdraw */ +/** TPSL open orders response from swap_tpsl_openorders and swap_cross_tpsl_openorders */ +export type FuturesTpslOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** Transfer id to begin search */ +/** TPSL history order item from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ +export interface FuturesTpslHisOrder { + symbol: string; + contract_code: string; + margin_mode: string; + margin_account: string; + volume: number; + order_type: number; + tpsl_order_type: string; + direction: string; + order_id: number | string; + order_id_str: string; + order_source: string; + trigger_type: string; + trigger_price: number | string; + price_protect?: boolean; + created_at: number; + order_price_type: string; + order_price: number | string; + status: number; + source_order_id: string | null; + relation_tpsl_order_id: string; + canceled_at: number | null; + fail_code: number | null; + fail_reason: string | null; + triggered_price: number | string | null; + relation_order_id: string; + update_time: number; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; +} ⋮---- -/** Items to return [1-50]. Default 50. */ +/** Cross margin only */ ⋮---- -/** prev (asc) or next (desc). Default next. */ +/** TPSL history orders response from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ +export type FuturesTpslHisOrders = FuturesPaginatedOrders; ⋮---- -/** Req for GET /v2/account/withdraw/address. Query withdraw address. */ -export interface SpotWithdrawAddressReq { - /** - * Crypto currency. - * Use "t247117" for universal address. - * Use "t397342" to query Poloniex UID withdraw addresses added on platform. - */ - currency?: string; - /** Block chain name. Omit for all chains. */ - chain?: string; - /** Note of withdraw address. Omit for all. */ - note?: string; - /** Items to return [1-500]. Default 100. */ - limit?: number; - /** First record ID for next page. */ - fromId?: number; +/** TPSL order info item within relation_tpsl_order response. getRelationTpslOrder, getCoinMDeliveryRelationTpslOrder, getCoinMPerpRelationTpslOrder. */ +export interface FuturesRelationTpslOrderTpslInfo { + volume: number; + tpsl_order_type: string; + direction: string; + order_id: number | string; + order_id_str: string; + trigger_type: string; + trigger_price: number | string; + created_at: number; + order_price: number | string; + status: number; + relation_tpsl_order_id: string; + relation_order_id: string; + order_price_type?: string; + price_protect?: boolean; + canceled_at: number | null; + fail_code: number | null; + fail_reason: string | null; + triggered_price: number | string | null; } ⋮---- -/** - * Crypto currency. - * Use "t247117" for universal address. - * Use "t397342" to query Poloniex UID withdraw addresses added on platform. - */ +/** Relation TPSL order from getRelationTpslOrder, getCoinMDeliveryRelationTpslOrder, getCoinMPerpRelationTpslOrder. Product-specific optional. */ +export interface FuturesRelationTpslOrder { + symbol: string; + contract_code: string; + volume: number; + price: number | string; + order_price_type: string; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + client_order_id: number | string | null; + created_at: number; + trade_volume: number; + trade_turnover: number | string; + fee: number | string; + trade_avg_price: number | string; + margin_frozen: number | string; + profit: number | string; + status: number; + order_type: number | null; + order_source: string; + fee_asset: string; + canceled_at: number; + tpsl_order_info: FuturesRelationTpslOrderTpslInfo[]; + /** USDM only */ + margin_mode?: string; + margin_account?: string; + /** CM Delivery: required; USDM/CM Perp: optional */ + contract_type?: string; + pair?: string; + business_type?: string; +} ⋮---- -/** Block chain name. Omit for all chains. */ +/** USDM only */ ⋮---- -/** Note of withdraw address. Omit for all. */ +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Items to return [1-500]. Default 100. */ +/** Trailing order open order item from swap_track_openorders and swap_cross_track_openorders */ +export interface FuturesTrackOpenOrder { + symbol: string; + contract_code: string; + volume: number; + order_type: number; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + order_source: string; + created_at: number; + order_price_type: string; + status: number; + callback_rate: number | string; + active_price: number | string; + is_active: number; + margin_mode: string; + margin_account: string; + reduce_only: number; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; +} ⋮---- -/** First record ID for next page. */ +/** Cross margin only */ ⋮---- -/** Req for POST /broker/v1/sub-user/fee_rate/add. Set sub-user trading fee rate. */ -export interface SpotBrokerSubUserFeeRateAddReq { - /** Sub-account ids, max 10 */ - subUids: number[]; - /** 0 all, 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ - bizType: number; - /** Type: 1 fixed (0.001-0.5), 2 percent (1-1000) */ - type: number; - /** Additional taker fee. Either taker or maker required. */ - taker?: string; - /** Additional maker fee. Either taker or maker required. */ - maker?: string; - /** YYYYMMDD effect date. Omit for T+1. */ - effectAt?: string; +/** Trailing open orders response data from swap_track_openorders and swap_cross_track_openorders */ +export type FuturesTrackOpenOrders = + FuturesPaginatedOrders; +⋮---- +/** Trailing order history item from swap_track_hisorders and swap_cross_track_hisorders */ +export interface FuturesTrackHisOrder { + symbol: string; + contract_code: string; + volume: number; + order_type: number; + direction: string; + offset: string; + lever_rate: number; + order_id: number | string; + order_id_str: string; + order_source: string; + created_at: number; + update_time: number; + order_price_type: string; + status: number; + canceled_at: number | null; + fail_code: number | null; + fail_reason: string | null; + callback_rate: number | string; + active_price: number | string; + is_active: number; + market_limit_price: number | string | null; + formula_price: number | string | null; + real_volume: number | string; + triggered_price: number | string | null; + relation_order_id: string; + margin_mode: string; + margin_account: string; + reduce_only: number; + /** Cross margin only */ + contract_type?: string; + pair?: string; + business_type?: string; } ⋮---- -/** Sub-account ids, max 10 */ +/** Cross margin only */ ⋮---- -/** 0 all, 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ +/** Trailing history orders response from swap_track_hisorders and swap_cross_track_hisorders */ +export type FuturesTrackHisOrders = + FuturesPaginatedOrders; ⋮---- -/** Type: 1 fixed (0.001-0.5), 2 percent (1-1000) */ +/** Cross swap item within unified_account_info */ +export interface FuturesUnifiedAccountCrossSwap { + symbol: string; + contract_code: string; + margin_mode: string; + margin_available: number | string; + cross_max_available?: number | string; + lever_rate: number | string; + contract_type: string; + business_type: string; +} ⋮---- -/** Additional taker fee. Either taker or maker required. */ +/** Cross futures item within unified_account_info */ +export interface FuturesUnifiedAccountCrossFuture { + symbol: string; + contract_code: string; + margin_mode: string; + margin_available: number | string; + cross_max_available?: number | string; + lever_rate: number | string; + contract_type: string; + business_type: string; +} ⋮---- -/** Additional maker fee. Either taker or maker required. */ +/** Isolated swap item within unified_account_info */ +export interface FuturesUnifiedAccountIsolatedSwap { + symbol: string; + contract_code: string; + margin_mode: string; + margin_available: number | string; + withdraw_available?: number | string; + lever_rate: number | string; + position_mode?: string; +} ⋮---- -/** YYYYMMDD effect date. Omit for T+1. */ +/** Unified account info item from unified_account_info */ +export interface FuturesUnifiedAccountInfo { + margin_balance: number | string; + margin_static: number | string; + cross_profit_unreal: number | string; + cross_margin_static: number | string; + margin_asset: string; + margin_frozen: number | string; + withdraw_available: number | string; + cross_risk_rate: number | string | null; + cross_swap: FuturesUnifiedAccountCrossSwap[]; + cross_future: FuturesUnifiedAccountCrossFuture[]; + isolated_swap: FuturesUnifiedAccountIsolatedSwap[]; + userId?: string | null; +} ⋮---- -/** Req for POST /broker/v1/account_capital_snapshot_everyday. Account asset snapshot. */ -export interface SpotBrokerAccountCapitalSnapshotReq { - /** Account type: spot, margin-api, super-margin-api, delivery, swap, linear */ - account_type: string; - /** Start time (ms). Omit with end_time for last 7 days. */ - start_time?: number; - /** End time (ms). Max 30 days from start. */ - end_time?: number; +/** Linear swap overview account info item from linear_swap_overview_account_info */ +export interface FuturesLinearSwapOverviewAccountInfo { + margin_asset: string; + margin_balance: number | string; + margin_available: number | string; } ⋮---- -/** Account type: spot, margin-api, super-margin-api, delivery, swap, linear */ +/** Fix position margin change record item from fix_position_margin_change_record */ +export interface FuturesFixPositionMarginChangeRecord { + query_id: number; + order_id: string; + amount: number | string; + asset: string; + symbol: string; + type: number; + direction: number; +} ⋮---- -/** Start time (ms). Omit with end_time for last 7 days. */ +/** Fix position margin change response data from fix_position_margin_change */ +export interface FuturesFixPositionMarginChange { + amount: number | string; + asset: string; + contract_code: string; + type: number; + direction: number; + order_id: string; + client_order_id: number | string | null; +} ⋮---- -/** End time (ms). Max 30 days from start. */ +/** + * USDT Margined Futures Multi Asset - Account (v5 API) + */ ⋮---- -/** Req for POST /v2/sub-user/tradable-market. Set tradable market for sub users. */ -export interface SpotSubUserTradableMarketReq { - /** Sub user UIDs, comma-separated, max 50 */ - subUids: string; - /** isolated-margin or cross-margin */ - accountType: 'isolated-margin' | 'cross-margin'; - /** activated or deactivated */ - activation: 'activated' | 'deactivated'; +/** Currency detail from /v5/account/balance */ +export interface FuturesV5AccountBalanceDetail { + currency: string; + equity: string; + isolated_equity: string; + available: string; + isolated_available?: string; + withdraw_available: string; + profit_unreal: string; + isolated_profit_unreal: string; + initial_margin: string; + maintenance_margin: string; + maintenance_margin_rate: string; + initial_margin_rate: string; + voucher: string; + voucher_value: string; + created_time: number; + updated_time: number; } ⋮---- -/** Sub user UIDs, comma-separated, max 50 */ +/** Account balance data from /v5/account/balance */ +export interface FuturesV5AccountBalance { + /** "normal" | "liquidating" | "adl" | "open_limit" */ + state: string; + equity: string; + initial_margin: string; + maintenance_margin: string; + maintenance_margin_rate: string; + profit_unreal: string; + available_margin: string; + voucher_value: string; + created_time: number; + updated_time: number; + details: FuturesV5AccountBalanceDetail[]; +} ⋮---- -/** isolated-margin or cross-margin */ +/** "normal" | "liquidating" | "adl" | "open_limit" */ ⋮---- -/** activated or deactivated */ +/** Set asset mode response data from POST /v5/account/asset_mode */ +export interface FuturesV5AssetMode { + /** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ + assets_mode: 0 | 1 | 2; +} ⋮---- -/** Req for setSubUserTransferPermissions. Set asset transfer permission. */ -export interface SpotSubUserTransferPermissionsReq { - /** Sub user UIDs, comma-separated, max 50 */ - subUids: string; - /** true or false */ - transferrable: boolean; - /** Account type. Default spot. */ - accountType?: 'spot'; +/** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ +⋮---- +/** Get asset mode response data from GET /v5/account/asset_mode */ +export interface FuturesV5AssetModeGet { + /** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ + asset_mode: 0 | 1 | 2; } ⋮---- -/** Sub user UIDs, comma-separated, max 50 */ +/** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ ⋮---- -/** true or false */ +/** Fee deduction crypto from /v5/account/fee_deduction_currency */ +export interface FuturesV5FeeDeductionCurrency { + /** 1: Yes; 0: No */ + fee_option: 0 | 1; + /** Deduction currency (e.g. htx, trx). Not returned when fee_option = 0 */ + deduction_currency?: string; +} ⋮---- -/** Account type. Default spot. */ +/** 1: Yes; 0: No */ ⋮---- -/** Req for POST /v1/subuser/transfer. Transfer asset between parent and sub account. */ -export interface SpotSubUserTransferReq { - /** Sub account UID */ - 'sub-uid': number; - /** Currency e.g. btc, usdt */ +/** Deduction currency (e.g. htx, trx). Not returned when fee_option = 0 */ +⋮---- +/** Financial record item from /v5/account/bills */ +export interface FuturesV5Bill { + id: string; + contract_code: string; + margin_mode: string; + /** + * Financial type code. + * 160: dividend settlement income. 161: dividend settlement expense. + */ + type: string; currency: string; - /** Amount to transfer */ amount: string; - /** master-transfer-in, master-transfer-out, master-point-transfer-in, master-point-transfer-out */ - type: - | 'master-transfer-in' - | 'master-transfer-out' - | 'master-point-transfer-in' - | 'master-point-transfer-out'; - /** Client order id for idempotency */ - 'client-order-id'?: string; + created_time: string; } ⋮---- -/** Sub account UID */ -⋮---- -/** Currency e.g. btc, usdt */ -⋮---- -/** Amount to transfer */ +/** + * Financial type code. + * 160: dividend settlement income. 161: dividend settlement expense. + */ ⋮---- -/** master-transfer-in, master-transfer-out, master-point-transfer-in, master-point-transfer-out */ +/** + * USDT Margined Futures Multi Asset - Orders (v5 API) + */ ⋮---- -/** Client order id for idempotency */ -⋮---- -/** Req for getSubUserDepositHistory. Query sub user deposit history. */ -export interface SpotSubUserDepositHistoryReq { - /** Sub user UID */ - subUid: number; - /** Crypto currency. Omit for all. */ - currency?: string; - /** Start time (ms). Default endTime - 30 days. */ - startTime?: number; - /** End time (ms). Default now. */ - endTime?: number; - /** asc or desc */ - sort?: 'asc' | 'desc'; - /** Items per page [1-500]. Default 100. */ - limit?: number; - /** First record ID for next page. */ - fromId?: number; +/** Place order response from POST /v5/trade/order */ +export interface FuturesV5PlaceOrderResp { + order_id: string; + client_order_id?: string; } ⋮---- -/** Sub user UID */ -⋮---- -/** Crypto currency. Omit for all. */ -⋮---- -/** Start time (ms). Default endTime - 30 days. */ -⋮---- -/** End time (ms). Default now. */ -⋮---- -/** asc or desc */ +/** Batch place order item from POST /v5/trade/batch_orders */ +export interface FuturesV5PlaceBatchOrderRespItem { + order_id: string; + client_order_id?: string; + code: number; + message: string; +} ⋮---- -/** Items per page [1-500]. Default 100. */ +/** Close position response from POST /v5/trade/position */ +export interface FuturesV5ClosePositionResp { + order_id: string | number; + client_order_id?: string; +} ⋮---- -/** First record ID for next page. */ +/** Open order / order info / order history item from v5 trade endpoints */ +export interface FuturesV5Order { + id: string; + contract_code: string; + contract_type?: string; + side: string; + position_side: string; + type: string; + price_match?: string | null; + order_id: string; + client_order_id: string; + margin_mode: string; + price?: string; + volume: string; + lever_rate?: number; + state: string | number; + order_source: string; + reduce_only?: boolean | string; + time_in_force: string; + tp_trigger_price?: string; + tp_order_price?: string; + tp_type?: string | null; + tp_trigger_price_type?: string | null; + sl_trigger_price?: string; + sl_order_price?: string; + sl_type?: string | null; + sl_trigger_price_type?: string | null; + trade_avg_price?: string; + trade_volume?: string; + trade_turnover?: string; + fee_currency?: string; + fee?: string; + profit?: string | null; + price_protect?: boolean | string; + cancel_reason?: string | null; + created_time?: string; + updated_time?: string; + self_match_prevent?: string; + cancel_volume?: string; +} ⋮---- -/** Req for GET /v2/sub-user/managed-transfer-history. Managed sub-account transfer history. */ -export interface SpotSubUserManagedTransferHistoryReq { - /** Sub user UID. Omit for all managed sub-accounts. */ - uid?: number; - /** Currency filter */ - currency?: string; - /** 0: master to sub, 1: sub to master */ +/** Execution/trade detail from GET /v5/trade/order/details */ +export interface FuturesV5OrderExecutionDetail { + id?: string; + contract_code?: string; + order_id?: string; + trade_id?: string; + side?: string; + position_side?: string; + order_type?: string; + margin_mode?: string; type?: string; - /** Start time (ms). Max 48h window, within 120 days. */ - startTime?: number; - /** End time (ms). */ - endTime?: number; - /** Search id to begin with. */ - from?: string; - /** next or prev. Default next. */ - direct?: 'next' | 'prev'; - /** Items to return [1-100]. Default 100. */ - size?: string; + client_order_id?: string; + role?: string; + trade_price?: string; + trade_volume?: string; + trade_turnover?: string; + created_time?: string; + updated_time?: string; + order_source?: string; + fee_currency?: string; + trade_fee?: string; + deduction_price?: string; + profit?: string; + contract_type?: string; } ⋮---- -/** Sub user UID. Omit for all managed sub-accounts. */ -⋮---- -/** Currency filter */ -⋮---- -/** 0: master to sub, 1: sub to master */ -⋮---- -/** Start time (ms). Max 48h window, within 120 days. */ -⋮---- -/** End time (ms). */ -⋮---- -/** Search id to begin with. */ +/** Cancel-after response from POST /v5/trade/cancel-after */ +export interface FuturesV5CancelAfterResp { + current_time: string; + trigger_time?: string; +} ⋮---- -/** next or prev. Default next. */ +/** Place algo order item from POST /v5/algo/order */ +export interface FuturesV5PlaceAlgoOrderResp { + algo_id: string; + algo_client_order_id?: string; +} ⋮---- -/** Items to return [1-100]. Default 100. */ +/** Cancel algo order item from POST /v5/algo/cancel_orders */ +export interface FuturesV5CancelAlgoOrderResp { + algo_id: string; + algo_client_order_id?: string; + code?: number; + message?: string; +} ⋮---- -/** Req for createSubUserApiKey. Create sub user API key. */ -export interface SpotSubUserApiKeyCreationReq { - /** Sub user UID */ - subUid: number; - /** Google OTP (6 digits) if parent has 2FA */ - otpToken?: string; - /** API key note, max 255 chars */ - note?: string; - /** readOnly, trade. readOnly required. Comma-separated. */ - permission?: string; - /** IP addresses, comma-separated, max 20 */ - ipAddresses?: string; +/** Algo order from GET /v5/algo/order, /opens, /history */ +export interface FuturesV5AlgoOrder { + id?: string | number; + algo_id: string; + algo_client_order_id?: string; + contract_code: string; + volume?: string; + type: string; + state: string; + position_side: string; + margin_mode: string; + side: string; + tp_trigger_price?: string; + tp_order_price?: string; + tp_type?: string; + tp_trigger_price_type?: string; + sl_trigger_price?: string; + sl_order_price?: string; + sl_type?: string; + sl_trigger_price_type?: string; + price?: string; + price_match?: string; + trigger_price?: string; + trigger_price_type?: string; + active_price?: string; + order_price_type?: string; + callback_rate?: string; + reduce_only?: boolean | string; + actual_volume?: string; + actual_price?: string; + actual_time?: string; + relation_order_id?: string; + created_time?: string; + updated_time?: string; + order_source?: string; } ⋮---- -/** Sub user UID */ +/** + * USDT Margined Futures Multi Asset - Positions (v5 API) + */ ⋮---- -/** Google OTP (6 digits) if parent has 2FA */ +/** Position from GET /v5/trade/position/opens */ +export interface FuturesV5Position { + contract_code: string; + position_side: string; + direction: string; + margin_mode: string; + open_avg_price: string; + volume: string; + available: string; + lever_rate: string | number; + adl_risk_percent?: number | null; + liquidation_price: string; + initial_margin: string; + maintenance_margin: string; + profit_unreal: string; + profit_rate: string; + margin_rate: string; + margin_currency: string; + last_price?: string; + mark_price?: string; + contract_type: string; + created_time: string; + updated_time: string; +} ⋮---- -/** API key note, max 255 chars */ +/** Leverage list entry from GET /v5/position/lever */ +export interface FuturesV5LeverListEntry { + contract_code: string; + contract_type: string; + margin_mode: string; + position_side: string; + lever_rate: number; + available_lever: string | string[]; +} ⋮---- -/** readOnly, trade. readOnly required. Comma-separated. */ +/** Set leverage response from POST /v5/position/lever */ +export interface FuturesV5SetLeverageResp { + contract_code: string; + margin_mode: string; + position_side?: string; + lever_rate: number; +} ⋮---- -/** IP addresses, comma-separated, max 20 */ +/** Position mode from GET/POST /v5/position/mode */ +export interface FuturesV5PositionModeResp { + position_mode: 'single_side' | 'dual_side'; +} ⋮---- -/** Req for updateSubUserApiKey. Modify sub user API key. */ -export interface SpotSubUserApiKeyUpdateReq { - /** Sub user UID */ - subUid: number; - /** Access key to modify */ - accessKey: string; - /** API key note, max 255 chars */ - note?: string; - /** readOnly, trade. Comma-separated. */ - permission?: string; - /** IP addresses, comma-separated, max 20 */ - ipAddresses?: string; +/** Risk limit entry from GET /v5/position/risk/limit */ +export interface FuturesV5RiskLimitEntry { + contract_code: string; + contract_type?: string; + margin_mode: string; + position_side: string; + max_lever: string; + maintenance_margin_rate: string; + max_volume: string; + min_volume: string; + volume_unit: string; } ⋮---- -/** Sub user UID */ -⋮---- -/** Access key to modify */ -⋮---- -/** API key note, max 255 chars */ +/** Risk limit tier entry from GET /v5/position/risk/limit_tier */ +export interface FuturesV5RiskLimitTierEntry { + contract_code: string; + margin_mode: string; + tier: number; + max_lever: string; + maintenance_margin_rate: string; + max_volume: string; + min_volume: string; + volume_unit: string; +} ⋮---- -/** readOnly, trade. Comma-separated. */ +/** + * USDT Margined Futures Multi Asset - Basic Information (v5 API) + */ ⋮---- -/** IP addresses, comma-separated, max 20 */ +/** Funding fee type on GET /v5/market/funding_rate_history */ +export type FuturesV5FundingFeeType = 'normal' | 'dividend_settlement'; ⋮---- -/** Req for GET /v2/account/ledger */ -export interface SpotGetAccountLedgerReq { - /** Account ID */ - accountId: string; - /** Currency. Default all. */ - currency?: string; - /** Transaction types, comma-separated. Phase 1: transfer only. */ - transactTypes?: string; - /** Start time (unix ms). Max 10-day window, within 180 days. */ - startTime?: number; - /** End time (unix ms). */ - endTime?: number; - /** Sort order: asc, desc. Deprecated. */ - sort?: string; - /** Max items [1-500]. Default 100. */ - limit?: number; - /** First record ID for pagination (next page) */ - fromId?: number; +/** Historical funding rate item from GET /v5/market/funding_rate_history */ +export interface FuturesV5FundingRateHistory { + id: string; + /** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ + contract_code: string; + funding_rate: string; + /** Funding time, unix ms */ + funding_time: string; + /** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ + funding_fee_type: FuturesV5FundingFeeType; } ⋮---- -/** Account ID */ -⋮---- -/** Currency. Default all. */ +/** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ ⋮---- -/** Transaction types, comma-separated. Phase 1: transfer only. */ +/** Funding time, unix ms */ ⋮---- -/** Start time (unix ms). Max 10-day window, within 180 days. */ +/** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ ⋮---- -/** End time (unix ms). */ +/** Risk limit entry from GET /v5/market/risk/limit */ +export interface FuturesV5MarketRiskLimitEntry { + contract_code: string; + margin_mode: string; + tier: number; + max_lever: string; + maintenance_margin_rate: string; + max_volume: string; + min_volume: string; + volume_unit?: string; +} ⋮---- -/** Sort order: asc, desc. Deprecated. */ +/** Assets deduction currency from GET /v5/market/assets_deduction_currency */ +export interface FuturesV5AssetsDeductionCurrencyResp { + currency: string[]; +} ⋮---- -/** Max items [1-500]. Default 100. */ +/** Multi-assets margin from GET /v5/market/multi_assets_margin */ +export interface FuturesV5MultiAssetsMarginResp { + multi_assets: string[]; +} ⋮---- -/** First record ID for pagination (next page) */ +/** + * Coin-M Delivery - Reference Data (FuturesCmDelivery) + */ ⋮---- -/** Req for GET /v2/invitee/rebate/history. Referral rebate history. */ -export interface SpotReferralRebateHistoryReq { - /** Invitee UID */ - inviteeUid: number; - /** Start date yyyy-MM-dd. Last 90 days. */ - startTime?: string; - /** End date yyyy-MM-dd. Last 90 days. */ - endTime?: string; - /** next or prev. Default prev. */ - direct?: 'next' | 'prev'; - /** Pagination cursor. Min query_id for prev, max for next. */ - fromId?: string; - /** Items per page, max 100. Default 100. */ - limit?: number; +/** Ladder item from contract_adjustfactor */ +export interface FuturesCmDeliveryAdjustFactorLadder { + ladder: number; + min_size: number; + max_size: number | null; + adjust_factor: number; } ⋮---- -/** Invitee UID */ +/** Lever item in adjust factor list */ +export interface FuturesCmDeliveryAdjustFactorLeverItem { + lever_rate: number; + ladders: FuturesCmDeliveryAdjustFactorLadder[]; +} ⋮---- -/** Start date yyyy-MM-dd. Last 90 days. */ +/** GET /api/v1/contract_adjustfactor */ +export interface FuturesCmDeliveryAdjustFactor { + symbol: string; + list: FuturesCmDeliveryAdjustFactorLeverItem[]; +} ⋮---- -/** End date yyyy-MM-dd. Last 90 days. */ +/** Tick from contract_his_open_interest */ +export interface FuturesCmDeliveryOpenInterestTick { + volume: string; + amount_type: number; + ts: number; +} ⋮---- -/** next or prev. Default prev. */ +/** GET /api/v1/contract_his_open_interest */ +export interface FuturesCmDeliveryOpenInterest { + symbol: string; + contract_type: string; + tick: FuturesCmDeliveryOpenInterestTick[]; +} ⋮---- -/** Pagination cursor. Min query_id for prev, max for next. */ +/** Ladder item from contract_ladder_margin */ +export interface FuturesCmDeliveryLadderMarginLadder { + min_margin_balance: number; + max_margin_balance: number | null; + min_margin_available: number; + max_margin_available: number | null; +} ⋮---- -/** Items per page, max 100. Default 100. */ +/** Lever item in ladder margin list */ +export interface FuturesCmDeliveryLadderMarginLeverItem { + lever_rate: number; + ladders: FuturesCmDeliveryLadderMarginLadder[]; +} ⋮---- -/** Req for GET /v2/invitee/rebate/all_rebate/detail. All rebate detail. */ -export interface SpotReferralAllRebateDetailReq { - /** next or prev. Default prev. */ - direct?: 'next' | 'prev'; - /** Pagination cursor. */ - fromId?: string; - /** Items per page, max 100. Default 100. */ - limit?: number; +/** GET /api/v1/contract_ladder_margin */ +export interface FuturesCmDeliveryLadderMargin { + symbol: string; + list: FuturesCmDeliveryLadderMarginLeverItem[]; } ⋮---- -/** next or prev. Default prev. */ +/** Ladder from GET /swap-api/v1/swap_adjustfactor */ +export interface FuturesCmPerpAdjustFactorLadder { + ladder: number; + min_size: number; + max_size: number | null; + adjust_factor: number; +} ⋮---- -/** Pagination cursor. */ +/** Lever item from swap_adjustfactor list */ +export interface FuturesCmPerpAdjustFactorLeverItem { + lever_rate: number; + ladders: FuturesCmPerpAdjustFactorLadder[]; +} ⋮---- -/** Items per page, max 100. Default 100. */ +/** GET /swap-api/v1/swap_adjustfactor */ +export interface FuturesCmPerpAdjustFactor { + symbol: string; + contract_code: string; + list: FuturesCmPerpAdjustFactorLeverItem[]; +} ⋮---- -/** Req for GET /v2/invitee/rebate/referrals. Invited user list. */ -export interface SpotReferralReferralsReq { - /** Invitee UIDs, comma-separated, max 50. */ - inviteeUidList?: string; - /** Referral code used at registration. */ - referralCode?: string; - /** Start date yyyy-MM-dd. Last 14 days. */ - startTime?: string; - /** End date yyyy-MM-dd. Last 14 days. */ - endTime?: string; - /** prev or next. Default next. */ - direct?: 'prev' | 'next'; - /** Pagination cursor. */ - fromId?: string; - /** Items per page, max 100. Default 30. */ - limit?: number; +/** Tick from GET /swap-api/v1/swap_his_open_interest */ +export interface FuturesCmPerpOpenInterestTick { + volume: number; + amount_type: number; + ts: number; } ⋮---- -/** Invitee UIDs, comma-separated, max 50. */ +/** GET /swap-api/v1/swap_his_open_interest */ +export interface FuturesCmPerpOpenInterest { + symbol: string; + contract_code: string; + tick: FuturesCmPerpOpenInterestTick[]; +} ⋮---- -/** Referral code used at registration. */ +/** Ladder from GET /swap-api/v1/swap_ladder_margin */ +export interface FuturesCmPerpTieredMarginLadder { + min_margin_balance: number; + max_margin_balance: number | null; + min_margin_available: number; + max_margin_available: number | null; +} ⋮---- -/** Start date yyyy-MM-dd. Last 14 days. */ +/** Lever item from swap_ladder_margin list */ +export interface FuturesCmPerpTieredMarginLeverItem { + lever_rate: number; + ladders: FuturesCmPerpTieredMarginLadder[]; +} ⋮---- -/** End date yyyy-MM-dd. Last 14 days. */ +/** GET /swap-api/v1/swap_ladder_margin */ +export interface FuturesCmPerpTieredMargin { + symbol: string; + contract_code: string; + list: FuturesCmPerpTieredMarginLeverItem[]; +} ⋮---- -/** prev or next. Default next. */ +/** List item from GET /swap-api/v1/swap_elite_account_ratio */ +export interface FuturesCmPerpAccountRatioItem { + buy_ratio: number; + sell_ratio: number; + locked_ratio: number; + ts: number; +} ⋮---- -/** Pagination cursor. */ -⋮---- -/** Items per page, max 100. Default 30. */ -⋮---- -/** Req for GET /v1/api/c2c/order/history. P2P order history. */ -export interface SpotP2POrderHistoryReq { - /** 0: buy, 1: sell */ - side?: string; - /** Start time (ms). Last 90 days. */ - startTime?: number; - /** End time (ms). Last 90 days. */ - endTime?: number; - /** next or prev. Default prev. */ - direct?: 'next' | 'prev'; - /** Pagination cursor. Min query_id for prev, max for next. */ - fromId?: number; - /** Items per page, max 100. Default 100. */ - limit?: number; +/** GET /swap-api/v1/swap_elite_account_ratio */ +export interface FuturesCmPerpAccountRatio { + symbol: string; + contract_code: string; + list: FuturesCmPerpAccountRatioItem[]; } ⋮---- -/** 0: buy, 1: sell */ -⋮---- -/** Start time (ms). Last 90 days. */ -⋮---- -/** End time (ms). Last 90 days. */ -⋮---- -/** next or prev. Default prev. */ -⋮---- -/** Pagination cursor. Min query_id for prev, max for next. */ -⋮---- -/** Items per page, max 100. Default 100. */ +/** List item from GET /swap-api/v1/swap_elite_position_ratio */ +export interface FuturesCmPerpPositionRatioItem { + buy_ratio: number; + sell_ratio: number; + ts: number; +} ⋮---- -/** Req for GET /v1/earn/project/queryEarnProjectList. Earn product query. */ -export interface SpotEarnProjectListReq { - /** Crypto currency filter */ - currency?: string; - /** Page number. Default 1. */ - pageNum: number; - /** Items per page, max 100. Default 10. */ - pageSize: number; +/** GET /swap-api/v1/swap_elite_position_ratio */ +export interface FuturesCmPerpPositionRatio { + symbol: string; + contract_code: string; + list: FuturesCmPerpPositionRatioItem[]; } ⋮---- -/** Crypto currency filter */ +/** Item from GET /swap-api/v1/swap_estimated_settlement_price data[] */ +export interface FuturesCmPerpEstimatedSettlementPrice { + contract_code: string; + estimated_settlement_price: number | null; + settlement_type: 'delivery' | 'settlement'; +} ⋮---- -/** Page number. Default 1. */ +/** GET /swap-api/v1/swap_api_state */ +export interface FuturesCmPerpSystemStatus { + symbol: string; + contract_code: string; + open: number; + close: number; + cancel: number; + transfer_in: number; + transfer_out: number; + master_transfer_sub: number; + sub_transfer_master: number; +} ⋮---- -/** Items per page, max 100. Default 10. */ +/** GET /swap-api/v1/swap_funding_rate */ +export interface FuturesCmPerpFundingRate { + symbol: string; + contract_code: string; + fee_asset: string; + funding_time: string; + funding_rate: string; + estimated_rate: string | null; + next_funding_time: string | null; +} ⋮---- -/** Req for POST /v1/earn/order/demand/add. Earn subscription. */ -export interface SpotEarnSubscribeReq { - /** Project ID */ - id: number; - /** Subscription amount */ - amount: string; - /** Idempotent ID (e.g. Snowflake). */ - requestId: string; +/** Item from GET /swap-api/v1/swap_historical_funding_rate data[] */ +export interface FuturesCmPerpHistoricalFundingRate { + symbol: string; + contract_code: string; + fee_asset: string; + funding_time: string; + funding_rate: string; + /** Deprecated, default null */ + realized_rate?: string | null; + avg_premium_index: string; } ⋮---- -/** Project ID */ +/** Deprecated, default null */ ⋮---- -/** Subscription amount */ +/** Paginated wrapper for GET /swap-api/v1/swap_historical_funding_rate */ +export type FuturesCmPerpHistoricalFundingRatePage = + FuturesPaginatedData; ⋮---- -/** Idempotent ID (e.g. Snowflake). */ +/** Item from GET /swap-api/v3/swap_liquidation_orders data[] */ +export interface FuturesCmPerpLiquidationOrder { + query_id?: number; + contract_code: string; + symbol: string; + direction: string; + offset: string; + volume: number; + price: number; + created_at: number; + amount: number; +} ⋮---- -/** Req for POST /v1/earn/order/demand/redeem-order. Earn redemption. */ -export interface SpotEarnRedeemReq { - /** Order ID */ - orderId: number; - /** Redemption amount */ - amount: string; - /** Idempotent ID (e.g. Snowflake). */ - requestId?: string; +/** Item from GET /swap-api/v1/swap_settlement_records settlement_record[] */ +export interface FuturesCmPerpSettlementRecord { + symbol: string; + contract_code: string; + settlement_time: number; + clawback_ratio: number; + settlement_price: number; + settlement_type: string; } ⋮---- -/** Order ID */ +/** Paginated wrapper for GET /swap-api/v1/swap_settlement_records */ +export type FuturesCmPerpSettlementRecordsPage = + FuturesPaginatedSettlement; ⋮---- -/** Redemption amount */ +/** Index constituents from GET /swap-api/market/swap_constituents. data is object. */ +export interface FuturesCmPerpIndexConstituents { + contract_code: string; + ts: number; + index_price: string; + components: FuturesIndexConstituentComponent[]; +} ⋮---- -/** Idempotent ID (e.g. Snowflake). */ +/** Item from GET /swap-api/v1/swap_contract_info data[] */ +export interface FuturesCmPerpContractInfo { + symbol: string; + contract_code: string; + contract_size: number; + price_tick: number; + settlement_date: string; + settlement_period: string; + create_date: string; + delivery_time: string; + contract_status: number; + labels?: string[]; +} ⋮---- -/** Req for GET /v1/earn/order/user/assets/list. Earn position query. */ -export interface SpotEarnUserAssetsReq { - /** Project type: 0 = Flexible */ - projectType?: number; - /** Crypto currency filter */ - currency?: string; - /** Page number. Default 1. */ - pageNum: number; - /** Items per page, max 100. Default 10. */ - pageSize: number; +/** Item from GET /swap-api/v1/swap_open_interest data[] */ +export interface FuturesCmPerpOpenInterestCurrent { + symbol: string; + contract_code: string; + volume: number; + amount: number; + trade_amount: number; + trade_volume: number; + trade_turnover: number; } ⋮---- -/** Project type: 0 = Flexible */ +/** contract_infos[] item from GET /swap-api/v1/swap_query_elements */ +export interface FuturesCmPerpContractElementsContractInfo { + contract_code: string; + settlement_date: string; + /** Empty string when no delivery */ + delivery_time: string; + create_date: string; + contract_status: number; + instrument_type?: number; +} ⋮---- -/** Crypto currency filter */ +/** Empty string when no delivery */ ⋮---- -/** Page number. Default 1. */ +/** Market depth tick from GET /swap-ex/market/depth. Payload in "tick". */ +export interface FuturesCmPerpMarketDepth { + mrid: number; + id: number; + asks: [number, number][]; + bids: [number, number][]; + ts: number; + version: number; + ch: string; +} ⋮---- -/** Items per page, max 100. Default 10. */ +/** BBO tick from GET /swap-ex/market/bbo. ask/bid: [price, qty]. Payload in "ticks". */ +export interface FuturesCmPerpMarketBbo { + contract_code: string; + mrid: number; + ask: [number, number]; + bid: [number, number]; + ts: number; +} ⋮---- -/** Account type for POST /v5/account/universal_transfer */ -export type SpotUniversalTransferAccountType = - | 'otc' - | 'spot' - | 'linear-swap' - | 'futures' - | 'swap' - | 'margin' - | 'super-margin' - | 'otc-options'; +/** Kline item from GET /swap-ex/market/history/kline */ +export interface FuturesCmPerpKline { + id: number; + vol: number; + count: number; + open: number; + close: number; + low: number; + high: number; + amount: number; +} ⋮---- -/** Req for POST /v5/account/universal_transfer. Create universal transfer. */ -export interface SpotUniversalTransferReq { - amount: number | string; - currency: string; - from_account_type: SpotUniversalTransferAccountType; - to_account_type: SpotUniversalTransferAccountType; - from_asset_type?: string; - to_asset_type?: string; +/** Mark price kline item from GET /index/market/history/swap_mark_price_kline */ +export interface FuturesCmPerpMarkPriceKline { + id: number; + vol: string; + count: string; + open: string; + close: string; + low: string; + high: string; + amount: string; + trade_turnover: string; } ⋮---- -/** Req for GET /v5/account/universal_transfer_records. Universal transfer history. */ -export interface SpotUniversalTransferRecordsReq { - transfer_id?: number | string; - currency?: string; - status?: 'success' | 'pending' | 'failed'; - start_time?: number; - end_time?: number; - from?: number; - limit?: number; - direct?: 'prev' | 'next'; +/** 24h ticker from GET /swap-ex/market/detail/merged. Payload in "tick". */ +export interface FuturesCmPerp24hTicker { + id: number; + ts: number; + vol: string; + count: number; + open: string; + close: string; + low: string; + high: string; + amount: string; + ask: [number, number]; + bid: [number, number]; } - -================ -File: src/lib/requestUtils.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -⋮---- -import { - OrderIdProperty, - SpotOrderIdProperty, -} from '../types/response/shared.types.js'; -import { - HTXWSAPIRequest, - WSAPIDerivativesOperation, - WSAPISpotOperation, -} from '../types/websockets/ws-api.js'; -import { - isDerivativesWSAPIRequest, - isSpotWSAPIRequest, -} from './websocket/type-guards.js'; -import { WS_KEY_MAP, WsKey } from './websocket/websocket-util.js'; -⋮---- -/** - * Used to switch how authentication/requests work under the hood - */ -⋮---- -/** Spot */ ⋮---- -/** Spot AWS */ -⋮---- -/** - * Futures Cloudflare CDN (default for futures clients) - */ -⋮---- -/** - * Futures - * - * If you can't connect "https://api.hbdm.com", please use "https://api.btcgateway.pro" for debug purpose. If your server is deployed in AWS, we recommend using "https://api.hbdm.vn". - */ -⋮---- -/** - * Futures AWS CDN - */ +/** 24h ticker item from GET /v2/swap-ex/market/detail/batch_merged */ +export interface FuturesCmPerp24hTickers { + contract_code: string; + id: number; + ts: number; + amount: string; + count: number; + vol: string; + number_of: string; + open: string; + close: string; + low: string; + high: string; + ask: [number, number]; + bid: [number, number]; +} ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +/** Trade item from GET /swap-ex/market/trade and history/trade */ +export interface FuturesCmPerpTrade { + id: number; + price: string; + amount: string; + direction: string; + ts: number; + quantity: string; + contract_code?: string; +} ⋮---- -[REST_CLIENT_TYPE_ENUM.futures]: 'https://api.hbdm.com', // Cloudflare's CDN -// If you can't connect "https://api.hbdm.com", please use "https://api.btcgateway.pro" for debug purpose. If your server is deployed in AWS, HTX recommend using "https://api.hbdm.vn". +/** Last trade tick from GET /swap-ex/market/trade. Payload in "tick". */ +export interface FuturesCmPerpLastTrade { + id: number; + ts: number; + data: FuturesCmPerpTrade[]; +} ⋮---- -[REST_CLIENT_TYPE_ENUM.futuresAWS]: 'https://api.hbdm.vn', // AWS's CDN +/** Trade history group from GET /swap-ex/market/history/trade. Each group has trades by timestamp. */ +export interface FuturesCmPerpTradeHistory { + id: number; + ts: number; + data: FuturesCmPerpTrade[]; +} ⋮---- -export interface RestClientOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - /** - * Use access token instead of sign, if this is provided. - * For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2 - */ - apiAccessToken?: string; - - /** Default: false. If true, we'll throw errors if any params are undefined */ - strictParamValidation?: boolean; - - /** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.huobi.pro' - **/ - baseUrl?: string; - - /** - * Advanced: force a specific base URL. - * - For AWS deployments, use REST_CLIENT_TYPE_ENUM.spotAWS for spot or REST_CLIENT_TYPE_ENUM.futuresAWS for futures. - * - If you can't connect to the default futures endpoint (Cloudflare's CDN), you can use REST_CLIENT_TYPE_ENUM.futuresAlt1 to connect to the alternative endpoint (btcgateway.pro). https://www.htx.com/en-us/opend/newApiPages/?id=707 - */ - baseUrlKey?: RestClientType; - - /** Default: true. whether to try and post-process request exceptions (and throw them). */ - parseExceptions?: boolean; - - customTimestampFn?: () => number; - - /** - * Enable keep alive for REST API requests (via axios). - */ - keepAlive?: boolean; - - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) - */ - keepAliveMsecs?: number; - - /** - * 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; +/** Estimated funding rate kline item from GET /index/market/history/swap_estimated_rate_kline */ +export interface FuturesCmPerpFundingRateKline { + id: number; + vol: string; + count: string; + open: string; + close: string; + low: string; + high: string; + amount: string; } ⋮---- -/** Your API key */ +/** Premium index kline item from GET /index/market/history/swap_premium_index_kline */ +export interface FuturesCmPerpPremiumIndexKline { + id: number; + vol: string; + count: string; + open: string; + close: string; + low: string; + high: string; + amount: string; +} ⋮---- -/** Your API secret */ +/** Basis data item from GET /index/market/history/swap_basis */ +export interface FuturesCmPerpBasisData { + id: number; + contract_price: string; + index_price: string; + basis: string; + basis_rate: string; +} ⋮---- -/** - * Use access token instead of sign, if this is provided. - * For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2 - */ +/** Account info from POST /swap-api/v1/swap_account_info */ +export interface FuturesCmPerpAccountInfo { + symbol: string; + contract_code: string; + margin_balance: number; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_real?: number; + profit_unreal: number; + risk_rate: number | null; + new_risk_rate?: string | null; + trade_partition?: string; + withdraw_available: number; + liquidation_price: number | null; + lever_rate: number; + adjust_factor: number; + margin_static: number; +} ⋮---- -/** Default: false. If true, we'll throw errors if any params are undefined */ +/** Position info from POST /swap-api/v1/swap_position_info */ +export interface FuturesCmPerpPositionInfo { + symbol: string; + contract_code: string; + volume: number; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; + profit: number; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; + adl_risk_percent?: string | number; + liq_px: string; + new_risk_rate?: string | null; + trade_partition?: string; +} ⋮---- -/** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.huobi.pro' - **/ +/** Position item in getCoinMPerpAccountFull positions[] */ +export interface FuturesCmPerpAccountFullPosition { + symbol: string; + contract_code: string; + volume: number; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; + profit: number; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; + adl_risk_percent?: string | number; +} ⋮---- -/** - * Advanced: force a specific base URL. - * - For AWS deployments, use REST_CLIENT_TYPE_ENUM.spotAWS for spot or REST_CLIENT_TYPE_ENUM.futuresAWS for futures. - * - If you can't connect to the default futures endpoint (Cloudflare's CDN), you can use REST_CLIENT_TYPE_ENUM.futuresAlt1 to connect to the alternative endpoint (btcgateway.pro). https://www.htx.com/en-us/opend/newApiPages/?id=707 - */ +/** Account + positions from getCoinMPerpAccountFull */ +/** Account + positions from getCoinMPerpAccountFull */ +export interface FuturesCmPerpAccountFull { + symbol: string; + contract_code: string; + margin_balance: number; + margin_static: number; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_real?: number; + profit_unreal: number; + risk_rate: number | null; + withdraw_available: number; + liquidation_price: number | null; + lever_rate: number; + adjust_factor: number; + new_risk_rate?: string | null; + trade_partition?: string; + positions: FuturesCmPerpAccountFullPosition[]; +} ⋮---- -/** Default: true. whether to try and post-process request exceptions (and throw them). */ +/** Sub-auth error from swap_sub_auth and swap_sub_auth_list */ +export interface FuturesCmPerpSubPermissionsError { + sub_uid: string; + err_code: number | string; + err_msg: string; +} ⋮---- -/** - * Enable keep alive for REST API requests (via axios). - */ +/** Sub-auth response from updateCoinMPerpSubPermissions */ +export interface FuturesCmPerpUpdateSubPermissions { + errors: FuturesCmPerpSubPermissionsError[]; + successes: string; +} ⋮---- -/** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) - */ +/** Sub-auth success item from swap_sub_auth_list */ +export interface FuturesCmPerpSubPermissionsSuccess { + query_id?: number; + sub_uid: string; + sub_auth: number | 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. - */ +/** Sub-auth list from getCoinMPerpSubPermissions */ +export interface FuturesCmPerpSubPermissions { + errors: FuturesCmPerpSubPermissionsError[]; + successes: FuturesCmPerpSubPermissionsSuccess[]; +} ⋮---- -export type GenericAPIResponse = Promise; +/** Sub-account list item from getCoinMPerpSubAccounts list[] */ +export interface FuturesCmPerpSubAccountsItem { + symbol: string; + contract_code: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | null; + query_id?: number; +} ⋮---- -export function serializeParams< - T extends Record | undefined = object, ->( - params: T, - strict_validation: boolean | undefined, - encodeValues: boolean, - prefixWith: string, - repeatArrayValuesAsKVPairs: boolean, -): string +/** Sub-account entry from getCoinMPerpSubAccounts (data array element) */ +export interface FuturesCmPerpSubAccounts { + sub_uid: number; + list: FuturesCmPerpSubAccountsItem[]; +} ⋮---- -// Only prefix if there's a value +/** Account info item from getCoinMPerpSubAccountsAssets account_info_list[] */ +export interface FuturesCmPerpSubAccountsAssetsAccount { + symbol: string; + contract_code: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | null; +} ⋮---- -export function logInvalidOrderId( - orderIdProperty: SpotOrderIdProperty, - expectedOrderIdPrefix: string, - params: object, -) +/** Sub-list item from getCoinMPerpSubAccountsAssets sub_list[] */ +export interface FuturesCmPerpSubAccountsAssetsSub { + sub_uid: number; + account_info_list: FuturesCmPerpSubAccountsAssetsAccount[]; +} ⋮---- -function getWSAPICustomOrderIdProperties( - operation: WSAPISpotOperation | string, - wsKey: WsKey, -): OrderIdProperty[] +/** Response from getCoinMPerpSubAccounts */ +export type FuturesCmPerpSubAccountsAssets = + FuturesPaginatedSubList; ⋮---- -function isOrderParamRecord(value: unknown): value is Record +/** Sub-account account info from getCoinMPerpSubAccountAssets (data array element) */ +export interface FuturesCmPerpSubAccountAssets { + symbol: string; + contract_code: string; + margin_balance: number; + margin_position: number; + margin_frozen: number; + margin_available: number; + profit_real?: number; + profit_unreal: number; + risk_rate: number | null; + liquidation_price: number | null; + withdraw_available: number; + lever_rate: number; + adjust_factor: number; + margin_static: number; + new_risk_rate?: string | null; + trade_partition?: string; +} ⋮---- -function getOrderParamRecords(params: unknown): Record[] +/** Sub-account position from getCoinMPerpSubPositions (data array element) */ +export interface FuturesCmPerpSubPositions { + symbol: string; + contract_code: string; + volume: number; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; + profit: number; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; + adl_risk_percent?: string | number; + liq_px: string; + new_risk_rate?: string | null; + trade_partition?: string; +} ⋮---- -export function requiresWSAPINewCustomOID( - request: HTXWSAPIRequest, - wsKey: WsKey, -): boolean +/** Financial record from POST /swap-api/v3/swap_financial_record and swap_financial_record_exact */ +export interface FuturesCmPerpFinancialRecord { + query_id: number; + id: number | string; + ts: number; + symbol: string; + contract_code: string; + type: number; + amount: number | string; +} ⋮---- -export function validateWSAPICustomOrderID( - request: HTXWSAPIRequest, - wsKey: WsKey, -): void +/** Available leverage from getCoinMPerpAvailableLeverage */ +export interface FuturesCmPerpAvailableLeverage { + contract_code: string; + available_level_rate: string; +} ⋮---- -function isDerivativesWSAPIOrderPlacementOperation( - operation: WSAPIDerivativesOperation | string, -): boolean +/** Order limit list item from swap_order_limit list[] */ +export interface FuturesCmPerpOrderLimitList { + symbol: string; + contract_code: string; + open_limit: number; + close_limit: number; +} ⋮---- -export function validateWSAPIDerivativesChannelKey( - request: HTXWSAPIRequest, - wsKey: WsKey, -): void +/** Order limit from POST /swap-api/v1/swap_order_limit */ +export interface FuturesCmPerpOrderLimit { + order_price_type: string; + list: FuturesCmPerpOrderLimitList[]; +} ⋮---- -export function isEmptyObject(obj: any, acceptStringIfNotEmpty: boolean) +/** Fee from POST /swap-api/v1/swap_fee */ +export interface FuturesCmPerpFee { + symbol: string; + contract_code: string; + open_maker_fee: string; + open_taker_fee: string; + close_maker_fee: string; + close_taker_fee: string; + fee_asset: string; + delivery_fee?: string; +} ⋮---- -export function getRestBaseUrl( - restClientOptions: RestClientOptions, - restClientType: RestClientType, -): string +/** Transfer limit from POST /swap-api/v1/swap_transfer_limit */ +export interface FuturesCmPerpTransferLimit { + symbol: string; + contract_code: string; + transfer_in_max_each: number; + transfer_in_min_each: number; + transfer_out_max_each: number; + transfer_out_min_each: number; + transfer_in_max_daily: number; + transfer_out_max_daily: number; + net_transfer_in_max_daily: number; + net_transfer_out_max_daily: number; +} ⋮---- -/** - * Iterates to extract pure domain from URL. - * https://example.com/v1/endpoint -> example.com - */ -export function getBaseDomain(url: string): string +/** Position limit from POST /swap-api/v1/swap_position_limit */ +export interface FuturesCmPerpPositionLimit { + symbol: string; + contract_code: string; + buy_limit: number; + sell_limit: number; +} ⋮---- -export function generateNewOrderID(): string +/** API trading status COR from getCoinMPerpApiStatus */ +export interface FuturesCmPerpApiStatusCor { + orders_threshold: number; + orders: number; + invalid_cancel_orders: number; + cancel_ratio_threshold: number; + cancel_ratio: number; + is_trigger: number; + is_active: number; +} ⋮---- -export function getOrderIdPrefix(): string - -================ -File: README.md -================ -# Node.js & JavaScript SDK for HTX REST APIs & WebSockets - -[![Build & Test](https://github.com/sieblyio/htx-api/actions/workflows/e2etest.yml/badge.svg?branch=main)](https://github.com/sieblyio/htx-api/actions/workflows/e2etest.yml) -[![npm version](https://img.shields.io/npm/v/%40siebly%2Fhtx-api)][1] -[![npm size](https://img.shields.io/bundlephobia/min/%40siebly%2Fhtx-api/latest)][1] -[![npm downloads](https://img.shields.io/npm/dt/%40siebly%2Fhtx-api)][1] -[![last commit](https://img.shields.io/github/last-commit/sieblyio/htx-api)][1] -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) -[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/sieblyio/htx-api) - -

- - - - SDK Logo - - -

- -[1]: https://www.npmjs.com/package/@siebly/htx-api - -Complete & robust JavaScript & Node.js SDK for the HTX REST APIs and WebSockets: - -- Professional, robust & complete HTX SDK for all JavaScript runtimes. -- Complete integration with HTX REST APIs and WebSockets. - - Dedicated REST clients for Spot and Derivatives (linear swap, coin swap, delivery futures) - - Unified WebSocket client for all markets -- Complete TypeScript support (with type declarations for most API requests & responses). - - Strongly typed requests and responses. - - Automated end-to-end tests ensuring reliability. -- Actively maintained with a modern, promise-driven interface. -- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. - - Event driven messaging. - - Smart WebSocket persistence with automatic reconnection handling. - - Emit `reconnected` event when dropped connection is restored. - - Support for both public and private WebSocket streams. -- Portable HMAC signing support for trusted server-side runtimes. -- Automatically supports both ESM and CJS projects. -- Heavy automated end-to-end testing with real API calls. -- Proxy support via axios integration. -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). -- Looking to get started as soon as possible? Review our [HTX JavaScript QuickStart Guide](https://siebly.io/sdk/htx/javascript) on our website. -- Looking to learn about all product groups & features? Review our [HTX JavaScript Tutorial](https://siebly.io/sdk/htx/javascript/tutorial) on our website. - -## Table of Contents - -- [Installation](#installation) -- [Why not raw ws?](#why-not-raw-ws) -- [Examples](#examples) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation](#documentation) -- [Structure](#structure) -- [Usage](#usage) - - [REST API Clients](#rest-api) - - [Spot Trading](#spot-trading) - - [Derivatives (Futures) Trading](#derivatives-futures-trading) - - [WebSockets](#websockets) - - [Public WebSocket Streams](#public-websocket-streams) - - [Private WebSocket Streams](#private-websocket-streams) - - [WebSocket API (WebsocketAPIClient)](#websocket-api-websocketapiclient) -- [Customise Logging](#customise-logging) -- [Browser/Frontend Usage](#browserfrontend-usage) - - [React and Vite](#react-and-vite) - - [Webpack](#webpack) - - [Browser Requirements](#browser-requirements) - - [Security and CORS](#security-and-cors) -- [LLMs & AI](#use-with-llms--ai) -- [Used By](#used-by) -- [Contributions & Thanks](#contributions--thanks) - -## Installation - -```bash -npm install --save @siebly/htx-api -``` - -Install **`@siebly/htx-api`**. That is the package name for this SDK. The unscoped npm package `htx-api` is a different package (a stale 0.0.9 pre-release). - -Node.js usage requires Node 22.13.0 or newer. Browser applications should follow the public-data and credential-safety guidance below. - -## Why not raw ws? - -A raw `ws` socket still has to gzip-decode HTX frames, answer ping/pong, sign private auth, reconnect, and resubscribe. `WebsocketClient` does that and emits typed events. - -```javascript -import { WebsocketClient, WS_KEY_MAP } from '@siebly/htx-api'; -const ws = new WebsocketClient(); -ws.subscribe('market.btcusdt.ticker', WS_KEY_MAP.spotPublic); -``` - -## Examples - -Refer to the [examples](./examples) folder for implementation demos, including: - -- **Spot WebSocket Examples**: public and private market/account streams -- **Derivatives WebSocket Examples**: linear swap, coin swap, delivery futures, and index streams - -## Issues & Discussion - -- Issues? Check the [issues tab](https://github.com/sieblyio/htx-api/issues). -- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. -- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) - - - -## Related Projects - -Check out our JavaScript/TypeScript/Node.js SDKs & Projects: - -- Visit our website: [https://Siebly.io](https://siebly.io/) -- Try our REST API & WebSocket SDKs published on npmjs: - - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) - - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) - - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) - - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) - - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) - - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) - - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) - - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) - - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) -- Try my misc utilities: - - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) -- Check out my examples: - - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) - - -## Documentation - -Most methods accept JS objects. These can be populated using parameters specified by HTX's API documentation, or check the type definition in each class within this repository. - -### API Documentation Links - -- [HTX API Documentation](https://www.htx.com/en-us/opend/newApiPages/) - - [Spot Trading API](https://www.htx.com/en-us/opend/newApiPages/) - - [Derivatives Trading API](https://www.htx.com/en-us/opend/newApiPages/) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) - -## Structure - -This project uses typescript. Resources are stored in 2 key structures: - -- [src](./src) - the whole connector written in typescript -- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! - ---- - -# Usage - -Create API credentials on HTX's website: - -- [HTX API Key Management](https://www.htx.com/apikey/) - -## REST API - -The SDK provides dedicated REST clients for different trading products: - -- **SpotClient** - for spot trading, margin, earn, sub-accounts, and account operations -- **FuturesClient** - for linear swap, coin swap, delivery futures, and copy trading operations - -Both clients default to HTX's AWS CDN domains for better connectivity. You can override this via `baseUrlKey` in the client options if needed. - -### Spot Trading - -To use HTX's Spot APIs, import (or require) the `SpotClient`: - -```javascript -import { SpotClient } from '@siebly/htx-api'; -// or if you prefer require: -// const { SpotClient } = require('@siebly/htx-api'); - -// For public endpoints, API credentials are optional -const publicClient = new SpotClient(); - -// For private endpoints, provide API credentials -const client = new SpotClient({ - apiKey: 'your-api-key', - apiSecret: 'your-api-secret', -}); - -// Public API Examples - -// Get ticker information -const ticker = await publicClient.getTicker({ - symbol: 'btcusdt', -}); -console.log('Ticker: ', ticker); - -// Get order book -const orderBook = await publicClient.getMarketDepth({ - symbol: 'btcusdt', - depth: 10, -}); -console.log('Order Book: ', orderBook); - -// Private API Examples (requires authentication) - -// Get accounts and balances -client - .getAccounts() - .then(async (accounts) => { - console.log('Accounts: ', accounts); - - const accountId = accounts.data?.[0]?.id; - if (accountId) { - const balance = await client.getAccountBalance({ accountId }); - console.log('Account Balance: ', balance); - } - }) - .catch((err) => { - console.error('Error: ', err); - }); - -// Submit a limit order -client - .submitOrder({ - 'account-id': 'your-account-id', // Retrievable via getAccounts() as shown above - symbol: 'btcusdt', - type: 'buy-limit', - amount: '0.0001', - price: '10000', - 'client-order-id': client.generateNewOrderID(), - }) - .then((result) => { - console.log('Limit Order Result: ', result); - }) - .catch((err) => { - console.error('Error: ', err); - }); - -// Submit batch of orders (max 10 per batch) -client - .submitBatchOrders([ - { - 'account-id': 'your-account-id', // Retrievable via getAccounts() as shown above - symbol: 'btcusdt', - type: 'buy-limit', - amount: '0.0001', - price: '10000.00', - 'client-order-id': client.generateNewOrderID(), - }, - { - 'account-id': 'your-account-id', - symbol: 'btcusdt', - type: 'sell-limit', - amount: '0.0001', - price: '13000.00', - 'client-order-id': client.generateNewOrderID(), - }, - ]) - .then((result) => { - console.log('Batch Order Result: ', JSON.stringify(result, null, 2)); - }) - .catch((err) => { - console.error('Error: ', err); - }); -``` - -See [SpotClient](./src/SpotClient.ts) for further information. - -### Derivatives (Futures) Trading - -Use the `FuturesClient` for futures and swap trading operations: - -```javascript -import { FuturesClient } from '@siebly/htx-api'; -// or if you prefer require: -// const { FuturesClient } = require('@siebly/htx-api'); - -// For public endpoints, API credentials are optional -const publicClient = new FuturesClient(); - -// For private endpoints, provide API credentials -const client = new FuturesClient({ - apiKey: 'your-api-key', - apiSecret: 'your-api-secret', -}); - -// Public API Examples - -// Get order book for a specific contract -const orderBook = await publicClient.getLinearSwapMarketDepth({ - contract_code: 'BTC-USDT', - type: 'step0', -}); -console.log('Futures Order Book: ', orderBook); - -// Get ticker information -const ticker = await publicClient.getLinearSwapTicker({ - contract_code: 'BTC-USDT', -}); -console.log('Futures Ticker: ', ticker); - -// Private API Examples (requires authentication) - -// Get cross margin account info -client - .getLinearSwapCrossAccountInfo() - .then((accounts) => { - console.log('Cross Account Info: ', accounts); - }) - .catch((err) => { - console.error('Error: ', err); - }); - -// Submit a cross margin limit order -client - .submitLinearSwapCrossOrder({ - contract_code: 'BTC-USDT', - direction: 'buy', - volume: 1, - lever_rate: 5, - order_price_type: 'limit', - price: 10000, - }) - .then((result) => { - console.log('Limit Order Result: ', JSON.stringify(result, null, 2)); - }) - .catch((err) => { - console.error('Error: ', err); - }); -``` - -See [FuturesClient](./src/FuturesClient.ts) for further information. - -## WebSockets - -HTX supports two types of WebSocket connections: - -1. **WebSocket Subscriptions** - Real-time market data and account updates via the `WebsocketClient` -2. **WebSocket API** - REST-like request/response trading via `WebsocketAPIClient` or `sendWSAPIRequest()` - -### WebSocket Subscriptions (WebsocketClient) - -The unified `WebsocketClient` handles all HTX WebSocket streams with automatic connection management and reconnection. - -Key WebSocket features: - -- Event driven messaging -- Smart WebSocket persistence with automatic reconnection -- Heartbeat mechanisms to detect disconnections -- Automatic resubscription after reconnection -- Support for Spot and Derivatives markets (linear swap, coin swap, delivery) -- Support for both public and private WebSocket streams - -Each connection is tracked using a `WsKey` (see [WS_KEY_MAP](./src/lib/websocket/websocket-util.ts)). Pass the appropriate `WsKey` when subscribing so the client routes your request to the correct endpoint. - -### Public WebSocket Streams - -For public market data, API credentials are not required: - -```javascript -import { WebsocketClient, WS_KEY_MAP } from '@siebly/htx-api'; -// or if you prefer require: -// const { WebsocketClient, WS_KEY_MAP } = require('@siebly/htx-api'); - -// Create WebSocket client for public streams -const wsClient = new WebsocketClient(); - -// Set up event handlers -wsClient.on('open', (data) => { - console.log('WebSocket connected: ', data?.wsKey); -}); - -wsClient.on('message', (data) => { - console.log('Data received: ', JSON.stringify(data, null, 2)); -}); - -wsClient.on('reconnected', (data) => { - console.log('WebSocket reconnected: ', data); -}); - -wsClient.on('exception', (data) => { - console.error('WebSocket error: ', data); -}); - -// Spot - Subscribe to public data streams -wsClient.subscribe( - [ - 'market.btcusdt.kline.1min', - 'market.btcusdt.ticker', - 'market.btcusdt.depth.step0', - 'market.btcusdt.trade.detail', - ], - WS_KEY_MAP.spotPublic, -); - -// Spot feed - high-frequency topics such as BBO and MBP -wsClient.subscribe( - ['market.btcusdt.mbp.5', 'market.btcusdt.trade.detail'], - WS_KEY_MAP.spotFeed, -); - -// Linear swap (USDT-margined) public streams -wsClient.subscribe( - [ - 'market.BTC-USDT.kline.1min', - 'market.BTC-USDT.detail', - 'market.BTC-USDT.trade.detail', - 'market.BTC-USDT.bbo', - ], - WS_KEY_MAP.linearSwapPublic, -); - -// Derivatives index/mark price streams -wsClient.subscribe( - ['market.BTC-USDT.index.1min', 'market.BTC-USDT.mark_price.1min'], - WS_KEY_MAP.derivativesIndex, -); -``` - -### Private WebSocket Streams - -For private account data streams, API credentials are required: - -```javascript -import { WebsocketClient, WS_KEY_MAP } from '@siebly/htx-api'; - -// Create WebSocket client with API credentials for private streams -const wsClient = new WebsocketClient({ - apiKey: 'your-api-key', - apiSecret: 'your-api-secret', -}); - -// Set up event handlers -wsClient.on('open', (data) => { - console.log('Private WebSocket connected: ', data?.wsKey); -}); - -wsClient.on('message', (data) => { - console.log('Private data received: ', JSON.stringify(data, null, 2)); -}); - -wsClient.on('authenticated', (data) => { - console.log('WebSocket authenticated: ', data); -}); - -wsClient.on('response', (data) => { - console.log('WebSocket response: ', data); -}); - -wsClient.on('exception', (data) => { - console.error('WebSocket error: ', data); -}); - -// Spot - Subscribe to private data streams -// Note: SDK automatically handles authentication before subscribing -wsClient.subscribe( - ['accounts.update#1', 'orders#btcusdt', 'trade.clearing#btcusdt#0'], - WS_KEY_MAP.spotPrivateV2, -); - -// Linear swap private streams -wsClient.subscribe( - ['orders.BTC-USDT', 'accounts.BTC-USDT', 'positions.BTC-USDT'], - WS_KEY_MAP.linearSwapPrivate, -); -``` - -For more comprehensive examples, including custom logging and error handling, check the [examples](./examples/Spot/WebSockets) and [examples](./examples/Derivatives/WebSockets) folders. - -### WebSocket API (WebsocketAPIClient) - -Use `WebsocketAPIClient` for typed REST-like trading methods over a persisted WebSocket connection, or call `WebsocketClient.sendWSAPIRequest()` directly for lower-level control. - -Trade connections connect and authenticate lazily on the first request. Optional pre-connect: `client.getWSClient().connectWSAPI(WS_KEY_MAP.spotTrade)`. - -Trade keys: `spotTrade`, `linearSwapTrade`, `coinDeliveryTrade`, `coinSwapTrade`. - -```javascript -import { WebsocketAPIClient, WS_KEY_MAP } from '@siebly/htx-api'; - -const client = new WebsocketAPIClient({ - apiKey: 'your-api-key', - apiSecret: 'your-api-secret', -}); - -// Spot -const order = await client.submitSpotOrder({ - 'account-id': 123456, - symbol: 'btcusdt', - type: 'buy-limit', - amount: '0.001', - price: '20000', - source: 'spot-api', -}); - -// Derivatives -const linearOrder = await client.placeLinearSwapOrder({ - contract_code: 'BTC-USDT', - margin_mode: 'cross', - position_side: 'long', - side: 'buy', - type: 'limit', - time_in_force: 'gtc', - price: '20000', - volume: '1', - reduce_only: 0, -}); -``` - -See [WebsocketAPIClient](./src/WebsocketAPIClient.ts) for all typed methods. Examples: [Spot](./examples/Spot/WebSockets/wsAPI.ts), [Derivatives](./examples/Derivatives/WebSockets/wsAPI.ts), [raw spot](./examples/Spot/WebSockets/wsAPI.RAW.ts), [raw derivatives](./examples/Derivatives/WebSockets/wsAPI.RAW.ts). - ---- - -## 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 '@siebly/htx-api'; - -// E.g. customise logging for only the trace level: -const customLogger = { - ...DefaultLogger, - trace: (...params) => { - // console.log('trace', ...params); - }, - info: (...params) => { - console.log('info', ...params); - }, - error: (...params) => { - console.error('error', ...params); - }, -}; - -const ws = new WebsocketClient( - { - apiKey: 'apiKeyHere', - apiSecret: 'apiSecretHere', - }, - customLogger, -); -``` - -In rare situations, you may want to see the raw HTTP requests being built as well as the API response. These can be enabled by setting the `HTXTRACE` env var to `true`. - -## Browser/Frontend Usage - -The package's ESM entry can be imported directly by modern frontend bundlers. Do not build or copy a separate SDK bundle into your application. - -Browser applications should use the SDK only for public market data. Keep API keys, API secrets, authenticated REST calls, private WebSocket subscriptions, and WebSocket API trading on a trusted backend. - -### React and Vite - -Install and import the package normally; no SDK-specific Vite plugin or Node.js polyfill is required: - -```bash -npm install @siebly/htx-api -``` - -```tsx -import { useEffect, useState } from 'react'; -import { SpotClient, WebsocketClient, WS_KEY_MAP } from '@siebly/htx-api'; - -export function BtcTicker() { - const [ticker, setTicker] = useState(); - - useEffect(() => { - const restClient = new SpotClient(); - const wsClient = new WebsocketClient(); - - restClient.getTicker({ symbol: 'btcusdt' }).then(setTicker); - - const onMessage = (message: unknown) => setTicker(message); - wsClient.on('message', onMessage); - wsClient.subscribe('market.btcusdt.ticker', WS_KEY_MAP.spotPublic); - - return () => { - wsClient.off('message', onMessage); - wsClient.closeAll(); - }; - }, []); - - return
{JSON.stringify(ticker, null, 2)}
; -} -``` - -The cleanup is important during navigation, hot reloads, and React Strict Mode development checks so that an old socket is not left reconnecting in the background. - -### Webpack - -Webpack 5 can consume the same package entry directly: - -```javascript -import { SpotClient, WebsocketClient } from '@siebly/htx-api'; -``` - -Use a normal `target: 'web'` application build. The SDK does not require a checked-in UMD bundle or `resolve.fallback` shims for Node.js core modules. - -Direct `