From 3221c0f98eb5041b5d8b2d8e8f6c42d19eb86ae1 Mon Sep 17 00:00:00 2001 From: JJ-Cro Date: Mon, 9 Nov 2026 09:13:51 +0100 Subject: [PATCH 1/2] feat(v1.0.8): add stock chain response fields - Add optional stock chain flag, on-chain token name, and issuer name to chain information. - Bump the SDK patch version to 1.0.8. --- package-lock.json | 4 ++-- package.json | 2 +- src/types/response/spot.types.ts | 6 ++++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index c8a6161..36999d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@siebly/htx-api", - "version": "1.0.7", + "version": "1.0.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@siebly/htx-api", - "version": "1.0.7", + "version": "1.0.8", "license": "MIT", "dependencies": { "axios": "1.20.0", diff --git a/package.json b/package.json index 7bdd5a2..2a31145 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@siebly/htx-api", - "version": "1.0.7", + "version": "1.0.8", "description": "Complete & robust Node.js SDK for HTX's REST APIs and WebSockets, with TypeScript & strong end to end tests.", "scripts": { "clean": "node scripts/clean.mjs", diff --git a/src/types/response/spot.types.ts b/src/types/response/spot.types.ts index 44c38e8..7ba0324 100644 --- a/src/types/response/spot.types.ts +++ b/src/types/response/spot.types.ts @@ -282,6 +282,12 @@ export interface SpotV1ChainInfo { 'replace-chain-popup-desc'?: string; ca?: string; cct?: number; + /** Whether the chain is a stock chain */ + isc?: boolean; + /** On-chain token name; empty for non-stock chains */ + tkn?: string; + /** Issuer name; empty for non-stock chains */ + isrn?: string; 'withdraw-tips-desc'?: string; 'suspend-visible-desc'?: string; } From ee378f1f90a16fde8b3b53ffab81e9fd5609c384 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 9 Nov 2026 09:14:45 +0100 Subject: [PATCH 2/2] chore: regenerate endpoint docs and examples --- llms.txt | 15566 ++++++++++++++++++++++++++--------------------------- 1 file changed, 7736 insertions(+), 7830 deletions(-) diff --git a/llms.txt b/llms.txt index 603acf9..0b098cb 100644 --- a/llms.txt +++ b/llms.txt @@ -2333,12 +2333,12 @@ public setLogger(logger: DefaultLogger, loggerCategory: object): void public getSpotRESTClient( restOptions: RestClientOptions, requestOptions?: AxiosRequestConfig, -): SpotClient + ): SpotClient ⋮---- public async fetchSpotWebSocketToken( _restOptions: RestClientOptions, _requestOptions?: AxiosRequestConfig, -): Promise< + ): Promise<{ token: string; expiresAtMs: number; timeLeftMs: number }> ⋮---- // still valid for at least 10s ⋮---- @@ -2350,7 +2350,7 @@ const token = ''; //tokenResult?.result?.token; public getDerivativesRESTClient( restOptions: RestClientOptions, requestOptions?: AxiosRequestConfig, -): FuturesClient + ): FuturesClient ================ File: src/lib/event-emitter.browser.ts @@ -3285,7 +3285,7 @@ get( get( key: WsKey, createIfMissing?: boolean, -): WsStoredState | undefined + ): WsStoredState | undefined ⋮---- getKeys(): WsKey[] ⋮---- @@ -3310,13 +3310,13 @@ setWs(key: WsKey, wsConnection: WebSocketLike): WebSocketLike getDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, -): DeferredPromise | undefined + ): DeferredPromise | undefined ⋮---- createDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, throwIfExists: boolean, -): DeferredPromise + ): DeferredPromise ⋮---- // console.log('existing promise'); ⋮---- @@ -3329,19 +3329,19 @@ resolveDeferredPromise( promiseRef: string | DeferredPromiseRef, value: unknown, removeAfter: boolean, -): void + ): void ⋮---- rejectDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, value: unknown, removeAfter: boolean, -): void + ): void ⋮---- removeDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, -): void + ): void ⋮---- // Just in case it's pending ⋮---- @@ -3352,11 +3352,11 @@ rejectAllDeferredPromises(wsKey: WsKey, reason: string): void /** Get promise designed to track a connection attempt in progress. Resolves once connected. */ getConnectionInProgressPromise( wsKey: WsKey, -): DeferredPromise | undefined + ): DeferredPromise | undefined ⋮---- getAuthenticationInProgressPromise( wsKey: WsKey, -): DeferredPromise | undefined ⋮---- /** * Create a deferred promise designed to track a connection attempt in progress. @@ -3366,12 +3366,12 @@ getAuthenticationInProgressPromise( createConnectionInProgressPromise( wsKey: WsKey, throwIfExists: boolean, -): DeferredPromise + ): DeferredPromise ⋮---- createAuthenticationInProgressPromise( wsKey: WsKey, throwIfExists: boolean, -): DeferredPromise ⋮---- /** Remove promise designed to track a connection attempt in progress */ removeConnectingInProgressPromise(wsKey: WsKey): void @@ -3568,7 +3568,7 @@ constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, -) + ) ⋮---- getWSClient(): WebsocketClient ⋮---- @@ -3580,170 +3580,125 @@ getOrderIdPrefix(): string ⋮---- submitSpotOrder( params: WSAPISpotOrderParams, -): Promise> + ): Promise> ⋮---- submitSpotBatchOrders( params: WSAPISpotBatchOrderParams, -): Promise> + ): Promise> ⋮---- submitSpotMarginOrder( params: WSAPISpotMarginOrderParams, -): Promise> + ): Promise> ⋮---- cancelSpotOrders( params: WSAPISpotCancelOrdersParams, -): Promise> + ): Promise> ⋮---- cancelAllSpotOrders( params: WSAPISpotCancelAllOrdersParams, -): Promise> + ): Promise> ⋮---- submitLinearSwapOrder( params: WSAPIDerivativesOrderParams, -): Promise> + ): Promise> ⋮---- submitLinearSwapCrossOrder( params: WSAPIDerivativesOrderParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'create_cross_order', - params, - ); + > ⋮---- submitLinearSwapBatchOrders( params: WSAPIDerivativesBatchOrderParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'create_batchorder', - params, - ); + > ⋮---- submitLinearSwapCrossBatchOrders( params: WSAPIDerivativesBatchOrderParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'create_cross_batchorder', - params, - ); + > ⋮---- cancelLinearSwapOrder( params: WSAPIDerivativesCancelOrderParams, -): Promise> + ): Promise> ⋮---- cancelLinearSwapCrossOrder( params: WSAPIDerivativesCancelOrderParams, -): Promise> + ): Promise> ⋮---- cancelAllLinearSwapOrders( params: WSAPIDerivativesCancelAllOrdersParams, -): Promise> + ): Promise> ⋮---- cancelAllLinearSwapCrossOrders( params: WSAPIDerivativesCancelAllOrdersParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'cross_cancelall', - params, - ); + > ⋮---- placeLinearSwapOrder( params: WSAPIDerivativesPlaceOrderParams, -): Promise> + ): Promise> ⋮---- placeLinearSwapBatchOrders( params: WSAPIDerivativesBatchPlaceOrderParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'place_batch_orders', - params, - ); + > ⋮---- cancelLinearSwapV5Order( params: WSAPIDerivativesV5CancelOrderParams, -): Promise> + ): Promise> ⋮---- cancelLinearSwapV5BatchOrders( params: WSAPIDerivativesV5CancelOrderParams[], ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'cancel_batch_orders', - params, - ); + > ⋮---- cancelAllLinearSwapV5Orders( params: WSAPIDerivativesV5CancelAllOrdersParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.linearSwapTrade, - 'cancel_all_orders', - params, - ); + > ⋮---- submitCoinDeliveryOrder( params: WSAPIDerivativesOrderParams, -): Promise> + ): Promise> ⋮---- submitCoinDeliveryBatchOrders( params: WSAPIDerivativesBatchOrderParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.coinDeliveryTrade, - 'create_batchorder', - params, - ); + > ⋮---- cancelCoinDeliveryOrder( params: WSAPIDerivativesCancelOrderParams, -): Promise> + ): Promise> ⋮---- cancelAllCoinDeliveryOrders( params: WSAPIDerivativesCancelAllOrdersParams, -): Promise> + ): Promise> ⋮---- submitCoinSwapOrder( params: WSAPIDerivativesOrderParams, -): Promise> + ): Promise> ⋮---- submitCoinSwapBatchOrders( params: WSAPIDerivativesBatchOrderParams, ): Promise< WSAPIBaseResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.coinSwapTrade, - 'create_batchorder', - params, - ); + > ⋮---- cancelCoinSwapOrder( params: WSAPIDerivativesCancelOrderParams, -): Promise> + ): Promise> ⋮---- cancelAllCoinSwapOrders( params: WSAPIDerivativesCancelAllOrdersParams, -): Promise> + ): Promise> ⋮---- private setupDefaultEventListeners() @@ -4394,6 +4349,11 @@ export interface WsLinearSwapTradeDetail { ⋮---- /** Whether the trade involved an RPI order */ +================ +File: src/index.ts +================ + + ================ File: examples/Derivatives/WebSockets/privateWs.ts ================ @@ -8499,2790 +8459,2455 @@ export interface FuturesCopyTraderApikeyReq { /** Product type. PERP = Perpetual Swap */ ================ -File: src/types/websockets/ws-general.ts +File: src/types/response/spot.types.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. - * 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; -} -⋮---- -/** 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. - * Futures public WS closes a connection that has had no ping for 25s, without notice. Keep this under 25s. The SDK default is 10s. - */ -⋮---- -/** 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) + * Reference Data */ -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) - */ +/** 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; + }; +} ⋮---- -/** - * Whether to use native WebSocket ping/pong frames for heartbeats - */ +/** Market status: 1=normal, 2=halted, 3=cancel-only */ +export type SpotMarketStatus = 1 | 2 | 3; ⋮---- -export type WsMarket = 'spot' | 'futures'; +/** Halt reason: 2=emergency-maintenance, 3=scheduled-maintenance */ +export type SpotHaltReason = 2 | 3; ⋮---- -export type WsEventInternalSrc = 'event' | 'function' | 'frame'; +export interface SpotMarketStatusData { + marketStatus: SpotMarketStatus; + haltStartTime?: number; + haltEndTime?: number; + haltReason?: SpotHaltReason; + affectedSymbols?: string; +} ⋮---- -export interface WsSpotAuthParams { - authType: 'api'; - accessKey: string; - signatureMethod: 'HmacSHA256' | 'Ed25519'; - signatureVersion: '2.1'; - timestamp: string; - signature: string; +export interface SpotMarketStatusResponse { + code: number; + message: string; + data: SpotMarketStatusData; } ⋮---- -export interface WsDerivativesAuthParams { - op: 'auth'; - type: 'api'; - AccessKeyId: string; - SignatureMethod: 'HmacSHA256' | 'Ed25519'; - SignatureVersion: '2'; - Timestamp: string; - Signature: 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 }[]; } ⋮---- -/** 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. - */ -⋮---- -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]; -⋮---- -export type WSTopic = - | WSSpotPublicTopic - | WSSpotPrivateTopic - | WSDerivativesPublicTopic - | WSDerivativesPrivateTopic - | string; -⋮---- -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'; +/** Whether the symbol supports RPI trading */ ⋮---- -/** Spot Market Data */ +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; +} ⋮---- -/** Spot high-frequency market data */ +/** 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; +} ⋮---- -/** Spot Account Events */ +/** 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; +} ⋮---- -/** Spot WS API */ +/** 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; +} ⋮---- -/** - * 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. - */ +/** @deprecated No longer valid. */ ⋮---- -/** Linear futures account events */ +/** @deprecated No longer valid. */ ⋮---- -/** Linear futures WS API */ +/** @deprecated No longer valid. */ ⋮---- -/** V5 unified derivatives account events */ +/** 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; + /** Whether the chain is a stock chain */ + isc?: boolean; + /** On-chain token name; empty for non-stock chains */ + tkn?: string; + /** Issuer name; empty for non-stock chains */ + isrn?: string; + 'withdraw-tips-desc'?: string; + 'suspend-visible-desc'?: string; +} ⋮---- -/** This is used to differentiate between each of the available websocket streams. */ -export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; +/** Whether the chain is a stock chain */ ⋮---- -export type WSOperation = 'subscribe' | 'unsubscribe'; +/** On-chain token name; empty for non-stock chains */ ⋮---- -export type HtxWSNetwork = 'standard' | 'aws'; +/** Issuer name; empty for non-stock chains */ ⋮---- -/** - * 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; -} -⋮---- -/** Conveniently allow users to request either string topics or topic objects. */ -export type WSTopicRequestOrStringTopic< - TWSTopic extends WSTopic, - TWSPayload = Record, -> = WSTopicRequest | string; -⋮---- -export interface HTXSpotMarketWSRequest { - sub?: string | string[]; - unsub?: string | string[]; - req?: string; - id?: string | number; -} -⋮---- -export interface HTXSpotPrivateWSRequest { - action: 'sub' | 'unsub' | 'req' | 'ping' | 'pong'; - ch?: string; - params?: Record; - data?: Record; +/** 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; } ⋮---- -export interface HTXDerivativesWSRequest { - op: 'sub' | 'unsub' | 'req' | 'ping' | 'pong' | 'auth' | string; - cid?: string; - topic?: string; - data?: Record | Record[]; - [key: string]: unknown; +/** 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; } ⋮---- -export type HTXWSRequest = - | HTXSpotMarketWSRequest - | HTXSpotPrivateWSRequest - | HTXDerivativesWSRequest; -⋮---- -export interface HTXSpotWSAPIRawRequest< - TOperation extends string = string, - TParams = unknown, -> { - cid: string; - ch: TOperation; - params?: TParams; -} +/** RPI order fee rate */ ⋮---- -export interface HTXDerivativesWSAPIRawRequest< - TOperation extends string = string, - TParams = unknown, -> { - op: TOperation; - cid: string; - data?: TParams; +/** 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; } ⋮---- -export type HTXWSAPIRawRequest = - | HTXSpotWSAPIRawRequest - | HTXDerivativesWSAPIRawRequest; +/** Whether the currency supports direct transfers to Poloniex */ ⋮---- /** - * 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. + * Market Data */ -export function safeTerminateWs( - ws?: WebSocketLike | unknown, - fallbackToClose?: boolean, -): boolean -⋮---- -export function isSpotWsKey(wsKey: WsKey): boolean ⋮---- -export function isDerivativesWsKey(wsKey: WsKey): boolean +/** 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; +} ⋮---- -export function isPrivateWsKey(wsKey: WsKey): boolean +/** 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]; +} ⋮---- -export function isTradeWsKey(wsKey: WsKey): boolean +/** [price, size] */ ⋮---- -export function isGzipWsKey(wsKey: WsKey): boolean +/** [price, size] */ ⋮---- -export function getWsBaseUrl(wsKey: WsKey, network: HtxWSNetwork): string +/** 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; +} ⋮---- -export function getWsUrl(wsKey: WsKey, network: HtxWSNetwork): 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][]; +} ⋮---- -export function getPromiseRefForWSAPIRequest( - wsKey: WsKey, - requestEvent: HTXWSAPIRawRequest, -): string +/** 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; +} ⋮---- -export function getPromiseRefPrefixForWSAPIRequest(wsKey: WsKey): 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; +} ⋮---- -export function isBufferMessageEvent( - msg: unknown, -): msg is MessageEventLike +/** Trade tick from /market/trade (payload is in "tick" not "data"). */ +export interface SpotLastTrade { + id: number; + ts: number; + data: SpotTrade[]; +} ⋮---- -export function isBinaryLike(data: unknown): data is WebSocketBinaryData +/** Timestamp group from /market/history/trade. Each element in data array. */ +export interface SpotTradeTimestampGroup { + id: number; + ts: number; + data: SpotTrade[]; +} ⋮---- -export function binaryDataToUint8Array( - data: WebSocketBinaryData, -): Uint8Array +/** + * Account + */ ⋮---- -export function bufferLooksLikeText( - data?: WebSocketBinaryData | null, -): boolean +/** Account from /v1/account/accounts */ +export interface SpotAccount { + id: number; + type: string; + subtype?: string; + state: string; +} ⋮---- -export async function decompressMessageEvent( - event: MessageEventLike, - format: WebSocketCompressionFormat = 'gzip', -): Promise> +/** 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; +} ⋮---- -start(controller) +/** Account balance from /v1/account/accounts/{account-id}/balance */ +export interface SpotAccountBalance { + id: number; + type: string; + state: string; + list: SpotBalance[]; +} ⋮---- -export type WebSocketCompressionFormat = 'deflate' | 'deflate-raw' | 'gzip'; +/** Profit account balance item from /v2/account/valuation */ +export interface SpotV2ProfitAccountBalance { + distributionType: string; + balance: number; + success: boolean; + accountBalance: string; +} ⋮---- -function isNodeBuffer(data: unknown): data is Uint8Array +/** Updated info from /v2/account/valuation */ +export interface SpotV2ValuationUpdated { + success: boolean; + time: number; +} ⋮---- -Buffer?: - -================ -File: src/lib/BaseWSClient.ts -================ -import WebSocketImplementation from 'isomorphic-ws'; +/** Response from /v2/account/valuation */ +export interface SpotV2AccountValuation { + totalBalance?: string; + todayProfit?: string; + todayProfitRate?: string; + profitAccountBalanceList?: SpotV2ProfitAccountBalance[]; + updated?: SpotV2ValuationUpdated; +} ⋮---- -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'; +/** Response from /v2/account/asset-valuation */ +export interface SpotV2AssetValuation { + balance: string; + timestamp: number; +} ⋮---- -interface WebSocketConstructor { - new ( - url: string, - protocols?: string | string[], - options?: Omit, - ): WebSocketLike; +/** Transfer result from POST /v1/account/transfer */ +export interface SpotAccountTransferResult { + 'transact-id': number; + 'transact-time': number; } ⋮---- -function isNativeBrowserWebSocket(ws: WebSocketLike): boolean +export interface SpotV2PointAccountGroupId { + groupId: number; + expiryDate: number | null; + remainAmt: string; +} ⋮---- -type UseTheExceptionEventInstead = never; -type WSClientEventPayload = Record & { - wsKey: WsKey; -}; +/** Point balance from GET /v2/point/account */ +export interface SpotV2PointAccount { + accountId: string; + accountStatus: string; + acctBalance: string; + groupIds: SpotV2PointAccountGroupId[]; +} ⋮---- -type WSClientEventPayloadOrArray = - | WSClientEventPayload - | WSClientEventPayload[]; +/** Point transfer result from POST /v2/point/transfer */ +export interface SpotV2PointTransfer { + transactId: string; + transactTime: 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; +/** 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; } ⋮---- -/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ +/** 1=point card deduction, 0=no */ ⋮---- -/** Reconnecting a dropped connection */ +/** 1=HTX deduction, 0=no. Choose one of point card and HTX deduction. */ ⋮---- -/** Successfully reconnected a connection that dropped */ +/** 1: limited, 0: unlimited */ ⋮---- -/** Connection closed */ +/** Total deductible (USDT). Only when deductionType=1 */ ⋮---- -/** Received reply to websocket command (e.g. after subscribing to topics) */ +/** Remaining deductible (USDT). Only when deductionType=1 */ ⋮---- -/** Received data for topic */ +/** Deductible currency info from GET /v1/account/overview/info */ +export interface SpotV1AccountOverviewInfo { + currency: string; +} ⋮---- -/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ +/** 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; +} ⋮---- -/** - * 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. - */ +/** Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ ⋮---- -/** Confirmation that a connection successfully authenticated */ +/** 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; +} ⋮---- -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; +/** 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; } ⋮---- -| 'connectionReady' // tied to "requireConnectionReadyConfirmation"; -| 'connectionReadyForAuth'; // tied to specific events we need to wait for, before we can begin post-connect auth +/** Margin order result from POST /v1/order/auto/place */ +export interface SpotV1OrderAutoPlaceResult { + 'order-id': number; +} ⋮---- -// 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; -} +/** Canceled order id from POST /v1/order/orders/{order-id}/submitcancel */ +export type SpotV1OrderCancelResult = string; ⋮---- -/** @internal preserves the request-event generic on the merged class type. */ +/** 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; ⋮---- -on>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** 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; +} ⋮---- -addListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Next order id to cancel, -1 = none */ ⋮---- -once>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** 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; +} ⋮---- -prependListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Result from POST /v2/algo-orders/cancel-all-after (Dead man's switch) */ +export interface SpotV2AlgoOrdersCancelAllAfterResult { + currentTime: number; + triggerTime: number; +} ⋮---- -prependOnceListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** + * Conditional Order + */ ⋮---- -off>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Result from POST /v2/algo-orders (Place a conditional order) */ +export interface SpotV2AlgoOrdersPlaceResult { + clientOrderId: string; +} ⋮---- -removeListener>( - event: U, - listener: WSClientEventMap[U], - ): this; +/** Result from POST /v2/algo-orders/cancellation (Cancel conditional orders before triggering) */ +export interface SpotV2AlgoOrdersCancellationResult { + accepted: string[]; + rejected: string[]; +} ⋮---- -removeAllListeners(event?: keyof WSClientEventMap): this; +/** 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; +} ⋮---- -listeners(event: keyof WSClientEventMap): EventListener[]; +/** Only for orderStatus=triggered */ ⋮---- -listenerCount( - event: keyof WSClientEventMap, - listener?: WSClientEventMap[keyof WSClientEventMap], - ): number; +/** Order trigger time. Only for orderStatus=triggered */ ⋮---- -emit>( - event: U, - ...args: Parameters[U]> - ): boolean; +/** Only for orderStatus=rejected */ ⋮---- -/** - * 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; -} +/** Only for orderStatus=rejected */ ⋮---- /** - * Appends wsKey and isWSAPIResponse to all events. - * Some events are arrays, this handles that nested scenario too. + * Margin Loan (Cross/Isolated) */ -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[] -⋮---- -// Some topics just emit an array. -// This is consistent with how it was before the WS API upgrade: ⋮---- -// const { event, ...others } = emittable; -// return { -// ...others, -// event: event.map((subEvent) => -// getFinalEmittable(subEvent, wsKey, isWSAPIResponse), -// ), -// }; +/** Repayment result from POST /v2/account/repayment. Check transaction record to confirm status. */ +export interface SpotMarginRepaymentResult { + repayId: string | number; + repayTime: 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[] +/** Transact ID detail from GET /v2/account/repayment (Repayment Record Reference) */ +export interface SpotRepaymentRecordTransactId { + transactId: number; + repaidPrincipal?: string; + repaidInterest?: string; + paidHt?: string; + paidPoint?: string; +} ⋮---- -// passed as string, convert to object +/** 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[]; +} ⋮---- -// already a normalised object, thanks to user +/** 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; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -export abstract class BaseWebsocketClient< -TWSKey extends string, +/** Symbol from GET /v1/margin/loan-info */ +export interface SpotMarginLoanInfo { + symbol: string; + currencies: SpotMarginLoanInfoCurrency[]; +} ⋮---- -constructor( - options?: WSClientConfigurableOptions & { wsLoggerCategory: string }, - logger?: DefaultLogger, -) +/** 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; +} ⋮---- -// Futures public WS closes a socket with no ping for 25s. Default 10s stays under that. +/** Balance row from GET /v1/margin/accounts/balance */ +export interface SpotMarginBalance { + currency: string; + type: string; + balance: string; +} ⋮---- -// Requires a confirmation "response" from the ws connection before assuming it is ready +/** 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[]; +} ⋮---- -// Automatically auth after opening a connection? +/** 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[]; +} ⋮---- -// Automatically include auth/sign/token with every WS request. -// Automatically handled during getWsRequestEvents. -⋮---- -// Automatically re-auth WS API, if we were auth'd before and get reconnected -⋮---- -// Whether to use native heartbeats (depends on the exchange) -⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used -⋮---- -/** - * Return true if this wsKey connection should automatically authenticate immediately after connecting - */ -protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; -⋮---- -protected abstract isCustomReconnectionNeeded(wsKey: TWSKey): boolean; +/** 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; +} ⋮---- -protected abstract triggerCustomReconnectionWorkflow( - wsKey: TWSKey, - ): Promise; +/** Position limit from GET /v2/margin/limit */ +export interface SpotMarginLimit { + currency: string; + 'max-holdings': string; +} ⋮---- -protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocketLike): boolean; +/** 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[]; +} ⋮---- -protected abstract sendPongEvent( - wsKey: TWSKey, - ws: WebSocketLike, - event?: unknown, - ): void; +/** Successfully canceled order ids or client-order-ids */ ⋮---- -protected abstract isWsPing(data: unknown): boolean; +/** Failed cancel requests */ ⋮---- -protected abstract isWsPong(data: unknown): boolean; +/** 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; +} ⋮---- -protected abstract authPrivateConnectionsOnConnect(_wsKey: TWSKey): boolean; +/** 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; +} ⋮---- -/** - * 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; +/** 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; +} ⋮---- -protected abstract isPrivateTopicRequest( - request: WSTopicRequest, - wsKey: TWSKey, - ): boolean; +/** Next start-time or end-time for pagination. Only when results exceed size. */ ⋮---- -protected abstract getPrivateWSKeys(): TWSKey[]; +/** 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; +} ⋮---- -protected abstract getWsUrl(wsKey: TWSKey): Promise; +/** Deposit address item from GET /v2/account/deposit/address */ +export interface SpotDepositAddress { + userId: number; + currency: string; + address: string; + addressTag: string; + chain: string; +} ⋮---- -protected abstract getMaxTopicsPerSubscribeEvent( - wsKey: TWSKey, - ): number | null; +/** 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; +} ⋮---- -/** - * @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[]>; +/** Withdraw quota from GET /v2/account/withdraw/quota */ +export interface SpotWithdrawQuota { + currency: string; + chains: SpotWithdrawQuotaChain[]; +} ⋮---- /** - * 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[]; + * 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'; ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -protected abstract connectAll(): Promise[]; +/** 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; +} ⋮---- -protected isPrivateWsKey(wsKey: TWSKey): boolean +/** See {@link SpotWithdrawAddressStatus}. */ ⋮---- -/** Returns auto-incrementing request ID, used to track promise references for async requests */ -protected getNewRequestId(): 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; +} ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - operation: string, - params?: unknown, - ): Promise; +/** Chain name. Poloniex rapid transfer defaults to t397342. */ ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - channel: string, - params: unknown, - ): Promise; +/** On-chain address, or UID:XXXX for Poloniex→HTX rapid transfers. */ ⋮---- -public getTimeOffsetMs() +/** VASP exchange from GET /v1/query/vasp-list */ +export interface SpotVaspExchange { + 'vasp-id': string; + 'vasp-name': string; + 'legal-name': string; +} ⋮---- -public setTimeOffsetMs(newOffset: number) -⋮---- -/** - * 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, -) -⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +/** User rebate status from GET /broker/v1/user_rebate_status */ +export interface SpotBrokerUserRebateStatus { + spotRebateStatus: boolean; + contractRebateStatus: boolean; + spotIsNewUser: boolean; + contractIsNewUser?: boolean; +} ⋮---- -// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +/** 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; +} ⋮---- -// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. +/** Fee rate add result from POST /broker/v1/sub-user/fee_rate/add */ +export interface SpotBrokerFeeRateAddResult { + subUserIds: number[]; + effectAt: string; +} ⋮---- -/** - * Are we in the process of connection? Nothing to send yet. - */ +/** 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[]; +} ⋮---- -// We're connected. Check if auth is needed and if already authenticated +/** Deduct mode result item from POST /v2/sub-user/deduct-mode */ +export interface SpotSubUserDeductModeResult { + subUid: string; + deductMode: string | null; + errCode?: string; + errMessage?: 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. - */ +/** API key from getSubUserApiKey */ +export interface SpotSubUserApiKey { + accessKey: string; + status: string; + note: string; + permission: string; + ipAddresses: string; + validDays: number; + createTime: number; + updateTime: number; +} ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +/** 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; +} ⋮---- -protected async unsubscribeTopicsForWsKey( - wsTopicRequests: WSTopicRequestOrStringTopic[], - wsKey: TWSKey, -): Promise +/** Spot account id for spot order transactions */ ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +/** Sub user from GET /v2/sub-user/user-list */ +export interface SpotSubUserList { + uid: number; + userState: string; + subUserName: string; + note: string; +} ⋮---- -// 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. +/** Result from updateSubUserLockStatus */ +export interface SpotSubUserLockStatusResult { + subUid: number; + userState: string; +} ⋮---- -// We're connected. Check if auth is needed and if already authenticated +/** Result from getSubUserStatus */ +export interface SpotSubUserStatusResult { + uid: number; + userState: string; +} ⋮---- -/** - * 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. - */ +/** Tradable market result item from POST /v2/sub-user/tradable-market */ +export interface SpotSubUserTradableMarketResult { + subUid: string; + accountType: string; + activation: string; + errCode?: number; + errMessage?: string; +} ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +/** Result item from setSubUserTransferPermissions */ +export interface SpotSubUserTransferPermissionsResult { + subUid: number; + accountType: string; + transferrable: boolean; + errCode?: number; + errMessage?: string; +} ⋮---- -/** - * Splits topic requests into two groups, public & private topic requests - */ -private sortTopicRequestsIntoPublicPrivate( - wsTopicRequests: WSTopicRequest[], - wsKey: TWSKey, -): +/** Account ID from sub user account list */ +export interface SpotSubUserAccountId { + accountId: number; + subType?: string; + accountStatus?: string; +} ⋮---- -/** Get the WsStore that tracks websockets & topics */ -public getWsStore(): WsStore> +/** Account from sub user account list */ +export interface SpotSubUserAccount { + accountType: string; + activation: string; + transferrable?: boolean; + accountIds?: SpotSubUserAccountId[]; +} ⋮---- -public close(wsKey: TWSKey, force?: boolean) +/** Result from getSubUserAccounts */ +export interface SpotSubUserAccountsResult { + uid: number; + deductMode: string; + list: SpotSubUserAccount[]; +} ⋮---- -public closeAll(force?: boolean) +/** Result from createSubUserApiKey */ +export interface SpotSubUserApiKeyCreationResult { + accessKey: string; + secretKey: string; + note: string; + permission: string; + ipAddresses: string; +} ⋮---- -public isConnected(wsKey: TWSKey): boolean +/** Result from updateSubUserApiKey */ +export interface SpotSubUserApiKeyUpdateResult { + note: string; + permission: string; + ipAddresses: string; +} ⋮---- -/** - * Request connection to a specific websocket, instead of waiting for automatic connection. - */ -public async connect( - wsKey: TWSKey, - customUrl?: string | undefined, - throwOnError?: boolean, -): Promise +/** 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; +} ⋮---- -// Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()! +/** Balance from getSubUsersAggregatedBalance */ +export interface SpotSubUsersAggregatedBalance { + currency: string; + type: string; + balance: string; +} ⋮---- -private connectToWsUrl(url: string, wsKey: TWSKey): WebSocketLike +/** Result from getSubUserBalance */ +export interface SpotSubUserBalanceResult { + id: number; + type: string; + state: string; + list: SpotBalance[]; + symbol?: string; +} ⋮---- -// Event handlers for native heartbeats / ping/pong frames +/** Custody sub-account from GET /v2/sub-user/entrust-user-list */ +export interface SpotSubUserEntrustUser { + uid: number; + subUserName: string; +} ⋮---- -private parseWsError( - context: string, - error: unknown, - wsKey: TWSKey, -): boolean +/** 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; +} ⋮---- -// Allow retry by default (in some places that call this). Prevent deadloop in hard failure (401) +/** 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; +} ⋮---- -/** Get a signature, build the auth request and send it */ -private async sendAuthRequest( - wsKey: TWSKey, - eventToAuth?: object, -): Promise +/** 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; +} ⋮---- -private async advanceAuthRequest( - wsKey: TWSKey, - authPromise: DeferredPromise, - eventToAuth?: object, -): Promise +/** 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; +} ⋮---- -// If not required, this won't return anything +/** 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; +} ⋮---- -// Short-circuit this for the next time it's called +/** Tiered rate from Earn project */ +export interface SpotEarnTieredRate { + amountStart: string; + amountEnd: string; + rate: string; +} ⋮---- -private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: 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; +} ⋮---- -// Some streams need a specialist reconnection workflow. -// E.g. the user data stream can't just be reconnected as is. +/** Result from POST /v1/earn/order/demand/add */ +export interface SpotEarnSubscribeResult { + currency: string; + amount: string; + orderId: number; + status: number; +} ⋮---- -private ping(wsKey: TWSKey) +/** Result from POST /v1/earn/order/demand/redeem-order */ +export interface SpotEarnRedeemResult { + currency: string; + amount: string; + orderId: number; + status: number; +} ⋮---- -/** - * 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) +/** 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; +} ⋮---- -private clearTimers(wsKey: TWSKey) +/** 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; +} ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: TWSKey) +/** Whether advanced KYC was completed */ ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: TWSKey) +/** Invitee email */ ⋮---- -// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); +/** 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; +} ⋮---- -// this.logger.trace(`No active pong timer for "${wsKey}"`); +/** Result from POST /v5/account/universal_transfer */ +export interface SpotUniversalTransferResult { + transfer_id: number; +} ⋮---- -private clearReconnectTimer(wsKey: TWSKey) +/** 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; + from_asset_type?: string; + to_asset_type?: string; + transfer_time?: number; +} + +================ +File: src/types/websockets/ws-general.ts +================ +import { AxiosRequestConfig } from 'axios'; ⋮---- -/** - * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics +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. + * 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. * - * 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 + * 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 * - * Events are automatically split into smaller batches, by this method, if needed. + * Look in the examples folder for a demonstration on using node's createHmac instead. */ -protected async getWsOperationEventsForTopics( - topics: WSTopicRequest[], - wsKey: TWSKey, - operation: WSOperation, -): Promise[]> + 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; +} ⋮---- -// Events that are ready to send (usually stringified JSON) +/** Your API key */ +⋮---- +/** Your API secret */ +⋮---- +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds. */ ⋮---- /** - * 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[], -) + * 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. + */ ⋮---- -// Automatically splits requests into smaller batches, if needed +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" +/** Delay in milliseconds before respawning the connection */ ⋮---- /** - * Simply builds and sends unsubscribe events for a list of topics for a ws key + * 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. * - * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. + * 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. */ -private async requestUnsubscribeTopics( - wsKey: TWSKey, - wsTopicRequests: WSTopicRequest[], -) ⋮---- /** - * Try sending a string event on a WS connection (identified by the WS Key) + * 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. */ -private tryWsSendWithResult( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -): boolean -⋮---- -public tryWsSend( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -): void -⋮---- -/** Send a message while reporting whether it reached the socket API. */ -protected tryWsSendWithStatus( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -): boolean -⋮---- -private async onWsOpen( - event: unknown, - wsKey: TWSKey, - url: string, - ws: WebSocketLike, -) -⋮---- -private resolveConnectionInProgressPromise(wsKey: TWSKey) -⋮---- -// Resolve & cleanup deferred "connection attempt in progress" promise ⋮---- /** - * 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. + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. */ -private async onWsReadyForEvents(wsKey: TWSKey) -⋮---- -// Some websockets require an auth packet to be sent after opening the connection ⋮---- -// Reconnect to topics known before it connected +/** + * Whether to use native WebSocket ping/pong frames for heartbeats. + */ ⋮---- -// Request sub to public topics, if any +/** + * 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; +} ⋮---- -// Request sub to private topics, if auth on connect isn't needed +/** + * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) + */ ⋮---- /** - * Handle subscription to private topics _after_ authentication successfully completes asynchronously. - * - * Only used for exchanges that require auth before sending private topic subscription requests + * Whether to use native WebSocket ping/pong frames for heartbeats */ -private onWsAuthenticated(wsKey: TWSKey, event: unknown) ⋮---- -// Resolve & cleanup deferred "auth attempt in progress" promise +export type WsMarket = 'spot' | 'futures'; ⋮---- -// Remove before continuing, in case there's more requests queued +export type WsEventInternalSrc = 'event' | 'function' | 'frame'; ⋮---- -private onWsPing( - event: unknown, - wsKey: TWSKey, - ws: WebSocketLike, - source: WsEventInternalSrc, -) +export interface WsSpotAuthParams { + authType: 'api'; + accessKey: string; + signatureMethod: 'HmacSHA256' | 'Ed25519'; + signatureVersion: '2.1'; + timestamp: string; + signature: string; +} ⋮---- -private onWsPong(event: unknown, wsKey: TWSKey, source: WsEventInternalSrc) +export interface WsDerivativesAuthParams { + op: 'auth'; + type: 'api'; + AccessKeyId: string; + SignatureMethod: 'HmacSHA256' | 'Ed25519'; + SignatureVersion: '2'; + Timestamp: string; + Signature: string; +} ⋮---- -// Necessary when native heartbeats are used +/** 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. + */ ⋮---- -private async onWsMessage( - event: unknown, - wsKey: TWSKey, - ws: WebSocketLike, - didDecompress = false, -): Promise +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]; ⋮---- -// 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 +export type WSTopic = + | WSSpotPublicTopic + | WSSpotPrivateTopic + | WSDerivativesPublicTopic + | WSDerivativesPrivateTopic + | string; ⋮---- -// console.log(`raw event: `, { data, dataType, emittableEvents }); +export function isPrivateTopic(topic: string): boolean + +================ +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'; ⋮---- -// Other event types are automatically emitted here +/** Spot Market Data */ ⋮---- -// this.logger.trace( -// `onWsMessage().emit(${emittable.eventType}).done()`, -// emittableFinalEvent, -// ); +/** Spot high-frequency market data */ ⋮---- -// this.logger.trace('Decompressed message event from buffer', { -// ...this.WS_LOGGER_CATEGORY, -// wsKey, -// decompressed, -// }); +/** Spot Account Events */ ⋮---- -private onWsClose(event: unknown, wsKey: TWSKey) +/** Spot WS API */ ⋮---- -// unintentional close, attempt recovery +/** + * 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. + */ ⋮---- -// clean up any pending promises for this connection +/** Linear futures account events */ ⋮---- -// this.clearTopicsPendingSubscriptions(wsKey, true, 'WS Closed'); +/** Linear futures WS API */ ⋮---- -// intentional close - clean up -// clean up any pending promises for this connection +/** V5 unified derivatives account events */ ⋮---- -// This was an intentional close, delete all state for this connection, as if it never existed: +/** This is used to differentiate between each of the available websocket streams. */ +export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; ⋮---- -private getWs(wsKey: TWSKey) +export type WSOperation = 'subscribe' | 'unsubscribe'; ⋮---- -private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) +export type HtxWSNetwork = 'standard' | 'aws'; ⋮---- /** - * 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 + * 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; +} ⋮---- -// Start connection, it should automatically store/return a promise. +/** Conveniently allow users to request either string topics or topic objects. */ +export type WSTopicRequestOrStringTopic< + TWSTopic extends WSTopic, + TWSPayload = Record, +> = WSTopicRequest | string; ⋮---- -/** - * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) - */ -public async assertIsAuthenticated(wsKey: TWSKey): Promise +export interface HTXSpotMarketWSRequest { + sub?: string | string[]; + unsub?: string | string[]; + req?: string; + id?: string | number; +} ⋮---- -// Already in progress? Await shared promise and retry +export interface HTXSpotPrivateWSRequest { + action: 'sub' | 'unsub' | 'req' | 'ping' | 'pong'; + ch?: string; + params?: Record; + data?: Record; +} +⋮---- +export interface HTXDerivativesWSRequest { + op: 'sub' | 'unsub' | 'req' | 'ping' | 'pong' | 'auth' | string; + cid?: string; + topic?: string; + data?: Record | Record[]; + [key: string]: unknown; +} +⋮---- +export type HTXWSRequest = + | HTXSpotMarketWSRequest + | HTXSpotPrivateWSRequest + | HTXDerivativesWSRequest; +⋮---- +export interface HTXSpotWSAPIRawRequest< + TOperation extends string = string, + TParams = unknown, +> { + cid: string; + ch: TOperation; + params?: TParams; +} +⋮---- +export interface HTXDerivativesWSAPIRawRequest< + TOperation extends string = string, + TParams = unknown, +> { + op: TOperation; + cid: string; + data?: TParams; +} +⋮---- +export type HTXWSAPIRawRequest = + | HTXSpotWSAPIRawRequest + | HTXDerivativesWSAPIRawRequest; ⋮---- -// Start authentication, it should automatically store/return a promise. - -================ -File: src/types/response/spot.types.ts -================ /** - * Reference Data + * 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 ⋮---- -/** 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; - }; -} +export function isSpotWsKey(wsKey: WsKey): boolean ⋮---- -/** Market status: 1=normal, 2=halted, 3=cancel-only */ -export type SpotMarketStatus = 1 | 2 | 3; +export function isDerivativesWsKey(wsKey: WsKey): boolean ⋮---- -/** Halt reason: 2=emergency-maintenance, 3=scheduled-maintenance */ -export type SpotHaltReason = 2 | 3; +export function isPrivateWsKey(wsKey: WsKey): boolean ⋮---- -export interface SpotMarketStatusData { - marketStatus: SpotMarketStatus; - haltStartTime?: number; - haltEndTime?: number; - haltReason?: SpotHaltReason; - affectedSymbols?: string; -} +export function isTradeWsKey(wsKey: WsKey): boolean ⋮---- -export interface SpotMarketStatusResponse { - code: number; - message: string; - data: SpotMarketStatusData; -} +export function isGzipWsKey(wsKey: WsKey): boolean ⋮---- -/** 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 }[]; -} +export function getWsBaseUrl(wsKey: WsKey, network: HtxWSNetwork): string ⋮---- -/** Whether the symbol supports RPI trading */ +export function getWsUrl(wsKey: WsKey, network: HtxWSNetwork): string ⋮---- -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; -} +export function getPromiseRefForWSAPIRequest( + wsKey: WsKey, + requestEvent: HTXWSAPIRawRequest, +): string ⋮---- -/** 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; -} +export function getPromiseRefPrefixForWSAPIRequest(wsKey: WsKey): string ⋮---- -/** 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; -} +export function isBufferMessageEvent( + msg: unknown, +): msg is MessageEventLike ⋮---- -/** 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; -} -⋮---- -/** @deprecated No longer valid. */ -⋮---- -/** @deprecated No longer valid. */ -⋮---- -/** @deprecated No longer valid. */ +export function isBinaryLike(data: unknown): data is WebSocketBinaryData ⋮---- -/** 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; -} +export function binaryDataToUint8Array( + data: WebSocketBinaryData, +): Uint8Array ⋮---- -/** 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; -} +export function bufferLooksLikeText( + data?: WebSocketBinaryData | null, +): boolean ⋮---- -/** 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; -} +export async function decompressMessageEvent( + event: MessageEventLike, + format: WebSocketCompressionFormat = 'gzip', +): Promise> ⋮---- -/** RPI order fee rate */ +start(controller) ⋮---- -/** 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; -} +export type WebSocketCompressionFormat = 'deflate' | 'deflate-raw' | 'gzip'; ⋮---- -/** Whether the currency supports direct transfers to Poloniex */ +function isNodeBuffer(data: unknown): data is Uint8Array ⋮---- -/** - * Market Data - */ +Buffer?: + +================ +File: src/lib/BaseWSClient.ts +================ +import WebSocketImplementation from 'isomorphic-ws'; ⋮---- -/** 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; -} +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'; ⋮---- -/** 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]; +interface WebSocketConstructor { + new ( + url: string, + protocols?: string | string[], + options?: Omit, + ): WebSocketLike; } ⋮---- -/** [price, size] */ -⋮---- -/** [price, size] */ +function isNativeBrowserWebSocket(ws: WebSocketLike): boolean ⋮---- -/** 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; -} +type UseTheExceptionEventInstead = never; +type WSClientEventPayload = Record & { + wsKey: WsKey; +}; ⋮---- -/** 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][]; -} +type WSClientEventPayloadOrArray = + | WSClientEventPayload + | WSClientEventPayload[]; ⋮---- -/** 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; -} -⋮---- -/** 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; -} -⋮---- -/** Trade tick from /market/trade (payload is in "tick" not "data"). */ -export interface SpotLastTrade { - id: number; - ts: number; - data: SpotTrade[]; +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; } ⋮---- -/** Timestamp group from /market/history/trade. Each element in data array. */ -export interface SpotTradeTimestampGroup { - id: number; - ts: number; - data: SpotTrade[]; -} +/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ ⋮---- -/** - * Account - */ +/** Reconnecting a dropped connection */ ⋮---- -/** Account from /v1/account/accounts */ -export interface SpotAccount { - id: number; - type: string; - subtype?: string; - state: string; -} +/** Successfully reconnected a connection that dropped */ ⋮---- -/** 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; -} +/** Connection closed */ ⋮---- -/** Account balance from /v1/account/accounts/{account-id}/balance */ -export interface SpotAccountBalance { - id: number; - type: string; - state: string; - list: SpotBalance[]; -} +/** Received reply to websocket command (e.g. after subscribing to topics) */ ⋮---- -/** Profit account balance item from /v2/account/valuation */ -export interface SpotV2ProfitAccountBalance { - distributionType: string; - balance: number; - success: boolean; - accountBalance: string; -} +/** Received data for topic */ ⋮---- -/** Updated info from /v2/account/valuation */ -export interface SpotV2ValuationUpdated { - success: boolean; - time: number; -} +/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ ⋮---- -/** Response from /v2/account/valuation */ -export interface SpotV2AccountValuation { - totalBalance?: string; - todayProfit?: string; - todayProfitRate?: string; - profitAccountBalanceList?: SpotV2ProfitAccountBalance[]; - updated?: SpotV2ValuationUpdated; -} +/** + * 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. + */ ⋮---- -/** Response from /v2/account/asset-valuation */ -export interface SpotV2AssetValuation { - balance: string; - timestamp: number; -} +/** Confirmation that a connection successfully authenticated */ ⋮---- -/** Transfer result from POST /v1/account/transfer */ -export interface SpotAccountTransferResult { - 'transact-id': number; - 'transact-time': number; +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; } ⋮---- -export interface SpotV2PointAccountGroupId { - groupId: number; - expiryDate: number | null; - remainAmt: string; -} +| 'connectionReady' // tied to "requireConnectionReadyConfirmation"; +| 'connectionReadyForAuth'; // tied to specific events we need to wait for, before we can begin post-connect auth ⋮---- -/** Point balance from GET /v2/point/account */ -export interface SpotV2PointAccount { - accountId: string; - accountStatus: string; - acctBalance: string; - groupIds: SpotV2PointAccountGroupId[]; +// 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; } ⋮---- -/** Point transfer result from POST /v2/point/transfer */ -export interface SpotV2PointTransfer { - transactId: string; - transactTime: number; -} +/** @internal preserves the request-event generic on the merged class type. */ ⋮---- -/** 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; -} +on>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** 1=point card deduction, 0=no */ +addListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** 1=HTX deduction, 0=no. Choose one of point card and HTX deduction. */ +once>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** 1: limited, 0: unlimited */ +prependListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Total deductible (USDT). Only when deductionType=1 */ +prependOnceListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Remaining deductible (USDT). Only when deductionType=1 */ +off>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** Deductible currency info from GET /v1/account/overview/info */ -export interface SpotV1AccountOverviewInfo { - currency: string; -} +removeListener>( + event: U, + listener: WSClientEventMap[U], + ): this; ⋮---- -/** 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; -} +removeAllListeners(event?: keyof WSClientEventMap): this; ⋮---- -/** Includes loan-disburse, loan-repay, loan-interest-refund, loan-interest-pay. */ +listeners(event: keyof WSClientEventMap): EventListener[]; ⋮---- -/** 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; -} +listenerCount( + event: keyof WSClientEventMap, + listener?: WSClientEventMap[keyof WSClientEventMap], + ): 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; -} +emit>( + event: U, + ...args: Parameters[U]> + ): boolean; ⋮---- -/** Margin order result from POST /v1/order/auto/place */ -export interface SpotV1OrderAutoPlaceResult { - 'order-id': 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; } ⋮---- -/** Canceled order id from POST /v1/order/orders/{order-id}/submitcancel */ -export type SpotV1OrderCancelResult = string; +/** + * 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[] ⋮---- -/** 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; +// Some topics just emit an array. +// This is consistent with how it was before the WS API upgrade: ⋮---- -/** 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; -} +// const { event, ...others } = emittable; +// return { +// ...others, +// event: event.map((subEvent) => +// getFinalEmittable(subEvent, wsKey, isWSAPIResponse), +// ), +// }; ⋮---- -/** Next order id to cancel, -1 = none */ +/** + * 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[] ⋮---- -/** 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; -} +// passed as string, convert to object ⋮---- -/** Result from POST /v2/algo-orders/cancel-all-after (Dead man's switch) */ -export interface SpotV2AlgoOrdersCancelAllAfterResult { - currentTime: number; - triggerTime: number; -} +// already a normalised object, thanks to user ⋮---- -/** - * Conditional Order - */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging +export abstract class BaseWebsocketClient< +TWSKey extends string, ⋮---- -/** Result from POST /v2/algo-orders (Place a conditional order) */ -export interface SpotV2AlgoOrdersPlaceResult { - clientOrderId: string; -} +constructor( + options?: WSClientConfigurableOptions & { wsLoggerCategory: string }, + logger?: DefaultLogger, + ) ⋮---- -/** Result from POST /v2/algo-orders/cancellation (Cancel conditional orders before triggering) */ -export interface SpotV2AlgoOrdersCancellationResult { - accepted: string[]; - rejected: string[]; -} +// Futures public WS closes a socket with no ping for 25s. Default 10s stays under that. ⋮---- -/** 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; -} +// Requires a confirmation "response" from the ws connection before assuming it is ready ⋮---- -/** Only for orderStatus=triggered */ +// Automatically auth after opening a connection? ⋮---- -/** Order trigger time. Only for orderStatus=triggered */ +// Automatically include auth/sign/token with every WS request. +// Automatically handled during getWsRequestEvents. ⋮---- -/** Only for orderStatus=rejected */ +// Automatically re-auth WS API, if we were auth'd before and get reconnected ⋮---- -/** Only for orderStatus=rejected */ +// Whether to use native heartbeats (depends on the exchange) +⋮---- +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- /** - * Margin Loan (Cross/Isolated) - */ + * Return true if this wsKey connection should automatically authenticate immediately after connecting + */ +protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; ⋮---- -/** Repayment result from POST /v2/account/repayment. Check transaction record to confirm status. */ -export interface SpotMarginRepaymentResult { - repayId: string | number; - repayTime: number; -} +protected abstract isCustomReconnectionNeeded(wsKey: TWSKey): boolean; ⋮---- -/** Transact ID detail from GET /v2/account/repayment (Repayment Record Reference) */ -export interface SpotRepaymentRecordTransactId { - transactId: number; - repaidPrincipal?: string; - repaidInterest?: string; - paidHt?: string; - paidPoint?: string; -} +protected abstract triggerCustomReconnectionWorkflow( + wsKey: TWSKey, + ): Promise; ⋮---- -/** 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[]; -} +protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocketLike): boolean; ⋮---- -/** 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; -} +protected abstract sendPongEvent( + wsKey: TWSKey, + ws: WebSocketLike, + event?: unknown, + ): void; ⋮---- -/** Symbol from GET /v1/margin/loan-info */ -export interface SpotMarginLoanInfo { - symbol: string; - currencies: SpotMarginLoanInfoCurrency[]; -} +protected abstract isWsPing(data: unknown): boolean; ⋮---- -/** 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; -} -⋮---- -/** Balance row from GET /v1/margin/accounts/balance */ -export interface SpotMarginBalance { - currency: string; - type: string; - balance: string; -} +protected abstract isWsPong(data: unknown): boolean; ⋮---- -/** 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[]; -} +protected abstract authPrivateConnectionsOnConnect(_wsKey: TWSKey): boolean; ⋮---- -/** 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[]; -} +/** + * 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; ⋮---- -/** 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; -} +protected abstract isPrivateTopicRequest( + request: WSTopicRequest, + wsKey: TWSKey, + ): boolean; ⋮---- -/** Position limit from GET /v2/margin/limit */ -export interface SpotMarginLimit { - currency: string; - 'max-holdings': string; -} +protected abstract getPrivateWSKeys(): TWSKey[]; ⋮---- -/** 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[]; -} +protected abstract getWsUrl(wsKey: TWSKey): Promise; ⋮---- -/** Successfully canceled order ids or client-order-ids */ +protected abstract getMaxTopicsPerSubscribeEvent( + wsKey: TWSKey, + ): number | null; ⋮---- -/** Failed cancel requests */ +/** + * @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[]>; ⋮---- -/** 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; -} +/** + * 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[]; ⋮---- -/** 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; -} +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +protected abstract connectAll(): Promise[]; ⋮---- -/** 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; -} +protected isPrivateWsKey(wsKey: TWSKey): boolean ⋮---- -/** Next start-time or end-time for pagination. Only when results exceed size. */ +/** Returns auto-incrementing request ID, used to track promise references for async requests */ +protected getNewRequestId(): number ⋮---- -/** 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; -} +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + operation: string, + params?: unknown, + ): Promise; ⋮---- -/** Deposit address item from GET /v2/account/deposit/address */ -export interface SpotDepositAddress { - userId: number; - currency: string; - address: string; - addressTag: string; - chain: string; -} +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + channel: string, + params: unknown, + ): Promise; ⋮---- -/** 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; -} +public getTimeOffsetMs() ⋮---- -/** Withdraw quota from GET /v2/account/withdraw/quota */ -export interface SpotWithdrawQuota { - currency: string; - chains: SpotWithdrawQuotaChain[]; -} +public setTimeOffsetMs(newOffset: 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'; + * 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, + ) ⋮---- -/** 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; -} +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- -/** See {@link SpotWithdrawAddressStatus}. */ +// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect ⋮---- -/** 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; -} +// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. ⋮---- -/** Chain name. Poloniex rapid transfer defaults to t397342. */ +/** + * Are we in the process of connection? Nothing to send yet. + */ ⋮---- -/** On-chain address, or UID:XXXX for Poloniex→HTX rapid transfers. */ +// We're connected. Check if auth is needed and if already authenticated ⋮---- -/** VASP exchange from GET /v1/query/vasp-list */ -export interface SpotVaspExchange { - 'vasp-id': string; - 'vasp-name': string; - 'legal-name': 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. + */ ⋮---- -/** User rebate status from GET /broker/v1/user_rebate_status */ -export interface SpotBrokerUserRebateStatus { - spotRebateStatus: boolean; - contractRebateStatus: boolean; - spotIsNewUser: boolean; - contractIsNewUser?: boolean; -} +// Finally, request subscription to topics if the connection is healthy and ready ⋮---- -/** 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; -} +protected async unsubscribeTopicsForWsKey( + wsTopicRequests: WSTopicRequestOrStringTopic[], + wsKey: TWSKey, + ): Promise ⋮---- -/** Fee rate add result from POST /broker/v1/sub-user/fee_rate/add */ -export interface SpotBrokerFeeRateAddResult { - subUserIds: number[]; - effectAt: string; -} +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- -/** 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[]; -} +// 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. ⋮---- -/** Deduct mode result item from POST /v2/sub-user/deduct-mode */ -export interface SpotSubUserDeductModeResult { - subUid: string; - deductMode: string | null; - errCode?: string; - errMessage?: string; -} +// We're connected. Check if auth is needed and if already authenticated ⋮---- -/** API key from getSubUserApiKey */ -export interface SpotSubUserApiKey { - accessKey: string; - status: string; - note: string; - permission: string; - ipAddresses: string; - validDays: number; - createTime: number; - updateTime: number; -} +/** + * 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. + */ ⋮---- -/** 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; -} +// Finally, request subscription to topics if the connection is healthy and ready ⋮---- -/** Spot account id for spot order transactions */ +/** + * Splits topic requests into two groups, public & private topic requests + */ +private sortTopicRequestsIntoPublicPrivate( + wsTopicRequests: WSTopicRequest[], + wsKey: TWSKey, + ): { + publicReqs: WSTopicRequest[]; + privateReqs: WSTopicRequest[]; + } ⋮---- -/** Sub user from GET /v2/sub-user/user-list */ -export interface SpotSubUserList { - uid: number; - userState: string; - subUserName: string; - note: string; -} +/** Get the WsStore that tracks websockets & topics */ +public getWsStore(): WsStore> ⋮---- -/** Result from updateSubUserLockStatus */ -export interface SpotSubUserLockStatusResult { - subUid: number; - userState: string; -} +public close(wsKey: TWSKey, force?: boolean) ⋮---- -/** Result from getSubUserStatus */ -export interface SpotSubUserStatusResult { - uid: number; - userState: string; -} +public closeAll(force?: boolean) ⋮---- -/** Tradable market result item from POST /v2/sub-user/tradable-market */ -export interface SpotSubUserTradableMarketResult { - subUid: string; - accountType: string; - activation: string; - errCode?: number; - errMessage?: string; -} +public isConnected(wsKey: TWSKey): boolean ⋮---- -/** Result item from setSubUserTransferPermissions */ -export interface SpotSubUserTransferPermissionsResult { - subUid: number; - accountType: string; - transferrable: boolean; - errCode?: number; - errMessage?: string; -} +/** + * Request connection to a specific websocket, instead of waiting for automatic connection. + */ +public async connect( + wsKey: TWSKey, + customUrl?: string | undefined, + throwOnError?: boolean, + ): Promise ⋮---- -/** Account ID from sub user account list */ -export interface SpotSubUserAccountId { - accountId: number; - subType?: string; - accountStatus?: string; -} +// Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()! ⋮---- -/** Account from sub user account list */ -export interface SpotSubUserAccount { - accountType: string; - activation: string; - transferrable?: boolean; - accountIds?: SpotSubUserAccountId[]; -} +private connectToWsUrl(url: string, wsKey: TWSKey): WebSocketLike ⋮---- -/** Result from getSubUserAccounts */ -export interface SpotSubUserAccountsResult { - uid: number; - deductMode: string; - list: SpotSubUserAccount[]; -} +// Event handlers for native heartbeats / ping/pong frames ⋮---- -/** Result from createSubUserApiKey */ -export interface SpotSubUserApiKeyCreationResult { - accessKey: string; - secretKey: string; - note: string; - permission: string; - ipAddresses: string; -} +private parseWsError( + context: string, + error: unknown, + wsKey: TWSKey, + ): boolean ⋮---- -/** Result from updateSubUserApiKey */ -export interface SpotSubUserApiKeyUpdateResult { - note: string; - permission: string; - ipAddresses: string; -} +// Allow retry by default (in some places that call this). Prevent deadloop in hard failure (401) ⋮---- -/** 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; -} +/** Get a signature, build the auth request and send it */ +private async sendAuthRequest( + wsKey: TWSKey, + eventToAuth?: object, + ): Promise ⋮---- -/** Balance from getSubUsersAggregatedBalance */ -export interface SpotSubUsersAggregatedBalance { - currency: string; - type: string; - balance: string; -} +private async advanceAuthRequest( + wsKey: TWSKey, + authPromise: DeferredPromise, + eventToAuth?: object, + ): Promise ⋮---- -/** Result from getSubUserBalance */ -export interface SpotSubUserBalanceResult { - id: number; - type: string; - state: string; - list: SpotBalance[]; - symbol?: string; -} +// If not required, this won't return anything ⋮---- -/** Custody sub-account from GET /v2/sub-user/entrust-user-list */ -export interface SpotSubUserEntrustUser { - uid: number; - subUserName: string; -} +// Short-circuit this for the next time it's called ⋮---- -/** 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; -} +private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) ⋮---- -/** 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; -} +// Some streams need a specialist reconnection workflow. +// E.g. the user data stream can't just be reconnected as is. ⋮---- -/** 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; -} +private ping(wsKey: TWSKey) ⋮---- -/** 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; -} +/** + * 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) ⋮---- -/** 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; -} +private clearTimers(wsKey: TWSKey) ⋮---- -/** Tiered rate from Earn project */ -export interface SpotEarnTieredRate { - amountStart: string; - amountEnd: string; - rate: string; -} +// Send a ping at intervals +private clearPingTimer(wsKey: TWSKey) ⋮---- -/** 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; -} +// Expect a pong within a time limit +private clearPongTimer(wsKey: TWSKey) ⋮---- -/** Result from POST /v1/earn/order/demand/add */ -export interface SpotEarnSubscribeResult { - currency: string; - amount: string; - orderId: number; - status: number; -} +// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); ⋮---- -/** Result from POST /v1/earn/order/demand/redeem-order */ -export interface SpotEarnRedeemResult { - currency: string; - amount: string; - orderId: number; - status: number; -} +// this.logger.trace(`No active pong timer for "${wsKey}"`); ⋮---- -/** 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; -} +private clearReconnectTimer(wsKey: TWSKey) ⋮---- -/** 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; -} +/** + * 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[]> ⋮---- -/** Whether advanced KYC was completed */ +// Events that are ready to send (usually stringified JSON) ⋮---- -/** Invitee email */ +/** + * 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[], + ) ⋮---- -/** 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; -} +// Automatically splits requests into smaller batches, if needed ⋮---- -/** Result from POST /v5/account/universal_transfer */ -export interface SpotUniversalTransferResult { - transfer_id: number; -} +`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" ⋮---- -/** 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; - 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'; -⋮---- -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; -} -⋮---- -/** If true, will skip auth requirement for this WS API request. */ +/** + * 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[], + ) ⋮---- -/** Optional caller-supplied correlation id. Generated automatically when omitted. */ +/** + * Try sending a string event on a WS connection (identified by the WS Key) + */ +private tryWsSendWithResult( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, + ): boolean ⋮---- -interface WsEndpointParts { - url: string; - host: string; - path: string; -} +public tryWsSend( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, + ): void ⋮---- -interface WSAPIInflightRequestRef { - wsKey: WSAPIWsKey; - operation: WSAPIOperation; - cid: string; -} +/** Send a message while reporting whether it reached the socket API. */ +protected tryWsSendWithStatus( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, + ): boolean ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +private async onWsOpen( + event: unknown, + wsKey: TWSKey, + url: string, + ws: WebSocketLike, + ) ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +private resolveConnectionInProgressPromise(wsKey: TWSKey) ⋮---- -// For most connections, heartbeats are messages for HTX, not WS-level frames +// Resolve & cleanup deferred "connection attempt in progress" promise ⋮---- /** - * Request connection of all market/private sockets that are useful for subscriptions. - * Trade-command sockets are intentionally opened lazily by sendWSAPIRequest(). + * 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. */ -public connectAll(): Promise[] +private async onWsReadyForEvents(wsKey: TWSKey) ⋮---- -/** - * Ensures a WS API connection is active and, unless skipped, authenticated. - */ -public connectWSAPI( - wsKey: WSAPIWsKey = WS_KEY_MAP.spotTrade, - skipAuth?: boolean, -): Promise +// Some websockets require an auth packet to be sent after opening the connection ⋮---- -public subscribe( - requests: - | (WSTopicRequest | WSTopic) - | (WSTopicRequest | WSTopic)[], - wsKey: WsKey, -) +// Reconnect to topics known before it connected ⋮---- -public unsubscribe( - requests: - | (WSTopicRequest | WSTopic) - | (WSTopicRequest | WSTopic)[], - wsKey: WsKey, -) +// Request sub to public topics, if any ⋮---- -/** - * WS API Methods - similar to the REST API, but via WebSockets - */ +// Request sub to private topics, if auth on connect isn't needed ⋮---- /** - * 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. + * Handle subscription to private topics _after_ authentication successfully completes asynchronously. * - * @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 + * Only used for exchanges that require auth before sending private topic subscription requests */ -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; +private onWsAuthenticated(wsKey: TWSKey, event: unknown) ⋮---- -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 +// Resolve & cleanup deferred "auth attempt in progress" promise ⋮---- -// Used by other exchanges for commands that don't require authentication. +// Remove before continuing, in case there's more requests queued ⋮---- -protected isCustomReconnectionNeeded(): boolean +private onWsPing( + event: unknown, + wsKey: TWSKey, + ws: WebSocketLike, + source: WsEventInternalSrc, + ) ⋮---- -public generateNewOrderID(): string +private onWsPong(event: unknown, wsKey: TWSKey, source: WsEventInternalSrc) ⋮---- -public getOrderIdPrefix(): string +// Necessary when native heartbeats are used ⋮---- -protected async triggerCustomReconnectionWorkflow(): Promise +private async onWsMessage( + event: unknown, + wsKey: TWSKey, + ws: WebSocketLike, + didDecompress = false, + ): Promise ⋮---- -protected async getWsUrl(wsKey: WsKey): Promise +// 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 ⋮---- -protected sendPingEvent(wsKey: WsKey, ws: WebSocketLike): boolean +// console.log(`raw event: `, { data, dataType, emittableEvents }); ⋮---- -// These WS Keys use native ping frames, since the JSON ping is not supported for these websocket endpoints (confirmed by HTX) +// Other event types are automatically emitted here ⋮---- -protected sendPongEvent(wsKey: WsKey, _ws: WebSocketLike, event?: unknown) +// this.logger.trace( +// `onWsMessage().emit(${emittable.eventType}).done()`, +// emittableFinalEvent, +// ); ⋮---- -protected isWsPing(event: unknown): boolean +// this.logger.trace('Decompressed message event from buffer', { +// ...this.WS_LOGGER_CATEGORY, +// wsKey, +// decompressed, +// }); ⋮---- -protected isWsPong(event: unknown): boolean +private onWsClose(event: unknown, wsKey: TWSKey) ⋮---- -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] +// unintentional close, attempt recovery ⋮---- -protected isPrivateTopicRequest( - request: WSTopicRequest, - wsKey: WsKey, -): boolean +// clean up any pending promises for this connection ⋮---- -protected getPrivateWSKeys(): WsKey[] +// this.clearTopicsPendingSubscriptions(wsKey, true, 'WS Closed'); ⋮---- -protected authPrivateConnectionsOnConnect(wsKey: WsKey): boolean +// intentional close - clean up +// clean up any pending promises for this connection ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +// This was an intentional close, delete all state for this connection, as if it never existed: ⋮---- -protected getMaxTopicsPerSubscribeEvent(): number | null +private getWs(wsKey: TWSKey) ⋮---- -protected async getWsRequestEvents( - wsKey: WsKey, - operation: WSOperation, - requests: WSTopicRequest[], -): Promise[]> +private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, -): Promise +/** + * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) + */ +protected async assertIsConnected(wsKey: TWSKey): Promise ⋮---- -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 +// Already in progress? Await shared promise and retry ⋮---- -private resolveWSAPIResponse( - wsKey: WsKey, - parsed: ParsedWsMessage, -): EmittableEvent[] +// Start connection, it should automatically store/return a promise. ⋮---- -private async getSpotAuthParams(wsKey: WsKey): 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 ⋮---- -private async getDerivativesAuthParams( - wsKey: WsKey, -): Promise -⋮---- -private async signHtxParams( - host: string, - path: string, - params: Record, -): Promise -⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: SignEncodeMethod, - algorithm: SignAlgorithm, -): Promise -⋮---- -private getSignatureMethod(): 'HmacSHA256' | 'Ed25519' -⋮---- -private getTimestampForSignature(): string -⋮---- -private async getWsEndpointParts(wsKey: WsKey): Promise -⋮---- -private getWsNetwork(): HtxWSNetwork -⋮---- -private isMarketProtocolWsKey(wsKey: WsKey): boolean -⋮---- -private isSpotPrivateProtocolWsKey(wsKey: WsKey): boolean -⋮---- -private isDerivativesTopicProtocolWsKey(wsKey: WsKey): boolean -⋮---- -private isDerivativesOperationProtocolWsKey(wsKey: WsKey): boolean -⋮---- -private parseWsMessage(event: unknown): ParsedWsMessage | undefined -⋮---- -private getHeartbeatTimestamp(parsed?: ParsedWsMessage): string | number -⋮---- -private getPayloadRecord(payload: unknown): Record -⋮---- -private getPayloadStringOrNumber( - payload: Record, - key: string, -): string | number | undefined -⋮---- -private isAuthResponse(parsed: ParsedWsMessage): boolean -⋮---- -private isWSAPIResponse(wsKey: WsKey, parsed: ParsedWsMessage): boolean -⋮---- -private isSubscriptionResponse(parsed: ParsedWsMessage): boolean -⋮---- -private isRequestResponse(parsed: ParsedWsMessage): boolean -⋮---- -private isErrorEvent(parsed: ParsedWsMessage): boolean -⋮---- -private getEventOperation(parsed: ParsedWsMessage): string | undefined -⋮---- -private trackWSAPIRequestRef( - promiseRef: string, - wsKey: WSAPIWsKey, - operation: WSAPIOperation, - cid: string, -): void -⋮---- -private getPromiseRefForWSAPIResponse( - wsKey: WsKey, - parsed: ParsedWsMessage, -): string | undefined -⋮---- -/** - * - * Misc Utility Methods - * - */ +// Already in progress? Await shared promise and retry ⋮---- -/** - * Validate syntax meets requirements set by HTX. - * Log warning if not. - */ -public validateOrderId( - params: SpotV1OrderPlaceReq | SpotV1OrderAutoPlaceReq, - orderIdProperty: OrderIdProperty, -): void +// Start authentication, it should automatically store/return a promise. ================ File: src/types/request/spot.types.ts @@ -12631,3223 +12256,2850 @@ export interface SpotUniversalTransferRecordsReq { } ================ -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 +File: src/WebsocketClient.ts ================ -/** - * Reference - */ +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'; ⋮---- -/** Paginated response base. Use FuturesPaginatedData or FuturesPaginatedSettlement for specific data keys. */ -export interface FuturesPaginatedBase { - total_page: number; - current_page: number; - total_size: number; +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; } ⋮---- -/** Paginated response with `data` array (e.g. historical funding rate, liquidation orders). */ -export type FuturesPaginatedData = FuturesPaginatedBase & { data: T[] }; -⋮---- -/** Paginated response with `settlement_record` array. */ -export type FuturesPaginatedSettlement = FuturesPaginatedBase & { - settlement_record: T[]; -}; -⋮---- -/** Paginated response with `sub_list` array (sub-account info list). */ -export type FuturesPaginatedSubList = FuturesPaginatedBase & { - sub_list: T[]; -}; +/** If true, will skip auth requirement for this WS API request. */ ⋮---- -/** Paginated response with `transfer_record` array (master-sub transfers). */ -export type FuturesPaginatedTransferRecord = FuturesPaginatedBase & { - transfer_record: T[]; -}; +/** Optional caller-supplied correlation id. Generated automatically when omitted. */ ⋮---- -/** Paginated response with `orders` array (open orders, trigger orders, etc.). */ -export type FuturesPaginatedOrders = FuturesPaginatedBase & { orders: T[] }; +interface WsEndpointParts { + url: string; + host: string; + path: string; +} ⋮---- -/** 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; +interface WSAPIInflightRequestRef { + wsKey: WSAPIWsKey; + operation: WSAPIOperation; + cid: string; } ⋮---- -/** Deprecated, default null */ +export class WebsocketClient extends BaseWebsocketClient< ⋮---- -/** Deprecated, default null */ +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- -/** 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; -} -⋮---- -/** Deprecated, default null */ +// For most connections, heartbeats are messages for HTX, not WS-level frames ⋮---- -/** Paginated wrapper for swap_historical_funding_rate data */ -export type FuturesHistoricalFundingRatePage = - FuturesPaginatedData; +/** + * Request connection of all market/private sockets that are useful for subscriptions. + * Trade-command sockets are intentionally opened lazily by sendWSAPIRequest(). + */ +public connectAll(): Promise[] ⋮---- -/** 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; -} +/** + * Ensures a WS API connection is active and, unless skipped, authenticated. + */ +public connectWSAPI( + wsKey: WSAPIWsKey = WS_KEY_MAP.spotTrade, + skipAuth?: boolean, + ): Promise ⋮---- -/** 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 subscribe( + requests: + | (WSTopicRequest | WSTopic) + | (WSTopicRequest | WSTopic)[], + wsKey: WsKey, + ) ⋮---- -/** Paginated settlement records from swap_settlement_records */ -export type FuturesSettlementRecordsPage = - FuturesPaginatedSettlement; +public unsubscribe( + requests: + | (WSTopicRequest | WSTopic) + | (WSTopicRequest | WSTopic)[], + wsKey: WsKey, + ) ⋮---- -/** Elite ratio list item (account and position) */ -export interface FuturesEliteRatioList { - buy_ratio: number; - sell_ratio: number; - /** Account ratio only */ - locked_ratio?: number; - ts: number; -} +/** + * WS API Methods - similar to the REST API, but via WebSockets + */ ⋮---- -/** Account ratio only */ +/** + * 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; ⋮---- -/** 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[]; -} +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 ⋮---- -/** 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; -} +// Used by other exchanges for commands that don't require authentication. ⋮---- -/** 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; -} +protected isCustomReconnectionNeeded(): boolean ⋮---- -/** Cross ladder margin list item */ -export interface FuturesCrossLadderMarginList { - lever_rate: number; - ladders: FuturesLadderMarginTier[]; -} +public generateNewOrderID(): string ⋮---- -/** 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; -} +public getOrderIdPrefix(): 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; -} +protected async triggerCustomReconnectionWorkflow(): Promise ⋮---- -/** 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; -} +protected async getWsUrl(wsKey: WsKey): Promise ⋮---- -/** Adjust factor list item */ -export interface FuturesAdjustFactorList { - lever_rate: number; - ladders: FuturesAdjustFactorLadder[]; -} +protected sendPingEvent(wsKey: WsKey, ws: WebSocketLike): boolean ⋮---- -/** 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; -} +// These WS Keys use native ping frames, since the JSON ping is not supported for these websocket endpoints (confirmed by HTX) ⋮---- -/** Risk reserve balance from /v1/insurance_fund_info */ -export interface FuturesInsuranceFundInfo { - insurance_fund: string; - quote_currency?: string; -} +protected sendPongEvent(wsKey: WsKey, _ws: WebSocketLike, event?: unknown) ⋮---- -/** Historical risk reserve item from /v1/insurance_fund_history */ -export interface FuturesInsuranceFundHistory { - query_id: number; - insurance_fund: string; - date: string; -} +protected isWsPing(event: unknown): boolean ⋮---- -/** 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; -} +protected isWsPong(event: unknown): boolean ⋮---- -/** 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; -} +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, + ): EmittableEvent[] ⋮---- -/** 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[]; -} +protected isPrivateTopicRequest( + request: WSTopicRequest, + wsKey: WsKey, + ): boolean ⋮---- -/** 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; -} +protected getPrivateWSKeys(): WsKey[] ⋮---- -/** 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; -} +protected authPrivateConnectionsOnConnect(wsKey: WsKey): boolean ⋮---- -/** Price as string. -1 means HTX masked proprietary third-party index pricing. */ +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -/** 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[]; -} +protected getMaxTopicsPerSubscribeEvent(): number | null ⋮---- -/** Contract elements price tick / value item */ -export interface FuturesContractElementsPrice { - business_type: number; - price: string; -} +protected async getWsRequestEvents( + wsKey: WsKey, + operation: WSOperation, + requests: WSTopicRequest[], + ): Promise[]> ⋮---- -/** Contract elements order limit item */ -export interface FuturesContractElementsOrderLimit { - instrument_type: number; - open: string; - close: string; - order_type?: number; - open_after_closing?: string; -} +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise ⋮---- -/** 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; -} +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 ⋮---- -/** Timestamp response from /api/v1/timestamp. No data field. */ -export interface FuturesTimestamp { - status: string; - ts: number; -} +private resolveWSAPIResponse( + wsKey: WsKey, + parsed: ParsedWsMessage, + ): EmittableEvent[] ⋮---- -/** 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; -} +private async getSpotAuthParams(wsKey: WsKey): Promise ⋮---- -/** 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[]; -} +private async getDerivativesAuthParams( + wsKey: WsKey, + ): Promise ⋮---- -/** - * Market - */ +private async signHtxParams( + host: string, + path: string, + params: Record, + ): Promise ⋮---- -/** 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; -} +private async signMessage( + paramsStr: string, + secret: string, + method: SignEncodeMethod, + algorithm: SignAlgorithm, + ): Promise ⋮---- -/** 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; -} +private getSignatureMethod(): 'HmacSHA256' | 'Ed25519' ⋮---- -/** 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; -} +private getTimestampForSignature(): 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; -} +private async getWsEndpointParts(wsKey: WsKey): Promise ⋮---- -/** 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; -} +private getWsNetwork(): HtxWSNetwork ⋮---- -/** 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; -} +private isMarketProtocolWsKey(wsKey: WsKey): boolean ⋮---- -/** 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; +private isSpotPrivateProtocolWsKey(wsKey: WsKey): boolean +⋮---- +private isDerivativesTopicProtocolWsKey(wsKey: WsKey): boolean +⋮---- +private isDerivativesOperationProtocolWsKey(wsKey: WsKey): boolean +⋮---- +private parseWsMessage(event: unknown): ParsedWsMessage | undefined +⋮---- +private getHeartbeatTimestamp(parsed?: ParsedWsMessage): string | number +⋮---- +private getPayloadRecord(payload: unknown): Record +⋮---- +private getPayloadStringOrNumber( + payload: Record, + key: string, + ): string | number | undefined +⋮---- +private isAuthResponse(parsed: ParsedWsMessage): boolean +⋮---- +private isWSAPIResponse(wsKey: WsKey, parsed: ParsedWsMessage): boolean +⋮---- +private isSubscriptionResponse(parsed: ParsedWsMessage): boolean +⋮---- +private isRequestResponse(parsed: ParsedWsMessage): boolean +⋮---- +private isErrorEvent(parsed: ParsedWsMessage): boolean +⋮---- +private getEventOperation(parsed: ParsedWsMessage): string | undefined +⋮---- +private trackWSAPIRequestRef( + promiseRef: string, + wsKey: WSAPIWsKey, + operation: WSAPIOperation, + cid: string, + ): void +⋮---- +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/response/futures.types.ts +================ +/** + * Reference + */ +⋮---- +/** Paginated response base. Use FuturesPaginatedData or FuturesPaginatedSettlement for specific data keys. */ +export interface FuturesPaginatedBase { + total_page: number; + current_page: number; + total_size: number; } ⋮---- -/** Whether the trade involved an RPI order. USDT-M uses snake_case. */ +/** Paginated response with `data` array (e.g. historical funding rate, liquidation orders). */ +export type FuturesPaginatedData = FuturesPaginatedBase & { data: T[] }; ⋮---- -/** Whether the trade is an RPI trade. Coin-M uses the hyphenated name. */ +/** Paginated response with `settlement_record` array. */ +export type FuturesPaginatedSettlement = FuturesPaginatedBase & { + settlement_record: T[]; +}; ⋮---- -/** Last trade tick from market/trade. Payload in "tick". */ -export interface FuturesLastTrade { - id: number; - ts: number; - data: FuturesTrade[]; +/** Paginated response with `sub_list` array (sub-account info list). */ +export type FuturesPaginatedSubList = FuturesPaginatedBase & { + sub_list: T[]; +}; +⋮---- +/** Paginated response with `transfer_record` array (master-sub transfers). */ +export type FuturesPaginatedTransferRecord = FuturesPaginatedBase & { + transfer_record: T[]; +}; +⋮---- +/** 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; + fee_asset: string; + funding_time: string; + /** Deprecated, default null */ + estimated_rate?: string | null; + /** Deprecated, default null */ + next_funding_time?: string | null; } ⋮---- -/** Trade history group from market/history/trade. Each group has trades by timestamp. */ -export interface FuturesTradeHistory { - id: number; - ts: number; - data: FuturesTrade[]; +/** Deprecated, default null */ +⋮---- +/** Deprecated, default null */ +⋮---- +/** 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; } ⋮---- -/** Open interest tick item from swap_his_open_interest */ -export interface FuturesOpenInterestTick { +/** Deprecated, default null */ +⋮---- +/** Paginated wrapper for swap_historical_funding_rate data */ +export type FuturesHistoricalFundingRatePage = + FuturesPaginatedData; +⋮---- +/** 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_type: number; - ts: number; - value: number; + amount: number; + price: number; + trade_turnover: number; + pair: string; + business_type: string; } ⋮---- -/** Open interest data from swap_his_open_interest. data is object with tick array. */ -export interface FuturesHistoricalOpenInterest { +/** Settlement record item from swap_settlement_records */ +export interface FuturesSettlementRecord { symbol: string; contract_code: string; - contract_type: string; - pair: string; + settlement_time: number; + clawback_ratio: number; + settlement_price: number; + settlement_type: string; business_type: string; - tick: FuturesOpenInterestTick[]; + pair: string; } ⋮---- -/** - * Account - */ +/** Paginated settlement records from swap_settlement_records */ +export type FuturesSettlementRecordsPage = + FuturesPaginatedSettlement; ⋮---- -/** Asset valuation item from swap_balance_valuation */ -export interface FuturesBalanceValuation { - valuation_asset: string; - balance: string; +/** Elite ratio list item (account and position) */ +export interface FuturesEliteRatioList { + buy_ratio: number; + sell_ratio: number; + /** Account ratio only */ + locked_ratio?: number; + ts: number; } ⋮---- -/** 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; -} +/** Account ratio only */ ⋮---- -/** Cross account contract detail (swap + futures) from swap_cross_account_info */ -export interface FuturesCrossAccountContractDetail { +/** Elite account/position ratio data from swap_elite_account_ratio and swap_elite_position_ratio */ +export interface FuturesEliteRatio { 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; + list: FuturesEliteRatioList[]; } ⋮---- -/** 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[]; -} -⋮---- -/** Position info item from swap_position_info and swap_cross_position_info */ -export interface FuturesPositionInfo { +/** System status item from swap_api_state. 1=available, 0=unavailable */ +export interface FuturesApiState { 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; + 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; } ⋮---- -/** 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; +/** 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; +} +⋮---- +/** Cross ladder margin list item */ +export interface FuturesCrossLadderMarginList { 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; + ladders: FuturesLadderMarginTier[]; } ⋮---- -/** Account + positions from swap_account_position_info (Isolated) */ -export interface FuturesIsolatedAccountPosition { +/** 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_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; + list: FuturesCrossLadderMarginList[]; + business_type?: string; + pair?: string; + contract_type?: string; } ⋮---- -/** Cross position item (in positions array) from swap_cross_account_position_info */ -export interface FuturesCrossAccountPositionItem { - symbol: string; +/** Estimated settlement price item from swap_estimated_settlement_price. Empty around settlement/delivery. */ +export interface FuturesEstimatedSettlementPrice { 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; + estimated_settlement_price: number | null; + settlement_type: string; contract_type: string; pair: string; business_type: string; - position_mode: string; - new_risk_rate?: string | null; - trade_partition?: string; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** 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; +/** Adjust factor list item */ +export interface FuturesAdjustFactorList { + lever_rate: number; + ladders: FuturesAdjustFactorLadder[]; } ⋮---- -/** Sub auth response data from swap_sub_auth */ -export interface FuturesSubAuth { - errors: FuturesSubAuthError[]; - successes: string; +/** 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; } ⋮---- -/** Sub auth success item from swap_sub_auth_list */ -export interface FuturesSubAuthSuccess { - query_id?: number; - sub_uid: string; - sub_auth: number | string; +/** Risk reserve balance from /v1/insurance_fund_info */ +export interface FuturesInsuranceFundInfo { + insurance_fund: string; + quote_currency?: string; } ⋮---- -/** Sub permissions response from getSubPermissions */ -export interface FuturesSubPermissions { - errors: FuturesSubAuthError[]; - successes: FuturesSubAuthSuccess[]; +/** Historical risk reserve item from /v1/insurance_fund_history */ +export interface FuturesInsuranceFundHistory { + query_id: number; + insurance_fund: string; + date: string; } ⋮---- -/** Isolated sub-account list item from swap_sub_account_list */ -export interface FuturesIsolatedSubAccountList { +/** Price limit item from swap_price_limit. business_type, pair, contract_type optional for CM products. */ +export interface FuturesPriceLimit { 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; + high_limit: number; + low_limit: number; + business_type?: string; + pair?: string; + contract_type?: string; } ⋮---- -/** Used as from_id for next/prev pagination */ -⋮---- -/** Isolated sub-account entry from swap_sub_account_list (data array element) */ -export interface FuturesIsolatedSubAccountListEntry { - sub_uid: number; - list: FuturesIsolatedSubAccountList[]; +/** 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; } ⋮---- -/** 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; +/** 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[]; } ⋮---- -/** 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[]; +/** 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; } ⋮---- -/** 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; -} -⋮---- -/** Account info item from swap_sub_account_info_list */ -export interface FuturesSubAccountInfoAccount { +/** Index constituent component from swap_contract_constituents */ +export interface FuturesIndexConstituentComponent { + exchange: string; 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; -} -⋮---- -/** Sub-account item in swap_sub_account_info_list data.sub_list */ -export interface FuturesSubAccountInfoSub { - sub_uid: number; - account_info_list: FuturesSubAccountInfoAccount[]; + /** Price as string. -1 means HTX masked proprietary third-party index pricing. */ + symbol_price: string; + weights: string; } ⋮---- -/** object from swap_sub_account_info_list */ -export type FuturesSubAccountInfoList = - FuturesPaginatedSubList; +/** Price as string. -1 means HTX masked proprietary third-party index pricing. */ ⋮---- -/** 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; +/** 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[]; } ⋮---- -/** Cross sub-account info list: sub_list item */ -export interface FuturesCrossSubAccountInfoListSub { - sub_uid: number; - account_info_list: FuturesCrossSubAccountInfoListAccount[]; +/** Contract elements price tick / value item */ +export interface FuturesContractElementsPrice { + business_type: number; + price: string; } ⋮---- -/** Cross sub-account info list: unite_sub_list item */ -export interface FuturesCrossSubAccountInfoListUnite { - sub_uid: number; - asset_multi_sub: FuturesCrossSubAccountAssetMultiSub; +/** Contract elements order limit item */ +export interface FuturesContractElementsOrderLimit { + instrument_type: number; + open: string; + close: string; + order_type?: number; + open_after_closing?: string; } ⋮---- -/** object from swap_cross_sub_account_info_list */ -export type FuturesCrossSubAccountInfoList = - FuturesPaginatedSubList & { - unite_sub_list: FuturesCrossSubAccountInfoListUnite[]; - }; -⋮---- -/** Isolated sub-account info item from swap_sub_account_info (single sub, data array element) */ -export interface FuturesIsolatedSubAccountInfo { - symbol: string; +/** Contract elements contract info item */ +export interface FuturesContractElementsContractInfo { 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; + instrument_type: number; + settlement_date: string; + delivery_time: string; + create_date: string; + contract_status: number; + delivery_date: string; + trigger_protect?: number; } ⋮---- -/** 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[]; +/** Timestamp response from /api/v1/timestamp. No data field. */ +export interface FuturesTimestamp { + status: string; + ts: number; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** Available leverage item from swap_available_level_rate */ -export interface FuturesAvailableLevelRate { +/** Contract elements item from swap_query_elements */ +export interface FuturesContractElements { contract_code: string; - margin_mode: string; - available_level_rate: 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[]; } ⋮---- -/** 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; +/** + * Market + */ +⋮---- +/** 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 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; +/** 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; } ⋮---- -/** from swap_order_limit */ -export interface FuturesOrderLimit { - order_price_type: string; - list: FuturesOrderLimitList[]; +/** 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; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** 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; -} -⋮---- -/** 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; -} -⋮---- -/** 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; -} -⋮---- -/** 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; -} -⋮---- -/** 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; -} -⋮---- -/** Lever position limit item from swap_lever_position_limit */ -export interface FuturesLeverPositionLimit { - symbol: string; - contract_code: string; - margin_mode: string; - list: FuturesLeverPositionLimitList[]; -} -⋮---- -/** 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[]; -} -⋮---- -/** Master-sub transfer response from transfer*MasterSub */ -export interface FuturesMasterSubTransfer { - order_id: string; - client_order_id?: number; +/** 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; } ⋮---- -/** Transfer record item from master_sub_transfer_record. asset, margin_account, symbol, contract_code optional per product. */ -export interface FuturesMasterSubTransferRecordItem { +/** 24h ticker from market detail/merged. contract_code, symbol, business_type optional per product. */ +export interface FuturesTicker { 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; + 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; } ⋮---- -/** Master-sub transfer records from swap_master_sub_transfer_record */ -export type FuturesMasterSubTransferRecords = - FuturesPaginatedTransferRecord; -⋮---- -/** Cancel-after response data from linear-cancel-after */ -export interface FuturesCancelAfter { - current_time: number; - trigger_time: number; -} -⋮---- -/** 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; +/** 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; } ⋮---- -/** Batch order error item from swap_batchorder and swap_cross_batchorder */ -export interface FuturesBatchOrderError { - index: number; - err_code: number; - err_msg: string; -} +/** Whether the trade involved an RPI order. USDT-M uses snake_case. */ ⋮---- -/** 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; -} +/** Whether the trade is an RPI trade. Coin-M uses the hyphenated name. */ ⋮---- -/** Cancel order error item from swap_cancel and swap_cross_cancel */ -export interface FuturesCancelOrderError { - order_id: string; - err_code: number; - err_msg: string; +/** Last trade tick from market/trade. Payload in "tick". */ +export interface FuturesLastTrade { + id: number; + ts: number; + data: FuturesTrade[]; } ⋮---- -/** 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; +/** Trade history group from market/history/trade. Each group has trades by timestamp. */ +export interface FuturesTradeHistory { + id: number; + ts: number; + data: FuturesTrade[]; } ⋮---- -/** Comma-separated list of successfully cancelled order_id or client_order_id */ -⋮---- -/** Switch leverage response data from swap_switch_lever_rate */ -export interface FuturesSwitchLeverRate { - contract_code: string; - margin_mode: string; - lever_rate: number; +/** Open interest tick item from swap_his_open_interest */ +export interface FuturesOpenInterestTick { + volume: number; + amount_type: number; + ts: number; + value: number; } ⋮---- -/** Switch leverage response data from swap_cross_switch_lever_rate */ -export interface FuturesCrossSwitchLeverRate { +/** Open interest data from swap_his_open_interest. data is object with tick array. */ +export interface FuturesHistoricalOpenInterest { + symbol: string; contract_code: string; - margin_mode: string; - lever_rate: number; contract_type: string; pair: string; business_type: string; + tick: FuturesOpenInterestTick[]; } ⋮---- /** - * Batch order response data from swap_batchorder and swap_cross_batchorder. - * A successful request can contain both accepted and rejected orders. + * Account */ -export interface FuturesBatchOrder { - errors: FuturesBatchOrderError[]; - success: FuturesBatchOrderSuccess[]; +⋮---- +/** Asset valuation item from swap_balance_valuation */ +export interface FuturesBalanceValuation { + valuation_asset: string; + balance: string; } ⋮---- -/** Position mode item from swap_switch_position_mode and swap_cross_switch_position_mode */ -export interface FuturesSwitchPositionMode { +/** 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; } ⋮---- -/** Order info item from getOrderInfo, getCoinMDeliveryOrderInfo, getCoinMPerpOrderInfo. Product-specific fields optional. */ -export interface FuturesOrderInfo { +/** Cross account contract detail (swap + futures) from swap_cross_account_info */ +export interface FuturesCrossAccountContractDetail { 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_position: number; 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; + 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; } ⋮---- -/** USDM only */ -⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ -⋮---- -/** 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; +/** 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[]; } ⋮---- -/** Order detail from getOrderDetail, getCoinMDeliveryOrderDetail, getCoinMPerpOrderDetail. Product-specific fields optional. */ -export interface FuturesOrderDetail { +/** Position info item from swap_position_info and swap_cross_position_info */ +export interface FuturesPositionInfo { 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; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: 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 */ + 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; - canceled_source?: string; - self_match_prevent?: number; + margin?: number | string; } ⋮---- -/** USDM only */ -⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ -⋮---- -/** Open order item from swap_openorders and swap_cross_openorders */ -export interface FuturesOpenOrder { +/** Nested position in swap_account_position_info */ +export interface FuturesAccountPosition { 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; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: number; profit: number; - status: number; - order_source: string; - fee_asset: string; - liquidation_type: string | null; - canceled_at: number | null; + margin_asset: string; + position_margin: number; + lever_rate: number; + direction: string; + last_price: number; 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; + position_mode: string; + adl_risk_percent?: string | number; + new_risk_rate?: string | null; + trade_partition?: 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; -}; -⋮---- -/** History order from getHistoryOrders, getCoinMDeliveryHistoryOrders, getCoinMPerpHistoryOrders. Product-specific optional. */ -export interface FuturesHistoryOrder { - query_id: number; - order_id: number | string; - order_id_str: string; +/** 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; - direction: string; - offset: string; + adjust_factor: number; + margin_mode: string; + margin_account: string; + position_mode: string; + positions: FuturesAccountPosition[]; + adl_risk_percent?: string | number; +} +⋮---- +/** Cross position item (in positions array) from swap_cross_account_position_info */ +export interface FuturesCrossAccountPositionItem { + symbol: string; + contract_code: 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; + available: number; + frozen: number; + cost_open: number; + cost_hold: number; + profit_unreal: number; + profit_rate: 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; -} -⋮---- -/** USDM only */ -⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ -⋮---- -/** 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; + margin_asset: string; + position_margin: number; + lever_rate: number; 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; -} -⋮---- -/** 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 { + last_price: number; + margin_mode: string; margin_account: string; - position_mode: 'single_side' | 'dual_side'; + contract_type: string; + pair: string; + business_type: string; + position_mode: string; + new_risk_rate?: string | null; + trade_partition?: string; } ⋮---- -/** Transfer state item from swap_cross_transfer_state */ -export interface FuturesCrossTransferState { +/** Cross account + positions from swap_cross_account_position_info. data is object, not array. */ +export interface FuturesCrossAccountPosition { 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; + 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; } ⋮---- -/** 1: available, 0: unavailable */ +/** 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; +} ⋮---- -/** 1: available, 0: unavailable */ +/** Sub auth response data from swap_sub_auth */ +export interface FuturesSubAuth { + errors: FuturesSubAuthError[]; + successes: string; +} ⋮---- -/** 1: available, 0: unavailable */ +/** Sub auth success item from swap_sub_auth_list */ +export interface FuturesSubAuthSuccess { + query_id?: number; + sub_uid: string; + sub_auth: number | string; +} ⋮---- -/** 1: available, 0: unavailable */ +/** Sub permissions response from getSubPermissions */ +export interface FuturesSubPermissions { + errors: FuturesSubAuthError[]; + successes: FuturesSubAuthSuccess[]; +} ⋮---- -/** Trade state item from swap_cross_trade_state */ -export interface FuturesCrossTradeState { +/** 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; - 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; + /** Used as from_id for next/prev pagination */ + query_id?: number; } ⋮---- -/** 1=available, 0=unavailable */ -⋮---- -/** 1=available, 0=unavailable */ +/** Used as from_id for next/prev pagination */ ⋮---- -/** 1=available, 0=unavailable */ +/** Isolated sub-account entry from swap_sub_account_list (data array element) */ +export interface FuturesIsolatedSubAccountListEntry { + sub_uid: number; + list: FuturesIsolatedSubAccountList[]; +} ⋮---- -/** 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; +/** Cross sub-account list item from swap_cross_sub_account_list */ +export interface FuturesCrossSubAccountList { margin_mode: string; margin_account: string; - reduce_only: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: string; + margin_asset: string; + margin_balance: number; + risk_rate: number | string | null; + trade_partition?: string; } ⋮---- -/** Cross margin only */ +/** 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[]; +} ⋮---- -/** Trigger open orders response from swap_trigger_openorders and swap_cross_trigger_openorders */ -export type FuturesTriggerOpenOrders = - FuturesPaginatedOrders; +/** 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; +} ⋮---- -/** Trigger order history item from swap_trigger_hisorders and swap_cross_trigger_hisorders */ -export interface FuturesTriggerOrderHisOrder { +/** Account info item from swap_sub_account_info_list */ +export interface FuturesSubAccountInfoAccount { 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; + margin_mode: string; + margin_asset: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | string | null; } ⋮---- -/** Cross margin only */ -⋮---- -/** Trigger history orders response from getTriggerHistoryOrders, getCrossTriggerHistoryOrders */ -export type FuturesTriggerHistoryOrders = - FuturesPaginatedOrders; +/** Sub-account item in swap_sub_account_info_list data.sub_list */ +export interface FuturesSubAccountInfoSub { + sub_uid: number; + account_info_list: FuturesSubAccountInfoAccount[]; +} ⋮---- -/** 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; +/** object from swap_sub_account_info_list */ +export type FuturesSubAccountInfoList = + FuturesPaginatedSubList; +⋮---- +/** 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; } ⋮---- -/** 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; +/** Cross sub-account info list: sub_list item */ +export interface FuturesCrossSubAccountInfoListSub { + sub_uid: number; + account_info_list: FuturesCrossSubAccountInfoListAccount[]; } ⋮---- -/** TPSL open order item from swap_tpsl_openorders and swap_cross_tpsl_openorders */ -export interface FuturesTpslOpenOrder { +/** Cross sub-account info list: unite_sub_list item */ +export interface FuturesCrossSubAccountInfoListUnite { + sub_uid: number; + asset_multi_sub: FuturesCrossSubAccountAssetMultiSub; +} +⋮---- +/** object from swap_cross_sub_account_info_list */ +export type FuturesCrossSubAccountInfoList = + FuturesPaginatedSubList & { + unite_sub_list: FuturesCrossSubAccountInfoListUnite[]; + }; +⋮---- +/** 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; - 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; + position_mode: string; } ⋮---- -/** Cross margin only */ +/** 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[]; +} ⋮---- -/** TPSL open orders response from swap_tpsl_openorders and swap_cross_tpsl_openorders */ -export type FuturesTpslOpenOrders = - FuturesPaginatedOrders; +/** 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; +} ⋮---- -/** TPSL history order item from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ -export interface FuturesTpslHisOrder { - symbol: string; +/** Available leverage item from swap_available_level_rate */ +export interface FuturesAvailableLevelRate { 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; + available_level_rate: string; } ⋮---- -/** Cross margin only */ +/** 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; +} ⋮---- -/** TPSL history orders response from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ -export type FuturesTpslHisOrders = FuturesPaginatedOrders; +/** 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; +} ⋮---- -/** 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; +/** from swap_order_limit */ +export interface FuturesOrderLimit { + order_price_type: string; + list: FuturesOrderLimitList[]; } ⋮---- -/** Relation TPSL order from getRelationTpslOrder, getCoinMDeliveryRelationTpslOrder, getCoinMPerpRelationTpslOrder. Product-specific optional. */ -export interface FuturesRelationTpslOrder { +/** Fee item from swap_fee */ +export interface FuturesFee { 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; + open_maker_fee: string; + open_taker_fee: string; + close_maker_fee: string; + close_taker_fee: 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; + contract_type: string; + pair: string; + business_type: string; + delivery_fee: string; } ⋮---- -/** USDM only */ -⋮---- -/** CM Delivery: required; USDM/CM Perp: optional */ -⋮---- -/** Trailing order open order item from swap_track_openorders and swap_cross_track_openorders */ -export interface FuturesTrackOpenOrder { +/** Transfer limit item from swap_transfer_limit */ +export interface FuturesTransferLimit { 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; + 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; } ⋮---- -/** Cross margin only */ -⋮---- -/** 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; +/** Transfer limit item from swap_cross_transfer_limit */ +export interface FuturesCrossTransferLimit { margin_mode: string; margin_account: string; - reduce_only: number; - /** Cross margin only */ - contract_type?: string; - pair?: string; - business_type?: 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; } ⋮---- -/** 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 { +/** Position limit item from swap_position_limit */ +export interface FuturesPositionLimit { 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; + buy_limit: number; + sell_limit: number; + lever_rate: number; + buy_limit_value: number; + sell_limit_value: number; + mark_price: number; } ⋮---- -/** Cross futures item within unified_account_info */ -export interface FuturesUnifiedAccountCrossFuture { +/** Position limit item from swap_cross_position_limit */ +export interface FuturesCrossPositionLimit { symbol: string; contract_code: string; margin_mode: string; - margin_available: number | string; - cross_max_available?: number | string; - lever_rate: number | 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; } ⋮---- -/** Isolated swap item within unified_account_info */ -export interface FuturesUnifiedAccountIsolatedSwap { +/** 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; +} +⋮---- +/** Lever position limit item from swap_lever_position_limit */ +export interface FuturesLeverPositionLimit { symbol: string; contract_code: string; margin_mode: string; - margin_available: number | string; - withdraw_available?: number | string; - lever_rate: number | string; - position_mode?: 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; + list: FuturesLeverPositionLimitList[]; } ⋮---- -/** 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; +/** 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[]; } ⋮---- -/** Fix position margin change record item from fix_position_margin_change_record */ -export interface FuturesFixPositionMarginChangeRecord { - query_id: number; +/** Master-sub transfer response from transfer*MasterSub */ +export interface FuturesMasterSubTransfer { order_id: string; - amount: number | string; - asset: string; - symbol: string; - type: number; - direction: number; + client_order_id?: number; } ⋮---- -/** Fix position margin change response data from fix_position_margin_change */ -export interface FuturesFixPositionMarginChange { +/** 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; - contract_code: string; - type: number; - direction: number; - order_id: string; - client_order_id: number | string | null; + asset?: string; + margin_account?: string; + from_margin_account?: string; + to_margin_account?: string; + symbol?: string; + contract_code?: string; } ⋮---- -/** - * USDT Margined Futures Multi Asset - Account (v5 API) - */ +/** Master-sub transfer records from swap_master_sub_transfer_record */ +export type FuturesMasterSubTransferRecords = + FuturesPaginatedTransferRecord; ⋮---- -/** 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; +/** Cancel-after response data from linear-cancel-after */ +export interface FuturesCancelAfter { + current_time: number; + trigger_time: 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[]; +/** 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; } ⋮---- -/** "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; +/** Batch order error item from swap_batchorder and swap_cross_batchorder */ +export interface FuturesBatchOrderError { + index: number; + err_code: number; + err_msg: string; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ +/** Cancel order error item from swap_cancel and swap_cross_cancel */ +export interface FuturesCancelOrderError { + order_id: string; + err_code: number; + err_msg: string; +} ⋮---- -/** 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; +/** 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; } ⋮---- -/** 1: Yes; 0: No */ -⋮---- -/** Deduction currency (e.g. htx, trx). Not returned when fee_option = 0 */ +/** Comma-separated list of successfully cancelled order_id or client_order_id */ ⋮---- -/** Financial record item from /v5/account/bills */ -export interface FuturesV5Bill { - id: string; +/** Switch leverage response data from swap_switch_lever_rate */ +export interface FuturesSwitchLeverRate { contract_code: string; margin_mode: string; - /** - * Financial type code. - * 160: dividend settlement income. 161: dividend settlement expense. - */ - type: string; - currency: string; - amount: string; - created_time: string; + lever_rate: number; } ⋮---- -/** - * Financial type code. - * 160: dividend settlement income. 161: dividend settlement expense. - */ +/** 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; +} ⋮---- /** - * USDT Margined Futures Multi Asset - Orders (v5 API) + * Batch order response data from swap_batchorder and swap_cross_batchorder. + * A successful request can contain both accepted and rejected orders. */ -⋮---- -/** Place order response from POST /v5/trade/order */ -export interface FuturesV5PlaceOrderResp { - order_id: string; - client_order_id?: string; -} -⋮---- -/** Batch place order item from POST /v5/trade/batch_orders */ -export interface FuturesV5PlaceBatchOrderRespItem { - order_id: string; - client_order_id?: string; - code: number; - message: string; +export interface FuturesBatchOrder { + errors: FuturesBatchOrderError[]; + success: FuturesBatchOrderSuccess[]; } ⋮---- -/** Close position response from POST /v5/trade/position */ -export interface FuturesV5ClosePositionResp { - order_id: string | number; - client_order_id?: string; +/** Position mode item from swap_switch_position_mode and swap_cross_switch_position_mode */ +export interface FuturesSwitchPositionMode { + margin_account: string; + position_mode: string; } ⋮---- -/** Open order / order info / order history item from v5 trade endpoints */ -export interface FuturesV5Order { - id: string; +/** Order info item from getOrderInfo, getCoinMDeliveryOrderInfo, getCoinMPerpOrderInfo. Product-specific fields optional. */ +export interface FuturesOrderInfo { + symbol: 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; + 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; - 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; -} -⋮---- -/** 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; + fee_asset: string; + liquidation_type: string | null; + is_tpsl: number; + real_profit: number; + update_time?: number; + /** USDM only */ + margin_asset?: 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; + 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; } ⋮---- -/** Cancel-after response from POST /v5/trade/cancel-after */ -export interface FuturesV5CancelAfterResp { - current_time: string; - trigger_time?: string; -} -⋮---- -/** Place algo order item from POST /v5/algo/order */ -export interface FuturesV5PlaceAlgoOrderResp { - algo_id: string; - algo_client_order_id?: string; -} +/** USDM only */ ⋮---- -/** 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; -} +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** 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; +/** 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; - 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; + fee_asset?: string; + canceled_source?: string; + self_match_prevent?: string | number; } ⋮---- -/** - * USDT Margined Futures Multi Asset - Positions (v5 API) - */ -⋮---- -/** Position from GET /v5/trade/position/opens */ -export interface FuturesV5Position { +/** Order detail from getOrderDetail, getCoinMDeliveryOrderDetail, getCoinMPerpOrderDetail. Product-specific fields optional. */ +export interface FuturesOrderDetail { + symbol: string; contract_code: string; - position_side: string; + lever_rate: number; 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; + 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; } ⋮---- -/** 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[]; -} +/** USDM only */ ⋮---- -/** Set leverage response from POST /v5/position/lever */ -export interface FuturesV5SetLeverageResp { +/** CM Delivery: required; USDM/CM Perp: optional */ +⋮---- +/** Open order item from swap_openorders and swap_cross_openorders */ +export interface FuturesOpenOrder { + symbol: string; contract_code: string; - margin_mode: string; - position_side?: 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; } ⋮---- -/** Position mode from GET/POST /v5/position/mode */ -export interface FuturesV5PositionModeResp { - position_mode: 'single_side' | 'dual_side'; -} +/** Cross margin only */ ⋮---- -/** 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; -} +/** 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; +}; ⋮---- -/** Risk limit tier entry from GET /v5/position/risk/limit_tier */ -export interface FuturesV5RiskLimitTierEntry { +/** 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; - margin_mode: string; - tier: number; - max_lever: string; - maintenance_margin_rate: string; - max_volume: string; - min_volume: string; - volume_unit: 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; } ⋮---- -/** - * USDT Margined Futures Multi Asset - Basic Information (v5 API) - */ +/** USDM only */ ⋮---- -/** Funding fee type on GET /v5/market/funding_rate_history */ -export type FuturesV5FundingFeeType = 'normal' | 'dividend_settlement'; +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Historical funding rate item from GET /v5/market/funding_rate_history */ -export interface FuturesV5FundingRateHistory { +/** Fill / match result from getFills, getCoinMDeliveryFills, getCoinMPerpFills. Product-specific optional. */ +export interface FuturesMatchResult { id: string; - /** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ + query_id: number; + match_id: number | string; + order_id: number | string; + order_id_str: string; + symbol: string; 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; + 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; } ⋮---- -/** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ +/** USDM only */ ⋮---- -/** Funding time, unix ms */ +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ +/** getFillsExact only */ ⋮---- -/** Risk limit entry from GET /v5/market/risk/limit */ -export interface FuturesV5MarketRiskLimitEntry { - contract_code: string; +/** Position mode item from swap_position_side and swap_cross_position_side */ +export interface FuturesPositionSideInfo { + margin_account: string; + position_mode: 'single_side' | 'dual_side'; +} +⋮---- +/** Transfer state item from swap_cross_transfer_state */ +export interface FuturesCrossTransferState { margin_mode: string; - tier: number; - max_lever: string; - maintenance_margin_rate: string; - max_volume: string; - min_volume: string; - volume_unit?: 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; } ⋮---- -/** Assets deduction currency from GET /v5/market/assets_deduction_currency */ -export interface FuturesV5AssetsDeductionCurrencyResp { - currency: string[]; -} -⋮---- -/** Multi-assets margin from GET /v5/market/multi_assets_margin */ -export interface FuturesV5MultiAssetsMarginResp { - multi_assets: string[]; -} -⋮---- -/** - * Coin-M Delivery - Reference Data (FuturesCmDelivery) - */ -⋮---- -/** Ladder item from contract_adjustfactor */ -export interface FuturesCmDeliveryAdjustFactorLadder { - ladder: number; - min_size: number; - max_size: number | null; - adjust_factor: number; -} +/** 1: available, 0: unavailable */ ⋮---- -/** Lever item in adjust factor list */ -export interface FuturesCmDeliveryAdjustFactorLeverItem { - lever_rate: number; - ladders: FuturesCmDeliveryAdjustFactorLadder[]; -} +/** 1: available, 0: unavailable */ ⋮---- -/** GET /api/v1/contract_adjustfactor */ -export interface FuturesCmDeliveryAdjustFactor { - symbol: string; - list: FuturesCmDeliveryAdjustFactorLeverItem[]; -} +/** 1: available, 0: unavailable */ ⋮---- -/** Tick from contract_his_open_interest */ -export interface FuturesCmDeliveryOpenInterestTick { - volume: string; - amount_type: number; - ts: number; -} +/** 1: available, 0: unavailable */ ⋮---- -/** GET /api/v1/contract_his_open_interest */ -export interface FuturesCmDeliveryOpenInterest { +/** 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; - tick: FuturesCmDeliveryOpenInterestTick[]; -} -⋮---- -/** 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; -} -⋮---- -/** Lever item in ladder margin list */ -export interface FuturesCmDeliveryLadderMarginLeverItem { - lever_rate: number; - ladders: FuturesCmDeliveryLadderMarginLadder[]; + pair: string; + business_type: string; + /** 1=available, 0=unavailable */ + open: number; + /** 1=available, 0=unavailable */ + close: number; + /** 1=available, 0=unavailable */ + cancel: number; } ⋮---- -/** GET /api/v1/contract_ladder_margin */ -export interface FuturesCmDeliveryLadderMargin { - symbol: string; - list: FuturesCmDeliveryLadderMarginLeverItem[]; -} +/** 1=available, 0=unavailable */ ⋮---- -/** Ladder from GET /swap-api/v1/swap_adjustfactor */ -export interface FuturesCmPerpAdjustFactorLadder { - ladder: number; - min_size: number; - max_size: number | null; - adjust_factor: number; -} +/** 1=available, 0=unavailable */ ⋮---- -/** Lever item from swap_adjustfactor list */ -export interface FuturesCmPerpAdjustFactorLeverItem { - lever_rate: number; - ladders: FuturesCmPerpAdjustFactorLadder[]; -} +/** 1=available, 0=unavailable */ ⋮---- -/** GET /swap-api/v1/swap_adjustfactor */ -export interface FuturesCmPerpAdjustFactor { +/** Trigger order open order item from swap_trigger_openorders and swap_cross_trigger_openorders */ +export interface FuturesTriggerOrderOpenOrder { symbol: string; contract_code: string; - list: FuturesCmPerpAdjustFactorLeverItem[]; -} -⋮---- -/** Tick from GET /swap-api/v1/swap_his_open_interest */ -export interface FuturesCmPerpOpenInterestTick { + trigger_type: string; volume: number; - amount_type: number; - ts: number; -} -⋮---- -/** GET /swap-api/v1/swap_his_open_interest */ -export interface FuturesCmPerpOpenInterest { - symbol: string; - contract_code: string; - tick: FuturesCmPerpOpenInterestTick[]; + 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; } ⋮---- -/** 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; -} +/** Cross margin only */ ⋮---- -/** Lever item from swap_ladder_margin list */ -export interface FuturesCmPerpTieredMarginLeverItem { - lever_rate: number; - ladders: FuturesCmPerpTieredMarginLadder[]; -} +/** Trigger open orders response from swap_trigger_openorders and swap_cross_trigger_openorders */ +export type FuturesTriggerOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** GET /swap-api/v1/swap_ladder_margin */ -export interface FuturesCmPerpTieredMargin { +/** Trigger order history item from swap_trigger_hisorders and swap_cross_trigger_hisorders */ +export interface FuturesTriggerOrderHisOrder { symbol: string; contract_code: string; - list: FuturesCmPerpTieredMarginLeverItem[]; + 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; } ⋮---- -/** 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; -} +/** Cross margin only */ ⋮---- -/** GET /swap-api/v1/swap_elite_account_ratio */ -export interface FuturesCmPerpAccountRatio { - symbol: string; - contract_code: string; - list: FuturesCmPerpAccountRatioItem[]; +/** Trigger history orders response from getTriggerHistoryOrders, getCrossTriggerHistoryOrders */ +export type FuturesTriggerHistoryOrders = + FuturesPaginatedOrders; +⋮---- +/** 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; } ⋮---- -/** List item from GET /swap-api/v1/swap_elite_position_ratio */ -export interface FuturesCmPerpPositionRatioItem { - buy_ratio: number; - sell_ratio: number; - ts: number; +/** 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; } ⋮---- -/** GET /swap-api/v1/swap_elite_position_ratio */ -export interface FuturesCmPerpPositionRatio { +/** TPSL open order item from swap_tpsl_openorders and swap_cross_tpsl_openorders */ +export interface FuturesTpslOpenOrder { symbol: string; contract_code: string; - list: FuturesCmPerpPositionRatioItem[]; + 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; } ⋮---- -/** 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'; -} +/** Cross margin only */ ⋮---- -/** GET /swap-api/v1/swap_api_state */ -export interface FuturesCmPerpSystemStatus { +/** TPSL open orders response from swap_tpsl_openorders and swap_cross_tpsl_openorders */ +export type FuturesTpslOpenOrders = + FuturesPaginatedOrders; +⋮---- +/** TPSL history order item from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ +export interface FuturesTpslHisOrder { 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; + 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; } ⋮---- -/** 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; +/** Cross margin only */ +⋮---- +/** TPSL history orders response from swap_tpsl_hisorders and swap_cross_tpsl_hisorders */ +export type FuturesTpslHisOrders = FuturesPaginatedOrders; +⋮---- +/** 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; } ⋮---- -/** Item from GET /swap-api/v1/swap_historical_funding_rate data[] */ -export interface FuturesCmPerpHistoricalFundingRate { +/** 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; - funding_time: string; - funding_rate: string; - /** Deprecated, default null */ - realized_rate?: string | null; - avg_premium_index: 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; } ⋮---- -/** Deprecated, default null */ +/** USDM only */ ⋮---- -/** Paginated wrapper for GET /swap-api/v1/swap_historical_funding_rate */ -export type FuturesCmPerpHistoricalFundingRatePage = - FuturesPaginatedData; +/** CM Delivery: required; USDM/CM Perp: optional */ ⋮---- -/** Item from GET /swap-api/v3/swap_liquidation_orders data[] */ -export interface FuturesCmPerpLiquidationOrder { - query_id?: number; - contract_code: 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; - volume: number; - price: number; + lever_rate: number; + order_id: number | string; + order_id_str: string; + order_source: string; created_at: number; - amount: 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; } ⋮---- -/** Item from GET /swap-api/v1/swap_settlement_records settlement_record[] */ -export interface FuturesCmPerpSettlementRecord { +/** Cross margin only */ +⋮---- +/** 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; - settlement_time: number; - clawback_ratio: number; - settlement_price: number; - settlement_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 | 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; } ⋮---- -/** Paginated wrapper for GET /swap-api/v1/swap_settlement_records */ -export type FuturesCmPerpSettlementRecordsPage = - FuturesPaginatedSettlement; +/** Cross margin only */ ⋮---- -/** Index constituents from GET /swap-api/market/swap_constituents. data is object. */ -export interface FuturesCmPerpIndexConstituents { +/** 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; - ts: number; - index_price: string; - components: FuturesIndexConstituentComponent[]; + margin_mode: string; + margin_available: number | string; + cross_max_available?: number | string; + lever_rate: number | string; + contract_type: string; + business_type: string; } ⋮---- -/** Item from GET /swap-api/v1/swap_contract_info data[] */ -export interface FuturesCmPerpContractInfo { +/** Cross futures item within unified_account_info */ +export interface FuturesUnifiedAccountCrossFuture { 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[]; + margin_mode: string; + margin_available: number | string; + cross_max_available?: number | string; + lever_rate: number | string; + contract_type: string; + business_type: string; } ⋮---- -/** Item from GET /swap-api/v1/swap_open_interest data[] */ -export interface FuturesCmPerpOpenInterestCurrent { +/** Isolated swap item within unified_account_info */ +export interface FuturesUnifiedAccountIsolatedSwap { symbol: string; contract_code: string; - volume: number; - amount: number; - trade_amount: number; - trade_volume: number; - trade_turnover: number; + margin_mode: string; + margin_available: number | string; + withdraw_available?: number | string; + lever_rate: number | string; + position_mode?: string; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** Empty string when no delivery */ +/** 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; +} ⋮---- -/** 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; +/** 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; } ⋮---- -/** BBO tick from GET /swap-ex/market/bbo. ask/bid: [price, qty]. Payload in "ticks". */ -export interface FuturesCmPerpMarketBbo { +/** Fix position margin change response data from fix_position_margin_change */ +export interface FuturesFixPositionMarginChange { + amount: number | string; + asset: string; contract_code: string; - mrid: number; - ask: [number, number]; - bid: [number, number]; - ts: number; + type: number; + direction: number; + order_id: string; + client_order_id: number | string | null; } ⋮---- -/** 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; -} +/** + * USDT Margined Futures Multi Asset - Account (v5 API) + */ ⋮---- -/** 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; +/** 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; } ⋮---- -/** 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]; +/** 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[]; } ⋮---- -/** 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]; -} +/** "normal" | "liquidating" | "adl" | "open_limit" */ ⋮---- -/** 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; +/** 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; } ⋮---- -/** Last trade tick from GET /swap-ex/market/trade. Payload in "tick". */ -export interface FuturesCmPerpLastTrade { - id: number; - ts: number; - data: FuturesCmPerpTrade[]; +/** 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; } ⋮---- -/** 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[]; +/** 0: Single-asset collateral (old); 1: Multi-assets collateral; 2: Single-asset collateral (new) */ +⋮---- +/** 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; } ⋮---- -/** 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; +/** 1: Yes; 0: No */ +⋮---- +/** 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: string; + created_time: 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; - amount: string; +/** + * Financial type code. + * 160: dividend settlement income. 161: dividend settlement expense. + */ +⋮---- +/** + * USDT Margined Futures Multi Asset - Orders (v5 API) + */ +⋮---- +/** Place order response from POST /v5/trade/order */ +export interface FuturesV5PlaceOrderResp { + order_id: string; + client_order_id?: string; } ⋮---- -/** 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; +/** Batch place order item from POST /v5/trade/batch_orders */ +export interface FuturesV5PlaceBatchOrderRespItem { + order_id: string; + client_order_id?: string; + code: number; + message: string; } ⋮---- -/** 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; +/** Close position response from POST /v5/trade/position */ +export interface FuturesV5ClosePositionResp { + order_id: string | number; + client_order_id?: string; } ⋮---- -/** Position info from POST /swap-api/v1/swap_position_info */ -export interface FuturesCmPerpPositionInfo { - symbol: string; +/** Open order / order info / order history item from v5 trade endpoints */ +export interface FuturesV5Order { + id: 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; + 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; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** 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[]; +/** Cancel-after response from POST /v5/trade/cancel-after */ +export interface FuturesV5CancelAfterResp { + current_time: string; + trigger_time?: string; } ⋮---- -/** 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; +/** Place algo order item from POST /v5/algo/order */ +export interface FuturesV5PlaceAlgoOrderResp { + algo_id: string; + algo_client_order_id?: string; } ⋮---- -/** Sub-auth response from updateCoinMPerpSubPermissions */ -export interface FuturesCmPerpUpdateSubPermissions { - errors: FuturesCmPerpSubPermissionsError[]; - successes: string; +/** 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; } ⋮---- -/** Sub-auth success item from swap_sub_auth_list */ -export interface FuturesCmPerpSubPermissionsSuccess { - query_id?: number; - sub_uid: string; - sub_auth: number | 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-auth list from getCoinMPerpSubPermissions */ -export interface FuturesCmPerpSubPermissions { - errors: FuturesCmPerpSubPermissionsError[]; - successes: FuturesCmPerpSubPermissionsSuccess[]; -} +/** + * USDT Margined Futures Multi Asset - Positions (v5 API) + */ ⋮---- -/** Sub-account list item from getCoinMPerpSubAccounts list[] */ -export interface FuturesCmPerpSubAccountsItem { - symbol: string; +/** Position from GET /v5/trade/position/opens */ +export interface FuturesV5Position { contract_code: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | null; - query_id?: number; + 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; } ⋮---- -/** Sub-account entry from getCoinMPerpSubAccounts (data array element) */ -export interface FuturesCmPerpSubAccounts { - sub_uid: number; - list: FuturesCmPerpSubAccountsItem[]; +/** 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[]; } ⋮---- -/** Account info item from getCoinMPerpSubAccountsAssets account_info_list[] */ -export interface FuturesCmPerpSubAccountsAssetsAccount { - symbol: string; +/** Set leverage response from POST /v5/position/lever */ +export interface FuturesV5SetLeverageResp { contract_code: string; - margin_balance: number; - liquidation_price: number | null; - risk_rate: number | null; + margin_mode: string; + position_side?: string; + lever_rate: number; } ⋮---- -/** Sub-list item from getCoinMPerpSubAccountsAssets sub_list[] */ -export interface FuturesCmPerpSubAccountsAssetsSub { - sub_uid: number; - account_info_list: FuturesCmPerpSubAccountsAssetsAccount[]; +/** Position mode from GET/POST /v5/position/mode */ +export interface FuturesV5PositionModeResp { + position_mode: 'single_side' | 'dual_side'; } ⋮---- -/** Response from getCoinMPerpSubAccounts */ -export type FuturesCmPerpSubAccountsAssets = - FuturesPaginatedSubList; -⋮---- -/** Sub-account account info from getCoinMPerpSubAccountAssets (data array element) */ -export interface FuturesCmPerpSubAccountAssets { - symbol: string; +/** Risk limit entry from GET /v5/position/risk/limit */ +export interface FuturesV5RiskLimitEntry { 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; + 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-account position from getCoinMPerpSubPositions (data array element) */ -export interface FuturesCmPerpSubPositions { - symbol: string; +/** Risk limit tier entry from GET /v5/position/risk/limit_tier */ +export interface FuturesV5RiskLimitTierEntry { 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; + margin_mode: string; + tier: number; + max_lever: string; + maintenance_margin_rate: string; + max_volume: string; + min_volume: string; + volume_unit: string; } ⋮---- -/** 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; +/** + * USDT Margined Futures Multi Asset - Basic Information (v5 API) + */ +⋮---- +/** Funding fee type on GET /v5/market/funding_rate_history */ +export type FuturesV5FundingFeeType = 'normal' | 'dividend_settlement'; +⋮---- +/** 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; - type: number; - amount: number | string; + funding_rate: string; + /** Funding time, unix ms */ + funding_time: string; + /** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ + funding_fee_type: FuturesV5FundingFeeType; } ⋮---- -/** Available leverage from getCoinMPerpAvailableLeverage */ -export interface FuturesCmPerpAvailableLeverage { +/** Perpetual (e.g. BTC-USDT) or delivery (e.g. BTC-USDT-210625) */ +⋮---- +/** Funding time, unix ms */ +⋮---- +/** `normal`: normal funding fee. `dividend_settlement`: dividend settlement. */ +⋮---- +/** Risk limit entry from GET /v5/market/risk/limit */ +export interface FuturesV5MarketRiskLimitEntry { contract_code: string; - available_level_rate: string; + margin_mode: string; + tier: number; + max_lever: string; + maintenance_margin_rate: string; + max_volume: string; + min_volume: string; + volume_unit?: string; } ⋮---- -/** Order limit list item from swap_order_limit list[] */ -export interface FuturesCmPerpOrderLimitList { - symbol: string; - contract_code: string; - open_limit: number; - close_limit: number; +/** Assets deduction currency from GET /v5/market/assets_deduction_currency */ +export interface FuturesV5AssetsDeductionCurrencyResp { + currency: string[]; } ⋮---- -/** Order limit from POST /swap-api/v1/swap_order_limit */ -export interface FuturesCmPerpOrderLimit { - order_price_type: string; - list: FuturesCmPerpOrderLimitList[]; +/** Multi-assets margin from GET /v5/market/multi_assets_margin */ +export interface FuturesV5MultiAssetsMarginResp { + multi_assets: string[]; } ⋮---- -/** 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; +/** + * Coin-M Delivery - Reference Data (FuturesCmDelivery) + */ +⋮---- +/** Ladder item from contract_adjustfactor */ +export interface FuturesCmDeliveryAdjustFactorLadder { + ladder: number; + min_size: number; + max_size: number | null; + adjust_factor: number; } ⋮---- -/** 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; +/** Lever item in adjust factor list */ +export interface FuturesCmDeliveryAdjustFactorLeverItem { + lever_rate: number; + ladders: FuturesCmDeliveryAdjustFactorLadder[]; } ⋮---- -/** Position limit from POST /swap-api/v1/swap_position_limit */ -export interface FuturesCmPerpPositionLimit { +/** GET /api/v1/contract_adjustfactor */ +export interface FuturesCmDeliveryAdjustFactor { symbol: string; - contract_code: string; - buy_limit: number; - sell_limit: number; + list: FuturesCmDeliveryAdjustFactorLeverItem[]; } ⋮---- -/** 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; +/** Tick from contract_his_open_interest */ +export interface FuturesCmDeliveryOpenInterestTick { + volume: string; + amount_type: number; + ts: number; } ⋮---- -/** API trading status TDN from getCoinMPerpApiStatus */ -export interface FuturesCmPerpApiStatusTdn { - disables_threshold: number; - disables: number; - is_trigger: number; - is_active: number; +/** GET /api/v1/contract_his_open_interest */ +export interface FuturesCmDeliveryOpenInterest { + symbol: string; + contract_type: string; + tick: FuturesCmDeliveryOpenInterestTick[]; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** Cancel-after response from setCoinMPerpCancelAfter */ -export interface FuturesCmPerpCancelAfter { - current_time: number; - trigger_time: number; +/** Lever item in ladder margin list */ +export interface FuturesCmDeliveryLadderMarginLeverItem { + lever_rate: number; + ladders: FuturesCmDeliveryLadderMarginLadder[]; } ⋮---- -/** Trigger open order item from getCoinMPerpTriggerOpenOrders */ -export interface FuturesCmPerpTriggerOpenOrder { +/** GET /api/v1/contract_ladder_margin */ +export interface FuturesCmDeliveryLadderMargin { 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; + list: FuturesCmDeliveryLadderMarginLeverItem[]; } ⋮---- -/** Trigger open orders response from getCoinMPerpTriggerOpenOrders */ -export type FuturesCmPerpTriggerOpenOrders = - FuturesPaginatedOrders; +/** Ladder from GET /swap-api/v1/swap_adjustfactor */ +export interface FuturesCmPerpAdjustFactorLadder { + ladder: number; + min_size: number; + max_size: number | null; + adjust_factor: number; +} ⋮---- -/** Trigger history order item from getCoinMPerpTriggerHisOrders */ -export interface FuturesCmPerpTriggerHisOrder { - symbol: string; - contract_code: string; - trigger_type: string; - volume: number; - order_type: number; - direction: string; - offset: string; +/** Lever item from swap_adjustfactor list */ +export interface FuturesCmPerpAdjustFactorLeverItem { 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; + ladders: FuturesCmPerpAdjustFactorLadder[]; } ⋮---- -/** Trigger history orders response from getCoinMPerpTriggerHistoryOrders */ -export type FuturesCmPerpTriggerHistoryOrders = - FuturesPaginatedOrders; -⋮---- -/** TPSL open order item from getCoinMPerpTpslOpenOrders */ -export interface FuturesCmPerpTpslOpenOrder { +/** GET /swap-api/v1/swap_adjustfactor */ +export interface FuturesCmPerpAdjustFactor { 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; + list: FuturesCmPerpAdjustFactorLeverItem[]; } ⋮---- -/** TPSL open orders response from getCoinMPerpTpslOpenOrders */ -export type FuturesCmPerpTpslOpenOrders = - FuturesPaginatedOrders; -⋮---- -/** TPSL history order item from getCoinMPerpTpslHistoryOrders */ -export interface FuturesCmPerpTpslHisOrder { - symbol: string; - contract_code: string; +/** Tick from GET /swap-api/v1/swap_his_open_interest */ +export interface FuturesCmPerpOpenInterestTick { 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; + amount_type: number; + ts: number; } ⋮---- -/** TPSL history orders response from getCoinMPerpTpslHistoryOrders */ -export type FuturesCmPerpTpslHisOrders = - FuturesPaginatedOrders; -⋮---- -/** Trailing open order item from getCoinMPerpTrailingOpenOrders */ -export interface FuturesCmPerpTrailingOpenOrder { +/** GET /swap-api/v1/swap_his_open_interest */ +export interface FuturesCmPerpOpenInterest { 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; + tick: FuturesCmPerpOpenInterestTick[]; } ⋮---- -/** Trailing open orders response from getCoinMPerpTrailingOpenOrders */ -export type FuturesCmPerpTrailingOpenOrders = - FuturesPaginatedOrders; -⋮---- -/** 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; +/** 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; } ⋮---- -/** Trailing history orders response from getCoinMPerpTrailingHistoryOrders */ -export type FuturesCmPerpTrailingHisOrders = - FuturesPaginatedOrders; -⋮---- -/** Update leverage response from updateCoinMPerpLeverage */ -export interface FuturesCmPerpUpdateLeverage { - contract_code: string; +/** Lever item from swap_ladder_margin list */ +export interface FuturesCmPerpTieredMarginLeverItem { lever_rate: number; + ladders: FuturesCmPerpTieredMarginLadder[]; } ⋮---- -/** Open order item from getCoinMPerpOpenOrders */ -export interface FuturesCmPerpOpenOrder { +/** GET /swap-api/v1/swap_ladder_margin */ +export interface FuturesCmPerpTieredMargin { 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; -} -⋮---- -/** Open orders response from getCoinMPerpOpenOrders */ -export type FuturesCmPerpOpenOrders = - FuturesPaginatedOrders & { - canceled_source?: string; - self_match_prevent?: number; - }; -⋮---- -/** 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[]; + list: FuturesCmPerpTieredMarginLeverItem[]; } ⋮---- -/** List item from contract_elite_account_ratio */ -export interface FuturesCmDeliveryEliteAccountRatioItem { +/** 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; } ⋮---- -/** GET /api/v1/contract_elite_account_ratio */ -export interface FuturesCmDeliveryEliteAccountRatio { +/** GET /swap-api/v1/swap_elite_account_ratio */ +export interface FuturesCmPerpAccountRatio { symbol: string; - list: FuturesCmDeliveryEliteAccountRatioItem[]; + contract_code: string; + list: FuturesCmPerpAccountRatioItem[]; } ⋮---- -/** List item from contract_elite_position_ratio */ -export interface FuturesCmDeliveryElitePositionRatioItem { +/** List item from GET /swap-api/v1/swap_elite_position_ratio */ +export interface FuturesCmPerpPositionRatioItem { buy_ratio: number; sell_ratio: number; ts: number; } ⋮---- -/** GET /api/v1/contract_elite_position_ratio */ -export interface FuturesCmDeliveryElitePositionRatio { +/** GET /swap-api/v1/swap_elite_position_ratio */ +export interface FuturesCmPerpPositionRatio { symbol: string; - list: FuturesCmDeliveryElitePositionRatioItem[]; + contract_code: string; + list: FuturesCmPerpPositionRatioItem[]; } ⋮---- -/** 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; +/** 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'; } ⋮---- -/** Kline item from GET /market/history/kline */ -export interface FuturesCmDeliveryKline { - id: number; - vol: number; - count: number; +/** GET /swap-api/v1/swap_api_state */ +export interface FuturesCmPerpSystemStatus { + symbol: string; + contract_code: string; open: number; close: number; - low: number; - high: number; - amount: number; + cancel: number; + transfer_in: number; + transfer_out: number; + master_transfer_sub: number; + sub_transfer_master: number; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** Ticker from GET /market/detail/merged. 24h summary + best bid/ask. Payload in "tick". Alias: getCoinMDeliveryTicker/getCoinMDeliveryTickers. */ -export interface FuturesCmDeliveryTicker { +/** 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; +} +⋮---- +/** Deprecated, default null */ +⋮---- +/** Paginated wrapper for GET /swap-api/v1/swap_historical_funding_rate */ +export type FuturesCmPerpHistoricalFundingRatePage = + FuturesPaginatedData; +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** Paginated wrapper for GET /swap-api/v1/swap_settlement_records */ +export type FuturesCmPerpSettlementRecordsPage = + FuturesPaginatedSettlement; +⋮---- +/** 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[]; +} +⋮---- +/** 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[]; +} +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** Empty string when no delivery */ +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** 24h ticker from GET /swap-ex/market/detail/merged. Payload in "tick". */ +export interface FuturesCmPerp24hTicker { id: number; ts: number; vol: string; @@ -15861,136 +15113,105 @@ export interface FuturesCmDeliveryTicker { bid: [number, number]; } ⋮---- -export interface FuturesCmDeliveryTrade { +/** 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]; +} +⋮---- +/** 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; - symbol: string; - /** Whether the trade is an RPI trade */ - 'is-rpi-trade'?: boolean | number | string; + contract_code?: string; } ⋮---- -/** Whether the trade is an RPI trade */ -⋮---- -/** Last trade tick from GET /market/trade. Payload in "tick". */ -export interface FuturesCmDeliveryLastTrade { +/** Last trade tick from GET /swap-ex/market/trade. Payload in "tick". */ +export interface FuturesCmPerpLastTrade { id: number; ts: number; - data: FuturesCmDeliveryTrade[]; + data: FuturesCmPerpTrade[]; } ⋮---- -/** Trade item from GET /market/history/trade data array. No symbol in response. */ -export interface FuturesCmDeliveryTradeHistoryItem { +/** Trade history group from GET /swap-ex/market/history/trade. Each group has trades by timestamp. */ +export interface FuturesCmPerpTradeHistory { 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; + data: FuturesCmPerpTrade[]; } ⋮---- -/** Whether the trade is an RPI trade */ +/** 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; +} ⋮---- -/** Trade history from GET /market/history/trade. Each group has trades by timestamp. Payload in "data". Alias: getCoinMDeliveryTradeHistory. */ -export interface FuturesCmDeliveryTradeHistory { +/** Premium index kline item from GET /index/market/history/swap_premium_index_kline */ +export interface FuturesCmPerpPremiumIndexKline { id: number; - ts: number; - data: FuturesCmDeliveryTradeHistoryItem[]; + vol: string; + count: string; + open: string; + close: string; + low: string; + high: string; + amount: string; } ⋮---- -/** Index kline item from GET /index/market/history/index. vol/count/amount typically 0. Alias: getCoinMDeliveryIndexKlines. */ -export interface FuturesCmDeliveryIndexKline { +/** Basis data item from GET /index/market/history/swap_basis */ +export interface FuturesCmPerpBasisData { id: number; - vol: number; - count: number; - open: number; - close: number; - low: number; - high: number; - amount: number; + contract_price: string; + index_price: string; + basis: string; + basis_rate: string; } ⋮---- -/** Account info from POST /api/v1/contract_account_info. Per-symbol margin account. */ -export interface FuturesCmDeliveryAccountInfo { +/** 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_real?: number; profit_unreal: number; risk_rate: number | null; - new_risk_rate: string; - trade_partition: string; - liquidation_price: 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; } ⋮---- -/** 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; -} -⋮---- -/** All sub-account from POST /api/v1/contract_sub_account_list. Alias: getCoinMDeliveryAllSubAccounts. */ -export interface FuturesCmDeliveryAllSubAccount { - sub_uid: number; - list: FuturesCmDeliverySubAccountListItem[]; -} -⋮---- -/** 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; -} -⋮---- -/** Sub-list item from POST /api/v1/contract_sub_account_info_list */ -export interface FuturesCmDeliverySubAccountInfoListSub { - sub_uid: number; - account_info_list: FuturesCmDeliverySubAccountInfoListItem[]; -} -⋮---- -/** Sub-accounts assets from POST /api/v1/contract_sub_account_info_list. Alias: getCoinMDeliverySubAccounts. */ -export type FuturesCmDeliverySubAccountsAssets = - FuturesPaginatedSubList; -⋮---- -/** 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; -} -⋮---- -/** Position info from POST /api/v1/contract_sub_position_info. Single sub-account positions, data array element. */ -export interface FuturesCmDeliverySubPositionInfo { +/** Position info from POST /swap-api/v1/swap_position_info */ +export interface FuturesCmPerpPositionInfo { symbol: string; contract_code: string; - contract_type: string; volume: number; available: number; frozen: number; @@ -16005,15 +15226,14 @@ export interface FuturesCmDeliverySubPositionInfo { last_price: number; adl_risk_percent?: string | number; liq_px: string; - new_risk_rate: string; - trade_partition: string; + new_risk_rate?: string | null; + trade_partition?: string; } ⋮---- -/** Position info from POST /api/v1/contract_position_info. */ -export interface FuturesCmDeliveryPositionInfo { +/** Position item in getCoinMPerpAccountFull positions[] */ +export interface FuturesCmPerpAccountFullPosition { symbol: string; contract_code: string; - contract_type: string; volume: number; available: number; frozen: number; @@ -16027,164 +15247,238 @@ export interface FuturesCmDeliveryPositionInfo { direction: string; last_price: number; adl_risk_percent?: string | number; - liq_px: string; - new_risk_rate: string; - trade_partition: string; } ⋮---- -/** Liquidation order from GET /api/v3/contract_liquidation_orders */ -export interface FuturesCmDeliveryLiquidationOrder { - query_id: number; +/** Account + positions from getCoinMPerpAccountFull */ +/** Account + positions from getCoinMPerpAccountFull */ +export interface FuturesCmPerpAccountFull { symbol: string; contract_code: string; - direction: string; - offset: string; - volume: number; - amount: number; - price: number; - created_at: number; + 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[]; } ⋮---- -/** Settlement record list item from contract_settlement_records */ -export interface FuturesCmDeliverySettlementRecordItem { +/** 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; +} +⋮---- +/** Sub-auth response from updateCoinMPerpSubPermissions */ +export interface FuturesCmPerpUpdateSubPermissions { + errors: FuturesCmPerpSubPermissionsError[]; + successes: string; +} +⋮---- +/** Sub-auth success item from swap_sub_auth_list */ +export interface FuturesCmPerpSubPermissionsSuccess { + query_id?: number; + sub_uid: string; + sub_auth: number | string; +} +⋮---- +/** Sub-auth list from getCoinMPerpSubPermissions */ +export interface FuturesCmPerpSubPermissions { + errors: FuturesCmPerpSubPermissionsError[]; + successes: FuturesCmPerpSubPermissionsSuccess[]; +} +⋮---- +/** Sub-account list item from getCoinMPerpSubAccounts list[] */ +export interface FuturesCmPerpSubAccountsItem { + symbol: string; contract_code: string; - settlement_price: number; - settlement_type: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | null; + query_id?: number; } ⋮---- -/** Settlement record from GET /api/v1/contract_settlement_records */ -export interface FuturesCmDeliverySettlementRecord { +/** Sub-account entry from getCoinMPerpSubAccounts (data array element) */ +export interface FuturesCmPerpSubAccounts { + sub_uid: number; + list: FuturesCmPerpSubAccountsItem[]; +} +⋮---- +/** Account info item from getCoinMPerpSubAccountsAssets account_info_list[] */ +export interface FuturesCmPerpSubAccountsAssetsAccount { symbol: string; - settlement_time: number; - clawback_ratio: number; - list: FuturesCmDeliverySettlementRecordItem[]; + contract_code: string; + margin_balance: number; + liquidation_price: number | null; + risk_rate: number | null; } ⋮---- -/** GET /api/v1/contract_settlement_records */ -export interface FuturesCmDeliverySettlementRecords { - total_page: number; - current_page: number; - total_size: number; - settlement_record: FuturesCmDeliverySettlementRecord[]; +/** Sub-list item from getCoinMPerpSubAccountsAssets sub_list[] */ +export interface FuturesCmPerpSubAccountsAssetsSub { + sub_uid: number; + account_info_list: FuturesCmPerpSubAccountsAssetsAccount[]; } ⋮---- -/** Financial record from POST /api/v3/contract_financial_record and contract_financial_record_exact */ -export interface FuturesCmDeliveryFinancialRecord { - query_id?: number; - id: number; - ts: number; +/** Response from getCoinMPerpSubAccounts */ +export type FuturesCmPerpSubAccountsAssets = + FuturesPaginatedSubList; +⋮---- +/** Sub-account account info from getCoinMPerpSubAccountAssets (data array element) */ +export interface FuturesCmPerpSubAccountAssets { symbol: string; contract_code: string; - type: number; - amount: number | 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; } ⋮---- -/** Position in user settlement record from POST /api/v1/contract_user_settlement_records */ -export interface FuturesCmDeliveryUserSettlementRecordPosition { +/** Sub-account position from getCoinMPerpSubPositions (data array element) */ +export interface FuturesCmPerpSubPositions { symbol: string; contract_code: string; - direction: string; volume: number; + available: number; + frozen: number; cost_open: number; - cost_hold_pre: number; cost_hold: number; - settlement_profit_unreal: number; - settlement_price: number; - settlement_type: string; + 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; } ⋮---- -/** User settlement record from POST /api/v1/contract_user_settlement_records */ -export interface FuturesCmDeliveryUserSettlementRecord { +/** 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; - 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[]; + contract_code: string; + type: number; + amount: number | string; } ⋮---- -/** Response from POST /api/v1/contract_user_settlement_records */ -export interface FuturesCmDeliveryUserSettlementRecords { - total_page: number; - current_page: number; - total_size: number; - settlement_records: FuturesCmDeliveryUserSettlementRecord[]; +/** Available leverage from getCoinMPerpAvailableLeverage */ +export interface FuturesCmPerpAvailableLeverage { + contract_code: string; + available_level_rate: string; } ⋮---- -/** Order limit type from POST /api/v1/contract_order_limit list[].types */ -export interface FuturesCmDeliveryOrderLimitType { - contract_type: string; +/** Order limit list item from swap_order_limit list[] */ +export interface FuturesCmPerpOrderLimitList { + symbol: string; + contract_code: string; open_limit: number; close_limit: number; } ⋮---- -/** Order limit list item from POST /api/v1/contract_order_limit */ -export interface FuturesCmDeliveryOrderLimitListItem { - symbol: string; - types: FuturesCmDeliveryOrderLimitType[]; -} -⋮---- -/** Response from POST /api/v1/contract_order_limit */ -export interface FuturesCmDeliveryOrderLimit { +/** Order limit from POST /swap-api/v1/swap_order_limit */ +export interface FuturesCmPerpOrderLimit { order_price_type: string; - list: FuturesCmDeliveryOrderLimitListItem[]; + list: FuturesCmPerpOrderLimitList[]; } ⋮---- -/** Response from POST /api/v1/contract_switch_lever_rate */ -export interface FuturesCmDeliverySwitchLeverRate { +/** Fee from POST /swap-api/v1/swap_fee */ +export interface FuturesCmPerpFee { symbol: string; - lever_rate: number; + 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; } ⋮---- -/** Open order item from POST /api/v1/contract_openorders data.orders[] */ -export interface FuturesCmDeliveryOpenOrder { +/** Transfer limit from POST /swap-api/v1/swap_transfer_limit */ +export interface FuturesCmPerpTransferLimit { 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; + 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; } ⋮---- -/** Response from POST /api/v1/contract_openorders */ -export type FuturesCmDeliveryOpenOrders = - FuturesPaginatedOrders & { - self_match_prevent?: number; - canceled_source?: 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; +} ⋮---- -/** Trigger open order item from POST /api/v1/contract_trigger_openorders data.orders[] */ -export interface FuturesCmDeliveryTriggerOpenOrder { +/** 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; +} +⋮---- +/** API trading status TDN from getCoinMPerpApiStatus */ +export interface FuturesCmPerpApiStatusTdn { + disables_threshold: number; + disables: number; + is_trigger: number; + is_active: number; +} +⋮---- +/** 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; +} +⋮---- +/** Cancel-after response from setCoinMPerpCancelAfter */ +export interface FuturesCmPerpCancelAfter { + current_time: number; + trigger_time: number; +} +⋮---- +/** Trigger open order item from getCoinMPerpTriggerOpenOrders */ +export interface FuturesCmPerpTriggerOpenOrder { symbol: string; contract_code: string; - contract_type: string; trigger_type: string; volume: number; order_type: number; @@ -16194,22 +15488,21 @@ export interface FuturesCmDeliveryTriggerOpenOrder { order_id: number | string; order_id_str: string; order_source: string; - trigger_price: number; - order_price: number; + trigger_price: number | string; + order_price: number | string; created_at: number; order_price_type: string; status: number; } ⋮---- -/** Response from POST /api/v1/contract_trigger_openorders */ -export type FuturesCmDeliveryTriggerOpenOrders = - FuturesPaginatedOrders; +/** Trigger open orders response from getCoinMPerpTriggerOpenOrders */ +export type FuturesCmPerpTriggerOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** Trigger history order item from POST /api/v1/contract_trigger_hisorders data.orders[] */ -export interface FuturesCmDeliveryTriggerHistoryOrder { +/** Trigger history order item from getCoinMPerpTriggerHisOrders */ +export interface FuturesCmPerpTriggerHisOrder { symbol: string; contract_code: string; - contract_type: string; trigger_type: string; volume: number; order_type: number; @@ -16222,87 +15515,84 @@ export interface FuturesCmDeliveryTriggerHistoryOrder { order_price_type: string; status: number; order_source: string; - trigger_price: number; - triggered_price: number; - order_price: number; + trigger_price: number | string; + triggered_price: number | string | null; + order_price: number | string; created_at: number; - triggered_at: number; + triggered_at: number | null; order_insert_at: number; - canceled_at: number; + canceled_at: number | null; + update_time: number; fail_code: number | null; fail_reason: string | null; - update_time?: number; } ⋮---- -/** Response from POST /api/v1/contract_trigger_hisorders */ -export type FuturesCmDeliveryTriggerHistoryOrders = - FuturesPaginatedOrders; +/** Trigger history orders response from getCoinMPerpTriggerHistoryOrders */ +export type FuturesCmPerpTriggerHistoryOrders = + FuturesPaginatedOrders; ⋮---- -/** TPSL open order item from POST /api/v1/contract_tpsl_openorders data.orders[] */ -export interface FuturesCmDeliveryTpslOpenOrder { +/** TPSL open order item from getCoinMPerpTpslOpenOrders */ +export interface FuturesCmPerpTpslOpenOrder { symbol: string; contract_code: string; - contract_type: string; volume: number; order_type: number; - tpsl_order_type: 'tp' | 'sl'; + tpsl_order_type: string; direction: string; order_id: number | string; order_id_str: string; order_source: string; trigger_type: string; - trigger_price: number; - order_price: number; + 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; - price_protect?: boolean; } ⋮---- -/** Response from POST /api/v1/contract_tpsl_openorders */ -export type FuturesCmDeliveryTpslOpenOrders = - FuturesPaginatedOrders; +/** TPSL open orders response from getCoinMPerpTpslOpenOrders */ +export type FuturesCmPerpTpslOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** TPSL history order item from POST /api/v1/contract_tpsl_hisorders data.orders[] */ -export interface FuturesCmDeliveryTpslHistoryOrder { +/** TPSL history order item from getCoinMPerpTpslHistoryOrders */ +export interface FuturesCmPerpTpslHisOrder { symbol: string; contract_code: string; - contract_type: string; volume: number; order_type: number; - tpsl_order_type: 'tp' | 'sl'; + tpsl_order_type: string; direction: string; order_id: number | string; order_id_str: string; order_source: string; trigger_type: string; - trigger_price: number; - order_price: number; + 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; + canceled_at: number | null; fail_code: number | null; fail_reason: string | null; - triggered_price: number | null; + triggered_price: number | string | null; relation_order_id: string; update_time: number; - price_protect?: boolean; } ⋮---- -/** Response from POST /api/v1/contract_tpsl_hisorders */ -export type FuturesCmDeliveryTpslHistoryOrders = - FuturesPaginatedOrders; +/** TPSL history orders response from getCoinMPerpTpslHistoryOrders */ +export type FuturesCmPerpTpslHisOrders = + FuturesPaginatedOrders; ⋮---- -/** Trailing open order item from POST /api/v1/contract_track_openorders data.orders[] */ -export interface FuturesCmDeliveryTrailingOpenOrder { +/** Trailing open order item from getCoinMPerpTrailingOpenOrders */ +export interface FuturesCmPerpTrailingOpenOrder { symbol: string; contract_code: string; - contract_type: string; volume: number; order_type: number; direction: string; @@ -16314,20 +15604,19 @@ export interface FuturesCmDeliveryTrailingOpenOrder { created_at: number; order_price_type: string; status: number; - callback_rate: number; - active_price: number; + callback_rate: number | string; + active_price: number | string; is_active: number; } ⋮---- -/** Response from POST /api/v1/contract_track_openorders */ -export type FuturesCmDeliveryTrailingOpenOrders = - FuturesPaginatedOrders; +/** Trailing open orders response from getCoinMPerpTrailingOpenOrders */ +export type FuturesCmPerpTrailingOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** Trailing history order item from POST /api/v1/contract_track_hisorders data.orders[] */ -export interface FuturesCmDeliveryTrailingHistoryOrder { +/** Trailing history order item from getCoinMPerpTrailingHistoryOrders */ +export interface FuturesCmPerpTrailingHisOrder { symbol: string; contract_code: string; - contract_type: string; volume: number; order_type: number; direction: string; @@ -16340,2576 +15629,2571 @@ export interface FuturesCmDeliveryTrailingHistoryOrder { update_time: number; order_price_type: string; status: number; - canceled_at: number; + canceled_at: number | null; fail_code: number | null; fail_reason: string | null; - callback_rate: number; - active_price: number; + callback_rate: number | string; + active_price: number | string; is_active: number; - market_limit_price: number | null; - formula_price: number | null; - real_volume: number; - triggered_price: number | null; + market_limit_price: number | string | null; + formula_price: number | string | null; + real_volume: number | string; + triggered_price: number | string | null; relation_order_id: string; } ⋮---- -/** Response from POST /api/v1/contract_track_hisorders */ -export type FuturesCmDeliveryTrailingHistoryOrders = - FuturesPaginatedOrders; -⋮---- -/** 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; -} -⋮---- -/** 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; -} -⋮---- -/** 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; -} +/** Trailing history orders response from getCoinMPerpTrailingHistoryOrders */ +export type FuturesCmPerpTrailingHisOrders = + FuturesPaginatedOrders; ⋮---- -/** Position limit from POST /api/v1/contract_position_limit */ -export interface FuturesCmDeliveryPositionLimit { - symbol: string; - list: FuturesCmDeliveryPositionLimitListItem[]; +/** Update leverage response from updateCoinMPerpLeverage */ +export interface FuturesCmPerpUpdateLeverage { + contract_code: string; + lever_rate: number; } ⋮---- -/** Position in asset_position_info from POST /api/v1/contract_account_position_info */ -export interface FuturesCmDeliveryAssetPositionInfoPosition { +/** Open order item from getCoinMPerpOpenOrders */ +export interface FuturesCmPerpOpenOrder { 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; + 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; } ⋮---- -/** 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[]; +/** Open orders response from getCoinMPerpOpenOrders */ +export type FuturesCmPerpOpenOrders = + FuturesPaginatedOrders & { + canceled_source?: string; + self_match_prevent?: number; + }; +⋮---- +/** 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[]; } ⋮---- -/** 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; +/** List item from contract_elite_account_ratio */ +export interface FuturesCmDeliveryEliteAccountRatioItem { + buy_ratio: number; + sell_ratio: number; + locked_ratio: number; + ts: number; } ⋮---- -/** 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; +/** GET /api/v1/contract_elite_account_ratio */ +export interface FuturesCmDeliveryEliteAccountRatio { + symbol: string; + list: FuturesCmDeliveryEliteAccountRatioItem[]; } ⋮---- -/** 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; +/** List item from contract_elite_position_ratio */ +export interface FuturesCmDeliveryElitePositionRatioItem { + buy_ratio: number; + sell_ratio: number; + ts: number; } ⋮---- -/** Leverage rate from POST /api/v1/contract_available_level_rate. Alias: getCoinMDeliveryLeverageRate. */ -export interface FuturesCmDeliveryLeverageRate { +/** GET /api/v1/contract_elite_position_ratio */ +export interface FuturesCmDeliveryElitePositionRatio { symbol: string; - available_level_rate: string; + list: FuturesCmDeliveryElitePositionRatioItem[]; } ⋮---- -/** GET /api/v1/contract_open_interest */ -export interface FuturesCmDeliveryContractOpenInterest { +/** BBO tick from GET /market/bbo. ask/bid: [price, qty]. Uses symbol (e.g. BTC_CW). */ +export interface FuturesCmDeliveryMarketBbo { symbol: string; - contract_type: string; - contract_code: string; - volume: number; - amount: number; - trade_amount: number; - trade_volume: number; - trade_turnover: number; + mrid: number; + ask: [number, number]; + bid: [number, number]; + ts: number; } ⋮---- -/** Delivery price from GET /api/v1/contract_delivery_price */ -export interface FuturesCmDeliveryDeliveryPrice { - delivery_price: number; +/** 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; } ⋮---- -/** Estimated settlement price list item */ -export interface FuturesCmDeliveryEstimatedSettlementPriceItem { - contract_type: string; - contract_code: string; - estimated_settlement_price: number | null; - settlement_type: string; +/** 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; } ⋮---- -/** GET /api/v1/contract_estimated_settlement_price */ -export interface FuturesCmDeliveryEstimatedSettlementPrice { - symbol: string; - list: FuturesCmDeliveryEstimatedSettlementPriceItem[]; +/** 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]; } ⋮---- -/** GET /api/v1/contract_api_state */ -export interface FuturesCmDeliveryApiState { +export interface FuturesCmDeliveryTrade { + id: number; + price: string; + amount: string; + direction: string; + ts: number; + quantity: string; symbol: string; - open: number; - close: number; - cancel: number; - transfer_in: number; - transfer_out: number; - master_transfer_sub: number; - sub_transfer_master: number; + /** Whether the trade is an RPI trade */ + 'is-rpi-trade'?: boolean | number | string; } ⋮---- -/** 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[]; -} +/** Whether the trade is an RPI trade */ ⋮---- -/** GET /api/market/contract_constituents */ -export interface FuturesCmDeliveryConstituents { - symbol: string; +/** Last trade tick from GET /market/trade. Payload in "tick". */ +export interface FuturesCmDeliveryLastTrade { + id: number; ts: number; - index_price: string; - components: FuturesIndexConstituentComponent[]; + data: FuturesCmDeliveryTrade[]; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** Order limit in query elements */ -export interface FuturesCmDeliveryQueryElementsOrderLimit { - instrument_type: number; - open: string; - close: string; - trigger_protect?: number; +/** Whether the trade is an RPI trade */ +⋮---- +/** 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[]; } ⋮---- -/** 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[]; +/** 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; } ⋮---- -/** - * Copy Trading - */ -⋮---- -/** Lead trading instrument from GET /api/v6/copyTrading/trader/instruments */ -export interface FuturesCopyTraderInstrument { - instId: string; - instType: string; +/** 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; } ⋮---- -/** Profit detail item in trader statistics */ -export interface FuturesCopyTraderProfitDetail { - pnlRate: string; - pnl: string; - ts: string; +/** 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; } ⋮---- -/** 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[]; +/** All sub-account from POST /api/v1/contract_sub_account_list. Alias: getCoinMDeliveryAllSubAccounts. */ +export interface FuturesCmDeliveryAllSubAccount { + sub_uid: number; + list: FuturesCmDeliverySubAccountListItem[]; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** 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; +/** Sub-list item from POST /api/v1/contract_sub_account_info_list */ +export interface FuturesCmDeliverySubAccountInfoListSub { + sub_uid: number; + account_info_list: FuturesCmDeliverySubAccountInfoListItem[]; } ⋮---- -/** 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; +/** Sub-accounts assets from POST /api/v1/contract_sub_account_info_list. Alias: getCoinMDeliverySubAccounts. */ +export type FuturesCmDeliverySubAccountsAssets = + FuturesPaginatedSubList; +⋮---- +/** 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; } ⋮---- -/** Remove follower result item from POST /api/v6/copyTrading/trader/follower */ -export interface FuturesCopyTraderFollowerRemoveResult { - followerUid: string; - scode: string; - smsg: string; +/** 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; } ⋮---- -/** 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; +/** 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; } ⋮---- -/** Lead trading API key from POST /api/v6/copyTrading/trader/apikey */ -export interface FuturesCopyTraderApikey { - label: string; - accessKey: string; - secretKey: string; - perm: string[]; - ts: string; +/** 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; } - -================ -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'; +/** Settlement record list item from contract_settlement_records */ +export interface FuturesCmDeliverySettlementRecordItem { + contract_code: string; + settlement_price: number; + settlement_type: string; +} ⋮---- -/** - * Used to switch how authentication/requests work under the hood - */ -⋮---- -/** Spot */ +/** Settlement record from GET /api/v1/contract_settlement_records */ +export interface FuturesCmDeliverySettlementRecord { + symbol: string; + settlement_time: number; + clawback_ratio: number; + list: FuturesCmDeliverySettlementRecordItem[]; +} ⋮---- -/** Spot AWS */ +/** GET /api/v1/contract_settlement_records */ +export interface FuturesCmDeliverySettlementRecords { + total_page: number; + current_page: number; + total_size: number; + settlement_record: FuturesCmDeliverySettlementRecord[]; +} ⋮---- -/** - * Futures Cloudflare CDN (default for futures clients) - */ +/** 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; +} ⋮---- -/** - * 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". - */ +/** 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; +} ⋮---- -/** - * Futures AWS CDN - */ +/** 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[]; +} ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +/** Response from POST /api/v1/contract_user_settlement_records */ +export interface FuturesCmDeliveryUserSettlementRecords { + total_page: number; + current_page: number; + total_size: number; + settlement_records: FuturesCmDeliveryUserSettlementRecord[]; +} ⋮---- -[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". +/** Order limit type from POST /api/v1/contract_order_limit list[].types */ +export interface FuturesCmDeliveryOrderLimitType { + contract_type: string; + open_limit: number; + close_limit: number; +} ⋮---- -[REST_CLIENT_TYPE_ENUM.futuresAWS]: 'https://api.hbdm.vn', // AWS's CDN +/** Order limit list item from POST /api/v1/contract_order_limit */ +export interface FuturesCmDeliveryOrderLimitListItem { + symbol: string; + types: FuturesCmDeliveryOrderLimitType[]; +} ⋮---- -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; +/** Response from POST /api/v1/contract_order_limit */ +export interface FuturesCmDeliveryOrderLimit { + order_price_type: string; + list: FuturesCmDeliveryOrderLimitListItem[]; } ⋮---- -/** Your API key */ +/** Response from POST /api/v1/contract_switch_lever_rate */ +export interface FuturesCmDeliverySwitchLeverRate { + symbol: string; + lever_rate: number; +} ⋮---- -/** Your API secret */ +/** 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; +} ⋮---- -/** - * Use access token instead of sign, if this is provided. - * For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2 - */ +/** Response from POST /api/v1/contract_openorders */ +export type FuturesCmDeliveryOpenOrders = + FuturesPaginatedOrders & { + self_match_prevent?: number; + canceled_source?: string; + }; ⋮---- -/** Default: false. If true, we'll throw errors if any params are undefined */ +/** 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; +} ⋮---- -/** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.huobi.pro' - **/ +/** Response from POST /api/v1/contract_trigger_openorders */ +export type FuturesCmDeliveryTriggerOpenOrders = + FuturesPaginatedOrders; ⋮---- -/** - * 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 - */ +/** 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; +} ⋮---- -/** Default: true. whether to try and post-process request exceptions (and throw them). */ -⋮---- -/** - * Enable keep alive for REST API requests (via axios). - */ +/** Response from POST /api/v1/contract_trigger_hisorders */ +export type FuturesCmDeliveryTriggerHistoryOrders = + FuturesPaginatedOrders; ⋮---- -/** - * 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) - */ +/** 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; +} ⋮---- -/** - * 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. - */ +/** Response from POST /api/v1/contract_tpsl_openorders */ +export type FuturesCmDeliveryTpslOpenOrders = + FuturesPaginatedOrders; ⋮---- -export type GenericAPIResponse = Promise; +/** 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; +} ⋮---- -export function serializeParams< - T extends Record | undefined = object, ->( - params: T, - strict_validation: boolean | undefined, - encodeValues: boolean, - prefixWith: string, - repeatArrayValuesAsKVPairs: boolean, -): string +/** Response from POST /api/v1/contract_tpsl_hisorders */ +export type FuturesCmDeliveryTpslHistoryOrders = + FuturesPaginatedOrders; ⋮---- -// Only prefix if there's a value +/** 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; +} ⋮---- -export function logInvalidOrderId( - orderIdProperty: SpotOrderIdProperty, - expectedOrderIdPrefix: string, - params: object, -) +/** Response from POST /api/v1/contract_track_openorders */ +export type FuturesCmDeliveryTrailingOpenOrders = + FuturesPaginatedOrders; ⋮---- -function getWSAPICustomOrderIdProperties( - operation: WSAPISpotOperation | string, - wsKey: WsKey, -): OrderIdProperty[] +/** 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; +} ⋮---- -function isOrderParamRecord(value: unknown): value is Record +/** Response from POST /api/v1/contract_track_hisorders */ +export type FuturesCmDeliveryTrailingHistoryOrders = + FuturesPaginatedOrders; ⋮---- -function getOrderParamRecords(params: unknown): Record[] +/** 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; +} ⋮---- -export function requiresWSAPINewCustomOID( - request: HTXWSAPIRequest, - wsKey: WsKey, -): boolean +/** 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; +} ⋮---- -export function validateWSAPICustomOrderID( - request: HTXWSAPIRequest, - wsKey: WsKey, -): void +/** 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; +} ⋮---- -function isDerivativesWSAPIOrderPlacementOperation( - operation: WSAPIDerivativesOperation | string, -): boolean +/** Position limit from POST /api/v1/contract_position_limit */ +export interface FuturesCmDeliveryPositionLimit { + symbol: string; + list: FuturesCmDeliveryPositionLimitListItem[]; +} ⋮---- -export function validateWSAPIDerivativesChannelKey( - request: HTXWSAPIRequest, - wsKey: WsKey, -): void +/** 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; +} ⋮---- -export function isEmptyObject(obj: any, acceptStringIfNotEmpty: boolean) +/** 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[]; +} ⋮---- -export function getRestBaseUrl( - restClientOptions: RestClientOptions, - restClientType: RestClientType, -): string +/** 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; +} ⋮---- -/** - * Iterates to extract pure domain from URL. - * https://example.com/v1/endpoint -> example.com - */ -export function getBaseDomain(url: string): string +/** 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; +} ⋮---- -export function generateNewOrderID(): string +/** 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; +} ⋮---- -export function getOrderIdPrefix(): string - -================ -File: src/SpotClient.ts -================ -import { BaseRestClient } from './lib/BaseRestClient.js'; -import { - generateNewOrderID, - getOrderIdPrefix, - logInvalidOrderId, - REST_CLIENT_TYPE_ENUM, - RestClientType, -} from './lib/requestUtils.js'; -import type { - SpotAccountTransferReq, - SpotBrokerAccountCapitalSnapshotReq, - SpotBrokerSubUserFeeRateAddReq, - SpotCrossMarginLoanOrdersReq, - SpotDepositWithdrawQueryReq, - SpotEarnProjectListReq, - SpotEarnRedeemReq, - SpotEarnSubscribeReq, - SpotEarnUserAssetsReq, - SpotGetAccountHistoryReq, - SpotGetAccountLedgerReq, - SpotGetAssetValuationReq, - SpotGetChainsReq, - SpotGetDepthReq, - SpotGetKlineReq, - SpotGetMatchResultsReq, - SpotGetOpenOrdersReq, - SpotGetOrderHistory48hReq, - SpotGetOrderHistoryReq, - SpotMarginLoanOrderReq, - SpotMarginLoanOrdersReq, - SpotMarginRepaymentReq, - SpotMarginTransferInIsolatedReq, - SpotMarginTransferOutIsolatedReq, - SpotP2POrderHistoryReq, - SpotReferralAllRebateDetailReq, - SpotReferralRebateHistoryReq, - SpotReferralReferralsReq, - SpotRepaymentRecordReq, - SpotSubUserApiKeyCreationReq, - SpotSubUserApiKeyUpdateReq, - SpotSubUserDepositHistoryReq, - SpotSubUserManagedTransferHistoryReq, - SpotSubUserTradableMarketReq, - SpotSubUserTransferPermissionsReq, - SpotSubUserTransferReq, - SpotUniversalTransferRecordsReq, - SpotUniversalTransferReq, - SpotV1FuturesTransferReq, - SpotV1OrderAutoPlaceReq, - SpotV1OrderBatchCancelOpenOrdersReq, - SpotV1OrderPlaceReq, - SpotV2AccountTransferReq, - SpotV2AlgoOrdersHistoryReq, - SpotV2AlgoOrdersOpeningReq, - SpotV2AlgoOrdersPlaceReq, - SpotV2PointTransferReq, - SpotWithdrawAddressReq, - SpotWithdrawCreateReq, -} from './types/request/spot.types.js'; -import { - SpotAPISuccessResponse, - SpotOrderIdProperty, -} from './types/response/shared.types.js'; -import { - SpotAccount, - SpotAccountBalance, - SpotAccountHistory, - SpotAccountTransferResult, - SpotBrokerAccountCapitalSnapshot, - SpotBrokerFeeRateAddResult, - SpotBrokerSubUserFeeRate, - SpotBrokerUserRebateStatus, - SpotCrossMarginAccountBalance, - SpotCrossMarginLoanOrder, - SpotCurrency, - SpotDepositAddress, - SpotDepositWithdrawRecord, - SpotDepth, - SpotDetailTick, - SpotEarnProject, - SpotEarnRedeemResult, - SpotEarnSubscribeResult, - SpotEarnUserAsset, - SpotKline, - SpotLastTrade, - SpotMarginAccountBalance, - SpotMarginLimit, - SpotMarginLoanInfo, - SpotMarginLoanInfoCurrency, - SpotMarginLoanOrder, - SpotMarginRepaymentResult, - SpotMarketStatusResponse, - SpotMergedTicker, - SpotP2POrderHistory, - SpotReferralAllRebateDetail, - SpotReferralRebateDetail, - SpotReferralRebateHistoryRecord, - SpotReferralReferral, - SpotRepaymentRecord, - SpotSubUserAccountsResult, - SpotSubUserApiKey, - SpotSubUserApiKeyCreationResult, - SpotSubUserApiKeyUpdateResult, - SpotSubUserBalanceResult, - SpotSubUserCreationResult, - SpotSubUserDeductModeResult, - SpotSubUserDepositHistoryRecord, - SpotSubUserEntrustUser, - SpotSubUserList, - SpotSubUserLockStatusResult, - SpotSubUserManagedTransferRecord, - SpotSubUsersAggregatedBalance, - SpotSubUserStatusResult, - SpotSubUserTradableMarketResult, - SpotSubUserTransferPermissionsResult, - SpotTicker, - SpotTradeTimestampGroup, - SpotTradingSymbol, - SpotUniversalTransferRecord, - SpotUniversalTransferResult, - SpotV1AccountOverviewInfo, - SpotV1AccountSwitchUserInfo, - SpotV1ChainInfo, - SpotV1CurrencySettings, - SpotV1MarketSymbolSettings, - SpotV1OpenOrder, - SpotV1OrderAutoPlaceResult, - SpotV1OrderBatchCancelOpenOrdersResult, - SpotV1OrderBatchCancelResult, - SpotV1OrderBatchPlaceResult, - SpotV1OrderCancelByClientOrderIdResult, - SpotV1OrderCancelResult, - SpotV1OrderDetail, - SpotV1OrderHistory, - SpotV1OrderHistory48h, - SpotV1OrderMatchResult, - SpotV1SymbolSettings, - SpotV2AccountLedger, - SpotV2AccountValuation, - SpotV2AlgoOrder, - SpotV2AlgoOrdersCancelAllAfterResult, - SpotV2AlgoOrdersCancellationResult, - SpotV2AlgoOrdersPlaceResult, - SpotV2AssetValuation, - SpotV2CurrencyReference, - SpotV2PointAccount, - SpotV2PointTransfer, - SpotV2TransactFeeRate, - SpotVaspExchange, - SpotWithdrawAddress, - SpotWithdrawQuota, -} from './types/response/spot.types.js'; +/** Leverage rate from POST /api/v1/contract_available_level_rate. Alias: getCoinMDeliveryLeverageRate. */ +export interface FuturesCmDeliveryLeverageRate { + symbol: string; + available_level_rate: string; +} ⋮---- -/** - * The SpotClient provides integration to the HTX Spot API. - */ -export class SpotClient extends BaseRestClient +/** 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; +} ⋮---- -getClientType(): RestClientType +/** Delivery price from GET /api/v1/contract_delivery_price */ +export interface FuturesCmDeliveryDeliveryPrice { + delivery_price: number; +} ⋮---- -// Favour the spot AWS domain, as recommended by the API docs +/** Estimated settlement price list item */ +export interface FuturesCmDeliveryEstimatedSettlementPriceItem { + contract_type: string; + contract_code: string; + estimated_settlement_price: number | null; + settlement_type: string; +} ⋮---- -/** - * - * Misc Utility Methods - * - */ +/** GET /api/v1/contract_estimated_settlement_price */ +export interface FuturesCmDeliveryEstimatedSettlementPrice { + symbol: string; + list: FuturesCmDeliveryEstimatedSettlementPriceItem[]; +} ⋮---- -generateNewOrderID(): string +/** 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; +} ⋮---- -/** - * - * Reference Data - * - */ +/** 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[]; +} ⋮---- -/** - * Get Market Status - * - * Returns current market status. - * 1=normal, 2=halted, 3=cancel-only. - */ -getMarketStatus(): Promise +/** GET /api/market/contract_constituents */ +export interface FuturesCmDeliveryConstituents { + symbol: string; + ts: number; + index_price: string; + components: FuturesIndexConstituentComponent[]; +} ⋮---- -/** - * Get Current Timestamp (V1) - * - * Returns current server time in milliseconds since epoch. No signature required. - */ -getTimestamp(): Promise> +/** 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; +} ⋮---- -/** - * Get all Supported Trading Symbols (V2) - * - * Returns all supported trading symbols. Pass ts for incremental updates. - */ -getTradingSymbols(params?: { - ts?: number; -}): Promise> +/** Order limit in query elements */ +export interface FuturesCmDeliveryQueryElementsOrderLimit { + instrument_type: number; + open: string; + close: string; + trigger_protect?: number; +} +⋮---- +/** 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[]; +} ⋮---- /** - * Get all Supported Currencies (V2) - * - * Returns all supported currencies. Pass ts for incremental updates. - */ -getCurrencies(params?: { - ts?: number; -}): Promise> + * Copy Trading + */ +⋮---- +/** Lead trading instrument from GET /api/v6/copyTrading/trader/instruments */ +export interface FuturesCopyTraderInstrument { + instId: string; + instType: string; +} +⋮---- +/** Profit detail item in trader statistics */ +export interface FuturesCopyTraderProfitDetail { + pnlRate: string; + pnl: string; + ts: string; +} +⋮---- +/** 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[]; +} +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** 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; +} +⋮---- +/** Remove follower result item from POST /api/v6/copyTrading/trader/follower */ +export interface FuturesCopyTraderFollowerRemoveResult { + followerUid: string; + scode: string; + smsg: string; +} +⋮---- +/** 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; +} +⋮---- +/** 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: .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/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'; ⋮---- /** - * Get Currencys Settings (V1) - * - * Returns currency settings. No signature required. Pass ts for incremental updates. - */ -getCurrencysSettings(params?: { - ts?: number; -}): Promise> + * Used to switch how authentication/requests work under the hood + */ +⋮---- +/** Spot */ +⋮---- +/** Spot AWS */ ⋮---- /** - * Get Symbols Settings (V1) - * - * Returns symbol settings. No signature required. Pass ts for incremental updates. + * Futures Cloudflare CDN (default for futures clients) */ -getSymbolsSettings(params?: { - ts?: number; -}): Promise> ⋮---- /** - * Get Market Symbols Settings (V1) + * Futures * - * Returns market symbol settings. No signature required. Pass symbols (NA=all) and/or ts for incremental updates. + * 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". */ -getMarketSymbolsSettings(params?: { - symbols?: string; - ts?: number; -}): Promise> ⋮---- /** - * Get Chains Information (V1) - * - * Returns chain info per currency. No signature required. Pass show-desc, currency, and/or ts for incremental updates. + * Futures AWS CDN */ -getChainsInfo( - params?: SpotGetChainsReq, -): Promise> ⋮---- -/** - * Get Reference Currencies & Chains (V2) - * - * Returns static reference info for each currency and its chains. No signature required. - */ -getReferenceCurrencies(params?: { - currency?: string; - authorizedUser?: boolean; -}): Promise> +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -/** - * - * Market Data - * - */ +[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". ⋮---- -/** - * Get Klines (Candles) - * - * Returns candlestick data for a symbol. No signature required. - */ -getKlines( - params: SpotGetKlineReq, -): Promise> +[REST_CLIENT_TYPE_ENUM.futuresAWS]: 'https://api.hbdm.vn', // AWS's CDN ⋮---- -/** - * Get Latest Aggregated Ticker - * - * Returns latest ticker with 24h aggregated market data. No signature required. +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 */ -getTicker(params: { - symbol: string; -}): Promise> -⋮---- -/** - * Get Latest Tickers for All Pairs - * - * Returns latest tickers for all supported pairs. No signature required. + 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 */ -getTickers(): Promise> -⋮---- -/** - * Get Market Depth - * - * Returns order book for a symbol. No signature required. + 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). */ -getMarketDepth( - params: SpotGetDepthReq, -): Promise> -⋮---- -/** - * Get the Last Trade - * - * Returns latest trade with price, volume, direction. No signature required. + 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) */ -getLastTrade(params: { - symbol: string; -}): Promise> -⋮---- -/** - * Get the Most Recent Trades + keepAliveMsecs?: number; + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * - * Returns recent trades grouped by timestamp. No signature required. + * Look in the examples folder for a demonstration on using node's createHmac instead. */ -getHistoryTrades(params: { - symbol: string; - size?: number; -}): Promise> + customSignMessageFn?: (message: string, secret: string) => Promise; +} ⋮---- -/** - * Get the Last 24h Market Summary - * - * Returns 24h trading summary for a symbol. No signature required. - */ -get24hMarketSummary(params: { - symbol: string; -}): Promise> +/** Your API key */ ⋮---- -/** - * Get Full Order Book - * - * Returns complete market depth, up to 5000 levels. Updated once per second. No signature required. - */ -getFullOrderBook(params: { - symbol: string; -}): Promise> +/** Your API secret */ ⋮---- /** - * - * Account - * + * Use access token instead of sign, if this is provided. + * For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2 */ ⋮---- -/** - * Get all Accounts of the Current User - * - * Returns list of accounts owned by this API user. Signature required. - */ -getAccounts(): Promise> +/** Default: false. If true, we'll throw errors if any params are undefined */ ⋮---- /** - * Get Account Balance of a Specific Account - * - * Returns balance for account specified by account id. Signature required. OTC not supported. - */ -getAccountBalance(params: { - accountId: string | number; -}): Promise> + * Optionally override API protocol + domain + * e.g baseUrl: 'https://api.huobi.pro' + **/ ⋮---- /** - * Get The Total Valuation of Platform Assets - * - * Returns total asset valuation in BTC or fiat. Signature required. + * 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 */ -getAccountValuation(params?: { - accountType?: string; - valuationCurrency?: string; -}): Promise> ⋮---- -/** - * Get Asset Valuation - * - * Returns valuation of total assets in BTC or fiat. Signature required. - */ -getAssetValuation( - params?: SpotGetAssetValuationReq, -): Promise> +/** Default: true. whether to try and post-process request exceptions (and throw them). */ ⋮---- /** - * Asset Transfer - * - * Transfer asset between accounts (spot, margin, sub-users). Signature required. Trade permission. + * Enable keep alive for REST API requests (via axios). */ -submitTransfer( - params: SpotAccountTransferReq, -): Promise> ⋮---- /** - * Get Account History - * - * Returns amount changes of specified account. Signature required. Max 1h query window, 30 days range. + * 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) */ -getAccountHistory( - params: SpotGetAccountHistoryReq, - ): Promise< - SpotAPISuccessResponse & { 'next-id'?: number } - > { - return this.getPrivate('/v1/account/history', params); ⋮---- /** - * Get Account Ledger + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * - * Returns amount changes (phase 1: transfer only). Max 10-day window, 180 days range. Signature required. + * Look in the examples folder for a demonstration on using node's createHmac instead. */ -getAccountLedger( - params?: SpotGetAccountLedgerReq, - ): Promise< - SpotAPISuccessResponse & { nextId?: number } - > { - return this.getPrivate('/v2/account/ledger', params); ⋮---- -/** - * V2 Account Transfer - * - * Transfer funds between spot, linear-swap, otc, futures, swap. Signature required. Trade permission. - */ -submitV2AccountTransfer( - params: SpotV2AccountTransferReq, -): Promise> +export type GenericAPIResponse = Promise; ⋮---- -/** - * Create Universal Transfer - * - * Transfer between account types (spot, margin, futures, options, etc). Host: spot. Trade permission. Rate: 5/2s. - */ -submitUniversalTransfer( - params: SpotUniversalTransferReq, -): Promise> +export function serializeParams< + T extends Record | undefined = object, +>( + params: T, + strict_validation: boolean | undefined, + encodeValues: boolean, + prefixWith: string, + repeatArrayValuesAsKVPairs: boolean, +): string ⋮---- -/** - * Get Universal Transfer Records - * - * Query universal transfer history. Host: spot. Trade permission. Rate: 5/2s. - */ -getUniversalTransferRecords( - params?: SpotUniversalTransferRecordsReq, -): Promise> +// Only prefix if there's a value ⋮---- -/** - * Futures Transfer - * - * Transfer between spot and future contract account. pro-to-futures = spot -> contract, futures-to-pro = contract -> spot. Signature required. Trade permission. - */ -submitFuturesTransfer( - params: SpotV1FuturesTransferReq, -): Promise> +export function logInvalidOrderId( + orderIdProperty: SpotOrderIdProperty, + expectedOrderIdPrefix: string, + params: object, +) ⋮---- -/** - * Get Point Balance - * - * Query termless and terminable point balance. Parent can query sub user via subUid. Signature required. Read permission. Rate: 2/s. - */ -getPointBalance(params?: { - subUid?: string; -}): Promise> +function getWSAPICustomOrderIdProperties( + operation: WSAPISpotOperation | string, + wsKey: WsKey, +): OrderIdProperty[] ⋮---- -/** - * Point Transfer - * - * Transfer points between parent and sub user. groupId=0 for termless; for terminable query sub balance first. Signature required. Trade permission. Rate: 2/s. - */ -submitPointTransfer( - params: SpotV2PointTransferReq, -): Promise> +function isOrderParamRecord(value: unknown): value is Record ⋮---- -/** - * Get User Deduction Info - * - * Query point card vs HTX deduction settings. Signature required. Read permission. Rate: 5/s. - */ -getAccountSwitchUserInfo(): Promise< - SpotAPISuccessResponse - > { - return this.getPrivate('/v1/account/switch/user/info'); +function getOrderParamRecords(params: unknown): Record[] +⋮---- +export function requiresWSAPINewCustomOID( + request: HTXWSAPIRequest, + wsKey: WsKey, +): boolean +⋮---- +export function validateWSAPICustomOrderID( + request: HTXWSAPIRequest, + wsKey: WsKey, +): void +⋮---- +function isDerivativesWSAPIOrderPlacementOperation( + operation: WSAPIDerivativesOperation | string, +): boolean +⋮---- +export function validateWSAPIDerivativesChannelKey( + request: HTXWSAPIRequest, + wsKey: WsKey, +): void +⋮---- +export function isEmptyObject(obj: any, acceptStringIfNotEmpty: boolean) +⋮---- +export function getRestBaseUrl( + restClientOptions: RestClientOptions, + restClientType: RestClientType, +): string ⋮---- /** - * Get Deductible Currency Overview - * - * Query asset that can be used to deduct fees. Signature required. Read permission. Rate: 5/s. - */ -getAccountOverviewInfo(): Promise< - SpotAPISuccessResponse - > { - return this.getPrivate('/v1/account/overview/info'); + * Iterates to extract pure domain from URL. + * https://example.com/v1/endpoint -> example.com + */ +export function getBaseDomain(url: string): string +⋮---- +export function generateNewOrderID(): string +⋮---- +export function getOrderIdPrefix(): string + +================ +File: src/SpotClient.ts +================ +import { BaseRestClient } from './lib/BaseRestClient.js'; +import { + generateNewOrderID, + getOrderIdPrefix, + logInvalidOrderId, + REST_CLIENT_TYPE_ENUM, + RestClientType, +} from './lib/requestUtils.js'; +import type { + SpotAccountTransferReq, + SpotBrokerAccountCapitalSnapshotReq, + SpotBrokerSubUserFeeRateAddReq, + SpotCrossMarginLoanOrdersReq, + SpotDepositWithdrawQueryReq, + SpotEarnProjectListReq, + SpotEarnRedeemReq, + SpotEarnSubscribeReq, + SpotEarnUserAssetsReq, + SpotGetAccountHistoryReq, + SpotGetAccountLedgerReq, + SpotGetAssetValuationReq, + SpotGetChainsReq, + SpotGetDepthReq, + SpotGetKlineReq, + SpotGetMatchResultsReq, + SpotGetOpenOrdersReq, + SpotGetOrderHistory48hReq, + SpotGetOrderHistoryReq, + SpotMarginLoanOrderReq, + SpotMarginLoanOrdersReq, + SpotMarginRepaymentReq, + SpotMarginTransferInIsolatedReq, + SpotMarginTransferOutIsolatedReq, + SpotP2POrderHistoryReq, + SpotReferralAllRebateDetailReq, + SpotReferralRebateHistoryReq, + SpotReferralReferralsReq, + SpotRepaymentRecordReq, + SpotSubUserApiKeyCreationReq, + SpotSubUserApiKeyUpdateReq, + SpotSubUserDepositHistoryReq, + SpotSubUserManagedTransferHistoryReq, + SpotSubUserTradableMarketReq, + SpotSubUserTransferPermissionsReq, + SpotSubUserTransferReq, + SpotUniversalTransferRecordsReq, + SpotUniversalTransferReq, + SpotV1FuturesTransferReq, + SpotV1OrderAutoPlaceReq, + SpotV1OrderBatchCancelOpenOrdersReq, + SpotV1OrderPlaceReq, + SpotV2AccountTransferReq, + SpotV2AlgoOrdersHistoryReq, + SpotV2AlgoOrdersOpeningReq, + SpotV2AlgoOrdersPlaceReq, + SpotV2PointTransferReq, + SpotWithdrawAddressReq, + SpotWithdrawCreateReq, +} from './types/request/spot.types.js'; +import { + SpotAPISuccessResponse, + SpotOrderIdProperty, +} from './types/response/shared.types.js'; +import { + SpotAccount, + SpotAccountBalance, + SpotAccountHistory, + SpotAccountTransferResult, + SpotBrokerAccountCapitalSnapshot, + SpotBrokerFeeRateAddResult, + SpotBrokerSubUserFeeRate, + SpotBrokerUserRebateStatus, + SpotCrossMarginAccountBalance, + SpotCrossMarginLoanOrder, + SpotCurrency, + SpotDepositAddress, + SpotDepositWithdrawRecord, + SpotDepth, + SpotDetailTick, + SpotEarnProject, + SpotEarnRedeemResult, + SpotEarnSubscribeResult, + SpotEarnUserAsset, + SpotKline, + SpotLastTrade, + SpotMarginAccountBalance, + SpotMarginLimit, + SpotMarginLoanInfo, + SpotMarginLoanInfoCurrency, + SpotMarginLoanOrder, + SpotMarginRepaymentResult, + SpotMarketStatusResponse, + SpotMergedTicker, + SpotP2POrderHistory, + SpotReferralAllRebateDetail, + SpotReferralRebateDetail, + SpotReferralRebateHistoryRecord, + SpotReferralReferral, + SpotRepaymentRecord, + SpotSubUserAccountsResult, + SpotSubUserApiKey, + SpotSubUserApiKeyCreationResult, + SpotSubUserApiKeyUpdateResult, + SpotSubUserBalanceResult, + SpotSubUserCreationResult, + SpotSubUserDeductModeResult, + SpotSubUserDepositHistoryRecord, + SpotSubUserEntrustUser, + SpotSubUserList, + SpotSubUserLockStatusResult, + SpotSubUserManagedTransferRecord, + SpotSubUsersAggregatedBalance, + SpotSubUserStatusResult, + SpotSubUserTradableMarketResult, + SpotSubUserTransferPermissionsResult, + SpotTicker, + SpotTradeTimestampGroup, + SpotTradingSymbol, + SpotUniversalTransferRecord, + SpotUniversalTransferResult, + SpotV1AccountOverviewInfo, + SpotV1AccountSwitchUserInfo, + SpotV1ChainInfo, + SpotV1CurrencySettings, + SpotV1MarketSymbolSettings, + SpotV1OpenOrder, + SpotV1OrderAutoPlaceResult, + SpotV1OrderBatchCancelOpenOrdersResult, + SpotV1OrderBatchCancelResult, + SpotV1OrderBatchPlaceResult, + SpotV1OrderCancelByClientOrderIdResult, + SpotV1OrderCancelResult, + SpotV1OrderDetail, + SpotV1OrderHistory, + SpotV1OrderHistory48h, + SpotV1OrderMatchResult, + SpotV1SymbolSettings, + SpotV2AccountLedger, + SpotV2AccountValuation, + SpotV2AlgoOrder, + SpotV2AlgoOrdersCancelAllAfterResult, + SpotV2AlgoOrdersCancellationResult, + SpotV2AlgoOrdersPlaceResult, + SpotV2AssetValuation, + SpotV2CurrencyReference, + SpotV2PointAccount, + SpotV2PointTransfer, + SpotV2TransactFeeRate, + SpotVaspExchange, + SpotWithdrawAddress, + SpotWithdrawQuota, +} from './types/response/spot.types.js'; ⋮---- /** - * Set Spot/Margin Fee Deduction Method - * - * switchType: 0=point card, 1=currency (pass deductionCurrency), 2=close. Signature required. Read permission. Rate: 2/s. - */ -updateFeeDeductionMethod(params: { - switchType: 0 | 1 | 2; - deductionCurrency?: string; -}): Promise> + * The SpotClient provides integration to the HTX Spot API. + */ +export class SpotClient extends BaseRestClient +⋮---- +getClientType(): RestClientType +⋮---- +// Favour the spot AWS domain, as recommended by the API docs ⋮---- /** * - * Trading + * Misc Utility Methods * */ ⋮---- +generateNewOrderID(): string +⋮---- /** - * Place a New Order * - * Places order to be matched. Set account-id and source per account type. Signature required. Trade permission. Rate: 100/2s. + * Reference Data + * */ -submitOrder( - params: SpotV1OrderPlaceReq, -): Promise> ⋮---- /** - * Place a Batch of Orders + * Get Market Status * - * Max 10 orders per batch. Each returns order-id or err-code/err-msg. Signature required. Trade permission. Rate: 50/2s. + * Returns current market status. + * 1=normal, 2=halted, 3=cancel-only. */ -submitBatchOrders( - params: SpotV1OrderPlaceReq[], -): Promise> +getMarketStatus(): Promise ⋮---- /** - * Margin Order (Auto Borrow/Repay) + * Get Current Timestamp (V1) * - * Auto borrow to place or auto repay. Sub-accounts not supported. Use amount or market-amount. Signature required. Trade permission. Rate: 100/2s. + * Returns current server time in milliseconds since epoch. No signature required. */ -submitMarginOrder( - params: SpotV1OrderAutoPlaceReq, -): Promise> +getTimestamp(): Promise> ⋮---- /** - * Cancel Order by Order ID + * Get all Supported Trading Symbols (V2) * - * Submits cancel request. Verify via order status or match result. Signature required. Trade permission. Rate: 100/2s. + * Returns all supported trading symbols. Pass ts for incremental updates. */ -cancelOrderById(params: { - orderId: string; - symbol?: string; -}): Promise> +getTradingSymbols(params?: { + ts?: number; + }): Promise> ⋮---- /** - * Cancel Order by Client Order ID + * Get all Supported Currencies (V2) * - * Prefer cancelOrder (by order-id) when possible. Submits cancel request; verify via order status. Signature required. Trade permission. Rate: 100/2s. + * Returns all supported currencies. Pass ts for incremental updates. */ -cancelOrderByClientId(params: { - 'client-order-id': string; -}): Promise> +getCurrencies(params?: { + ts?: number; + }): Promise> ⋮---- /** - * Cancel All Spot Orders + * Get Currencys Settings (V1) * - * Cancel all open spot orders. Pass symbol for specific pair(s), comma-separated; omit for all. Signature required. Trade permission. Rate: 1/2s. + * Returns currency settings. No signature required. Pass ts for incremental updates. */ -cancelAllOrders(params?: { - symbol?: string; -}): Promise> +getCurrencysSettings(params?: { + ts?: number; + }): Promise> ⋮---- /** - * Get All Open Orders + * Get Symbols Settings (V1) * - * Returns unfilled orders. Filter by account-id, symbol, side. Signature required. Read permission. Rate: 50/2s. + * Returns symbol settings. No signature required. Pass ts for incremental updates. */ -getOpenOrders( - params?: SpotGetOpenOrdersReq, -): Promise> +getSymbolsSettings(params?: { + ts?: number; + }): Promise> ⋮---- /** - * Cancel Multiple Orders by Criteria + * Get Market Symbols Settings (V1) * - * Cancel up to 100 orders matching account-id, symbol, types, side. Submit only; verify via order status. Signature required. Trade permission. Rate: 50/2s. + * Returns market symbol settings. No signature required. Pass symbols (NA=all) and/or ts for incremental updates. */ -batchCancelOpenOrders( - params?: SpotV1OrderBatchCancelOpenOrdersReq, -): Promise> +getMarketSymbolsSettings(params?: { + symbols?: string; + ts?: number; + }): Promise> ⋮---- /** - * Cancel Multiple Orders by IDs + * Get Chains Information (V1) * - * Cancel by order-ids or client-order-ids (max 50). Prefer order-ids. Signature required. Trade permission. Rate: 50/2s. + * Returns chain info per currency. No signature required. Pass show-desc, currency, and/or ts for incremental updates. */ -batchCancelOrders(params: { - 'order-ids'?: string[]; - 'client-order-ids'?: string[]; -}): Promise> +getChainsInfo( + params?: SpotGetChainsReq, + ): Promise> ⋮---- /** - * Dead Man's Switch (Cancel All After) + * Get Reference Currencies & Chains (V2) * - * Turn on/off. timeout=0 to turn off. timeout>=5 to turn on: must call twice within timeout seconds or all spot orders (max 500) are canceled. Signature required. Trade permission. + * Returns static reference info for each currency and its chains. No signature required. */ -setCancelAllAfter(params: { - timeout: number; -}): Promise> +getReferenceCurrencies(params?: { + currency?: string; + authorizedUser?: boolean; + }): Promise> ⋮---- /** - * Get Order Detail by Order ID * - * Returns order detail. API-created orders not queryable 2h after cancel. Signature required. Read permission. Rate: 50/2s. + * Market Data + * */ -getOrder(params: { - orderId: string; -}): Promise> ⋮---- /** - * Get Order Detail by Client Order ID + * Get Klines (Candles) * - * Returns latest status of order with given client order ID. Signature required. Read permission. Rate: 50/2s. + * Returns candlestick data for a symbol. No signature required. */ -getOrderByClientId(params: { - clientOrderId: string; -}): Promise> +getKlines( + params: SpotGetKlineReq, + ): Promise> ⋮---- /** - * Get Match Results of an Order + * Get Latest Aggregated Ticker * - * Returns match/trade results for a specific order. Signature required. Read permission. Rate: 50/2s. + * Returns latest ticker with 24h aggregated market data. No signature required. */ -getOrderMatch(params: { - orderId: string; -}): Promise> +getTicker(params: { + symbol: string; + }): Promise> ⋮---- /** - * Search Past Orders + * Get Latest Tickers for All Pairs * - * Historical orders by symbol, states, time range. Max 48h window, 180 days range. API orders not queryable 2h after cancel. Signature required. Read permission. Rate: 50/2s. + * Returns latest tickers for all supported pairs. No signature required. */ -getOrderHistory( - params: SpotGetOrderHistoryReq, -): Promise> +getTickers(): Promise> ⋮---- /** - * Search Historical Orders within 48 Hours + * Get Market Depth * - * Orders by time range. Default: last 48h. next-time in last item when more exist. API orders not queryable 2h after cancel. Signature required. Read permission. Rate: 20/2s. + * Returns order book for a symbol. No signature required. */ -getOrderHistory48h( - params?: SpotGetOrderHistory48hReq, -): Promise> +getMarketDepth( + params: SpotGetDepthReq, + ): Promise> ⋮---- /** - * Search Match Results + * Get the Last Trade * - * Match results of filled/partial orders by symbol, types, time. 48h window, 120 days range. Signature required. Read permission. Rate: 20/2s. + * Returns latest trade with price, volume, direction. No signature required. */ -getMatchResults( - params?: SpotGetMatchResultsReq, -): Promise> +getLastTrade(params: { + symbol: string; + }): Promise> ⋮---- /** - * Get Transact Fee Rate + * Get the Most Recent Trades * - * Query fee rates for trading pairs. Max 10 symbols. Signature required. Read permission. Rate: 50/2s. + * Returns recent trades grouped by timestamp. No signature required. */ -getFeeRate(params: { - symbols: string; -}): Promise> +getHistoryTrades(params: { + symbol: string; + size?: number; + }): Promise> ⋮---- /** + * Get the Last 24h Market Summary * - * Conditional Order - * + * Returns 24h trading summary for a symbol. No signature required. */ +get24hMarketSummary(params: { + symbol: string; + }): Promise> ⋮---- /** - * Place a Conditional Order + * Get Full Order Book * - * Conditional orders only via this endpoint (not Trading section). Signature required. Trade permission. Rate: 20/2s. + * Returns complete market depth, up to 5000 levels. Updated once per second. No signature required. */ -placeConditionalOrder( - params: SpotV2AlgoOrdersPlaceReq, -): Promise> +getFullOrderBook(params: { + symbol: string; + }): Promise> ⋮---- /** - * Cancel Conditional Orders (before triggering) * - * Only cancels conditional orders that have not triggered yet. Max 50 orders. Signature required. Trade permission. Rate: 20/2s. + * Account + * */ -cancelConditionalOrders(params: { - clientOrderIds: string[]; -}): Promise> ⋮---- /** - * Query Open Conditional Orders (before triggering) + * Get all Accounts of the Current User * - * Returns conditional orders with orderStatus=created. Signature required. Read permission. Rate: 20/2s. + * Returns list of accounts owned by this API user. Signature required. */ -getOpenConditionalOrders( - params?: SpotV2AlgoOrdersOpeningReq, -): Promise & +getAccounts(): Promise> ⋮---- /** - * Query Conditional Order History + * Get Account Balance of a Specific Account * - * Returns canceled/rejected/triggered conditional orders. For triggered, use Trading section for latest status. Signature required. Read permission. Rate: 20/2s. + * Returns balance for account specified by account id. Signature required. OTC not supported. */ -getConditionalOrderHistory( - params?: SpotV2AlgoOrdersHistoryReq, -): Promise & +getAccountBalance(params: { + accountId: string | number; + }): Promise> ⋮---- /** - * Query a Specific Conditional Order + * Get The Total Valuation of Platform Assets * - * By clientOrderId. Covers created, triggered, canceled, rejected. Signature required. Read permission. Rate: 20/2s. + * Returns total asset valuation in BTC or fiat. Signature required. */ -getConditionalOrder(params: { - clientOrderId: string; -}): Promise> +getAccountValuation(params?: { + accountType?: string; + valuationCurrency?: string; + }): Promise> ⋮---- /** + * Get Asset Valuation * - * Margin Loan (Cross/Isolated) + * Returns valuation of total assets in BTC or fiat. Signature required. + */ +getAssetValuation( + params?: SpotGetAssetValuationReq, + ): Promise> +⋮---- +/** + * Asset Transfer * + * Transfer asset between accounts (spot, margin, sub-users). Signature required. Trade permission. */ +submitTransfer( + params: SpotAccountTransferReq, + ): Promise> ⋮---- /** - * Repayment Record Reference + * Get Account History * - * Query repayment records. Sorted by repayTime. Main and sub-accounts. Signature required. Read permission. Rate: 2/2s. + * Returns amount changes of specified account. Signature required. Max 1h query window, 30 days range. */ -getRepaymentRecords( - params?: SpotRepaymentRecordReq, +getAccountHistory( + params: SpotGetAccountHistoryReq, ): Promise< - SpotAPISuccessResponse & { nextId?: number } - > { - return this.getPrivate('/v2/account/repayment', params); + SpotAPISuccessResponse & { 'next-id'?: number } + > ⋮---- /** - * Repay Margin Loan (Cross/Isolated) + * Get Account Ledger * - * Loan interest paid first if no transactId. Main and sub-accounts. Signature required. Trade permission. Rate: 2/s. + * Returns amount changes (phase 1: transfer only). Max 10-day window, 180 days range. Signature required. */ -repayMarginLoan( - params: SpotMarginRepaymentReq, -): Promise> +getAccountLedger( + params?: SpotGetAccountLedgerReq, + ): Promise< + SpotAPISuccessResponse & { nextId?: number } + > ⋮---- /** - * Transfer Asset from Spot Trading Account to Isolated Margin Account + * V2 Account Transfer * - * Signature required. Trade permission. Rate: 2/2s. + * Transfer funds between spot, linear-swap, otc, futures, swap. Signature required. Trade permission. */ -transferSpotToIsolatedMargin( - params: SpotMarginTransferInIsolatedReq, -): Promise> +submitV2AccountTransfer( + params: SpotV2AccountTransferReq, + ): Promise> ⋮---- /** - * Transfer Asset from Isolated Margin Account to Spot Trading Account + * Create Universal Transfer * - * Signature required. Trade permission. Rate: 2/2s. + * Transfer between account types (spot, margin, futures, options, etc). Host: spot. Trade permission. Rate: 5/2s. */ -transferIsolatedMarginToSpot( - params: SpotMarginTransferOutIsolatedReq, -): Promise> +submitUniversalTransfer( + params: SpotUniversalTransferReq, + ): Promise> ⋮---- /** - * Get Loan Interest Rate and Quota (Isolated) + * Get Universal Transfer Records * - * Returns loan interest rates and quota per symbol. Signature required. Read permission. Rate: 20/2s. + * Query universal transfer history. Host: spot. Trade permission. Rate: 5/2s. */ -getMarginLoanInfo(params?: { - symbols?: string; -}): Promise> +getUniversalTransferRecords( + params?: SpotUniversalTransferRecordsReq, + ): Promise> ⋮---- /** - * Request a Margin Loan (Isolated) + * Futures Transfer * - * Places order to borrow margin. Signature required. Trade permission. Rate: 2/2s. + * Transfer between spot and future contract account. pro-to-futures = spot -> contract, futures-to-pro = contract -> spot. Signature required. Trade permission. */ -requestMarginLoan( - params: SpotMarginLoanOrderReq, -): Promise> +submitFuturesTransfer( + params: SpotV1FuturesTransferReq, + ): Promise> ⋮---- /** - * Repay Margin Loan (Isolated) + * Get Point Balance * - * Repays with asset in margin account. Signature required. Trade permission. Rate: 2/2s. + * Query termless and terminable point balance. Parent can query sub user via subUid. Signature required. Read permission. Rate: 2/s. */ -repayMarginLoanIsolated(params: { - orderId: string; - amount: string; -}): Promise> +getPointBalance(params?: { + subUid?: string; + }): Promise> ⋮---- /** - * Search Past Margin Orders (Isolated) + * Point Transfer * - * Returns margin loan orders by criteria. Signature required. Read permission. Rate: 100/2s. + * Transfer points between parent and sub user. groupId=0 for termless; for terminable query sub balance first. Signature required. Trade permission. Rate: 2/s. */ -getMarginLoanOrders( - params?: SpotMarginLoanOrdersReq, -): Promise> +submitPointTransfer( + params: SpotV2PointTransferReq, + ): Promise> ⋮---- /** - * Get the Balance of the Margin Loan Account (Isolated) + * Get User Deduction Info * - * Signature required. Read permission. Rate: 100/2s. + * Query point card vs HTX deduction settings. Signature required. Read permission. Rate: 5/s. */ -getMarginAccountBalance(params?: { - symbol?: string; - 'sub-uid'?: number; -}): Promise> +getAccountSwitchUserInfo(): Promise< + SpotAPISuccessResponse + > ⋮---- /** - * Transfer Asset from Spot Trading Account to Cross Margin Account + * Get Deductible Currency Overview * - * Signature required. Trade permission. + * Query asset that can be used to deduct fees. Signature required. Read permission. Rate: 5/s. */ -transferSpotToCrossMargin(params: { - currency?: string; - amount?: string; -}): Promise> +getAccountOverviewInfo(): Promise< + SpotAPISuccessResponse + > ⋮---- /** - * Transfer Asset from Cross Margin Account to Spot Trading Account + * Set Spot/Margin Fee Deduction Method * - * Signature required. Trade permission. + * switchType: 0=point card, 1=currency (pass deductionCurrency), 2=close. Signature required. Read permission. Rate: 2/s. */ -transferCrossMarginToSpot(params: { - currency?: string; - amount?: string; -}): Promise> +updateFeeDeductionMethod(params: { + switchType: 0 | 1 | 2; + deductionCurrency?: string; + }): Promise> ⋮---- /** - * Get Loan Interest Rate and Quota (Cross) * - * Returns loan interest rates and quota per currency. No params. Signature required. Read permission. Rate: 2/2s. + * Trading + * */ -getCrossMarginLoanInfo(): Promise< - SpotAPISuccessResponse - > { - return this.getPrivate('/v1/cross-margin/loan-info'); ⋮---- /** - * Request a Margin Loan (Cross) + * Place a New Order * - * Places order to borrow margin. Signature required. Trade permission. Rate: 2/2s. + * Places order to be matched. Set account-id and source per account type. Signature required. Trade permission. Rate: 100/2s. */ -requestCrossMarginLoan(params: { - currency?: string; - amount?: string; -}): Promise> +submitOrder( + params: SpotV1OrderPlaceReq, + ): Promise> ⋮---- /** - * Repay Margin Loan (Cross) + * Place a Batch of Orders * - * Repays with asset in cross margin account. Signature required. Trade permission. Rate: 2/2s. + * Max 10 orders per batch. Each returns order-id or err-code/err-msg. Signature required. Trade permission. Rate: 50/2s. */ -repayCrossMarginLoan(params: { - orderId: string; - amount: string; -}): Promise> +submitBatchOrders( + params: SpotV1OrderPlaceReq[], + ): Promise> ⋮---- /** - * Search Past Margin Orders (Cross) + * Margin Order (Auto Borrow/Repay) * - * Returns margin loan orders by criteria. Signature required. Read permission. Rate: 2/2s. + * Auto borrow to place or auto repay. Sub-accounts not supported. Use amount or market-amount. Signature required. Trade permission. Rate: 100/2s. */ -getCrossMarginLoanOrders( - params?: SpotCrossMarginLoanOrdersReq, -): Promise> +submitMarginOrder( + params: SpotV1OrderAutoPlaceReq, + ): Promise> ⋮---- /** - * Get the Balance of the Margin Loan Account (Cross) + * Cancel Order by Order ID * - * Returns single account object. Signature required. Read permission. Rate: 2/2s. + * Submits cancel request. Verify via order status or match result. Signature required. Trade permission. Rate: 100/2s. */ -getCrossMarginBalance(params?: { - 'sub-uid'?: number; -}): Promise> +cancelOrderById(params: { + orderId: string; + symbol?: string; + }): Promise> ⋮---- /** - * Obtain Leverage Position Limit (Cross) + * Cancel Order by Client Order ID * - * Returns position limit at user level per currency. Signature required. Read permission. Rate: 2/2s. + * Prefer cancelOrder (by order-id) when possible. Submits cancel request; verify via order status. Signature required. Trade permission. Rate: 100/2s. */ -getCrossMarginLimit(params?: { - currency?: string; -}): Promise> +cancelOrderByClientId(params: { + 'client-order-id': string; + }): Promise> ⋮---- /** + * Cancel All Spot Orders * - * Wallet (Deposit/Withdraw) - * + * Cancel all open spot orders. Pass symbol for specific pair(s), comma-separated; omit for all. Signature required. Trade permission. Rate: 1/2s. */ +cancelAllOrders(params?: { + symbol?: string; + }): Promise> ⋮---- /** - * Query Deposit Address + * Get All Open Orders * - * Query deposit address per chain for a currency. Signature required. Read permission. Rate: 20/2s. + * Returns unfilled orders. Filter by account-id, symbol, side. Signature required. Read permission. Rate: 50/2s. */ -getDepositAddress(params?: { - currency?: string; -}): Promise> +getOpenOrders( + params?: SpotGetOpenOrdersReq, + ): Promise> ⋮---- /** - * Query Withdraw Quota + * Cancel Multiple Orders by Criteria * - * Query withdrawing quota for currencies. Parent user only. Signature required. Read permission. Rate: 20/2s. + * Cancel up to 100 orders matching account-id, symbol, types, side. Submit only; verify via order status. Signature required. Trade permission. Rate: 50/2s. */ -getWithdrawQuota(params?: { - currency?: string; -}): Promise> +batchCancelOpenOrders( + params?: SpotV1OrderBatchCancelOpenOrdersReq, + ): Promise> ⋮---- /** - * Query Withdraw Address + * Cancel Multiple Orders by IDs * - * Query withdraw addresses available for API key. Parent user only. Signature required. Read permission. + * Cancel by order-ids or client-order-ids (max 50). Prefer order-ids. Signature required. Trade permission. Rate: 50/2s. */ -getWithdrawAddress( - params?: SpotWithdrawAddressReq, - ): Promise< - SpotAPISuccessResponse & { 'next-id'?: number } - > { - return this.getPrivate('/v2/account/withdraw/address', params); +batchCancelOrders(params: { + 'order-ids'?: string[]; + 'client-order-ids'?: string[]; + }): Promise> ⋮---- /** - * Create Withdraw Request + * Dead Man's Switch (Cancel All After) * - * Create withdraw to address in your withdraw list. Parent user only. Withdraw permission. Rate: 20/2s. + * Turn on/off. timeout=0 to turn off. timeout>=5 to turn on: must call twice within timeout seconds or all spot orders (max 500) are canceled. Signature required. Trade permission. + */ +setCancelAllAfter(params: { + timeout: number; + }): Promise> +⋮---- +/** + * Get Order Detail by Order ID * - * `api-not-support-temp-addr` means this address is not enabled for API withdrawal - * (Verification-exempt API checkbox, or the key's custom address list). Web - * whitelist status `white` on GET /v2/account/withdraw/address does not by itself - * enable the API withdraw path. + * Returns order detail. API-created orders not queryable 2h after cancel. Signature required. Read permission. Rate: 50/2s. */ -submitWithdraw( - params: SpotWithdrawCreateReq, -): Promise> +getOrder(params: { + orderId: string; + }): Promise> ⋮---- /** - * Query Withdrawal by Client Order ID + * Get Order Detail by Client Order ID * - * Query withdraw order submitted with client-order-id. Signature required. Read permission. + * Returns latest status of order with given client order ID. Signature required. Read permission. Rate: 50/2s. */ -getWithdrawByClientId(params: { +getOrderByClientId(params: { clientOrderId: string; -}): Promise> + }): Promise> ⋮---- /** - * Cancel Withdraw Request + * Get Match Results of an Order * - * Cancel withdraw by transfer id. Parent user only. Withdraw permission. Rate: 20/2s. + * Returns match/trade results for a specific order. Signature required. Read permission. Rate: 50/2s. */ -cancelWithdraw(params: { - withdrawId: number; -}): Promise> +getOrderMatch(params: { + orderId: string; + }): Promise> ⋮---- /** - * Search Deposit/Withdraw Records + * Search Past Orders * - * Search existed withdraws and deposits. Signature required. Read permission. Rate: 20/2s. + * Historical orders by symbol, states, time range. Max 48h window, 180 days range. API orders not queryable 2h after cancel. Signature required. Read permission. Rate: 50/2s. */ -getDepositWithdrawHistory( - params: SpotDepositWithdrawQueryReq, -): Promise> +getOrderHistory( + params: SpotGetOrderHistoryReq, + ): Promise> ⋮---- /** - * Get Exchange VASP List + * Search Historical Orders within 48 Hours * - * Exchange list for Korean users (withdraw flow). Public. No signature. Rate: 1/s. + * Orders by time range. Default: last 48h. next-time in last item when more exist. API orders not queryable 2h after cancel. Signature required. Read permission. Rate: 20/2s. */ -getVaspList(): Promise> +getOrderHistory48h( + params?: SpotGetOrderHistory48hReq, + ): Promise> ⋮---- /** + * Search Match Results * - * Broker API - * + * Match results of filled/partial orders by symbol, types, time. 48h window, 120 days range. Signature required. Read permission. Rate: 20/2s. */ +getMatchResults( + params?: SpotGetMatchResultsReq, + ): Promise> ⋮---- /** - * Check User Rebate Eligibility + * Get Transact Fee Rate * - * Check whether user meets rebate conditions. API brokers only. Signature required. Read permission. Rate: 20/2s. + * Query fee rates for trading pairs. Max 10 symbols. Signature required. Read permission. Rate: 50/2s. */ -getBrokerUserRebateStatus(params: { - /** User UID to check */ - queryUid: string; -}): Promise> -⋮---- -/** User UID to check */ +getFeeRate(params: { + symbols: string; + }): Promise> ⋮---- /** - * Get Broker Sub-Account Fee Rate * - * Query sub-account commission/fee rate. Signature required. Read permission. Rate: 100/2s. + * Conditional Order + * */ -getBrokerSubUserFeeRate(params: { - /** Sub-account id (user_id, UID minus last digit) */ - subUId: string; - /** 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ - bizType: string; -}): Promise> -⋮---- -/** Sub-account id (user_id, UID minus last digit) */ -⋮---- -/** 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ ⋮---- /** - * Set Broker Sub-User Fee Rate + * Place a Conditional Order * - * Set trading fee rate for sub-accounts. Signature required. Read permission. Rate: 100/2s. + * Conditional orders only via this endpoint (not Trading section). Signature required. Trade permission. Rate: 20/2s. */ -setBrokerSubUserFeeRate( - params: SpotBrokerSubUserFeeRateAddReq, -): Promise> +placeConditionalOrder( + params: SpotV2AlgoOrdersPlaceReq, + ): Promise> ⋮---- /** - * Get Account Capital Snapshot + * Cancel Conditional Orders (before triggering) * - * Request account asset snapshot. Signature required. Read permission. Rate: 100/2s. + * Only cancels conditional orders that have not triggered yet. Max 50 orders. Signature required. Trade permission. Rate: 20/2s. */ -getBrokerAccountCapitalSnapshot( - params: SpotBrokerAccountCapitalSnapshotReq, -): Promise> +cancelConditionalOrders(params: { + clientOrderIds: string[]; + }): Promise> ⋮---- /** + * Query Open Conditional Orders (before triggering) * - * SubAccount Management - * + * Returns conditional orders with orderStatus=created. Signature required. Read permission. Rate: 20/2s. */ +getOpenConditionalOrders( + params?: SpotV2AlgoOrdersOpeningReq, + ): Promise & { nextId?: number }> ⋮---- /** - * Set Deduction Mode + * Query Conditional Order History * - * Set deduction fee (HT or point) for parent and sub user. Signature required. Trade permission. + * Returns canceled/rejected/triggered conditional orders. For triggered, use Trading section for latest status. Signature required. Read permission. Rate: 20/2s. */ -updateSubUserDeductMode(params?: { - subUids?: string; - deductMode?: 'master' | 'sub'; -}): Promise> +getConditionalOrderHistory( + params?: SpotV2AlgoOrdersHistoryReq, + ): Promise & { nextId?: number }> ⋮---- /** - * Query API Key + * Query a Specific Conditional Order * - * Query own or sub user's API key info. Signature required. Read permission. + * By clientOrderId. Covers created, triggered, canceled, rejected. Signature required. Read permission. Rate: 20/2s. */ -getSubUserApiKey(params?: { - uid?: number; - accessKey?: string; -}): Promise> +getConditionalOrder(params: { + clientOrderId: string; + }): Promise> ⋮---- /** - * Get UID * - * Get current user's UID. Signature required. Read permission. + * Margin Loan (Cross/Isolated) + * */ -getUserUid(): Promise> ⋮---- /** - * Create Sub Users + * Repayment Record Reference * - * Create sub users, max 50 at a time. Signature required. Trade permission. + * Query repayment records. Sorted by repayTime. Main and sub-accounts. Signature required. Read permission. Rate: 2/2s. */ -createSubUser(params: { - /** Sub users to create, max 50 */ - userList: { userName: string; note?: string }[]; - /** GENERAL (default), CONTACT, GRID, FIRE-BLOCK */ - subAccountType?: string; -}): Promise> -⋮---- -/** Sub users to create, max 50 */ -⋮---- -/** GENERAL (default), CONTACT, GRID, FIRE-BLOCK */ +getRepaymentRecords( + params?: SpotRepaymentRecordReq, + ): Promise< + SpotAPISuccessResponse & { nextId?: number } + > ⋮---- /** - * Get Sub User List + * Repay Margin Loan (Cross/Isolated) * - * Query full list of sub users with UID and status. Signature required. Read permission. + * Loan interest paid first if no transactId. Main and sub-accounts. Signature required. Trade permission. Rate: 2/s. */ -getSubUserList(params?: { - fromId?: number; -}): Promise & +repayMarginLoan( + params: SpotMarginRepaymentReq, + ): Promise> ⋮---- /** - * Lock/Unlock Sub User + * Transfer Asset from Spot Trading Account to Isolated Margin Account * - * Lock or unlock a sub user. Signature required. Trade permission. Rate: 20/2s. + * Signature required. Trade permission. Rate: 2/2s. */ -updateSubUserLockStatus(params: { - subUid: number; - action: 'lock' | 'unlock'; -}): Promise> +transferSpotToIsolatedMargin( + params: SpotMarginTransferInIsolatedReq, + ): Promise> ⋮---- /** - * Get Sub User Status + * Transfer Asset from Isolated Margin Account to Spot Trading Account * - * Query sub user status by UID. Signature required. Read permission. + * Signature required. Trade permission. Rate: 2/2s. */ -getSubUserStatus(params: { - subUid: number; -}): Promise> +transferIsolatedMarginToSpot( + params: SpotMarginTransferOutIsolatedReq, + ): Promise> ⋮---- /** - * Set Tradable Market for Sub Users + * Get Loan Interest Rate and Quota (Isolated) * - * Set tradable market (isolated/cross margin) for sub users. Signature required. Trade permission. + * Returns loan interest rates and quota per symbol. Signature required. Read permission. Rate: 20/2s. */ -setSubUserTradableMarket( - params: SpotSubUserTradableMarketReq, -): Promise> +getMarginLoanInfo(params?: { + symbols?: string; + }): Promise> ⋮---- /** - * Set Asset Transfer Permission for Sub Users + * Request a Margin Loan (Isolated) * - * Set asset transfer permission for sub users. Signature required. Trade permission. + * Places order to borrow margin. Signature required. Trade permission. Rate: 2/2s. */ -setSubUserTransferPermissions( - params: SpotSubUserTransferPermissionsReq, -): Promise> +requestMarginLoan( + params: SpotMarginLoanOrderReq, + ): Promise> ⋮---- /** - * Get Sub User Account List + * Repay Margin Loan (Isolated) * - * Query account list of sub user by UID. Signature required. Read permission. + * Repays with asset in margin account. Signature required. Trade permission. Rate: 2/2s. */ -getSubUserAccounts(params: { - subUid: number; -}): Promise> +repayMarginLoanIsolated(params: { + orderId: string; + amount: string; + }): Promise> ⋮---- /** - * Create Sub User API Key + * Search Past Margin Orders (Isolated) * - * Create API key for sub user. Signature required. Trade permission. + * Returns margin loan orders by criteria. Signature required. Read permission. Rate: 100/2s. */ -createSubUserApiKey( - params: SpotSubUserApiKeyCreationReq, -): Promise> +getMarginLoanOrders( + params?: SpotMarginLoanOrdersReq, + ): Promise> ⋮---- /** - * Modify Sub User API Key + * Get the Balance of the Margin Loan Account (Isolated) * - * Modify sub user's API key. Signature required. Trade permission. + * Signature required. Read permission. Rate: 100/2s. */ -updateSubUserApiKey( - params: SpotSubUserApiKeyUpdateReq, -): Promise> +getMarginAccountBalance(params?: { + symbol?: string; + 'sub-uid'?: number; + }): Promise> ⋮---- /** - * Delete Sub User API Key + * Transfer Asset from Spot Trading Account to Cross Margin Account * - * Delete sub user's API key. Signature required. Trade permission. + * Signature required. Trade permission. */ -deleteSubUserApiKey(params: { - subUid: number; - accessKey: string; -}): Promise> +transferSpotToCrossMargin(params: { + currency?: string; + amount?: string; + }): Promise> ⋮---- /** - * Transfer Asset between Parent and Sub Account + * Transfer Asset from Cross Margin Account to Spot Trading Account * - * Transfer asset between parent and sub account. Signature required. Trade permission. Rate: 2/2s. + * Signature required. Trade permission. */ -submitSubUserTransfer( - params: SpotSubUserTransferReq, -): Promise> +transferCrossMarginToSpot(params: { + currency?: string; + amount?: string; + }): Promise> ⋮---- /** - * Query Sub User Deposit Address + * Get Loan Interest Rate and Quota (Cross) * - * Query sub user's deposit address per chain. Signature required. Read permission. + * Returns loan interest rates and quota per currency. No params. Signature required. Read permission. Rate: 2/2s. */ -getSubUserDepositAddress(params: { - subUid: number; +getCrossMarginLoanInfo(): Promise< + SpotAPISuccessResponse + > +⋮---- +/** + * Request a Margin Loan (Cross) + * + * Places order to borrow margin. Signature required. Trade permission. Rate: 2/2s. + */ +requestCrossMarginLoan(params: { currency?: string; -}): Promise> + amount?: string; + }): Promise> ⋮---- /** - * Query Sub User Deposit History + * Repay Margin Loan (Cross) * - * Query sub user's deposit history. Signature required. Read permission. + * Repays with asset in cross margin account. Signature required. Trade permission. Rate: 2/2s. */ -getSubUserDepositHistory(params: SpotSubUserDepositHistoryReq): Promise< - SpotAPISuccessResponse & { - nextId?: number; - } - > { - return this.getPrivate('/v2/sub-user/query-deposit', params); +repayCrossMarginLoan(params: { + orderId: string; + amount: string; + }): Promise> ⋮---- /** - * Get Aggregated Balance of All Sub Users + * Search Past Margin Orders (Cross) * - * Returns aggregated balance from all sub-users. Signature required. Read permission. Rate: 2/2s. + * Returns margin loan orders by criteria. Signature required. Read permission. Rate: 2/2s. */ -getSubUsersAggregatedBalance(): Promise< - SpotAPISuccessResponse - > { - return this.getPrivate('/v1/subuser/aggregate-balance'); +getCrossMarginLoanOrders( + params?: SpotCrossMarginLoanOrdersReq, + ): Promise> ⋮---- /** - * Get Account Balance of a Sub-User + * Get the Balance of the Margin Loan Account (Cross) * - * Returns balance of sub-user by sub-uid. Signature required. Read permission. Rate: 20/2s. + * Returns single account object. Signature required. Read permission. Rate: 2/2s. */ -getSubUserBalance(params: { - subUid: number; -}): Promise> +getCrossMarginBalance(params?: { + 'sub-uid'?: number; + }): Promise> ⋮---- /** - * Get Custody Trading Sub-Account List + * Obtain Leverage Position Limit (Cross) * - * Query list of sub-accounts currently being managed. Read permission. + * Returns position limit at user level per currency. Signature required. Read permission. Rate: 2/2s. */ -getSubUserEntrustUserList(params?: { - fromId?: number; - limit?: number; - }): Promise< - SpotAPISuccessResponse<{ list: SpotSubUserEntrustUser[] }> & { - nextId?: number; - } - > { - return this.getPrivate('/v2/sub-user/entrust-user-list', params); +getCrossMarginLimit(params?: { + currency?: string; + }): Promise> ⋮---- /** - * Get Managed Sub-Account Transfer History * - * Query transfer records of managed sub-accounts. Read permission. + * Wallet (Deposit/Withdraw) + * */ -getSubUserManagedTransferHistory( - params?: SpotSubUserManagedTransferHistoryReq, -): Promise> ⋮---- /** + * Query Deposit Address * - * Referral + * Query deposit address per chain for a currency. Signature required. Read permission. Rate: 20/2s. + */ +getDepositAddress(params?: { + currency?: string; + }): Promise> +⋮---- +/** + * Query Withdraw Quota * + * Query withdrawing quota for currencies. Parent user only. Signature required. Read permission. Rate: 20/2s. */ +getWithdrawQuota(params?: { + currency?: string; + }): Promise> +⋮---- /** - * Query Referral Rebate Detail + * Query Withdraw Address * - * Query rebate info of invitee. Signature required. Read permission. + * Query withdraw addresses available for API key. Parent user only. Signature required. Read permission. */ -getReferralRebateDetail(params: { - inviteeUid: number; -}): Promise> +getWithdrawAddress( + params?: SpotWithdrawAddressReq, + ): Promise< + SpotAPISuccessResponse & { 'next-id'?: number } + > ⋮---- /** - * Query Referral Rebate History + * Create Withdraw Request * - * Query historical rebate of invitee. Signature required. Read permission. + * Create withdraw to address in your withdraw list. Parent user only. Withdraw permission. Rate: 20/2s. + * + * `api-not-support-temp-addr` means this address is not enabled for API withdrawal + * (Verification-exempt API checkbox, or the key's custom address list). Web + * whitelist status `white` on GET /v2/account/withdraw/address does not by itself + * enable the API withdraw path. */ -getReferralRebateHistory( - params: SpotReferralRebateHistoryReq, -): Promise> +submitWithdraw( + params: SpotWithdrawCreateReq, + ): Promise> ⋮---- /** - * Query All Rebate Detail + * Query Withdrawal by Client Order ID * - * Query all rebate detail. Signature required. Read permission. + * Query withdraw order submitted with client-order-id. Signature required. Read permission. */ -getReferralAllRebateDetail(params?: SpotReferralAllRebateDetailReq): Promise< - SpotAPISuccessResponse & { - nextId?: string; - } - > { - return this.getPrivate('/v2/invitee/rebate/all_rebate/detail', params); +getWithdrawByClientId(params: { + clientOrderId: string; + }): Promise> ⋮---- /** - * Query Batcher Rebate Detail + * Cancel Withdraw Request * - * Query rebate detail for multiple invitees. Signature required. Read permission. + * Cancel withdraw by transfer id. Parent user only. Withdraw permission. Rate: 20/2s. */ -getReferralMultipleRebateDetail(params?: { - inviteeUidList?: string; -}): Promise> +cancelWithdraw(params: { + withdrawId: number; + }): Promise> ⋮---- /** - * Query Invited User List + * Search Deposit/Withdraw Records * - * KOL users: query invited user list. Signature required. Read permission. Rate: 1/s. + * Search existed withdraws and deposits. Signature required. Read permission. Rate: 20/2s. */ -getReferralInvitedUserList( - params?: SpotReferralReferralsReq, - ): Promise< - SpotAPISuccessResponse & { nextId?: string } - > { - return this.getPrivate('/v2/invitee/rebate/referrals', params); +getDepositWithdrawHistory( + params: SpotDepositWithdrawQueryReq, + ): Promise> ⋮---- /** + * Get Exchange VASP List * - * P2P + * Exchange list for Korean users (withdraw flow). Public. No signature. Rate: 1/s. + */ +getVaspList(): Promise> +⋮---- +/** + * + * Broker API * */ ⋮---- /** - * Query P2P Order History + * Check User Rebate Eligibility * - * Query C2C historical transaction records. No signature. Read permission. Rate: 20/2s. + * Check whether user meets rebate conditions. API brokers only. Signature required. Read permission. Rate: 20/2s. */ -getP2POrderHistory(params?: SpotP2POrderHistoryReq): Promise< - SpotAPISuccessResponse<{ - ts: number; - openApiC2COrderInfoVOList: SpotP2POrderHistory[]; - }> - > { - return this.get('/v1/api/c2c/order/history', params); +getBrokerUserRebateStatus(params: { + /** User UID to check */ + queryUid: string; + }): Promise> +⋮---- +/** User UID to check */ ⋮---- /** + * Get Broker Sub-Account Fee Rate * - * Earn + * Query sub-account commission/fee rate. Signature required. Read permission. Rate: 100/2s. + */ +getBrokerSubUserFeeRate(params: { + /** Sub-account id (user_id, UID minus last digit) */ + subUId: string; + /** 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ + bizType: string; + }): Promise> +⋮---- +/** Sub-account id (user_id, UID minus last digit) */ +⋮---- +/** 1 Spot, 2 U-standard linear, 3 Coin-Margined swap */ +⋮---- +/** + * Set Broker Sub-User Fee Rate * + * Set trading fee rate for sub-accounts. Signature required. Read permission. Rate: 100/2s. */ +setBrokerSubUserFeeRate( + params: SpotBrokerSubUserFeeRateAddReq, + ): Promise> ⋮---- /** - * Query Earn Product List + * Get Account Capital Snapshot * - * Product query. Signature required. Read permission. + * Request account asset snapshot. Signature required. Read permission. Rate: 100/2s. */ -getEarnProjectList( - params: SpotEarnProjectListReq, - ): Promise< - SpotAPISuccessResponse<{ total: number; items: SpotEarnProject[] }> - > { - return this.getPrivate('/v1/earn/project/queryEarnProjectList', params); +getBrokerAccountCapitalSnapshot( + params: SpotBrokerAccountCapitalSnapshotReq, + ): Promise> ⋮---- /** - * Earn Subscription * - * Subscribe to Earn product. Signature required. Trade permission. + * SubAccount Management + * */ -earnSubscribe( - params: SpotEarnSubscribeReq, -): Promise> ⋮---- /** - * Earn Redemption + * Set Deduction Mode * - * Redeem Earn product. Signature required. Trade permission. Arrival may be delayed. + * Set deduction fee (HT or point) for parent and sub user. Signature required. Trade permission. */ -earnRedeem( - params: SpotEarnRedeemReq, -): Promise> +updateSubUserDeductMode(params?: { + subUids?: string; + deductMode?: 'master' | 'sub'; + }): Promise> ⋮---- /** - * Query Earn User Assets + * Query API Key * - * Position query. Signature required. Read permission. + * Query own or sub user's API key info. Signature required. Read permission. */ -getEarnUserAssets( - params: SpotEarnUserAssetsReq, - ): Promise< - SpotAPISuccessResponse<{ total: number; items: SpotEarnUserAsset[] }> - > { - return this.getPrivate('/v1/earn/order/user/assets/list', params); +getSubUserApiKey(params?: { + uid?: number; + accessKey?: string; + }): Promise> ⋮---- /** - * Validate syntax meets requirements set by HTX. Log warning if not. + * Get UID + * + * Get current user's UID. Signature required. Read permission. */ -private validateOrderId( - params: Partial>, - orderIdProperty: SpotOrderIdProperty, -): void - -================ -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) -[![HTX Tutorial](https://img.shields.io/badge/HTX%20Tutorial-siebly.io-blue)](https://siebly.io/sdk/htx/javascript/tutorial) - -

- - - - 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); - }); -``` - -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 - -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. 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 - -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, -); - -// 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'], - 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 `