This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter). ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/, dist/, lib/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter - Files are sorted by Git change count (files with more changes are at the bottom) ================================================================ Directory Structure ================================================================ docs/ GATE_SDK_QUICKSTART_GUIDE.md examples/ Rest/ futures/ futures-balance-trade.ts getBalances.ts getContractSize.ts getContractSizeExample.ts getOrders.ts getTickers.ts submitLimitOrder.ts submitMarketOrder.ts testnet.ts otc/ createOTCBank.ts getOTCBankList.ts submitOTCBankPersonalSupplement.ts spot/ getBalances.ts getCandles.ts getOrders.ts getTickers.ts submitLimitOrder.ts submitMarketOrder.ts Websocket/ WS-API/ ws-api-client.ts ws-private-perp-futures-wsapi.ts ws-private-spot-wsapi.ts ws-private-perp-futures.ts ws-private-spot.ts ws-public.ts README.md src/ lib/ websocket/ websocket-util.ts WsStore.ts WsStore.types.ts BaseRestClient.ts BaseWSClient.ts logger.ts misc-util.ts multipartUtil.ts requestUtils.ts webCryptoAPI.ts types/ request/ account.ts alpha.ts announcement.ts autoinvest.ts collateralLoan.ts crossex.ts delivery.ts earn.ts earnuni.ts flashswap.ts futures.ts margin.ts marginuni.ts multicollateralLoan.ts options.ts otc.ts p2pMerchant.ts rebate.ts spot.ts stock.ts subaccount.ts tradfi.ts unified.ts wallet.ts withdrawal.ts response/ account.ts alpha.ts announcement.ts autoinvest.ts collateralloan.ts crossex.ts delivery.ts earn.ts earnuni.ts flashswap.ts futures.ts margin.ts marginuni.ts multicollateralLoan.ts options.ts otc.ts p2pMerchant.ts rebate.ts spot.ts stock.ts subaccount.ts tradfi.ts unified.ts wallet.ts withdrawal.ts websockets/ client.ts events.ts requests.ts wsAPI.ts shared.ts index.ts RestClient.ts WebsocketAPIClient.ts WebsocketClient.ts webpack/ webpack.config.cjs .eslintrc.cjs .gitignore .npmrc .nvmrc .prettierrc jest.config.ts LICENSE.md package.json postBuild.sh README.md tsconfig.cjs.json tsconfig.esm.json tsconfig.json tsconfig.linting.json ================================================================ Files ================================================================ ================ File: examples/README.md ================ # Examples These samples can be executed using `ts-node` or `tsx`: ``` ts-node ./examples/ws-public.ts ``` Most examples also have minimal typescript, so if you rename them to "js" they should execute fine with just node. TypeScript is recommended but completely optional: ``` node ./examples/spot/getTickers.js ``` ================ File: src/lib/websocket/websocket-util.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { WSAPIRequest } from '../../types/websockets/requests.js'; import { FuturesWSAPITopic, SpotWSAPITopic, } from '../../types/websockets/wsAPI.js'; ⋮---- /** * Should be one WS key per unique URL. Some URLs may need a suffix. */ ⋮---- /** * Spot & Margin * https://www.gate.io/docs/developers/apiv4/ws/en/ */ ⋮---- /** * Perpetual futures (USDT) * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 */ ⋮---- /** * Perpetual futures (BTC) * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 */ ⋮---- /** * Delivery Futures (USDT) * https://www.gate.io/docs/developers/delivery/ws/en/ */ ⋮---- /** * Delivery Futures (BTC) * https://www.gate.io/docs/developers/delivery/ws/en/ */ ⋮---- /** * Options * https://www.gate.io/docs/developers/options/ws/en/ */ ⋮---- /** * Announcements V4 * https://www.gate.io/docs/developers/options/ws/en/ */ ⋮---- /** This is used to differentiate between each of the available websocket streams */ export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; ⋮---- export type FuturesWsKey = | typeof WS_KEY_MAP.perpFuturesUSDTV4 | typeof WS_KEY_MAP.perpFuturesBTCV4 | typeof WS_KEY_MAP.deliveryFuturesUSDTV4 | typeof WS_KEY_MAP.deliveryFuturesBTCV4; ⋮---- export type WsMarket = 'all'; ⋮---- /** * Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters. * * - Topic: the topic this event is for * - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters. */ export interface WsTopicRequest< TWSTopic extends string = string, TWSPayload = any, > { topic: TWSTopic; payload?: TWSPayload; } ⋮---- /** * Conveniently allow users to request a topic either as string topics or objects (containing string topic + params) */ export type WsTopicRequestOrStringTopic< TWSTopic extends string, TWSPayload = any, > = WsTopicRequest | string; ⋮---- /** * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges. * Examples: * - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'> * - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'> * - Only one livenet, no other networks: NetworkMap<'livenet'> */ type NetworkMap< TRequiredKeys extends string, TOptionalKeys extends string | undefined = undefined, > = Record & (TOptionalKeys extends string ? Record : Record); ⋮---- export function neverGuard(x: never, msg: string): Error ⋮---- /** * WS API promises are stored using a primary key. This key is constructed using * properties found in every request & reply. */ export function getPromiseRefForWSAPIRequest( requestEvent: WSAPIRequest, ): string ⋮---- export function getPrivateSpotTopics(): string[] ⋮---- // Consumeable channels for spot ⋮---- // WebSocket API for spot ⋮---- export function getPrivateFuturesTopics(): string[] ⋮---- // These are the same for perps vs delivery futures ⋮---- export function getPrivateOptionsTopics(): string[] ⋮---- /** * 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?: WebSocket | any, fallbackToClose?: boolean, ): boolean ================ File: src/lib/websocket/WsStore.types.ts ================ /* eslint-disable @typescript-eslint/no-explicit-any */ import WebSocket from 'isomorphic-ws'; ⋮---- export enum WsConnectionStateEnum { INITIAL = 0, CONNECTING = 1, CONNECTED = 2, CLOSING = 3, RECONNECTING = 4, // ERROR_RECONNECTING = 5, ERROR = 5, } ⋮---- // ERROR_RECONNECTING = 5, ⋮---- export interface DeferredPromise { resolve?: (value: TSuccess) => TSuccess; reject?: (value: TError) => TError; promise?: Promise; } ⋮---- export interface WSConnectedResult { wsKey: string; ws: WebSocket; } ⋮---- export interface WsStoredState { /** The currently active websocket connection */ ws?: WebSocket; /** The current lifecycle state of the connection (enum) */ connectionState?: WsConnectionStateEnum; connectionStateChangedAt?: Date; /** A timer that will send an upstream heartbeat (ping) when it expires */ activePingTimer?: ReturnType | undefined; /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ activePongTimer?: ReturnType | undefined; /** If a reconnection is in progress, this will have the timer for the delayed reconnect */ activeReconnectTimer?: ReturnType | undefined; /** * When a connection attempt is in progress (even for reconnect), a promise is stored here. * * This promise will resolve once connected (and will then get removed); */ // connectionInProgressPromise?: DeferredPromise | undefined; deferredPromiseStore: Record; /** * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) * * A "Set" and a deep-object-match are used to ensure we only subscribe to a * topic once (tracking a list of unique topics we're expected to be connected to) */ subscribedTopics: Set; /** Whether this connection has completed authentication (only applies to private connections) */ isAuthenticated?: boolean; /** * Whether this connection has completed authentication before for the Websocket API, so it k * nows to automatically reauth if reconnected */ didAuthWSAPI?: boolean; /** To reauthenticate on the WS API, which channel do we send to? */ WSAPIAuthChannel?: string; } ⋮---- /** The currently active websocket connection */ ⋮---- /** The current lifecycle state of the connection (enum) */ ⋮---- /** A timer that will send an upstream heartbeat (ping) when it expires */ ⋮---- /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ ⋮---- /** If a reconnection is in progress, this will have the timer for the delayed reconnect */ ⋮---- /** * When a connection attempt is in progress (even for reconnect), a promise is stored here. * * This promise will resolve once connected (and will then get removed); */ // connectionInProgressPromise?: DeferredPromise | undefined; ⋮---- /** * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) * * A "Set" and a deep-object-match are used to ensure we only subscribe to a * topic once (tracking a list of unique topics we're expected to be connected to) */ ⋮---- /** Whether this connection has completed authentication (only applies to private connections) */ ⋮---- /** * Whether this connection has completed authentication before for the Websocket API, so it k * nows to automatically reauth if reconnected */ ⋮---- /** To reauthenticate on the WS API, which channel do we send to? */ ================ File: src/lib/logger.ts ================ export type LogParams = null | any; ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // console.log(_params); ⋮---- export type DefaultLogger = typeof DefaultLogger; ================ File: src/lib/misc-util.ts ================ export function neverGuard(x: never, msg: string): Error ================ File: src/lib/requestUtils.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { GateBaseUrlKey } from '../types/shared.js'; ⋮---- export interface RestClientOptions { /** Your API key */ apiKey?: string; /** Your API secret */ apiSecret?: string; /** * Override the default/global max size of the request window (in ms) for signed api calls. * If you don't include a recv window when making an API call, this value will be used as default */ recvWindow?: number; /** 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.gate.io' **/ baseUrl?: string; // manually override with one of the known base URLs in the library baseUrlKey?: GateBaseUrlKey; /** Default: true. whether to try and post-process request exceptions (and throw them). */ parseExceptions?: boolean; /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ 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; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** * Override the default/global max size of the request window (in ms) for signed api calls. * If you don't include a recv window when making an API call, this value will be used as default */ ⋮---- /** Default: false. If true, we'll throw errors if any params are undefined */ ⋮---- /** * Optionally override API protocol + domain * e.g baseUrl: 'https://api.gate.io' **/ ⋮---- // manually override with one of the known base URLs in the library ⋮---- /** Default: true. whether to try and post-process request exceptions (and throw them). */ ⋮---- /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ ⋮---- /** * 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) */ ⋮---- /** * 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. */ ⋮---- export function serializeParams | undefined = {}>( params: T, strict_validation: boolean | undefined, encodeValues: boolean, prefixWith: string, ): string ⋮---- // Only prefix if there's a value ⋮---- export function getRestBaseUrl(restClientOptions: RestClientOptions): string ⋮---- export interface MessageEventLike { target: WebSocket; type: 'message'; data: string; } ⋮---- export function isMessageEvent(msg: unknown): msg is MessageEventLike ================ File: src/lib/webCryptoAPI.ts ================ import { neverGuard } from './misc-util.js'; ⋮---- function bufferToB64(buffer: ArrayBuffer): string ⋮---- export type SignEncodeMethod = 'hex' | 'base64'; export type SignAlgorithm = 'SHA-256' | 'SHA-512'; ⋮---- /** * Similar to node crypto's `createHash()` function */ export async function hashMessage( message: string, method: SignEncodeMethod, algorithm: SignAlgorithm, ): Promise ⋮---- /** * Sign a message, with a secret, using the Web Crypto API */ export async function signMessage( message: string, secret: string, method: SignEncodeMethod, algorithm: SignAlgorithm, ): Promise ⋮---- export function checkWebCryptoAPISupported() ================ File: src/types/request/account.ts ================ /**========================================================================================================================== * ACCOUNT * ========================================================================================================================== */ ⋮---- export interface CreateStpGroupReq { name: string; id?: number; creator_id?: number; create_time?: number; } ================ File: src/types/request/announcement.ts ================ /** POST /ann/list_article */ ⋮---- export interface ListAnnouncementArticlesReq { title_query?: string; page?: string; size?: string; tags?: string; timer?: string; cate_name?: string; cate_level?: string; sub_website_id?: string; pinned?: number; update_after?: number; lang?: string; filter_empty_content?: number; } ================ File: src/types/request/collateralLoan.ts ================ /**========================================================================================================================== * COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface SubmitLoanOrderReq { collateral_amount: string; collateral_currency: string; borrow_amount: string; borrow_currency: string; } ⋮---- export interface GetLoanOrdersReq { page?: number; limit?: number; collateral_currency?: string; borrow_currency?: string; } ⋮---- export interface GetLoanRepaymentHistoryReq { source: 'repay' | 'liquidate'; borrow_currency?: string; collateral_currency?: string; page?: number; limit?: number; from?: number; to?: number; } ⋮---- export interface UpdateLoanCollateralReq { order_id: number; collateral_currency: string; collateral_amount: string; type: 'append' | 'redeem'; } ⋮---- export interface GetLoanCollateralRecordsReq { page?: number; limit?: number; from?: number; to?: number; borrow_currency?: string; collateral_currency?: string; } ================ File: src/types/request/delivery.ts ================ /**========================================================================================================================== * DELIVERY * ========================================================================================================================== */ ⋮---- export interface GetDeliveryOrderBookReq { settle: 'usdt'; contract: string; interval?: '0' | '0.1' | '0.01'; limit?: number; with_id?: boolean; } ⋮---- export interface GetDeliveryTradesReq { settle: 'usdt'; contract: string; limit?: number; last_id?: string; from?: number; to?: number; } ⋮---- export interface GetDeliveryCandlesReq { settle: 'usdt'; contract: string; from?: number; to?: number; limit?: number; interval?: | '10s' | '30s' | '1m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '8h' | '12h' | '1d' | '7d' | '1w' | '30d'; } ⋮---- export interface GetDeliveryBookReq { settle: 'usdt'; limit?: number; from?: number; to?: number; type?: | 'dnw' | 'pnl' | 'fee' | 'refr' | 'fund' | 'point_dnw' | 'point_fee' | 'point_refr' | 'bonus_offset'; } ⋮---- export interface SubmitDeliveryFuturesOrderReq { settle: 'usdt'; contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: string; text?: string; auto_size?: string; stp_act?: string; } ⋮---- export interface GetDeliveryOrdersReq { settle: 'usdt'; contract?: string; status: 'open' | 'finished'; limit?: number; offset?: number; last_id?: string; count_total?: 0 | 1; } ⋮---- export interface GetDeliveryTradingHistoryReq { settle: 'usdt'; contract?: string; order?: number; limit?: number; offset?: number; last_id?: string; count_total?: 0 | 1; } ⋮---- export interface GetDeliveryClosedPositionsReq { settle: 'usdt'; contract?: string; limit?: number; } ⋮---- export interface GetDeliveryLiquidationHistoryReq { settle: 'usdt'; contract?: string; limit?: number; at?: number; } ⋮---- export interface GetDeliverySettlementHistoryReq { settle: 'usdt'; contract?: string; limit?: number; at?: number; } export interface GetDeliveryAutoOrdersReq { settle: 'usdt'; status: 'open' | 'finished'; contract?: string; limit?: number; offset?: number; } ================ File: src/types/request/earnuni.ts ================ /**========================================================================================================================== * EARN UNI * ========================================================================================================================== */ ⋮---- export interface SubmitLendOrRedeemReq { currency: string; amount: string; type: 'lend' | 'redeem'; min_rate?: string; } ⋮---- export interface GetLendingOrdersReq { currency?: string; page?: number; limit?: number; } ⋮---- export interface GetLendingRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; type?: 'lend' | 'redeem'; } ⋮---- export interface GetLendingInterestRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; } ================ File: src/types/request/flashswap.ts ================ /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== */ ⋮---- export interface SubmitFlashSwapOrderReq { preview_id: string; sell_currency: string; sell_amount: string; buy_currency: string; buy_amount: string; } ⋮---- export interface GetFlashSwapOrdersReq { status?: number; sell_currency?: string; buy_currency?: string; reverse?: boolean; limit?: number; page?: number; } ⋮---- export interface GetFlashSwapOrderReq { order_id: number; } ⋮---- export interface SubmitFlashSwapOrderPreviewReq { sell_currency: string; sell_amount?: string; buy_currency: string; buy_amount?: string; } ================ File: src/types/request/margin.ts ================ /**========================================================================================================================== * MARGIN * ========================================================================================================================== */ ⋮---- export interface GetMarginBalanceHistoryReq { currency?: string; currency_pair?: string; type?: string; from?: number; to?: number; page?: number; limit?: number; } ⋮---- export interface GetCrossMarginAccountHistoryReq { currency?: string; from?: number; to?: number; page?: number; limit?: number; type?: string; } ⋮---- export interface SubmitCrossMarginBorrowLoanReq { currency: string; amount: string; text?: string; } ⋮---- export interface GetCrossMarginBorrowHistoryReq { status: number; currency?: string; limit?: number; offset?: number; reverse?: boolean; } ⋮---- export interface GetCrossMarginRepaymentsReq { currency?: string; loan_id?: string; limit?: number; offset?: number; reverse?: boolean; } ⋮---- export interface GetCrossMarginInterestRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; } ================ File: src/types/request/marginuni.ts ================ /**========================================================================================================================== * MARGIN UNI * ========================================================================================================================== */ ⋮---- export interface GetMarginUNILoansReq { currency_pair?: string; currency?: string; page?: number; limit?: number; } ⋮---- export interface GetMarginUNILoanRecordsReq { type?: 'borrow' | 'repay'; currency?: string; currency_pair?: string; page?: number; limit?: number; } ⋮---- export interface GetMarginUNIInterestRecordsReq { currency_pair?: string; currency?: string; page?: number; limit?: number; from?: number; to?: number; } ⋮---- export interface GetMarginUNIMaxBorrowReq { currency: string; currency_pair: string; } ================ File: src/types/request/multicollateralLoan.ts ================ /**========================================================================================================================== * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface SubmitMultiLoanOrderReq { order_id?: string; order_type?: string; fixed_type?: string; fixed_rate?: string; auto_renew?: boolean; auto_repay?: boolean; borrow_currency: string; borrow_amount: string; collateral_currencies?: { currency?: string; amount?: string; }[]; } export interface GetMultiLoanOrdersReq { page?: number; limit?: number; sort?: string; order_type?: string; } ⋮---- export interface RepayMultiLoanReq { order_id: number; repay_items: { currency?: string; amount?: string; repaid_all?: boolean; }[]; } ⋮---- export interface GetMultiLoanRepayRecordsReq { type: 'repay' | 'liquidate'; borrow_currency?: string; page?: number; limit?: number; from?: number; to?: number; } ⋮---- export interface UpdateMultiLoanReq { order_id: number; type: 'append' | 'redeem'; collaterals?: { currency?: string; amount?: string; }[]; } ⋮---- export interface GetMultiLoanAdjustmentRecordsReq { page?: number; limit?: number; from?: number; to?: number; collateral_currency?: string; } ================ File: src/types/request/subaccount.ts ================ export interface CreateSubAccountReq { login_name: string; remark?: string; password?: string; email?: string; } ⋮---- export interface CreateSubAccountApiKeyReq { user_id: number; mode?: number; // Mode: 1 - classic, 2 - portfolio account name?: string; // API key name perms?: { name?: | 'wallet' | 'spot' | 'futures' | 'delivery' | 'earn' | 'options' | 'account' | 'unified' | 'loan'; // Permission name read_only?: boolean; // Read only }[]; ip_whitelist?: string[]; // IP white list } ⋮---- mode?: number; // Mode: 1 - classic, 2 - portfolio account name?: string; // API key name ⋮---- | 'loan'; // Permission name read_only?: boolean; // Read only ⋮---- ip_whitelist?: string[]; // IP white list ⋮---- export type UpdateSubAccountApiKeyReq = { key: string; } & CreateSubAccountApiKeyReq; ================ File: src/types/request/withdrawal.ts ================ /**================================================================================================================================ * WITHDRAW * ========================================================================================================================== */ ⋮---- export interface SubmitWithdrawalReq { amount: string; currency: string; chain: string; withdraw_order_id?: string; address?: string; memo?: string; } ================ File: src/types/response/account.ts ================ /**========================================================================================================================== * ACCOUNT * ========================================================================================================================== */ ⋮---- export interface AccountDetail { user_id: number; ip_whitelist: string[]; currency_pairs: string[]; key: { mode: number; }; tier: number; copy_trading_role: number; } ⋮---- export interface AccountRateLimit { type: string; tier: string; ratio: string; main_ratio: string; updated_at: string; } ⋮---- export interface StpGroup { id: number; name: string; creator_id: number; create_time: number; } ⋮---- export interface StpGroupUser { user_id: number; stp_id: number; create_time: number; } ⋮---- export interface AccountMainKey { state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified name: string; currency_pairs: string[]; user_id: number; ip_whitelist: string[]; perms: { name: string; read_only: boolean; }[]; key: string; created_at: string; updated_at: string; last_access: string; } ⋮---- state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified ================ File: src/types/response/announcement.ts ================ export interface AnnouncementArticleLanguage { code?: string; name?: string; } ⋮---- export interface AnnouncementArticle { id?: number; title?: string; brief?: string; created?: string; updated?: string; release_time?: string; views?: number; author?: string; author_id?: number; tags?: string; cate?: string; is_top?: number; cate_id?: number; source?: string; content_lang_list?: AnnouncementArticleLanguage[]; } ⋮---- export interface AnnouncementArticleListData { list?: AnnouncementArticle[]; total?: number; } ⋮---- export interface AnnouncementArticleListResponse { code?: number; data?: AnnouncementArticleListData; message?: string; version?: string; } ================ File: src/types/response/collateralloan.ts ================ /**========================================================================================================================== * COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface LoanOrder { order_id: number; collateral_currency: string; collateral_amount: string; borrow_currency: string; borrow_amount: string; repaid_amount: string; repaid_principal: string; repaid_interest: string; init_ltv: string; current_ltv: string; liquidate_ltv: string; status: string; borrow_time: number; left_repay_total: string; left_repay_principal: string; left_repay_interest: string; } ⋮---- export interface LoanRepaymentHistoryRecord { order_id: number; record_id: number; repaid_amount: string; borrow_currency: string; collateral_currency: string; init_ltv: string; borrow_time: number; repay_time: number; total_interest: string; before_left_principal: string; after_left_principal: string; before_left_collateral: string; after_left_collateral: string; } ⋮---- export interface LoanCollateralRecord { order_id: number; record_id: number; borrow_currency: string; borrow_amount: string; collateral_currency: string; before_collateral: string; after_collateral: string; before_ltv: string; after_ltv: string; operate_time: number; } ⋮---- export interface LoanCollateralRatio { collateral_currency: string; borrow_currency: string; init_ltv: string; alert_ltv: string; liquidate_ltv: string; min_borrow_amount: string; left_borrowable_amount: string; } ================ File: src/types/response/earnuni.ts ================ /**========================================================================================================================== * EARN UNI * ========================================================================================================================== */ ⋮---- export interface LendingCurrency { currency: string; min_lend_amount: string; max_lend_amount: string; max_rate: string; min_rate: string; } ⋮---- export interface LendingOrder { currency: string; current_amount: string; amount: string; lent_amount: string; frozen_amount: string; min_rate: string; interest_status: string; reinvest_left_amount: string; create_time: number; update_time: number; } ⋮---- export interface LendingRecord { currency: string; amount: string; last_wallet_amount: string; last_lent_amount: string; last_frozen_amount: string; type: 'lend' | 'redeem'; create_time: number; } ⋮---- export interface LendingInterestRecord { status: number; currency: string; actual_rate: string; interest: string; interest_status: string; create_time: number; } ================ File: src/types/response/flashswap.ts ================ /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== */ ⋮---- export interface FlashSwapCurrencyPair { currency_pair: string; sell_currency: string; buy_currency: string; sell_min_amount: string; sell_max_amount: string; buy_min_amount: string; buy_max_amount: string; } ⋮---- export interface FlashSwapOrder { id: number; create_time: number; user_id: number; sell_currency: string; sell_amount: string; buy_currency: string; buy_amount: string; price: string; status: number; } ⋮---- export interface SubmitFlashSwapOrderPreviewResp { preview_id: string; sell_currency: string; sell_amount: string; buy_currency: string; buy_amount: string; price: string; } ================ File: src/types/response/subaccount.ts ================ export interface SubAccount { remark?: string; login_name: string; password?: string; email?: string; state: number; type: number; user_id: number; create_time: number; } ⋮---- export interface CreatedSubAccountAPIKey { user_id: string; mode?: number; name?: string; perms?: { name?: | 'wallet' | 'spot' | 'futures' | 'delivery' | 'earn' | 'options' | 'account' | 'unified' | 'loan'; read_only?: boolean; }[]; ip_whitelist?: string[]; key: string; state: number; created_at: number; updated_at: number; last_access: number; } ⋮---- export interface SubAccountAPIKey { user_id?: string; mode?: number; name?: string; perms?: { name?: | 'wallet' | 'spot' | 'futures' | 'delivery' | 'earn' | 'options' | 'account' | 'unified' | 'loan'; read_only?: boolean; }[]; ip_whitelist?: string[]; key?: string; state?: number; created_at?: number; updated_at?: number; last_access?: number; } ⋮---- export interface SubAccountMode { user_id: number; is_unified: boolean; mode: 'classic' | 'multi_currency' | 'portfolio'; } ================ File: src/types/websockets/events.ts ================ export interface WsDataEvent { data: TData; table: string; wsKey: TWSKey; } ================ File: src/types/websockets/requests.ts ================ import { CHANNEL_ID } from '../../lib/requestUtils.js'; import { WSAPITopic } from './wsAPI.js'; ⋮---- export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; ⋮---- export interface WsRequestAuthGate { method: 'api_key'; KEY: string; SIGN: string; } ⋮---- export interface WsRequestPing { time: number; channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; } ⋮---- export interface WsRequestOperationGate< TWSTopic extends string, TWSPayload = any, > { time: number; id?: number; channel: TWSTopic; auth?: WsRequestAuthGate; event?: WsOperation; payload?: TWSPayload; } ⋮---- export interface WSAPIRequest< TRequestParams = any, TWSChannel extends WSAPITopic = any, > { time: number; id?: number; channel: TWSChannel; event: 'api'; payload: { req_id: string; req_param?: TRequestParams | string; req_header: { 'X-Gate-Channel-Id': typeof CHANNEL_ID; }; api_key?: string; signature?: string; timestamp?: string; }; } ================ File: src/types/websockets/wsAPI.ts ================ import { WsKey } from '../../lib/websocket/websocket-util.js'; ⋮---- export type SpotWSAPITopic = | 'spot.login' | 'spot.order_place' | 'spot.order_cancel' | 'spot.order_cancel_ids' | 'spot.order_cancel_cp' | 'spot.order_amend' | 'spot.order_status' | 'spot.order_list'; ⋮---- export type FuturesWSAPITopic = | 'futures.login' | 'futures.order_place' | 'futures.order_batch_place' | 'futures.order_cancel' | 'futures.order_cancel_cp' | 'futures.order_amend' | 'futures.order_list' | 'futures.order_status' | 'futures.order_cancel_ids'; ⋮---- export interface WsAPIWsKeyTopicMap { spotV4: SpotWSAPITopic; perpFuturesUSDTV4: FuturesWSAPITopic; perpFuturesBTCV4: FuturesWSAPITopic; deliveryFuturesUSDTV4: FuturesWSAPITopic; deliveryFuturesBTCV4: FuturesWSAPITopic; // optionsV4: never; // announcementsV4: never; } ⋮---- // optionsV4: never; // announcementsV4: never; ⋮---- export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; ⋮---- // ==================================== // Spot WebSocket API Request Types // ==================================== ⋮---- export interface WSAPISpotOrderPlaceReq { text?: string; currency_pair: string; type?: 'limit' | 'market'; account?: 'spot' | 'margin' | 'unified' | 'cross_margin'; side: 'buy' | 'sell'; amount: string; price?: string; time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; iceberg?: string; auto_borrow?: boolean; auto_repay?: boolean; stp_act?: 'cn' | 'co' | 'cb'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- export interface WSAPISpotOrderCancelReq { order_id: string; currency_pair: string; account?: string; } ⋮---- export interface WSAPISpotOrderCancelIdsReq { currency_pair: string; id: string; account?: string; } ⋮---- export interface WSAPISpotOrderCancelCPReq { currency_pair: string; side?: 'buy' | 'sell'; account?: string; } ⋮---- export interface WSAPISpotOrderAmendReq { amount?: string; price?: string; amend_text?: string; order_id: string; currency_pair: string; account?: string; } ⋮---- export interface WSAPISpotOrderStatusReq { order_id: string; currency_pair: string; account?: string; } ⋮---- export interface WSAPISpotOrderListReq { currency_pair: string; status: 'open' | 'finished'; page?: number; limit?: number; account?: string; from?: number; to?: number; side?: 'buy' | 'sell'; } ⋮---- // ==================================== // Futures WebSocket API Request Types // ==================================== ⋮---- export interface WSAPIFuturesOrderPlaceReq { contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; text?: string; auto_size?: 'close_long' | 'close_short'; stp_act?: 'cn' | 'co' | 'cb'; } ⋮---- export interface WSAPIFuturesOrderCancelReq { order_id: string; } ⋮---- export interface WSAPIFuturesOrderCancelCPReq { contract: string; side?: 'bid' | 'ask'; } ⋮---- export interface WSAPIFuturesOrderAmendReq { order_id: string; price?: string; size?: number; amend_text?: string; } ⋮---- export interface WSAPIFuturesOrderListReq { contract: string; status: 'open' | 'finished'; limit?: number; offset?: number; last_id?: string; count_total?: number; } ⋮---- export interface WSAPIFuturesOrderStatusReq { order_id: string; } ⋮---- // ==================================== // Spot WebSocket API Response Types // ==================================== ⋮---- export interface WSAPISpotOrder { id: string; text: string; amend_text: string; create_time: string; update_time: string; create_time_ms: number; update_time_ms: number; status: string; currency_pair: string; type: string; account: string; side: string; amount: string; price: string; time_in_force: string; iceberg: string; left: string; fill_price?: string; filled_amount?: string; filled_total: string; avg_deal_price?: string; fee: string; fee_currency: string; point_fee: string; gt_fee: string; gt_maker_fee?: string; gt_taker_fee?: string; gt_discount?: boolean; rebated_fee: string; rebated_fee_currency: string; stp_id?: number; stp_act?: string; finish_as: string; } ⋮---- export interface WSAPISpotOrderCancelIdsRespItem { currency_pair: string; id: string; succeeded: boolean; } ⋮---- // ==================================== // Futures WebSocket API Response Types // ==================================== ⋮---- export interface WSAPIFuturesOrder { id: number; user: number; create_time: number; finish_time?: number; update_time?: number; finish_as?: string; status: string; contract: string; size: number; price: string; tif: string; left?: number; fill_price: string; text: string; tkfr: string; mkfr: string; stp_id?: number; stp_act?: string; amend_text?: string; } ⋮---- export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { succeeded: boolean; } ⋮---- export interface WSAPIFuturesOrderCancelIdsRespItem { id: string; user_id: number; succeeded?: boolean; message?: string; } ⋮---- // ==================================== // Request Parameter Mapping // ==================================== ⋮---- export interface WsAPITopicRequestParamMap { 'spot.login': undefined; 'futures.login': undefined; 'spot.order_place': WSAPISpotOrderPlaceReq; 'spot.order_cancel': WSAPISpotOrderCancelReq; 'spot.order_cancel_ids': WSAPISpotOrderCancelIdsReq[]; 'spot.order_cancel_cp': WSAPISpotOrderCancelCPReq; 'spot.order_amend': WSAPISpotOrderAmendReq; 'spot.order_status': WSAPISpotOrderStatusReq; 'spot.order_list': WSAPISpotOrderListReq; 'futures.order_place': WSAPIFuturesOrderPlaceReq; 'futures.order_batch_place': WSAPIFuturesOrderPlaceReq[]; 'futures.order_cancel': WSAPIFuturesOrderCancelReq; 'futures.order_cancel_ids': string[]; 'futures.order_cancel_cp': WSAPIFuturesOrderCancelCPReq; 'futures.order_amend': WSAPIFuturesOrderAmendReq; 'futures.order_list': WSAPIFuturesOrderListReq; 'futures.order_status': WSAPIFuturesOrderStatusReq; } ⋮---- export type WsAPITopicRequestParams = WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; ⋮---- // ==================================== // Response Headers and Base Response // ==================================== ⋮---- export interface WSAPIResponseHeader { /** String timestamp as ms */ response_time: string; /** Status of WS API call. "200" if successful, else exception is thrown */ status: '200' | string; channel: TChannel; event: 'api'; client_id: string; } ⋮---- /** String timestamp as ms */ ⋮---- /** Status of WS API call. "200" if successful, else exception is thrown */ ⋮---- export interface WSAPILoginResponse { api_key: string; uid: string; } ⋮---- export interface WSAPIOrderStatusResponse { left: string; update_time: string; amount: string; create_time: string; price: string; finish_as: string; time_in_force: string; currency_pair: string; type: string; account: string; side: string; amend_text: string; text: string; status: string; iceberg: string; avg_deal_price: string; filled_total: string; id: string; fill_price: string; update_time_ms: number; create_time_ms: number; } ⋮---- export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; ⋮---- export interface WSAPIResponse< TResponseData extends object = WSAPIResponseData | object, TChannel extends WSAPITopic = WSAPITopic, > { wsKey: WsKey; header: WSAPIResponseHeader; data: { result: TResponseData; }; /** Auto-generated */ request_id: string; } ⋮---- /** Auto-generated */ ⋮---- // ==================================== // Response Type Mapping // ==================================== ⋮---- export interface WsAPITopicResponseMap { 'spot.login': WSAPIResponse; 'futures.login': WSAPIResponse; 'spot.order_place': WSAPIResponse; 'spot.order_cancel': WSAPIResponse; 'spot.order_cancel_ids': WSAPIResponse< WSAPISpotOrderCancelIdsRespItem[], 'spot.order_cancel_ids' >; 'spot.order_cancel_cp': WSAPIResponse< WSAPISpotOrder[], 'spot.order_cancel_cp' >; 'spot.order_amend': WSAPIResponse; 'spot.order_status': WSAPIResponse; 'spot.order_list': WSAPIResponse; 'futures.order_place': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_place' >; 'futures.order_batch_place': WSAPIResponse< WSAPIFuturesOrderBatchPlaceRespItem[], 'futures.order_batch_place' >; 'futures.order_cancel': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_cancel' >; 'futures.order_cancel_ids': WSAPIResponse< WSAPIFuturesOrderCancelIdsRespItem[], 'futures.order_cancel_ids' >; 'futures.order_cancel_cp': WSAPIResponse< WSAPIFuturesOrder[], 'futures.order_cancel_cp' >; 'futures.order_amend': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_amend' >; 'futures.order_list': WSAPIResponse< WSAPIFuturesOrder[], 'futures.order_list' >; 'futures.order_status': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_status' >; } ⋮---- // export interface WsAPIResponseMap { // 'spot.login': WSAPIResponse; // 'futures.login': WSAPIResponse; // string: object; // } ================ File: src/WebsocketAPIClient.ts ================ import { DefaultLogger } from './lib/logger.js'; import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; import { WSClientConfigurableOptions } from './types/websockets/client.js'; import { WSAPIFuturesOrder, WSAPIFuturesOrderAmendReq, WSAPIFuturesOrderBatchPlaceRespItem, WSAPIFuturesOrderCancelCPReq, WSAPIFuturesOrderCancelIdsRespItem, WSAPIFuturesOrderCancelReq, WSAPIFuturesOrderListReq, WSAPIFuturesOrderPlaceReq, WSAPIFuturesOrderStatusReq, WSAPIResponse, WSAPISpotOrder, WSAPISpotOrderAmendReq, WSAPISpotOrderCancelCPReq, WSAPISpotOrderCancelIdsReq, WSAPISpotOrderCancelIdsRespItem, WSAPISpotOrderCancelReq, WSAPISpotOrderListReq, WSAPISpotOrderPlaceReq, WSAPISpotOrderStatusReq, WSAPIWsKey, } from './types/websockets/wsAPI.js'; import { WebsocketClient } from './WebsocketClient.js'; ⋮---- /** * Configurable options specific to only the REST-like WebsocketAPIClient */ export interface WSAPIClientConfigurableOptions { /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ attachEventListeners: boolean; } ⋮---- /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ ⋮---- /** * This is a minimal Websocket API wrapper around the WebsocketClient. * * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should * be used to transmit that message. This is only useful if you wish to use an alternative wss * domain that is supported by the SDK. * * Note: To use testnet, don't set the wsKey - use `testnet: true` in * the constructor instead. * * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some * may find the below methods slightly more intuitive. * * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 */ export class WebsocketAPIClient ⋮---- constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, ) ⋮---- public getWSClient(): WebsocketClient ⋮---- public setTimeOffsetMs(newOffset: number): void ⋮---- /* * * SPOT - Trading requests * */ ⋮---- /** * Submit a spot order */ submitNewSpotOrder( params: WSAPISpotOrderPlaceReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel a spot order */ cancelSpotOrder( params: WSAPISpotOrderCancelReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel all spot orders with the given id list */ cancelSpotOrderById( params: WSAPISpotOrderCancelIdsReq[], wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel a spot order for a given symbol */ cancelSpotOrderForSymbol( params: WSAPISpotOrderCancelCPReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Update a spot order */ updateSpotOrder( params: WSAPISpotOrderAmendReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get the status of a spot order */ getSpotOrderStatus( params: WSAPISpotOrderStatusReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get all spot orders */ getSpotOrders( params: WSAPISpotOrderListReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /* * * Futures - Trading requests * */ ⋮---- /** * Submit a futures order. * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ submitNewFuturesOrder( params: WSAPIFuturesOrderPlaceReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Submit a batch of futures orders * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ submitNewFuturesBatchOrder( params: WSAPIFuturesOrderPlaceReq[], wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel a futures order * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ cancelFuturesOrder( params: WSAPIFuturesOrderCancelReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel futures orders by id list * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ cancelFuturesOrderById( params: string[], wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel all open futures orders * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ cancelFuturesAllOpenOrders( params: WSAPIFuturesOrderCancelCPReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Update a futures order * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ updateFuturesOrder( params: WSAPIFuturesOrderAmendReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get all futures orders * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ getFuturesOrders( params: WSAPIFuturesOrderListReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get futures order status * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ getFuturesOrderStatus( params: WSAPIFuturesOrderStatusReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * * * * * * * * Private methods for handling some of the convenience/automation provided by the WS API Client * * * * * * * */ ⋮---- private setupDefaultEventListeners() ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- // Blind JSON.stringify can fail on circular references ⋮---- // JSON.stringify({ ...data, target: 'WebSocket' }), ================ File: src/WebsocketClient.ts ================ import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; import { neverGuard } from './lib/misc-util.js'; import { CHANNEL_ID, MessageEventLike } from './lib/requestUtils.js'; import { SignAlgorithm, SignEncodeMethod, signMessage, } from './lib/webCryptoAPI.js'; import { getPrivateFuturesTopics, getPrivateOptionsTopics, getPrivateSpotTopics, getPromiseRefForWSAPIRequest, WS_BASE_URL_MAP, WS_KEY_MAP, WsKey, WsMarket, WsTopicRequest, } from './lib/websocket/websocket-util.js'; import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; import { WSAPIRequest, WsOperation, WsRequestOperationGate, WsRequestPing, } from './types/websockets/requests.js'; import { WsAPITopicRequestParamMap, WsAPITopicResponseMap, WSAPIWsKey, WsAPIWsKeyTopicMap, } from './types/websockets/wsAPI.js'; ⋮---- export interface WSAPIRequestFlags { /** If true, will skip auth requirement for WS API connection */ authIsOptional?: boolean | undefined; } ⋮---- /** If true, will skip auth requirement for WS API connection */ ⋮---- /** * WS topics are always a string for gate. Some exchanges use complex objects */ export type WsTopic = string; ⋮---- export class WebsocketClient extends BaseWebsocketClient ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. * * Returns array of promises that individually resolve when each connection is successfully opened. */ public connectAll(): Promise[] ⋮---- /** * Ensures the WS API connection is active and ready. * * You do not need to call this, but if you call this before making any WS API requests, * it can accelerate the first request (by preparing the connection in advance). */ public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise ⋮---- /** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- /** * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters). * Objects should be formatted as {topic: string, params: object}. * * - Subscriptions are automatically routed to the correct websocket connection. * - Authentication/connection is automatic. * - Resubscribe after network issues is automatic. * * Call `unsubscribe(topics)` to remove topics */ public subscribe( requests: | (WsTopicRequest | WsTopic) | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) ⋮---- /** * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. * * - Requests are automatically routed to the correct websocket connection. * - These topics will be removed from the topic cache, so they won't be subscribed to again. */ public unsubscribe( requests: | (WsTopicRequest | WsTopic) | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) ⋮---- /** * WS API Methods - similar to the REST API, but via WebSockets */ ⋮---- /** * 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 (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4") * @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 */ ⋮---- // This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call) async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse extends | WsAPITopicResponseMap[TWSChannel] | object = WsAPITopicResponseMap[TWSChannel], >( wsKey: TWSKey, channel: TWSChannel, params?: TWSParams extends void | never ? undefined : TWSParams, requestFlags?: WSAPIRequestFlags, ): Promise; ⋮---- async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse = object, >( wsKey: TWSKey, channel: TWSChannel, params: TWSParams & { signRequest?: boolean }, requestFlags?: WSAPIRequestFlags, ): Promise ⋮---- // Some commands don't require authentication. ⋮---- // this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- // this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- // id: timeInSeconds, ⋮---- /** * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated * can introduce a small delay before the actual request is sent, if not connected before that request is * made. This can lead to a curious race condition, where the request timestamp is before * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. * * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, * it offsets that timestamp by the delay. */ ⋮---- // Sign request ⋮---- // Store deferred promise ⋮---- // Enrich returned promise with request context for easier debugging ⋮---- // throw e; ⋮---- // Send event ⋮---- // Return deferred promise, so caller can await this call ⋮---- /** * * Internal methods - not intended for public use * */ ⋮---- protected getWsUrl(wsKey: WsKey): string ⋮---- protected sendPingEvent(wsKey: WsKey) ⋮---- protected sendPongEvent(wsKey: WsKey) ⋮---- // Send a protocol layer pong ⋮---- // NOT IN USE for gate.io, pings for gate are protocol layer pings // eslint-disable-next-line @typescript-eslint/no-unused-vars protected isWsPing(_msg: any): boolean ⋮---- protected isWsPong(msg: any): boolean ⋮---- /** * Parse incoming events into categories, before emitting to the user */ protected resolveEmittableEvents( wsKey: WsKey, event: MessageEventLike, ): EmittableEvent[] ⋮---- // WS API Exception ⋮---- // WS API Success ⋮---- // Most events use "event: 'update'" for topic updates // The legacy "futures.order_book" topic uses "all" for this field // 'futures.obu' is used for the orderbook v2 event. Oddly in a different structure than the other topics. ⋮---- // These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- // Request/reply pattern for authentication success ⋮---- /** * Determines if a topic is for a private channel, using a hardcoded list of strings */ protected isPrivateTopicRequest( request: WsTopicRequest, wsKey: WsKey, ): boolean ⋮---- // No private announcements channels ⋮---- /** * Not in use for gate.io */ ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket ⋮---- /** * Not in use for gate.io */ protected getPrivateWSKeys(): WsKey[] ⋮---- protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** Force subscription requests to be sent in smaller batches, if a number is returned */ // eslint-disable-next-line @typescript-eslint/no-unused-vars protected getMaxTopicsPerSubscribeEvent(_wsKey: WsKey): number | null ⋮---- /** * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) */ protected async getWsOperationEventsForTopics( topics: WsTopicRequest[], wsKey: WsKey, operation: WsOperation, ): Promise ⋮---- // console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); // console.trace(); ⋮---- // Events that are ready to send (usually stringified JSON) ⋮---- /** * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ private async getWsRequestEvents( market: WsMarket, operation: WsOperation, requests: WsTopicRequest[], wsKey: WsKey, ): Promise[]> ⋮---- // If private topic request, build auth part for request ⋮---- // No key or secret, push event as failed ⋮---- private async signMessage( paramsStr: string, secret: string, method: 'hex' | 'base64', algorithm: SignAlgorithm, ): Promise ⋮---- protected async getWsAuthRequestEvent(wsKey: WsKey): Promise ⋮---- // id: timeInSeconds, ⋮---- /** * * @param requestEvent * @returns A signed updated WS API request object, ready to be sent */ private async signWSAPIRequest( requestEvent: WSAPIRequest, ): Promise> ================ File: .eslintrc.cjs ================ // 'no-unused-vars': ['warn'], ================ File: .prettierrc ================ { "tabWidth": 2, "singleQuote": true, "trailingComma": "all" } ================ File: jest.config.ts ================ /** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */ ⋮---- import type { Config } from 'jest'; ⋮---- // All imported modules in your tests should be mocked automatically // automock: false, ⋮---- // Stop running tests after `n` failures // bail: 0, bail: false, // enable to stop test when an error occur, ⋮---- // The directory where Jest should store its cached dependency information // cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- // Automatically clear mock calls, instances, contexts and results before every test ⋮---- // Indicates whether the coverage information should be collected while executing the test ⋮---- // An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- // The directory where Jest should output its coverage files ⋮---- // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // Indicates which provider should be used to instrument code for coverage ⋮---- // A list of reporter names that Jest uses when writing coverage reports // coverageReporters: [ // "json", // "text", // "lcov", // "clover" // ], ⋮---- // An object that configures minimum threshold enforcement for coverage results // coverageThreshold: undefined, ⋮---- // A path to a custom dependency extractor // dependencyExtractor: undefined, ⋮---- // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, ⋮---- // The default configuration for fake timers // fakeTimers: { // "enableGlobally": false // }, ⋮---- // Force coverage collection from ignored files using an array of glob patterns // forceCoverageMatch: [], ⋮---- // A path to a module which exports an async function that is triggered once before all test suites // globalSetup: undefined, ⋮---- // A path to a module which exports an async function that is triggered once after all test suites // globalTeardown: undefined, ⋮---- // A set of global variables that need to be available in all test environments // globals: {}, ⋮---- // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. // maxWorkers: "50%", ⋮---- // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ // "node_modules" // ], ⋮---- // An array of file extensions your modules use ⋮---- // modulePaths: ['src'], ⋮---- // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module // moduleNameMapper: {}, ⋮---- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], ⋮---- // Activates notifications for test results // notify: false, ⋮---- // An enum that specifies notification mode. Requires { notify: true } // notifyMode: "failure-change", ⋮---- // A preset that is used as a base for Jest's configuration // preset: undefined, ⋮---- // Run tests from one or more projects // projects: undefined, ⋮---- // Use this configuration option to add custom reporters to Jest // reporters: undefined, ⋮---- // Automatically reset mock state before every test // resetMocks: false, ⋮---- // Reset the module registry before running each individual test // resetModules: false, ⋮---- // A path to a custom resolver // resolver: undefined, ⋮---- // Automatically restore mock state and implementation before every test // restoreMocks: false, ⋮---- // The root directory that Jest should scan for tests and modules within // rootDir: undefined, ⋮---- // A list of paths to directories that Jest should use to search for files in // roots: [ // "" // ], ⋮---- // Allows you to use a custom runner instead of Jest's default test runner // runner: "jest-runner", ⋮---- // The paths to modules that run some code to configure or set up the testing environment before each test // setupFiles: [], ⋮---- // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], ⋮---- // The number of seconds after which a test is considered as slow and reported as such in the results. // slowTestThreshold: 5, ⋮---- // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], ⋮---- // The test environment that will be used for testing // testEnvironment: "jest-environment-node", ⋮---- // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, ⋮---- // Adds a location field to test results // testLocationInResults: false, ⋮---- // The glob patterns Jest uses to detect test files ⋮---- // "**/__tests__/**/*.[jt]s?(x)", ⋮---- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped // testPathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // The regexp pattern or array of patterns that Jest uses to detect test files // testRegex: [], ⋮---- // This option allows the use of a custom results processor // testResultsProcessor: undefined, ⋮---- // This option allows use of a custom test runner // testRunner: "jest-circus/runner", ⋮---- // A map from regular expressions to paths to transformers // transform: undefined, ⋮---- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ // "/node_modules/", // "\\.pnp\\.[^\\/]+$" // ], ⋮---- // Prevents import esm module error from v1 axios release, issue #5026 ⋮---- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them // unmockedModulePathPatterns: undefined, ⋮---- // Indicates whether each individual test should be reported during the run // verbose: undefined, verbose: true, // report individual test ⋮---- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode // watchPathIgnorePatterns: [], ⋮---- // Whether to use watchman for file crawling // watchman: true, ================ File: LICENSE.md ================ Copyright 2022 Tiago Siebler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================ File: postBuild.sh ================ #!/bin/bash # # Add package.json files to cjs/mjs subtrees # cat >dist/cjs/package.json <dist/mjs/package.json < reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ================ File: examples/Rest/futures/getBalances.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getFuturesBalances() ⋮---- // Fetch the futures account balance for USDT settlement ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get futures balances ================ File: examples/Rest/futures/getContractSize.ts ================ /** * Example: Get futures contract size (quanto_multiplier) and convert between * notional (e.g. USDT) and order size in contracts. * * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. * The contract details endpoint returns `quanto_multiplier`: the amount of * underlying (e.g. BTC) that 1 contract represents. So: * notional_in_settle = size * quanto_multiplier * price * size = notional_in_settle / (quanto_multiplier * price) * * This example: * 1) Fetches contract with getFuturesContract * 2) Reads quanto_multiplier and derives "contract size" in quote currency * 3) Converts a desired notional (e.g. 1000 USDT) to order size in contracts */ ⋮---- import { RestClient } from '../../../src/index.js'; // import { RestClient } from 'gateio-api'; ⋮---- async function getContractSizeExample() ⋮---- // 1) Get single contract (public, no auth required) ⋮---- // 2) Contract size in quote (settle) currency: 1 contract = q * p ⋮---- // 3) Convert desired notional (e.g. 1000 USDT) to size in contracts ⋮---- // Example: you would pass this size to submitFuturesOrder // await client.submitFuturesOrder({ // settle: SETTLE, // contract: CONTRACT, // size: size, // in contracts; positive = long, negative = short // price: markPrice, // tif: 'gtc', // }); ================ File: examples/Rest/futures/getContractSizeExample.ts ================ /** * Example: Get futures contract size (quanto_multiplier) and convert between * notional (e.g. USDT) and order size in contracts. * * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. * The contract details endpoint returns `quanto_multiplier`: the amount of * underlying (e.g. BTC) that 1 contract represents. So: * notional_in_settle = size * quanto_multiplier * price * size = notional_in_settle / (quanto_multiplier * price) * * This example: * 1) Fetches contract with getFuturesContract * 2) Reads quanto_multiplier and derives "contract size" in quote currency * 3) Converts a desired notional (e.g. 1000 USDT) to order size in contracts */ ⋮---- import { RestClient } from '../../../src/index.js'; // import { RestClient } from 'gateio-api'; ⋮---- async function getContractSizeExample() ⋮---- // 1) Get single contract (public, no auth required) ⋮---- // 2) Contract size in quote (settle) currency: 1 contract = q * p ⋮---- // 3) Convert desired notional (e.g. 1000 USDT) to size in contracts ⋮---- // Example: you would pass this size to submitFuturesOrder // await client.submitFuturesOrder({ // settle: SETTLE, // contract: CONTRACT, // size: size, // in contracts; positive = long, negative = short // price: markPrice, // tif: 'gtc', // }); ================ File: examples/Rest/futures/getOrders.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key or use environment variables secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret or use environment variables ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getFuturesOrders() ⋮---- // Fetch open futures orders with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency status: 'open', // Specify the status of the orders to fetch ⋮---- console.log('openOrders: ', openOrders); // Log the response to the console ⋮---- // Fetch finished futures orders with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency status: 'finished', // Specify the status of the orders to fetch ⋮---- console.log('finishedOrders: ', finishedOrders); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get futures orders ================ File: examples/Rest/futures/getTickers.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getFuturesTicker() ⋮---- // Fetch all futures tickers with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency ⋮---- console.log('allTickers: ', allTickers); // Log the response to the console ⋮---- // Fetch a specific futures ticker with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract ⋮---- console.log('ticker: ', ticker); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get futures tickers ================ File: examples/Rest/futures/submitLimitOrder.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitFuturesOrder() ⋮---- // Submit a limit order for futures trading ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract size: 10, // Order size: positive for long, negative for short price: '45000', // Limit price for the order tif: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to submit a futures order ================ File: examples/Rest/futures/submitMarketOrder.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitFuturesOrder() ⋮---- // Submit a market order for futures trading ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract size: 20, // Order size: positive for long, negative for short price: '0', // Market order, so price is set to '0' tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to submit a futures order ================ File: examples/Rest/futures/testnet.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- /** * To use a different base URL, use the baseUrl key. The SDK uses the live environment by default: * baseUrlKey: 'live', *'https://api.gateio.ws/api/v4' * But you can force it to use any of the available environments. Examples below. */ ⋮---- /* * Futures TestNet trading: * 'https://fx-api-testnet.gateio.ws/api/v4' */ ⋮---- /** * Futures live trading alternative (futures only): * 'https://fx-api.gateio.ws/api/v4' */ // baseUrlKey: 'futuresLiveAlternative' ⋮---- async function submitFuturesOrder() ⋮---- // Submit a market order for futures trading ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract size: 20, // Order size: positive for long, negative for short price: '0', // Market order, so price is set to '0' tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to submit a futures order ================ File: examples/Rest/otc/createOTCBank.ts ================ import { readFileSync } from 'fs'; ⋮---- import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- async function createOTCBankExample() ⋮---- // Path to account-opening proof (jpg/jpeg/png/pdf, max 4MB per Gate docs) ================ File: examples/Rest/otc/getOTCBankList.ts ================ import { RestClient } from '../../../src/index.js'; // import { RestClient } from 'gateio-api'; ⋮---- async function getOTCBankListExample() ================ File: examples/Rest/spot/getBalances.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotBalances() ⋮---- // Fetch the spot account balances ⋮---- console.log('Response: ', balances); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get spot balances ================ File: examples/Rest/spot/getCandles.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotCandles() ⋮---- // Fetch the spot account balances ⋮---- console.log('Response: ', balances); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get spot balances ================ File: examples/Rest/spot/getOrders.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotOrders() ⋮---- // Fetch open spot orders for the BTC_USDT currency pair ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair status: 'open', // Specify the status of the orders to fetch ⋮---- console.log('openOrders: ', openOrders); // Log the response to the console ⋮---- // Fetch finished spot orders for the BTC_USDT currency pair ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair status: 'finished', // Specify the status of the orders to fetch ⋮---- console.log('finishedOrders: ', finishedOrders); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get spot orders ================ File: examples/Rest/spot/getTickers.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotTicker() ⋮---- // Fetch the ticker for a specific currency pair (BTC_USDT) ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair ⋮---- console.log('Response: ', ticker); // Log the response to the console ⋮---- // Fetch all tickers ⋮---- console.log('Response: ', allTickers); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to get spot tickers ================ File: examples/Rest/spot/submitLimitOrder.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitSpotOrder() ⋮---- // Submit a limit order for spot trading ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair side: 'buy', // Specify the order side: 'buy' or 'sell' type: 'limit', // Specify the order type: 'limit' amount: '0.001', // Specify the amount to buy price: '45000', // Specify the limit price time_in_force: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to submit a spot order ================ File: examples/Rest/spot/submitMarketOrder.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitSpotOrder() ⋮---- // Submit a market order for spot trading ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair side: 'buy', // Specify the order side: 'buy' or 'sell' type: 'market', // Specify the order type: 'market' amount: '10', // Specify the amount to buy time_in_force: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to submit a spot order ================ File: examples/Websocket/WS-API/ws-api-client.ts ================ import { WebsocketAPIClient, WS_KEY_MAP } from '../../../src/index.js'; // import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- async function start() ⋮---- /** * Optional: authenticate in advance. This will prepare and authenticate a connection. * Useful to save time for the first request but completely optional. It will also happen automatically when you make your first request. */ // console.log(new Date(), 'Authenticating in advance...'); // await client.getWSClient().connectWSAPI('spotV4'); // console.log(new Date(), 'Authenticating in advance...OK!'); ⋮---- /* ============ SPOT TRADING EXAMPLES ============ */ ⋮---- // SPOT ORDER PLACE - Submit a new spot order ⋮---- // SPOT ORDER CANCEL - Cancel a specific spot order ⋮---- // SPOT ORDER CANCEL BY IDS - Cancel orders by ID list ⋮---- // SPOT ORDER CANCEL BY CURRENCY PAIR - Cancel all orders for a currency pair ⋮---- // SPOT ORDER AMEND - Update an existing spot order ⋮---- // SPOT ORDER STATUS - Get status of a specific spot order ⋮---- // SPOT ORDER LIST - Get list of spot orders ⋮---- /* ============ FUTURES TRADING EXAMPLES ============ */ ⋮---- /** * Gate has different websocket groups depending on the futures product. * * This affects which connection your command is sent to, so make sure to pass one matching your request. Look at WS_KEY_MAP (or the examples below) for details on the available product groups. */ ⋮---- /** * Also optional, as for spot. Keep in mind the first parameter (wsKey) might vary depending on which WS URL is needed. */ ⋮---- // console.log(new Date(), 'Authenticating in advance...'); // await client.getWSClient().connectWSAPI(futuresConnectionGroup); // await client.getWSClient().connectWSAPI('perpFuturesUSDTV4'); // await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); // await client.getWSClient().connectWSAPI('deliveryFuturesUSDTV4'); // await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); // console.log(new Date(), 'Authenticating in advance...OK!'); ⋮---- // FUTURES ORDER PLACE - Submit a new futures order ⋮---- // FUTURES ORDER BATCH PLACE - Submit multiple futures orders ⋮---- // FUTURES ORDER CANCEL - Cancel a specific futures order ⋮---- // FUTURES ORDER CANCEL BY IDS - Cancel futures orders by ID list ⋮---- // FUTURES ORDER CANCEL ALL - Cancel all open futures orders ⋮---- // FUTURES ORDER AMEND - Update an existing futures order ⋮---- // FUTURES ORDER LIST - Get list of futures orders ⋮---- // FUTURES ORDER STATUS - Get status of a specific futures order ================ File: examples/Websocket/WS-API/ws-private-perp-futures-wsapi.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ ⋮---- import { LogParams, WebsocketClient } from '../../../src/index.js'; // import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('update', (data) => { // // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); // console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); // }); ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('response', (data) => { // console.info( // new Date(), // 'ws server reply ', // JSON.stringify(data, null, 2), // '\n', // ); // }); ⋮---- // Optional, listen to this event if you prefer the event-driven approach. // See below comments on event-driven vs promise-driven. // client.on('authenticated', (data) => { // console.error(new Date(), 'ws authenticated: ', data); // }); ⋮---- /** * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. * * You have two ways to handle responses on the WS API. You can either: * - event-driven: process async `response` and `update` events from the websocket client, OR * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). */ ⋮---- /** * To authenticate, send an empty request to "futures.login". The SDK will handle all the parameters. * * Optional - you can inject rich types to set the response type * const loginResult = await client.sendWSAPIRequest>('perpFuturesUSDTV4', 'futures.login'); */ ⋮---- /** * For other channels, the 3rd parameter should have any parameters for the request (the payload). * * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. * */ ⋮---- /** * Submit futures order */ ⋮---- size: 20, // positive for long, negative for short ⋮---- /** * Submit batch futures order */ ⋮---- size: 10, // positive for long, negative for short ⋮---- size: 10, // positive for long, negative for short ⋮---- /** * Cancel futures order */ ⋮---- /** * Cancel all futures orders */ ⋮---- /** * Update/Amend Futures order */ ⋮---- /** * Get orders list */ ⋮---- /** * Get order status */ ================ File: examples/Websocket/WS-API/ws-private-spot-wsapi.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ ⋮---- import { LogParams, WebsocketClient } from '../../../src/index.js'; // import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('update', (data) => { // // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); // console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); // }); ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('response', (data) => { // console.info( // new Date(), // 'ws server reply ', // JSON.stringify(data, null, 2), // '\n', // ); // }); ⋮---- // Optional, listen to this event if you prefer the event-driven approach. // See below comments on event-driven vs promise-driven. // client.on('authenticated', (data) => { // console.error(new Date(), 'ws authenticated: ', data); // }); ⋮---- /** * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. * * You have two ways to handle responses on the WS API. You can either: * - event-driven: process async `response` and `update` events from the websocket client, OR * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). */ ⋮---- /** * No need to authenticate first - the SDK will automatically authenticate for you when you send your first request. * * Unless you want to prepare the connection before your first request, to speed up your first request. */ ⋮---- /** * For other channels, the 3rd parameter should have any parameters for the request (the payload that goes in req_param in the docs). * * See WsAPIRequestsTopicMap for a topic->parameter map. * * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. */ ⋮---- /** * Submit spot order */ ⋮---- /** * Cancel spot order */ ⋮---- /** * Batch cancel spot order */ ⋮---- /** * Amend/Update spot order */ ⋮---- /** * Get spot order status */ ⋮---- /** * If you don't want to use await (and prefer the async event emitter), make sure to still include a catch block. * * The response will come async via the event emitter in the WS Client. */ ⋮---- // client // .sendWSAPIRequest('spotV4', 'spot.order_status', { // order_id: '600995435390', // currency_pair: 'BTC_USDT', // }) // .catch((e) => { // console.error(`exception ws api call, get spot order status: `, e); // }); ================ File: examples/Websocket/ws-private-perp-futures.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { LogParams, WebsocketClient, WsTopicRequest } from '../../src/index.js'; // import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // console.log('auth with: ', account); ⋮---- // Data received ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- // TODO: many private topics use your user ID ⋮---- /** * Either send one topic (with params) at a time */ // client.subscribe({ // topic: 'futures.usertrades', // payload: [myUserID, '!all'], // }, 'perpFuturesUSDTV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: */ ================ File: examples/Websocket/ws-private-spot.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { LogParams, WebsocketClient, WsTopicRequest } from '../../src/index.js'; // import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // console.log('auth with: ', account); ⋮---- // Data received ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- // client.subscribe(topics, 'spotV4'); ⋮---- // This has the same effect as above, it's just a different way of messaging which topic this is for // const topicWithoutParamsAsObject: WsTopicRequest = { // topic: 'spot.balances', // }; ⋮---- /** * Either send one topic (with optional params) at a time */ // client.subscribe(topicWithoutParamsAsObject, 'spotV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: */ ⋮---- /** * You can also subscribe in separate function calls as you wish. * * Any duplicate requests should get filtered out (e.g. here we subscribed to "spot.balances" twice, but the WS client will filter this out) */ ================ File: examples/Websocket/ws-public.ts ================ // eslint-disable-next-line @typescript-eslint/no-unused-vars import { WebsocketClient, WsTopicRequest } from '../../src/index.js'; // import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // const customLogger = { // // eslint-disable-next-line @typescript-eslint/no-unused-vars // trace: (...params: LogParams): void => { // console.log('trace', ...params); // }, // info: (...params: LogParams): void => { // console.log('info', ...params); // }, // error: (...params: LogParams): void => { // console.error('error', ...params); // }, // }; ⋮---- async function start() ⋮---- // Optional, inject a custom logger // const client = new WebsocketClient({}, customLogger); ⋮---- // Data received ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- // const topicWithoutParamsAsString = 'spot.balances'; ⋮---- // This has the same effect as above, it's just a different way of messaging which topic this is for // const topicWithoutParamsAsObject: WsTopicRequest = { // topic: 'spot.balances', // }; ⋮---- /** * Either send one topic (with optional params) at a time */ // client.subscribe(tickersRequestWithParams, 'spotV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) */ ⋮---- // /** // * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: // */ // client.subscribe( // [tickersRequestWithParams, rawTradesRequestWithParams, topicWithoutParamsAsString], // 'spotV4', // ); ================ File: src/lib/websocket/WsStore.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { DefaultLogger } from '../logger.js'; import { DeferredPromise, WSConnectedResult, WsConnectionStateEnum, WsStoredState, } from './WsStore.types.js'; ⋮---- /** * Simple comparison of two objects, recursive for nested objects */ export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean ⋮---- type DeferredPromiseRef = (typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF]; ⋮---- export class WsStore< WsKey extends string, ⋮---- constructor(logger: DefaultLogger) ⋮---- /** Get WS stored state for key, optionally create if missing */ get( key: WsKey, createIfMissing?: true, ): WsStoredState; ⋮---- get( key: WsKey, createIfMissing?: false, ): WsStoredState | undefined; ⋮---- get( key: WsKey, createIfMissing?: boolean, ): WsStoredState | undefined ⋮---- getKeys(): WsKey[] ⋮---- create(key: WsKey): WsStoredState | undefined ⋮---- delete(key: WsKey): void ⋮---- // TODO: should we allow this at all? Perhaps block this from happening... ⋮---- /* connection websocket */ ⋮---- hasExistingActiveConnection(key: WsKey): boolean ⋮---- getWs(key: WsKey): WebSocket | undefined ⋮---- setWs(key: WsKey, wsConnection: WebSocket): WebSocket ⋮---- /** * deferred promises */ ⋮---- getDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, ): DeferredPromise | undefined ⋮---- createDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, throwIfExists: boolean, ): DeferredPromise ⋮---- // console.log('existing promise'); ⋮---- // console.log('create promise'); ⋮---- // TODO: Once stable, use Promise.withResolvers in future ⋮---- resolveDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, value: unknown, removeAfter: boolean, ): void ⋮---- rejectDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, value: unknown, removeAfter: boolean, ): void ⋮---- removeDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, ): void ⋮---- // Just in case it's pending ⋮---- rejectAllDeferredPromises(wsKey: WsKey, reason: string): void ⋮---- // Skip reserved keys, such as the connection promise ⋮---- /** Get promise designed to track a connection attempt in progress. Resolves once connected. */ getConnectionInProgressPromise( wsKey: WsKey, ): DeferredPromise | undefined ⋮---- getAuthenticationInProgressPromise( wsKey: WsKey, ): DeferredPromise ⋮---- createAuthenticationInProgressPromise( wsKey: WsKey, throwIfExists: boolean, ): DeferredPromise ⋮---- getTopicsByKey(): Record> ⋮---- /** * Find matching "topic" request from the store * @param key * @param topic * @returns */ getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- // Check for duplicate topic. If already tracked, don't store this one ⋮---- deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- // Check if we're subscribed to a topic like this ================ File: src/lib/BaseWSClient.ts ================ import EventEmitter from 'events'; import WebSocket from 'isomorphic-ws'; ⋮---- import { WebsocketClientOptions, WSClientConfigurableOptions, } from '../types/websockets/client.js'; import { WsOperation } from '../types/websockets/requests.js'; import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; import { DefaultLogger } from './logger.js'; import { isMessageEvent, MessageEventLike } from './requestUtils.js'; import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; import { safeTerminateWs, WsTopicRequest, WsTopicRequestOrStringTopic, } from './websocket/websocket-util.js'; import { WsStore } from './websocket/WsStore.js'; import { WSConnectedResult, WsConnectionStateEnum, } from './websocket/WsStore.types.js'; ⋮---- interface WSClientEventMap { /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ open: (evt: { wsKey: WsKey; event: any; wsUrl: string; ws: WebSocket; }) => void /** Reconnecting a dropped connection */; reconnect: (evt: { wsKey: WsKey; event: any }) => void; /** Successfully reconnected a connection that dropped */ reconnected: (evt: { wsKey: WsKey; event: any; wsUrl: string; ws: WebSocket; }) => void; /** Connection closed */ close: (evt: { wsKey: WsKey; event: any }) => void; /** Received reply to websocket command (e.g. after subscribing to topics) */ response: (response: any & { wsKey: WsKey }) => void; /** Received data for topic */ update: (response: any & { wsKey: WsKey }) => void; /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ exception: (response: any & { wsKey: WsKey }) => void; error: (response: any & { wsKey: WsKey }) => void; /** Confirmation that a connection successfully authenticated */ authenticated: (event: { wsKey: WsKey; event: any }) => void; } ⋮---- /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ ⋮---- }) => void /** Reconnecting a dropped connection */; ⋮---- /** Successfully reconnected a connection that dropped */ ⋮---- /** Connection closed */ ⋮---- /** Received reply to websocket command (e.g. after subscribing to topics) */ ⋮---- /** Received data for topic */ ⋮---- /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ ⋮---- /** Confirmation that a connection successfully authenticated */ ⋮---- export interface EmittableEvent { eventType: 'response' | 'update' | 'exception' | 'authenticated'; event: TEvent; } ⋮---- // Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 export interface BaseWebsocketClient { on>( event: U, listener: WSClientEventMap[U], ): this; emit>( event: U, ...args: Parameters[U]> ): boolean; } ⋮---- on>( event: U, listener: WSClientEventMap[U], ): this; ⋮---- emit>( event: U, ...args: Parameters[U]> ): boolean; ⋮---- /** * 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[] ⋮---- // passed as string, convert to object ⋮---- // already a normalised object, thanks to user ⋮---- /** * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" */ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export abstract class BaseWebsocketClient< ⋮---- /** * The WS connections supported by the client, each identified by a unique primary key */ ⋮---- /** * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected */ ⋮---- constructor( options?: WSClientConfigurableOptions, logger?: typeof DefaultLogger, ) ⋮---- // Some defaults: ⋮---- // Gate.io only has one connection (for both public & private). Auth works with every sub, not on connect, so this is turned off. ⋮---- // Gate.io requires auth to be added to every request, when subscribing to private topics. This is handled automatically. ⋮---- // Automatically re-auth WS API, if we were auth'd before and get reconnected ⋮---- // Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; ⋮---- protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; ⋮---- protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; ⋮---- protected abstract isWsPing(data: any): boolean; ⋮---- protected abstract isWsPong(data: any): boolean; ⋮---- protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; ⋮---- protected abstract isPrivateTopicRequest( request: WsTopicRequest, wsKey: TWSKey, ): boolean; ⋮---- protected abstract getPrivateWSKeys(): TWSKey[]; ⋮---- protected abstract getWsUrl(wsKey: TWSKey): string; ⋮---- protected abstract getMaxTopicsPerSubscribeEvent( wsKey: TWSKey, ): number | null; ⋮---- /** * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics */ protected abstract getWsOperationEventsForTopics( topics: WsTopicRequest[], wsKey: TWSKey, operation: WsOperation, ): Promise; ⋮---- /** * 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[]; ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ protected abstract connectAll(): Promise[]; ⋮---- protected isPrivateWsKey(wsKey: TWSKey): boolean ⋮---- /** Returns auto-incrementing request ID, used to track promise references for async requests */ protected getNewRequestId(): string ⋮---- protected abstract sendWSAPIRequest( wsKey: TWSKey, channel: string, params?: any, ): Promise; ⋮---- protected abstract sendWSAPIRequest( wsKey: TWSKey, channel: string, params: any, ): Promise; ⋮---- public getTimeOffsetMs() ⋮---- // TODO: not implemented 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 wsRequests array of topics to subscribe to * @param wsKey ws key referring to the ws connection these topics should be subscribed on */ protected subscribeTopicsForWsKey( wsTopicRequests: WsTopicRequestOrStringTopic[], wsKey: TWSKey, ) ⋮---- // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect ⋮---- // Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. ⋮---- /** * Are we in the process of connection? Nothing to send yet. */ ⋮---- // We're connected. Check if auth is needed and if already authenticated ⋮---- /** * 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. */ ⋮---- // Finally, request subscription to topics if the connection is healthy and ready ⋮---- protected unsubscribeTopicsForWsKey( wsTopicRequests: WsTopicRequestOrStringTopic[], wsKey: TWSKey, ) ⋮---- // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- // 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. ⋮---- // We're connected. Check if auth is needed and if already authenticated ⋮---- /** * 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. */ ⋮---- // Finally, request subscription to topics if the connection is healthy and ready ⋮---- /** * Splits topic requests into two groups, public & private topic requests */ private sortTopicRequestsIntoPublicPrivate( wsTopicRequests: WsTopicRequest[], wsKey: TWSKey, ): ⋮---- /** Get the WsStore that tracks websockets & topics */ public getWsStore(): WsStore> ⋮---- public close(wsKey: TWSKey, force?: boolean) ⋮---- public closeAll(force?: boolean) ⋮---- public isConnected(wsKey: TWSKey): boolean ⋮---- /** * Request connection to a specific websocket, instead of waiting for automatic connection. */ protected async connect( wsKey: TWSKey, ): Promise ⋮---- private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket ⋮---- private parseWsError(context: string, error: any, wsKey: TWSKey) ⋮---- /** Get a signature, build the auth request and send it */ private async sendAuthRequest(wsKey: TWSKey): Promise ⋮---- // console.log('ws auth req', request); ⋮---- private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) ⋮---- private ping(wsKey: TWSKey) ⋮---- private clearTimers(wsKey: TWSKey) ⋮---- // Send a ping at intervals private clearPingTimer(wsKey: TWSKey) ⋮---- // Expect a pong within a time limit private clearPongTimer(wsKey: TWSKey) ⋮---- // this.logger.trace(`Cleared pong timeout for "${wsKey}"`); ⋮---- // this.logger.trace(`No active pong timer for "${wsKey}"`); ⋮---- /** * 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, topics: WsTopicRequest[], ) ⋮---- // Automatically splits requests into smaller batches, if needed ⋮---- `Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" ⋮---- // console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2)); ⋮---- // this.logger.trace(`Sending batch via message: "${wsMessage}"`); ⋮---- /** * 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[], ) ⋮---- /** * Try sending a string event on a WS connection (identified by the WS Key) */ public tryWsSend( wsKey: TWSKey, wsMessage: string, throwExceptions?: boolean, ) ⋮---- private async onWsOpen( event: any, wsKey: TWSKey, url: string, ws: WebSocket, ) ⋮---- // Resolve & cleanup deferred "connection attempt in progress" promise ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // Remove before resolving, in case there's more requests queued ⋮---- // Some websockets require an auth packet to be sent after opening the connection ⋮---- // Reconnect to topics known before it connected ⋮---- // Request sub to public topics, if any ⋮---- // Request sub to private topics, if auth on connect isn't needed ⋮---- // If enabled, automatically reauth WS API if reconnected ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- /** * Handle subscription to private topics _after_ authentication successfully completes asynchronously. * * Only used for exchanges that require auth before sending private topic subscription requests */ private onWsAuthenticated( wsKey: TWSKey, event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, ) ⋮---- // Resolve & cleanup deferred "auth attempt in progress" promise ⋮---- // Remove before continuing, in case there's more requests queued ⋮---- private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) ⋮---- // any message can clear the pong timer - wouldn't get a message if the ws wasn't working ⋮---- // console.log(`raw event: `, { data, dataType, emittableEvents }); ⋮---- private onWsClose(event: unknown, wsKey: TWSKey) ⋮---- // unintentional close, attempt recovery ⋮---- // clean up any pending promises for this connection ⋮---- // intentional close - clean up // clean up any pending promises for this connection ⋮---- // clean up any pending promises for this connection ⋮---- // This was an intentional close, delete all state for this connection, as if it never existed: ⋮---- private getWs(wsKey: TWSKey) ⋮---- private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) ⋮---- /** * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) */ protected async assertIsConnected(wsKey: TWSKey): Promise ⋮---- // Already in progress? Await shared promise and retry ⋮---- // Start connection, it should automatically store/return a promise. ⋮---- /** * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) */ public async assertIsAuthenticated(wsKey: TWSKey): Promise ⋮---- // Already in progress? Await shared promise and retry ⋮---- // this.logger.trace('assertIsAuthenticated(): ok'); ⋮---- // Start authentication, it should automatically store/return a promise. ================ File: src/lib/multipartUtil.ts ================ /** File payload for Gate multipart/form-data OTC endpoints */ export type GateMultipartFile = | Blob | Buffer | { filename?: string; content: Blob | Buffer }; ⋮---- export function appendGateMultipartFile( form: FormData, fieldName: string, file: GateMultipartFile, ): void ⋮---- export function appendGateMultipartFields( form: FormData, fields: Record, ): void ================ File: src/types/request/options.ts ================ /**========================================================================================================================== * OPTIONS * ========================================================================================================================== */ export interface GetOptionsSettlementHistoryReq { underlying: string; limit?: number; offset?: number; from?: number; to?: number; } export interface GetOptionsMySettlementsReq { underlying: string; contract?: string; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface GetOptionsOrderBookReq { contract: string; interval?: '0' | '0.1' | '0.01'; limit?: number; with_id?: boolean; } ⋮---- export interface GetOptionsCandlesReq { contract: string; limit?: number; from?: number; to?: number; interval?: '1m' | '5m' | '15m' | '30m' | '1h'; } ⋮---- export interface GetOptionsUnderlyingCandlesReq { underlying: string; limit?: number; from?: number; to?: number; interval?: '1m' | '5m' | '15m' | '30m' | '1h'; } ⋮---- export interface GetOptionsTradesReq { contract?: string; type?: 'C' | 'P'; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface GetOptionsAccountChangeReq { limit?: number; offset?: number; from?: number; to?: number; type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; } ⋮---- export interface SubmitOptionsOrderReq { contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: 'gtc' | 'ioc' | 'poc'; text?: string; } ⋮---- export interface AmendOptionsOrderReq { contract: string; // Options contract name price: string; // Order price size: number; // Order size } ⋮---- contract: string; // Options contract name price: string; // Order price size: number; // Order size ⋮---- export interface GetOptionsOrdersReq { contract?: string; underlying?: string; status: 'open' | 'finished'; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface GetOptionsPersonalHistoryReq { underlying: string; contract?: string; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface OptionsMMPSettingsReq { underlying: string; window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) } ⋮---- window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) ================ File: src/types/request/rebate.ts ================ export interface GetAgencyTransactionHistoryReq { currency_pair?: string; user_id?: number; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface GetAgencyCommissionHistoryReq { currency?: string; user_id?: number; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface GetPartnerSubordinateListReq { user_id?: number; limit?: number; offset?: number; } ⋮---- export interface GetBrokerCommissionHistoryReq { limit?: number; offset?: number; user_id?: number; from?: number; to?: number; } ⋮---- export interface GetBrokerTransactionHistoryReq { limit?: number; offset?: number; user_id?: number; from?: number; to?: number; } ⋮---- // Interfaces for request and response export interface PartnerTransactionReq { currency_pair?: string; user_id?: number; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- /** GET /rebate/partner/data/aggregated */ export interface GetPartnerAgentDataAggregatedReq { /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default start of last 7 days */ start_date?: string; /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default end of last 7 days */ end_date?: string; /** * 0 All (default), 1 Spot, 2 Futures, 3 Alpha, 4 Web3, 5 Perps (DEX), * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. */ business_type?: number; } ⋮---- /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default start of last 7 days */ ⋮---- /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default end of last 7 days */ ⋮---- /** * 0 All (default), 1 Spot, 2 Futures, 3 Alpha, 4 Web3, 5 Perps (DEX), * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. */ ================ File: src/types/request/stock.ts ================ /** Stock / TradFi Spot API request types */ ⋮---- export interface GetStockUserAssetsReq { pnl_calc_type?: number; pnl_calc_price?: number; } ⋮---- export interface GetStockSymbolsReq { symbols?: string; exchange?: string; // us | hk | jp with_desc_i18n?: boolean; page?: number; page_size?: number; } ⋮---- exchange?: string; // us | hk | jp ⋮---- export interface GetStockSymbolDetailReq { symbols?: string; exchange?: string; // us | hk | jp page?: number; page_size?: number; } ⋮---- exchange?: string; // us | hk | jp ⋮---- export interface GetStockOrdersReq { symbol?: string; } ⋮---- export interface CreateStockOrderReq { volume: string; symbol: string; side: 1 | 2; price_type: 'market' | 'limit'; /** Limit: all only; market: regular only */ trading_session: 'all' | 'regular'; time_in_force: 'day'; price?: string; client_order_id?: string; } ⋮---- /** Limit: all only; market: regular only */ ⋮---- export interface GetStockOrderHistoryReq { symbol?: string; order_ids?: string; begin_time?: number; end_time?: number; side?: 1 | 2; page?: number; page_size?: number; } ⋮---- export interface UpdateStockOrderReq { volume: string; price: string; } ⋮---- export interface GetStockPositionsReq { pnl_calc_type?: number; pnl_calc_price?: number; symbol?: string; exchange?: string; // us | hk | jp } ⋮---- exchange?: string; // us | hk | jp ⋮---- export interface CloseStockPositionReq { symbol: string; close_type: 1 | 2; close_volume?: string; } ⋮---- export interface GetStockTransactionsReq { begin_time?: number; end_time?: number; ref_id?: string; type?: string; page?: number; page_size?: number; } ⋮---- export interface CreateStockTransactionReq { asset: string; change: string; type: 'deposit' | 'withdraw'; ref_id: string; } ================ File: src/types/response/alpha.ts ================ /**========================================================================================================================== * ALPHA * ========================================================================================================================== */ ⋮---- export interface AlphaAccount { currency: string; // Currency name available: string; // Available Balance locked: string; // Locked balance token_address: string; // Token address chain: string; // Blockchain name } ⋮---- currency: string; // Currency name available: string; // Available Balance locked: string; // Locked balance token_address: string; // Token address chain: string; // Blockchain name ⋮---- export interface AlphaAccountBook { id: number; // Order ID time: number; // Operation timestamp currency: string; // Currency name change: string; // Change amount balance: string; // Balance after change } ⋮---- id: number; // Order ID time: number; // Operation timestamp currency: string; // Currency name change: string; // Change amount balance: string; // Balance after change ⋮---- export interface CreateAlphaQuoteResp { quote_id: string; // Quote ID for order placement, valid for 1 minute min_amount: string; // Minimum order size max_amount: string; // Maximum order size price: string; // Token Price (USDT-based) slippage: string; // Slippage estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) order_fee: string; // Slippage tolerance (10 means 10% tolerance) target_token_min_amount: string; // Minimum received amount target_token_max_amount: string; // Maximum received amount error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) } ⋮---- quote_id: string; // Quote ID for order placement, valid for 1 minute min_amount: string; // Minimum order size max_amount: string; // Maximum order size price: string; // Token Price (USDT-based) slippage: string; // Slippage estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) order_fee: string; // Slippage tolerance (10 means 10% tolerance) target_token_min_amount: string; // Minimum received amount target_token_max_amount: string; // Maximum received amount error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) ⋮---- export interface CreateAlphaOrderResp { order_id: string; // Order ID status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) side: string; // Buy or sell orders (buy/sell) gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) create_time: number; // Creation timestamp amount: string; // Trade Quantity token_address: string; // Token contract address chain: string; // Blockchain name } ⋮---- order_id: string; // Order ID status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) side: string; // Buy or sell orders (buy/sell) gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) create_time: number; // Creation timestamp amount: string; // Trade Quantity token_address: string; // Token contract address chain: string; // Blockchain name ⋮---- export interface AlphaOrder { order_id: string; // Order ID tx_hash: string; // Transaction Hash side: string; // Buy or sell orders (buy/sell) usdt_amount: string; // Amount (USDT) currency: string; // Token currency_amount: string; // Token amount status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) chain: string; // Blockchain gas_fee: string; // Gas Fee (USDT-based) transaction_fee: string; // Trading Fee (USDT-based) failed_reason: string; // Failure reason (if applicable) create_time: number; // Creation timestamp } ⋮---- order_id: string; // Order ID tx_hash: string; // Transaction Hash side: string; // Buy or sell orders (buy/sell) usdt_amount: string; // Amount (USDT) currency: string; // Token currency_amount: string; // Token amount status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) chain: string; // Blockchain gas_fee: string; // Gas Fee (USDT-based) transaction_fee: string; // Trading Fee (USDT-based) failed_reason: string; // Failure reason (if applicable) create_time: number; // Creation timestamp ⋮---- export interface AlphaCurrency { currency: string; // Currency symbol name: string; // Currency name chain: string; // The main chain corresponding to the coin address: string; // Contract Address amount_precision: number; // Amount scale precision: number; // Price scale status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) } ⋮---- currency: string; // Currency symbol name: string; // Currency name chain: string; // The main chain corresponding to the coin address: string; // Contract Address amount_precision: number; // Amount scale precision: number; // Price scale status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) ⋮---- export interface AlphaTicker { currency: string; // Currency symbol last: string; // Last trading price change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) volume: string; // 24h Trading Volume (USDT) market_cap: string; // Current Token Market Cap } ⋮---- currency: string; // Currency symbol last: string; // Last trading price change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) volume: string; // 24h Trading Volume (USDT) market_cap: string; // Current Token Market Cap ================ File: src/types/response/autoinvest.ts ================ /**========================================================================================================================== * EARN AUTO INVEST * ========================================================================================================================== */ ⋮---- /** POST /earn/autoinvest/plans/create — example response shape */ export interface CreateAutoInvestPlanResp { id: number; amount: string; money: string; next_time: number; period_type: string; period_day: number; period_hour: number; fund_flow: string; fund_source: string; } ⋮---- export interface AutoInvestCoinItem { key: string; value: string; asset_icon_url: string; sort: number; } ⋮---- export interface AutoInvestMinAmountResp { min_amount: string; } ⋮---- export interface AutoInvestPlanExecutionRecord { id: number; type: string; money: string; user_id: number; plan_id: number; plan_version: number; amount: string; create_time: number; update_time: number; status: string; status_type: number; /** 2 = buy, other = sell */ side: number; status_message: string; detail: string; asset: string; } ⋮---- /** 2 = buy, other = sell */ ⋮---- export interface AutoInvestPlanExecutionRecordsPaginated { page: number; page_size: number; total_page: number; total: number; list: AutoInvestPlanExecutionRecord[]; } ⋮---- export interface AutoInvestOrderItem { id: number; type: string; amount: string; plan_id: number; side: number; asset: string; record_id: number; total_money: string; market: string; price: string; create_time: number; total: string; fund_flow: string; error_code: number; error_msg: string; status: number; } ⋮---- export interface AutoInvestConfigItem { coin: string; max_limit: string; } ⋮---- export interface AutoInvestPlanPortfolioItem { asset: string; ratio: string; cum_invest?: string; cum_hold?: string; cum_redeem?: string; avg_price?: string; redeem_status?: number; lend_amount?: string; } ⋮---- export interface AutoInvestPlanDetail { id: number; version: number; name: string; create_time: number; update_time: number; user_id: number; money: string; amount: string; period_type: string; period_day: number; period_hour: number; portfolio: AutoInvestPlanPortfolioItem[]; next_time?: number; period?: number; fund_source?: string; fund_flow?: string; } ⋮---- export interface AutoInvestPlansListResp { page: number; page_size: number; page_count: number; total_count: number; list: AutoInvestPlanDetail[]; } ================ File: src/types/response/delivery.ts ================ /**========================================================================================================================== * DELIVERY * ========================================================================================================================== */ ⋮---- export interface DeliveryOrderBook { id?: number; current: number; update: number; asks: { p: string; s: number }[]; bids: { p: string; s: number }[]; } ⋮---- export interface DeliveryTrade { id: number; create_time: number; create_time_ms: number; contract: string; size: number; price: string; is_internal?: boolean; // Deprecated } ⋮---- is_internal?: boolean; // Deprecated ⋮---- export interface DeliveryCandle { t: number; v?: number; c: string; h: string; l: string; o: string; } ⋮---- export interface DeliveryTicker { contract: string; last: string; change_percentage: string; total_size: string; low_24h: string; high_24h: string; volume_24h: string; volume_24h_btc?: string; volume_24h_usd?: string; volume_24h_base: string; volume_24h_quote: string; volume_24h_settle: string; mark_price: string; funding_rate: string; funding_rate_indicative: string; index_price: string; quanto_base_rate?: string; // Deprecated basis_rate: string; basis_value: string; lowest_ask: string; highest_bid: string; } ⋮---- quanto_base_rate?: string; // Deprecated ⋮---- export interface DeliveryAccount { total: string; // Balance, only applicable to classic contract account unrealised_pnl: string; position_margin?: string; // Deprecated order_margin: string; // Initial margin for all pending orders available: string; point: string; currency: string; in_dual_mode: boolean; position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) enable_credit: boolean; position_initial_margin: string; maintenance_margin: string; bonus: string; enable_evolved_classic?: boolean; // Deprecated cross_order_margin: string; cross_initial_margin: string; cross_maintenance_margin: string; cross_unrealised_pnl: string; cross_available: string; isolated_position_margin: string; enable_new_dual_mode?: boolean; // Deprecated margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode history: { dnw: string; pnl: string; fee: string; refr: string; fund: string; point_dnw: string; point_fee: string; point_refr: string; bonus_dnw: string; bonus_offset: string; }; enable_tiered_mm: boolean; } ⋮---- total: string; // Balance, only applicable to classic contract account ⋮---- position_margin?: string; // Deprecated order_margin: string; // Initial margin for all pending orders ⋮---- position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) ⋮---- enable_evolved_classic?: boolean; // Deprecated ⋮---- enable_new_dual_mode?: boolean; // Deprecated margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode ⋮---- export interface DeliveryBook { time: number; change: string; balance: string; type: | 'dnw' | 'pnl' | 'fee' | 'refr' | 'fund' | 'point_dnw' | 'point_fee' | 'point_refr' | 'bonus_offset'; text: string; contract?: string; trade_id?: string; } ⋮---- export interface DeliveryTradingHistoryRecord { id: number; create_time: number; contract: string; order_id: string; size: number; price: string; role: 'taker' | 'maker'; text: string; fee: string; point_fee: string; } ⋮---- export interface DeliveryClosedPosition { time: number; contract: string; side: 'long' | 'short'; pnl: string; pnl_pnl: string; pnl_fund: string; pnl_fee: string; text: string; max_size: string; first_open_time: number; long_price: string; short_price: string; } ⋮---- export interface DeliveryLiquidationHistoryRecord { time: number; contract: string; leverage?: string; size: number; margin?: string; entry_price?: string; liq_price?: string; mark_price?: string; order_id?: number; order_price: string; fill_price: string; left: number; } ⋮---- export interface DeliverySettlementHistoryRecord { time: number; contract: string; leverage: string; size: number; margin: string; entry_price: string; settle_price: string; profit: string; fee: string; } ================ File: src/types/response/margin.ts ================ /**========================================================================================================================== * MARGIN * ========================================================================================================================== */ ⋮---- export interface MarginAccount { currency_pair: string; locked: boolean; risk: string; base: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; quote: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; } ⋮---- export interface MarginBalanceHistoryRecord { id: string; time: string; time_ms: number; currency: string; currency_pair: string; change: string; balance: string; type: string; } ⋮---- export interface CrossMarginCurrency { name: string; rate: string; prec: string; discount: string; min_borrow_amount: string; user_max_borrow_amount: string; total_max_borrow_amount: string; price: string; loanable: boolean; status: number; } ⋮---- export interface CrossMarginAccount { user_id: number; refresh_time: number; locked: boolean; balances: { [currency: string]: { available: string; freeze: string; borrowed: string; interest: string; negative_liab: string; futures_pos_liab: string; equity: string; total_freeze: string; total_liab: string; }; }; total: string; borrowed: string; interest: string; risk: string; total_initial_margin: string; total_margin_balance: string; total_maintenance_margin: string; total_initial_margin_rate: string; total_maintenance_margin_rate: string; total_available_margin: string; portfolio_margin_total: string; portfolio_margin_total_liab: string; portfolio_margin_total_equity: string; } ⋮---- export interface CrossMarginAccountHistoryRecord { id: string; time: number; currency: string; change: string; balance: string; type: string; } ⋮---- export interface CrossMarginMorrowLoanRecord { id: string; create_time: number; update_time: number; currency: string; amount: string; text?: string; status: number; repaid: string; repaid_interest: string; unpaid_interest: string; } ⋮---- export interface MarginUserAccount { currency_pair: string; account_type: string; // Description updated to remove "risk" option leverage: string; locked: boolean; risk?: string; // Deprecated mmr?: string; // Refined description base: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; quote: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; } ⋮---- account_type: string; // Description updated to remove "risk" option ⋮---- risk?: string; // Deprecated mmr?: string; // Refined description ================ File: src/types/response/marginuni.ts ================ /**========================================================================================================================== * MARGIN UNI * ========================================================================================================================== */ ⋮---- export interface LendingMarket { currency_pair: string; base_min_borrow_amount: string; quote_min_borrow_amount: string; leverage: string; status?: string | number; delisted_time?: number; } ⋮---- export interface MarginUNILoan { currency: string; currency_pair: string; amount: string; type: string; // Lending type, margin indicates margin borrowing create_time: number; update_time: number; } ⋮---- type: string; // Lending type, margin indicates margin borrowing ⋮---- export interface MarginUNILoanRecord { type: string; currency_pair: string; currency: string; amount: string; create_time: number; } ⋮---- export interface MarginUNIInterestRecord { currency: string; currency_pair: string; actual_rate: string; interest: string; status: number; type: string; // Lending type, margin indicates margin borrowing create_time: number; } ⋮---- type: string; // Lending type, margin indicates margin borrowing ⋮---- export interface MarginUNIMaxBorrowable { currency: string; currency_pair: string; borrowable: string; } ================ File: src/types/response/multicollateralLoan.ts ================ /**========================================================================================================================== * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface MultiLoanOrder { order_id: string; order_type: string; fixed_type: string; fixed_rate: string; expire_time: number; auto_renew: boolean; auto_repay: boolean; current_ltv: string; status: string; borrow_time: number; total_left_repay_usdt: string; total_left_collateral_usdt: string; borrow_currencies: { currency: string; index_price: string; left_repay_principal: string; left_repay_interest: string; left_repay_usdt: string; }[]; collateral_currencies: { currency: string; index_price: string; left_collateral: string; left_collateral_usdt: string; }[]; } ⋮---- export interface RepayMultiLoanResp { order_id: number; repaid_currencies: { succeeded: boolean; label?: string; message?: string; currency: string; repaid_principal: string; repaid_interest: string; }[]; } ⋮---- export interface MultiLoanRepayRecord { order_id: number; record_id: number; init_ltv: string; before_ltv: string; after_ltv: string; borrow_time: number; repay_time: number; borrow_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; collateral_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; repaid_currencies: { currency: string; index_price: string; repaid_amount: string; repaid_principal: string; repaid_interest: string; repaid_amount_usdt: string; }[]; total_interest_list: { currency: string; index_price: string; amount: string; amount_usdt: string; }[]; left_repay_interest_list: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; } ⋮---- export interface UpdateMultiLoanResp { order_id: number; collateral_currencies: { succeeded: boolean; label?: string; message?: string; currency: string; amount: string; }[]; } ⋮---- export interface MultiLoanAdjustmentRecord { order_id: number; record_id: number; before_ltv: string; after_ltv: string; operate_time: number; borrow_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; collateral_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; } ⋮---- export interface MultiLoanCurrencyQuota { currency: string; index_price: string; min_quota: string; left_quota: string; left_quote_usdt: string; /** Remaining borrow/collateral limit for fixed-term currency */ left_quota_fixed?: string; /** Remaining currency limit for fixed-term converted to USDT */ left_quote_usdt_fixed?: string; } ⋮---- /** Remaining borrow/collateral limit for fixed-term currency */ ⋮---- /** Remaining currency limit for fixed-term converted to USDT */ ⋮---- export interface MultiLoanSupportedCurrencies { loan_currencies: { currency: string; price: string; }[]; collateral_currencies: { currency: string; index_price: string; discount: string; }[]; } ⋮---- export interface MultiLoanRatio { init_ltv: string; alert_ltv: string; liquidate_ltv: string; } ⋮---- export interface MultiLoanFixedRate { currency: string; rate_7d: string; rate_30d: string; update_time: number; } ================ File: src/types/response/options.ts ================ /**========================================================================================================================== * OPTIONS * ========================================================================================================================== */ ⋮---- export interface OptionsContract { name: string; tag: string; // Expiry period: day, week, month create_time: number; expiration_time: number; is_call: boolean; strike_price: string; last_price: string; mark_price: string; orderbook_id: number; trade_id?: number; // Deprecated trade_size: number; position_size: number; underlying: string; underlying_price: string; // Forward futures price for the delivery date multiplier: string; // Option contract multiplier order_price_round: string; mark_price_round: string; // Minimum unit of mark price maker_fee_rate: string; taker_fee_rate: string; price_limit_fee_rate: string; ref_discount_rate: string; ref_rebate_rate: string; order_price_deviate?: string; // Deprecated order_size_min: number; order_size_max: number; orders_limit: number; // Maximum number of orders per user in this market } ⋮---- tag: string; // Expiry period: day, week, month ⋮---- trade_id?: number; // Deprecated ⋮---- underlying_price: string; // Forward futures price for the delivery date multiplier: string; // Option contract multiplier ⋮---- mark_price_round: string; // Minimum unit of mark price ⋮---- order_price_deviate?: string; // Deprecated ⋮---- orders_limit: number; // Maximum number of orders per user in this market ⋮---- export interface OptionsSettlementHistoryRecord { time: number; contract: string; profit: string; fee: string; strike_price: string; settle_price: string; } ⋮---- export interface OptionsUserSettlement { time: number; underlying: string; contract: string; strike_price: string; settle_price: string; size: number; settle_profit: string; fee: string; realised_pnl: string; } ⋮---- export interface OptionsOrderBook { id?: number; current: number; update: number; asks: { p: string; s: number }[]; bids: { p: string; s: number }[]; } ⋮---- export interface OptionsTicker { name: string; last_price: string; mark_price: string; index_price: string; ask1_size: number; ask1_price: string; bid1_size: number; bid1_price: string; position_size: number; mark_iv: string; bid_iv: string; ask_iv: string; leverage: string; // Leverage calculation formula updated with reference note delta: string; gamma: string; vega: string; theta: string; rho: string; } ⋮---- leverage: string; // Leverage calculation formula updated with reference note ⋮---- export interface OptionsCandle { t: number; v?: number; c: string; h: string; l: string; o: string; } ⋮---- export interface OptionsUnderlyingCandle { t: number; v?: number; c: string; h: string; l: string; o: string; sum: string; } ⋮---- export interface OptionsTrade { id: number; create_time: number; create_time_ms: number; contract: string; size: number; price: string; is_internal?: boolean; // Deprecated } ⋮---- is_internal?: boolean; // Deprecated ⋮---- export interface OptionsAccount { user: number; total?: string; // Only applicable to classic options accounts (unified account limitation) equity?: string; // Only applicable to classic options accounts (unified account limitation) short_enabled: boolean; unrealised_pnl: string; // Enhanced with calculation formula init_margin: string; maint_margin: string; order_margin: string; available: string; point: string; currency: string; liq_triggered?: boolean; // Whether account is in liquidation status margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode } ⋮---- total?: string; // Only applicable to classic options accounts (unified account limitation) equity?: string; // Only applicable to classic options accounts (unified account limitation) ⋮---- unrealised_pnl: string; // Enhanced with calculation formula ⋮---- liq_triggered?: boolean; // Whether account is in liquidation status margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode ⋮---- export interface OptionsAccountChangeRecord { time: number; change: string; balance: string; type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; text: string; } ⋮---- export interface OptionsPositionsUnderlying { user: number; underlying: string; underlying_price: string; // Forward futures price for the delivery date contract: string; size: number; entry_price: string; mark_price: string; mark_iv: string; realised_pnl: string; unrealised_pnl: string; pending_orders: number; close_order: { id: number; price: string; is_liq: boolean; } | null; delta: string; gamma: string; vega: string; theta: string; } ⋮---- underlying_price: string; // Forward futures price for the delivery date ⋮---- export interface GetOptionsLiquidationResp { time: number; contract: string; side: 'long' | 'short'; pnl: string; text: string; settle_size: string; } ⋮---- export interface SubmitOptionsOrderResp { id: number; user: number; create_time: number; finish_time: number; finish_as: | 'filled' | 'cancelled' | 'liquidated' | 'ioc' | 'auto_deleveraged' | 'reduce_only' | 'position_closed'; status: 'open' | 'finished'; contract: string; size: number; iceberg: number; price: string; is_close: boolean; is_reduce_only: boolean; is_liq: boolean; tif: 'gtc' | 'ioc' | 'poc'; left: number; fill_price: string; text: string; tkfr: string; mkfr: string; refu: number; refr: string; } ⋮---- export interface OptionsUserHistoryRecord { id: number; create_time: number; contract: string; order_id: number; size: number; price: string; underlying_price: string; // Forward futures price for the delivery date role: 'taker' | 'maker'; } ⋮---- underlying_price: string; // Forward futures price for the delivery date ⋮---- export interface OptionsMMPSettings { underlying: string; window: number; frozen_period: number; qty_limit: string; delta_limit: string; trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered } ⋮---- trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered ================ File: src/types/response/rebate.ts ================ export interface AgencyTransactionHistoryRecord { transaction_time: number; user_id: number; group_name: string; fee: string; fee_asset: string; currency_pair: string; amount: string; amount_asset: string; source: string; } ⋮---- export interface AgencyCommissionHistoryRecord { commission_time: number; user_id: number; group_name: string; /** Rebate commission amount (not a generic trade notional). */ commission_amount: string; /** Asset of the rebate commission. */ commission_asset: string; source: string; } ⋮---- /** Rebate commission amount (not a generic trade notional). */ ⋮---- /** Asset of the rebate commission. */ ⋮---- export interface PartnerSubordinate { user_id: number; user_join_time: number; type: number; desc: string; } ⋮---- export interface BrokerCommissionHistoryRecord { commission_time: number; user_id: number; group_name: string; amount: string; fee: string; fee_asset: string; rebate_fee: string; source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi currency_pair: string; sub_broker_info: { user_id: number; original_commission_rate: string; relative_commission_rate: string; commission_rate: string; }; } ⋮---- source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi ⋮---- export interface BrokerTransactionHistoryRecord { transaction_time: number; user_id: number; group_name: string; fee: string; currency_pair: string; amount: string; fee_asset: string; source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi sub_broker_info: { user_id: number; original_commission_rate: string; relative_commission_rate: string; commission_rate: string; }; } ⋮---- source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi ⋮---- export interface PartnerCommission { commission_time: number; user_id: number; group_name: string; /** Rebate commission amount (not a generic trade notional). */ commission_amount: string; /** Asset of the rebate commission. */ commission_asset: string; source: string; } ⋮---- /** Rebate commission amount (not a generic trade notional). */ ⋮---- /** Asset of the rebate commission. */ ⋮---- export interface PartnerTransaction { transaction_time: number; user_id: number; group_name: string; fee: string; fee_asset: string; currency_pair: string; amount: string; amount_asset: string; source: string; } ⋮---- /** `data` object for GET /rebate/partner/data/aggregated */ export interface PartnerDataAggregated { rebate_amount: string; trade_volume: string; net_fee: string; customer_count: number; /** Only when querying all business types (`business_type=0`); may be null */ trading_user_count?: string | null; time_range_desc: string; business_type: number; business_type_desc: string; } ⋮---- /** Only when querying all business types (`business_type=0`); may be null */ ⋮---- export interface PartnerDataAggregatedResponse { code: number; message: string; data: PartnerDataAggregated; timestamp: number; } ================ File: src/types/response/stock.ts ================ export type StockCategory = | 'CS' | 'ETF' | 'ADRC' | 'ADR' | 'ETV' | 'PFD' | 'ETS' | 'ETN' | 'FUND'; ⋮---- export type StockAssetType = 'STOCK' | 'ETF'; ⋮---- export interface StockApiResp { timestamp?: number; data?: T; code?: number; message?: string; label?: string; } ⋮---- export interface StockListData { list?: T[]; total?: number; total_page?: number; } ⋮---- export interface StockUserAssets { equity?: string; balance?: string; available?: string; position_market_value?: string; position_pnl?: string; today_pnl?: string; user_exists?: boolean; option_position_market_value?: string; option_position_pnl?: string; option_today_pnl?: string; } ⋮---- export interface StockSymbolDescI18n { lang?: string; value?: string; } ⋮---- export interface StockSymbolItem { symbol?: string; exchange?: string; exchange_desc?: string; quote_currency?: string; quote_currency_precision?: number; fx_rate?: string; symbol_desc?: string; category?: StockCategory | string; asset_type?: StockAssetType; trade_status?: string; trade_mode?: number; order_fill_timing?: number; icon_link?: string; quote_currency_symbol?: string; price_precision?: number; volume_precision?: number; is_ipo?: boolean; ipo_price?: string; sell_price_protection?: string; buy_price_protection?: string; symbol_descs?: StockSymbolDescI18n[]; timestamp?: number; } ⋮---- export interface StockSymbolDetailItem { symbol?: string; exchange?: string; exchange_desc?: string; quote_currency?: string; quote_currency_precision?: number; fx_rate?: string; symbol_desc?: string; category?: StockCategory | string; asset_type?: StockAssetType; settlement_currency?: string; max_order_volume?: string; step_order_volume?: string; min_order_volume?: string; price_precision?: number; volume_precision?: number; is_ipo?: boolean; ipo_price?: string; price_protection?: string; sell_price_protection?: string; buy_price_protection?: string; slippage_rate?: string; commission_rate?: string; trade_status?: string; trade_mode?: number; order_fill_timing?: number; symbol_descs?: StockSymbolDescI18n[]; [key: string]: unknown; } ⋮---- export interface StockOrderBookLevel { p?: string; user_order?: boolean; [key: string]: unknown; } ⋮---- export interface StockOrderBook { symbol?: string; bids?: StockOrderBookLevel[]; asks?: StockOrderBookLevel[]; timestamp?: number; } ⋮---- export interface StockOrderItem { order_id?: string; symbol?: string; exchange?: string; quote_currency?: string; fx_rate?: string; symbol_desc?: string; trade_status?: string; trade_mode?: number; price_type?: string; side?: number; status?: number; volume?: string; fill_volume?: string; price?: string; time_setup?: number; time_update?: number; max_order_volume?: string; step_order_volume?: string; min_order_volume?: string; price_precision?: number; price_protection?: string; sell_price_protection?: string; buy_price_protection?: string; commission_rate?: string; slippage_rate?: string; [key: string]: unknown; } ⋮---- export interface StockCreateOrderResult { id?: string; } ⋮---- export interface StockOrderHistoryItem { order_id?: string; symbol?: string; exchange?: string; quote_currency?: string; fx_rate?: string; symbol_desc?: string; price_type?: string; status?: number; status_desc?: string; status_detail?: { title?: string; message?: string } | null; finish_as?: number; side?: number; time_in_force?: string; volume?: string; fill_volume?: string; price?: string; avg_fill_price?: string | null; commission?: string; time_setup?: number; time_done?: number; [key: string]: unknown; } ⋮---- export interface StockUpdateOrderResult { order_id?: number; } ⋮---- export interface StockPositionItem { symbol?: string; exchange?: string; quote_currency?: string; quote_currency_precision?: number; fx_rate?: string; trade_status?: string; symbol_desc?: string; position_pnl?: string; today_pnl?: string; pnl_rate?: string; today_sell_amount?: string; today_buy_amount?: string; today_sell_volume?: string; today_buy_volume?: string; yesterday_volume?: string; volume?: string; available?: string; transfer_out_pending_qty?: string; avg_cost_price?: string; diluted_cost_price?: string; last_price?: string; extended_last_price?: string | null; max_order_volume?: string; step_order_volume?: string; min_order_volume?: string; price_precision?: number; price_protection?: string; [key: string]: unknown; } ⋮---- export interface StockClosePositionResult { order_id?: number; } ⋮---- export interface StockTransactionItem { asset?: string; symbol?: string; symbol_display?: string; type?: string; type_desc?: string; change?: string; balance?: string; ref_id?: string; time?: number; unit_text?: string; detail?: object; } ⋮---- export interface StockExchangeItem { exchange?: string; exchange_desc?: string; icon_link?: string; support_transfer?: boolean; } ⋮---- export interface StockFeeRateItem { vip_level?: number; maker_fee?: string; taker_fee?: string; } ================ File: src/types/response/withdrawal.ts ================ export interface WithdrawalRecord { id: string; txid: string; block_number: string; withdraw_order_id: string; /** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ timestamp: string; amount: string; currency: string; address: string; memo?: string; status: | 'BCODE' // Deposit Code Operation | 'CANCEL' // Cancelled | 'CANCELPEND' // Withdrawal Cancellation Pending | 'DMOVE' // Pending Manual Review | 'DONE' // Completed | 'EXTPEND' // Sent and Waiting for Confirmation | 'FAIL' // On-Chain Failure Pending Confirmation | 'FVERIFY' // Facial Verification in Progress | 'INVALID' // Invalid Transaction | 'LOCKED' // Wallet-Side Order Locked | 'MANUAL' // Pending Manual Review | 'PEND' // Processing | 'PROCES' // Processing | 'REJECT' // Rejected | 'REQUEST' // Request in Progress | 'REVIEW' // Under Review | 'SPLITPEND' // Split Pending | 'VERIFY'; // Verification in Progress chain: string; } ⋮---- /** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ ⋮---- | 'BCODE' // Deposit Code Operation | 'CANCEL' // Cancelled | 'CANCELPEND' // Withdrawal Cancellation Pending | 'DMOVE' // Pending Manual Review | 'DONE' // Completed | 'EXTPEND' // Sent and Waiting for Confirmation | 'FAIL' // On-Chain Failure Pending Confirmation | 'FVERIFY' // Facial Verification in Progress | 'INVALID' // Invalid Transaction | 'LOCKED' // Wallet-Side Order Locked | 'MANUAL' // Pending Manual Review | 'PEND' // Processing | 'PROCES' // Processing | 'REJECT' // Rejected | 'REQUEST' // Request in Progress | 'REVIEW' // Under Review | 'SPLITPEND' // Split Pending | 'VERIFY'; // Verification in Progress ================ File: src/types/shared.ts ================ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' | 'futuresTestnet'; ⋮---- // interfaces ⋮---- export interface FromToPageLimit { from: number; to: number; page: number; limit: number; } ⋮---- // Used for spot and flash swap export interface CurrencyPair { id?: string; base?: string; base_name?: string; quote?: string; quote_name?: string; trade_quotes?: string[] | null; fee?: string; min_base_amount?: string; min_quote_amount?: string; max_base_amount?: string; max_quote_amount?: string; amount_precision?: number; precision?: number; trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; sell_start?: number; buy_start?: number; type: string; delisting_time?: number; trade_url?: string; up_rate?: string; // v4.106.4: Maximum price increase percentage down_rate?: string; // v4.106.4: Maximum price decrease percentage market_order_max_stock?: string | null; market_order_max_money?: string | null; } ⋮---- up_rate?: string; // v4.106.4: Maximum price increase percentage down_rate?: string; // v4.106.4: Maximum price decrease percentage ================ File: .npmrc ================ min-release-age=30 save-exact=true ================ File: .nvmrc ================ v24.18.0 ================ File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts ================ import { readFileSync } from 'fs'; ⋮---- import { RestClient } from '../../../src/index.js'; // import { RestClient } from 'gateio-api'; ⋮---- async function submitOTCBankPersonalSupplementExample() ================ File: src/types/request/alpha.ts ================ /**========================================================================================================================== * ALPHA * ========================================================================================================================== */ ⋮---- export interface GetAlphaAccountBookReq { from: number; // Start timestamp for the query to?: number; // End timestamp for the query, defaults to current time if not specified page?: number; // Page number limit?: number; // Maximum 100 items per page } ⋮---- from: number; // Start timestamp for the query to?: number; // End timestamp for the query, defaults to current time if not specified page?: number; // Page number limit?: number; // Maximum 100 items per page ⋮---- export interface CreateAlphaQuoteReq { currency: string; // Trading symbol side: 'buy' | 'sell'; // Buy or sell orders amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom } ⋮---- currency: string; // Trading symbol side: 'buy' | 'sell'; // Buy or sell orders amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom ⋮---- export interface CreateAlphaOrderReq { currency: string; // Trading symbol side: 'buy' | 'sell'; // Buy or sell orders amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom quote_id: string; // Quote ID returned from quotation API } ⋮---- currency: string; // Trading symbol side: 'buy' | 'sell'; // Buy or sell orders amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom quote_id: string; // Quote ID returned from quotation API ⋮---- export interface GetAlphaOrdersReq { currency?: string; // Trading symbol side?: 'buy' | 'sell'; // Buy or sell orders status?: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) from?: number; // Start time for order query to?: number; // End time for order query, defaults to current time if not specified limit?: number; // Maximum number of items returned. Default: 100, minimum: 1, maximum: 100 page?: number; // Page number } ⋮---- currency?: string; // Trading symbol side?: 'buy' | 'sell'; // Buy or sell orders status?: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) from?: number; // Start time for order query to?: number; // End time for order query, defaults to current time if not specified limit?: number; // Maximum number of items returned. Default: 100, minimum: 1, maximum: 100 page?: number; // Page number ⋮---- export interface GetAlphaOrderReq { order_id: string; // Order ID } ⋮---- order_id: string; // Order ID ⋮---- export interface GetAlphaCurrenciesReq { currency?: string; // Query currency information by currency symbol limit?: number; // Maximum number of records returned in a single list page?: number; // Page number } ⋮---- currency?: string; // Query currency information by currency symbol limit?: number; // Maximum number of records returned in a single list page?: number; // Page number ⋮---- export interface GetAlphaTickersReq { currency?: string; // Query by specified currency name limit?: number; // Maximum number of records returned in a single list page?: number; // Page number } ⋮---- currency?: string; // Query by specified currency name limit?: number; // Maximum number of records returned in a single list page?: number; // Page number ================ File: src/types/request/autoinvest.ts ================ /**========================================================================================================================== * EARN AUTO INVEST * ========================================================================================================================== */ ⋮---- export interface AutoInvestPlanPortfolioItemInput { asset: string; ratio: string; } ⋮---- /** POST /earn/autoinvest/plans/create */ export interface CreateAutoInvestPlanReq { plan_name?: string; plan_des?: string; plan_money: string; plan_amount: string; plan_period_type: | 'daily' | 'weekly' | 'biweekly' | 'monthly' | 'hourly' | '4-hourly'; plan_period_day: number; plan_period_hour: number; items: AutoInvestPlanPortfolioItemInput[]; /** Fund source: `spot` or `earn`; default spot */ fund_source?: string; /** Fund flow: `auto_invest` or `earn`; default auto_invest */ fund_flow?: string; /** 0 normal creation, 1 quick investment */ type?: number; } ⋮---- /** Fund source: `spot` or `earn`; default spot */ ⋮---- /** Fund flow: `auto_invest` or `earn`; default auto_invest */ ⋮---- /** 0 normal creation, 1 quick investment */ ⋮---- /** POST /earn/autoinvest/plans/update */ export interface UpdateAutoInvestPlanReq { plan_id: number; fund_source?: string; fund_flow?: string; } ⋮---- /** POST /earn/autoinvest/plans/stop */ export interface StopAutoInvestPlanReq { plan_id: number; } ⋮---- /** POST /earn/autoinvest/plans/add_position */ export interface AddAutoInvestPlanPositionReq { plan_id: number; amount: string; } ⋮---- /** POST /earn/autoinvest/min_invest_amount */ export interface GetAutoInvestMinAmountReq { money: string; items: AutoInvestPlanPortfolioItemInput[]; } ⋮---- /** GET /earn/autoinvest/coins */ export interface GetAutoInvestCoinsReq { /** Pricing currency: USDT or BTC; default USDT */ plan_money?: string; } ⋮---- /** Pricing currency: USDT or BTC; default USDT */ ⋮---- /** GET /earn/autoinvest/plans/records */ export interface GetAutoInvestPlanRecordsReq { plan_id: number; page?: number; page_size?: number; } ⋮---- /** GET /earn/autoinvest/orders */ export interface GetAutoInvestOrdersReq { plan_id: number; record_id: number; } ⋮---- /** GET /earn/autoinvest/plans/detail */ export interface GetAutoInvestPlanDetailReq { plan_id: number; } ⋮---- /** GET /earn/autoinvest/plans/list_info */ export interface GetAutoInvestPlansReq { /** Plan status: e.g. History (history) or Active (active) */ status: string; page?: number; page_size?: number; } ⋮---- /** Plan status: e.g. History (history) or Active (active) */ ================ File: src/types/request/p2pMerchant.ts ================ /** P2P Merchant API request types */ ⋮---- export interface P2PMerchantGetCounterpartyUserInfoReq { biz_uid: string; } ⋮---- export interface P2PMerchantGetMyselfPaymentReq { fiat?: string; } ⋮---- export interface P2PMerchantGetPendingTransactionListReq { crypto_currency: string; fiat_currency: string; order_tab?: string; select_type?: string; status?: string; txid?: number; start_time?: number; end_time?: number; } ⋮---- export interface P2PMerchantGetCompletedTransactionListReq { crypto_currency: string; fiat_currency: string; select_type?: string; status?: string; txid?: number; start_time?: number; end_time?: number; query_dispute?: number; page?: number; per_page?: number; } ⋮---- export interface P2PMerchantGetTransactionDetailsReq { txid: number; channel?: string; } ⋮---- export interface P2PMerchantConfirmPaymentReq { trade_id: string; payment_method: string; } ⋮---- export interface P2PMerchantConfirmReceiptReq { trade_id: string; } ⋮---- export interface P2PMerchantCancelTransactionReq { trade_id: string; reason_id?: string; reason_memo?: string; } ⋮---- export interface P2PMerchantPlaceBizPushOrderReq { currencyType: string; exchangeType: string; type: string; unitPrice: string; number: string; payType: string; minAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType maxAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType pay_type_json?: string; rateFixed?: string; oid?: string; tierLimit?: string; verifiedLimit?: string; regTimeLimit?: string; advertisersLimit?: string; hide_payment?: string; expire_min?: string; trade_tips?: string; auto_reply?: string; min_completed_limit?: string; max_completed_limit?: string; completed_rate_limit?: string; user_country_limit?: string; user_order_limit?: string; rateReferenceId?: string; rateOffset?: string; float_trend?: string; limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount; defaults to 0 fiatMinAmount?: string; // v4.106.102: Required when limitBasis is 1 fiatMaxAmount?: string; // v4.106.102: Required when limitBasis is 1 polymarket_limit?: string; // v4.106.102: Restrict trading with Polymarket users } ⋮---- minAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType maxAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType ⋮---- limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount; defaults to 0 fiatMinAmount?: string; // v4.106.102: Required when limitBasis is 1 fiatMaxAmount?: string; // v4.106.102: Required when limitBasis is 1 polymarket_limit?: string; // v4.106.102: Restrict trading with Polymarket users ⋮---- /** POST /p2p/merchant/account/set_merchant_work_hours — v4.106.96 */ export interface P2PMerchantSetMerchantWorkHoursReq { work_status: 0 | 1 | 2; // 0 resting, 1 working, 2 custom working hours cycle_type?: string; day_of_week?: string; time_zone?: string; // UTC offset -12 to +14 start_time?: string; end_time?: string; } ⋮---- work_status: 0 | 1 | 2; // 0 resting, 1 working, 2 custom working hours ⋮---- time_zone?: string; // UTC offset -12 to +14 ⋮---- export interface P2PMerchantAdsUpdateStatusReq { adv_no: number; adv_status: 1 | 3 | 4; /** Optional query param */ trade_type?: string; } ⋮---- /** Optional query param */ ⋮---- export interface P2PMerchantAdsDetailReq { adv_no: string; } ⋮---- export interface P2PMerchantMyAdsListReq { asset?: string; fiat_unit?: string; trade_type?: string; } ⋮---- export interface P2PMerchantGetAdsListReq { asset: string; fiat_unit: string; trade_type: string; } ⋮---- export interface P2PMerchantGetChatsListReq { txid: number; lastreceived?: number; firstreceived?: number; } ⋮---- export interface P2PMerchantSendChatMessageReq { txid: number; message: string; /** 0=Text, 1=File (video or image). Default 0 */ type?: 0 | 1; } ⋮---- /** 0=Text, 1=File (video or image). Default 0 */ ⋮---- export interface P2PMerchantUploadChatFileReq { image_content_type: string; base64_img: string; } ================ File: src/types/response/p2pMerchant.ts ================ /** P2P Merchant API response types */ ⋮---- export interface P2PMerchantApiResp { timestamp: number; method: string; code: number; message: string; data: T; version: string; } ⋮---- export interface P2PMerchantUserInfo { is_self?: boolean; user_timest?: string; counterparties_num?: number; email_verified?: string; verified?: string; has_phone?: string; user_name?: string; user_note?: string; complete_transactions?: string; paid_transactions?: string; accepted_transactions?: string; transactions_used_time?: string; cancelled_used_time_month?: string; complete_transactions_month?: string; complete_rate_month?: number; orders_buy_rate_month?: number; is_black?: number; is_follow?: number; have_traded?: number; biz_uid?: string; blue_vip?: number; work_status?: number; registration_days?: number; first_trade_days?: number; need_replenish?: number; merchant_info?: { type?: string; market?: string }; online_status?: number; work_hours?: Record | null; transactions_month?: number; transactions_all?: number; trade_versatile?: boolean; [key: string]: unknown; } ⋮---- export interface P2PMerchantCounterpartyUserInfo { user_timest?: string; email_verified?: string; verified?: string; has_phone?: string; user_name?: string; user_note?: string; complete_transactions?: string; paid_transactions?: string; accepted_transactions?: string; transactions_used_time?: string; cancelled_used_time_month?: string; complete_transactions_month?: string; complete_rate_month?: number; is_follow?: number; have_traded?: number; biz_uid?: string; registration_days?: number; first_trade_days?: number; trade_versatile?: boolean; [key: string]: unknown; } ⋮---- export interface P2PMerchantPaymentMethod { pay_type: string; pay_name: string; ids: number[]; list: Record[]; } ⋮---- export interface P2PMerchantTransactionListItem { type_buy?: number; timest?: string; timest_expire?: string; type?: string; trade_type?: string; timestamp?: number; rate?: string; amount?: string; total?: string; txid?: number; status?: string; order_status?: string; [key: string]: unknown; } ⋮---- export interface P2PMerchantTransactionListData { list: P2PMerchantTransactionListItem[]; trans_time?: { od_time?: number }[]; count: number; exported_num: number; } ⋮---- export interface P2PMerchantTransactionDetails { is_sell?: number; txid?: number; orderid?: number; timest?: number; last_pay_time?: number; remain_pay_time?: number; currencyType?: string; want_type?: string; rate?: string; amount?: string; total?: string; status?: string; state?: string; its_uid?: string; its_nickname?: string; its_realname?: string; [key: string]: unknown; } ⋮---- export interface P2PMerchantAdsDetail { rate?: string; type?: string; amount?: string; min_amount?: string; max_amount?: string; fiat_min_amount?: string; // v4.106.102: Min fiat amount per order fiat_max_amount?: string; // v4.106.102: Max fiat amount per order minFiatAmount?: string; // v4.106.102 maxFiatAmount?: string; // v4.106.102 limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount limitBasisText?: string; // v4.106.102 polymarket_limit?: string; // v4.106.102 total?: string; orderid?: number; timestamp?: number; currencyType?: string; want_type?: string; status?: string; [key: string]: unknown; } ⋮---- fiat_min_amount?: string; // v4.106.102: Min fiat amount per order fiat_max_amount?: string; // v4.106.102: Max fiat amount per order minFiatAmount?: string; // v4.106.102 maxFiatAmount?: string; // v4.106.102 limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount limitBasisText?: string; // v4.106.102 polymarket_limit?: string; // v4.106.102 ⋮---- export interface P2PMerchantMyAdsListItem { type?: string; rate?: string; amount?: string; total?: string; id?: string; status?: string; currencyType?: string; want_type?: string; fiat_min_amount?: string; // v4.106.102 fiat_max_amount?: string; // v4.106.102 limit_basis?: string; // v4.106.103 limit_basis_text?: string; // v4.106.103 [key: string]: unknown; } ⋮---- fiat_min_amount?: string; // v4.106.102 fiat_max_amount?: string; // v4.106.102 limit_basis?: string; // v4.106.103 limit_basis_text?: string; // v4.106.103 ⋮---- export interface P2PMerchantMyAdsListData { lists: P2PMerchantMyAdsListItem[]; } ⋮---- export interface P2PMerchantAdsListItem { index?: number; asset?: string; fiat_unit?: string; adv_no?: number; price?: string; max_single_trans_amount?: string; min_single_trans_amount?: string; nick_name?: string; surplus_amount?: string; // v4.106.103: Remaining tradable crypto quantity trade_methods?: string[]; // v4.106.103: Supported payment methods list fiat_min_amount?: string; // v4.106.103 fiat_max_amount?: string; // v4.106.103 limit_basis?: string; // v4.106.103 limit_basis_text?: string; // v4.106.103 } ⋮---- surplus_amount?: string; // v4.106.103: Remaining tradable crypto quantity trade_methods?: string[]; // v4.106.103: Supported payment methods list fiat_min_amount?: string; // v4.106.103 fiat_max_amount?: string; // v4.106.103 limit_basis?: string; // v4.106.103 limit_basis_text?: string; // v4.106.103 ⋮---- export interface P2PMerchantChatMessage { is_sell?: number; msg_type?: number; msg?: string; username?: string; uid?: string; timest?: number; type?: number; pic?: string; file_key?: string; file_type?: string; width?: string; height?: string; msg_obj?: Record; risk_type?: number; // v4.106.96: 1 off-platform traffic diversion risk toast_msg?: string; // v4.106.96 [key: string]: unknown; } ⋮---- risk_type?: number; // v4.106.96: 1 off-platform traffic diversion risk toast_msg?: string; // v4.106.96 ⋮---- /** v4.106.96: Risk control response when place_biz_push_order hits off-platform diversion check */ export interface P2PMerchantPlaceOrderRiskData { risk_code?: string; risk_event?: { type?: string; title?: string; msg?: string; action?: string; content_risk_type?: string; trade_tips?: string; auto_reply?: string; }; } ⋮---- /** v4.106.96: send_chat_message risk fields in data */ export interface P2PMerchantSendChatMessageData { risk_type?: number; toast_msg?: string; [key: string]: unknown; } ⋮---- export interface P2PMerchantChatsListData { messages: P2PMerchantChatMessage[]; has_history?: boolean; txid?: number; SRVTM?: number; order_status?: string; memo?: 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 bundleReport.html .history/ dist coverage localtest.sh repomix.sh doc examples/ignored/ ws-private-spot-wsapi-performance.ts ws-private-perp-futures-wsapi-readonly.ts privatetest.ts privaterepotracker restClientRegex.ts testfile.ts ================ File: docs/GATE_SDK_QUICKSTART_GUIDE.md ================ # Gate API JavaScript Tutorial for Node.js > [!TIP] > Read this guide in tutorial format on the Siebly website: [Gate JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/gate/javascript/tutorial) This tutorial uses [`gateio-api`](https://www.npmjs.com/package/gateio-api), Siebly's Node.js, JavaScript, and TypeScript SDK for Gate.com. It covers public and private REST API calls, Spot and Futures TestNet orders, live WebSocket streams, WebSocket API commands, API hosts, and proxies. The SDK handles REST API request signing, private WebSocket authentication, product-specific WebSocket routing, heartbeats, reconnects, resubscriptions, and WebSocket API response matching. Request and response types are included for TypeScript users. **Key links** - Gate JavaScript SDK by Siebly: [`gateio-api`](https://siebly.io/sdk/gate/javascript) - npm package: [`gateio-api`](https://www.npmjs.com/package/gateio-api) - GitHub repository: [`sieblyio/gateio-api`](https://github.com/sieblyio/gateio-api) - SDK examples: [Gate SDK examples](https://siebly.io/examples/Gate) - SDK endpoint map: [Gate JavaScript endpoint reference](./endpointFunctionList.md) - Gate REST API documentation: [Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) - Gate Spot WebSocket documentation: [Spot WebSocket API](https://www.gate.com/docs/developers/apiv4/ws/) - Gate Futures WebSocket documentation: [Futures WebSocket API](https://www.gate.com/docs/developers/futures/ws/) - Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) - More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) ## Why use `gateio-api`? The JavaScript SDK handles all the complexities of integrating with Gate's REST APIs & WebSockets, so you can focus on your system without wasting excessive time on plumbing. Private Gate REST API requests require a timestamp and HMAC-SHA512 signature. Private WebSocket subscriptions require authentication, and each product family has its own WebSocket connection. A Spot subscription cannot be sent through a USDT perpetual Futures connection. `gateio-api` handles those mechanics and gives each job a focused client: | Client | Use it for | | -------------------- | ------------------------------------------------------------ | | `RestClient` | Public and private REST API calls across Gate product groups | | `WebsocketClient` | Public and private WebSocket subscriptions | | `WebsocketAPIClient` | Promise-based Spot and Futures order commands over WebSocket | `WebsocketClient` also handles heartbeats, reconnects, cached subscriptions, and resubscription. `WebsocketAPIClient` adds login, request IDs, response matching, and promise resolution. ## Install the SDK ```bash npm install gateio-api ``` The package includes CommonJS, ESM, and TypeScript declarations. Every example below is plain JavaScript using ESM imports. ## Create Gate API keys Public market data does not require credentials. Private REST API calls, private streams, and WebSocket API commands require an API key and secret. Create and manage keys from the [Gate API key page](https://www.gate.com/myaccount/api_key_manage). Start with the least access your application needs: - Use a read-only key while building account views and recovery code. - Enable Spot read-write access only for Spot order workflows. - Enable perpetual-contract read-write access only for Futures order workflows. - Add an IP whitelist when your outbound IP is stable. - Keep live and TestNet credentials separate. - Allow a few minutes for API key and permission changes to take effect. - Do not enable withdrawal permission for anything in this tutorial. Set these live credential names in your shell, secret manager, or deployment environment: - `GATE_API_KEY` - `GATE_API_SECRET` Use separate names for TestNet: - `GATE_TESTNET_API_KEY` - `GATE_TESTNET_API_SECRET` - `GATE_PLACE_TESTNET_ORDER=true` The order examples check `GATE_PLACE_TESTNET_ORDER` before sending an order. Do not log API keys or secrets, and never put them in browser code. ## Gate products and request vocabulary Several short fields determine where a request goes and what its values mean: | Field | Example | Meaning | | --------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- | | `currency_pair` | `BTC_USDT` | A Spot or margin market | | `account` | `spot` | The account used by a Spot order or query | | `settle` | `usdt` | The settlement currency for a Futures or Delivery REST API request | | `contract` | `BTC_USDT` | The exact Futures, Delivery, or Options contract | | `size` | `1` or `-1` | Futures contract count, not a BTC or USDT amount | | `text` | `t-my-order-123` | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id) | | `wsKey` | `WS_KEY_MAP.perpFuturesUSDTV4` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) that selects a product connection | For Spot orders, `account` can be `spot`, `margin`, `cross_margin`, or `unified`, depending on the account and endpoint. This tutorial uses `spot`. For USDT perpetual Futures, use `settle: 'usdt'` and a contract such as `BTC_USDT`. The `size` is a number of contracts. In one-way mode, a positive size buys and a negative size sells. The contract's `quanto_multiplier` tells you how much underlying currency one contract represents. Keep these routing values visible in code and logs. They are part of the request, not interchangeable labels. ## Start building: first calls and streams Run each example on its own. Start with public data, then add authenticated account state and live streams. ### 1. Make public REST API calls Public calls need no API key. Gate response bodies are endpoint-specific: server time and order books are objects, tickers are arrays, and candles are tuple arrays. ```javascript import { RestClient } from 'gateio-api'; const client = new RestClient(); async function main() { try { const time = await client.getServerTime(); console.log('Server time:', time.server_time); } catch (error) { console.error('Server time request failed:', error); } try { const pair = await client.getSpotCurrencyPair({ currency_pair: 'BTC_USDT', }); console.log('BTC_USDT metadata:', pair); } catch (error) { console.error('Currency pair request failed:', error); } try { const tickers = await client.getSpotTicker({ currency_pair: 'BTC_USDT', }); console.log('BTC_USDT ticker:', tickers[0]); } catch (error) { console.error('Ticker request failed:', error); } try { const orderBook = await client.getSpotOrderBook({ currency_pair: 'BTC_USDT', limit: 5, }); console.log('Best bid:', orderBook.bids[0]); console.log('Best ask:', orderBook.asks[0]); } catch (error) { console.error('Order book request failed:', error); } try { const candles = await client.getSpotCandles({ currency_pair: 'BTC_USDT', interval: '1h', limit: 10, }); console.log('Latest candle:', candles[0]); } catch (error) { console.error('Candles request failed:', error); } } main(); ``` The SDK returns the endpoint body directly. There is no shared result wrapper to unwrap. Each Spot candle is a tuple: ```text [ timestamp, quoteVolume, close, high, low, open, baseVolume, closed ] ``` Use the [SDK endpoint map](./endpointFunctionList.md) or the official endpoint documentation when reading tuple positions and endpoint-specific objects. ### 2. Make private REST API calls Private calls use the same `RestClient`. Add your key and secret, then call private methods normally. The SDK adds the required timestamp and signature. ```javascript import { RestClient } from 'gateio-api'; const client = new RestClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); async function main() { try { const balances = await client.getSpotAccounts(); console.log('Spot balances:', balances); } catch (error) { console.error('Balance request failed:', error); } try { const openOrders = await client.getSpotOpenOrders({ account: 'spot', }); console.log('Open Spot orders grouped by pair:', openOrders); } catch (error) { console.error('Open-order request failed:', error); } try { const recentOrders = await client.getSpotOrders({ currency_pair: 'BTC_USDT', status: 'finished', account: 'spot', limit: 20, }); console.log('Recent BTC_USDT orders:', recentOrders); } catch (error) { console.error('Order-history request failed:', error); } try { const trades = await client.getSpotTradingHistory({ currency_pair: 'BTC_USDT', account: 'spot', limit: 20, }); console.log('Recent BTC_USDT trades:', trades); } catch (error) { console.error('Trade-history request failed:', error); } } main(); ``` `getSpotAccounts()`, `getSpotOrders()`, and `getSpotTradingHistory()` return arrays. `getSpotOpenOrders()` returns an array whose entries group open orders by currency pair. Other private endpoints return objects or different array shapes, so check the [SDK endpoint map](./endpointFunctionList.md) instead of assuming a common format. ### 3. Subscribe to public WebSocket streams Every subscription includes both a topic and an explicit `wsKey`. The key tells the SDK which Gate connection should carry the subscription. ```javascript import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; const ws = new WebsocketClient(); ws.on('response', (response) => { console.log('Subscription response:', response); }); ws.on('update', (update) => { console.log('WebSocket update:', update); }); ws.on('reconnect', ({ wsKey }) => { console.log('Reconnecting:', wsKey); }); ws.on('reconnected', (event) => { console.log('Reconnected:', event.wsKey); }); ws.on('exception', (error) => { console.error('WebSocket exception:', error); }); try { ws.subscribe( { topic: 'spot.tickers', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Spot subscription failed:', error); } try { ws.subscribe( { topic: 'futures.tickers', payload: ['BTC_USDT'], }, WS_KEY_MAP.perpFuturesUSDTV4, ); } catch (error) { console.error('Futures subscription failed:', error); } process.once('SIGINT', () => { ws.closeAll(); }); ``` Gate sends Spot ticker data as an object in `result`, while a Futures ticker update can contain an array. The SDK adds `wsKey` to each update so one event handler can identify the source connection. The main WebSocket events are: | Event | Meaning | | --------------- | ------------------------------------------------------------- | | `open` | A connection opened for the reported `wsKey` | | `response` | Subscription, unsubscription, or request response | | `update` | Market or account data | | `authenticated` | A private connection authenticated successfully | | `reconnect` | The connection dropped and a reconnect is starting | | `reconnected` | The connection is open and cached subscriptions were restored | | `close` | A connection closed for the reported `wsKey` | | `exception` | The client or connection reported an error | A successful `response` event confirms the [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). It does not mean that a market update has arrived yet. ### 4. Subscribe to private Spot streams Private streams use the same client with credentials. This example follows Spot balances, orders, and user trades. ```javascript import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; const ws = new WebsocketClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); ws.on('authenticated', ({ wsKey }) => { console.log('Authenticated:', wsKey); }); ws.on('response', (response) => { console.log('Subscription response:', response); }); ws.on('update', (update) => { console.log('Private Spot update:', update); }); ws.on('reconnected', (event) => { console.log('Reconnected:', event.wsKey); }); ws.on('exception', (error) => { console.error('WebSocket exception:', error); }); try { ws.subscribe( { topic: 'spot.balances', }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Balance subscription failed:', error); } try { ws.subscribe( { topic: 'spot.orders', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Order subscription failed:', error); } try { ws.subscribe( { topic: 'spot.usertrades', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Trade subscription failed:', error); } process.once('SIGINT', () => { ws.closeAll(); }); ``` Use the `authenticated` event as a connection-level signal. Use private updates as [private stream confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) of account and order changes. Other private Spot topics include `spot.margin_balances` and `spot.cross_balances`. Check each channel's payload rules before subscribing. ### 5. Subscribe to private Futures streams Futures private channels use your Gate user ID. Contract-specific channels also include the contract. Retrieve the user ID once from the REST API, then use the payload required by each channel. ```javascript import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; const rest = new RestClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); const ws = new WebsocketClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); ws.on('authenticated', ({ wsKey }) => { console.log('Authenticated:', wsKey); }); ws.on('response', (response) => { console.log('Subscription response:', response); }); ws.on('update', (update) => { console.log('Private Futures update:', update); }); ws.on('exception', (error) => { console.error('WebSocket exception:', error); }); async function main() { let account; try { account = await rest.getAccountDetail(); console.log('Gate user ID:', account.user_id); } catch (error) { console.error('Account detail request failed:', error); return; } const userId = String(account.user_id); const payload = [userId, 'BTC_USDT']; const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; try { ws.subscribe( { topic: 'futures.orders', payload, }, wsKey, ); } catch (error) { console.error('Order subscription failed:', error); } try { ws.subscribe( { topic: 'futures.usertrades', payload, }, wsKey, ); } catch (error) { console.error('Trade subscription failed:', error); } try { ws.subscribe( { topic: 'futures.balances', payload: [userId], }, wsKey, ); } catch (error) { console.error('Balance subscription failed:', error); } try { ws.subscribe( { topic: 'futures.positions', payload, }, wsKey, ); } catch (error) { console.error('Position subscription failed:', error); } } process.once('SIGINT', () => { ws.closeAll(); }); main(); ``` Keep the `wsKey` aligned with the settlement currency and product. USDT perpetual Futures use `WS_KEY_MAP.perpFuturesUSDTV4`; BTC perpetual Futures use `WS_KEY_MAP.perpFuturesBTCV4`. Gate also provides private Futures channels such as `futures.autoorders`. Use the payload documented for that specific channel. ### 6. Place and cancel a Spot order in TestNet Gate TestNet uses separate credentials and API hosts. This example: 1. Checks the explicit order opt-in. 2. Loads current `BTC_USDT` trading rules and the order book. 3. Calculates an amount that meets the pair's base and quote minimums. 4. Places a post-only limit buy at the current best bid. 5. Queries the order and cancels it if it remains open. The order uses `time_in_force: 'poc'`, Gate's post-only setting. A fast market can move before the request arrives, in which case Gate can reject or finish the order instead of leaving it on the book. ```javascript import { RestClient } from 'gateio-api'; const client = new RestClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); async function main() { if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); return; } if ( !process.env.GATE_TESTNET_API_KEY || !process.env.GATE_TESTNET_API_SECRET ) { console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); return; } let pair; try { pair = await client.getSpotCurrencyPair({ currency_pair: 'BTC_USDT', }); } catch (error) { console.error('Currency pair request failed:', error); return; } let orderBook; try { orderBook = await client.getSpotOrderBook({ currency_pair: 'BTC_USDT', limit: 5, }); } catch (error) { console.error('Order book request failed:', error); return; } if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { console.error('BTC_USDT is not currently buyable.'); return; } const price = orderBook.bids[0]?.[0]; const amountPrecision = pair.amount_precision; const minBase = Number(pair.min_base_amount); const minQuote = Number(pair.min_quote_amount); const priceNumber = Number(price); if ( !price || amountPrecision === undefined || !Number.isFinite(minBase) || !Number.isFinite(minQuote) || !Number.isFinite(priceNumber) || priceNumber <= 0 ) { console.error('Required market metadata is unavailable.'); return; } const amountStep = 10 ** -amountPrecision; const minimumAmount = Math.max(minBase, minQuote / priceNumber); const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; const amount = amountNumber.toFixed(amountPrecision); if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { console.error('Could not derive a valid TestNet order.'); return; } const maxBase = Number(pair.max_base_amount); const maxQuote = Number(pair.max_quote_amount); if ( (Number.isFinite(maxBase) && amountNumber > maxBase) || (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) ) { console.error('Derived amount exceeds the pair limits.'); return; } const text = `t-siebly${Date.now().toString().slice(-12)}`; let placedOrder; try { placedOrder = await client.submitSpotOrder({ currency_pair: 'BTC_USDT', account: 'spot', side: 'buy', type: 'limit', amount, price, time_in_force: 'poc', text, }); console.log('Placed Spot order:', placedOrder); } catch (error) { console.error('Spot order placement failed:', error); return; } if (!placedOrder.id) { console.error('Gate did not return an order ID.'); return; } let currentOrder; try { currentOrder = await client.getSpotOrder({ order_id: placedOrder.id, currency_pair: 'BTC_USDT', account: 'spot', }); console.log('Current Spot order:', currentOrder); } catch (error) { console.error('Spot order query failed:', error); } if (currentOrder && currentOrder.status !== 'open') { console.log('Order is no longer open:', currentOrder.status); return; } try { const cancelledOrder = await client.cancelSpotOrder({ order_id: placedOrder.id, currency_pair: 'BTC_USDT', account: 'spot', }); console.log('Cancelled Spot order:', cancelledOrder); } catch (error) { console.error('Spot order cancellation failed:', error); } } main(); ``` The extra amount increment avoids falling just below the quote minimum after decimal rounding. Before using another pair, read its `amount_precision`, `precision`, minimums, maximums, and `trade_status`. ### 7. Place and cancel a USDT perpetual order in TestNet A Futures `size` is a contract count. It is not an amount of BTC or USDT. This example reads the contract's minimum size and current price, and it only runs when the account is in one-way mode. It does not change account or position settings. ```javascript import { RestClient } from 'gateio-api'; const client = new RestClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); async function main() { if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); return; } if ( !process.env.GATE_TESTNET_API_KEY || !process.env.GATE_TESTNET_API_SECRET ) { console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); return; } let contract; try { contract = await client.getFuturesContract({ settle: 'usdt', contract: 'BTC_USDT', }); } catch (error) { console.error('Contract request failed:', error); return; } let orderBook; try { orderBook = await client.getFuturesOrderBook({ settle: 'usdt', contract: 'BTC_USDT', limit: 5, }); } catch (error) { console.error('Order book request failed:', error); return; } let account; try { account = await client.getFuturesAccount({ settle: 'usdt', }); } catch (error) { console.error('Futures account request failed:', error); return; } const oneWayMode = account.position_mode ? account.position_mode === 'single' : !account.in_dual_mode; if (!oneWayMode) { console.error('This example requires one-way Futures position mode.'); return; } if (contract.status && contract.status !== 'trading') { console.error('BTC_USDT Futures is not currently trading.'); return; } const price = orderBook.bids[0]?.p; const size = Number(contract.order_size_min); if ( !price || !Number.isFinite(Number(price)) || Number(price) <= 0 || !Number.isFinite(size) || size <= 0 || (contract.enable_decimal === false && !Number.isInteger(size)) ) { console.error('Required contract metadata is unavailable.'); return; } console.log('One contract represents:', contract.quanto_multiplier, 'BTC'); console.log('Price increment:', contract.order_price_round); const text = `t-siebly${Date.now().toString().slice(-12)}`; let placedOrder; try { placedOrder = await client.submitFuturesOrder({ settle: 'usdt', contract: 'BTC_USDT', size, price, tif: 'poc', text, }); console.log('Placed Futures order:', placedOrder); } catch (error) { console.error('Futures order placement failed:', error); return; } if (placedOrder.id === undefined) { console.error('Gate did not return an order ID.'); return; } const orderId = String(placedOrder.id); let currentOrder; try { currentOrder = await client.getFuturesOrder({ settle: 'usdt', order_id: orderId, }); console.log('Current Futures order:', currentOrder); } catch (error) { console.error('Futures order query failed:', error); } if (currentOrder && currentOrder.status !== 'open') { console.log('Order is no longer open:', currentOrder.status); return; } try { const cancelledOrder = await client.cancelFuturesOrder({ settle: 'usdt', order_id: orderId, }); console.log('Cancelled Futures order:', cancelledOrder); } catch (error) { console.error('Futures order cancellation failed:', error); } } main(); ``` In one-way mode, a positive `size` buys and a negative `size` sells. Dual-side mode uses different position semantics, so handle it in account-specific code after reading the [official Gate API v4 documentation](https://www.gate.com/docs/developers/apiv4/en/). The contract metadata supplies the size and price rules: - `order_size_min`: minimum contract count - `order_price_round`: permitted price increment - `quanto_multiplier`: underlying amount represented by one contract - `enable_decimal`: whether fractional contract sizes are supported Do not derive a Futures order size from Spot precision rules. ### 8. Send a Spot order through the WebSocket API `WebsocketAPIClient` turns Gate WebSocket API commands into promises. It connects and authenticates automatically on the first private command, adds a request ID, matches the response, and resolves the promise. This TestNet example uses the REST API only to read current market rules and the order book. The order, query, and cancellation use the WebSocket API. ```javascript import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; const rest = new RestClient({ baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); const wsApi = new WebsocketAPIClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', }); async function main() { if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); return; } if ( !process.env.GATE_TESTNET_API_KEY || !process.env.GATE_TESTNET_API_SECRET ) { console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); return; } let pair; try { pair = await rest.getSpotCurrencyPair({ currency_pair: 'BTC_USDT', }); } catch (error) { console.error('Currency pair request failed:', error); return; } let orderBook; try { orderBook = await rest.getSpotOrderBook({ currency_pair: 'BTC_USDT', limit: 5, }); } catch (error) { console.error('Order book request failed:', error); return; } if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { console.error('BTC_USDT is not currently buyable.'); return; } const price = orderBook.bids[0]?.[0]; const amountPrecision = pair.amount_precision; const minBase = Number(pair.min_base_amount); const minQuote = Number(pair.min_quote_amount); const priceNumber = Number(price); if ( !price || amountPrecision === undefined || !Number.isFinite(minBase) || !Number.isFinite(minQuote) || !Number.isFinite(priceNumber) || priceNumber <= 0 ) { console.error('Required market metadata is unavailable.'); return; } const amountStep = 10 ** -amountPrecision; const minimumAmount = Math.max(minBase, minQuote / priceNumber); const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; const amount = amountNumber.toFixed(amountPrecision); if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { console.error('Could not derive a valid TestNet order.'); return; } const maxBase = Number(pair.max_base_amount); const maxQuote = Number(pair.max_quote_amount); if ( (Number.isFinite(maxBase) && amountNumber > maxBase) || (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) ) { console.error('Derived amount exceeds the pair limits.'); return; } const text = `t-siebly${Date.now().toString().slice(-12)}`; const wsKey = WS_KEY_MAP.spotV4; try { let placedResponse; try { placedResponse = await wsApi.submitNewSpotOrder( { currency_pair: 'BTC_USDT', account: 'spot', side: 'buy', type: 'limit', amount, price, time_in_force: 'poc', text, }, wsKey, ); console.log('Command status:', placedResponse.header.status); console.log('Placed Spot order:', placedResponse.data.result); } catch (error) { console.error('Spot WebSocket API placement failed:', error); return; } const orderId = placedResponse.data.result.id; let statusResponse; try { statusResponse = await wsApi.getSpotOrderStatus( { order_id: orderId, currency_pair: 'BTC_USDT', account: 'spot', }, wsKey, ); console.log('Current Spot order:', statusResponse.data.result); } catch (error) { console.error('Spot WebSocket API query failed:', error); } if (statusResponse && statusResponse.data.result.status !== 'open') { console.log( 'Order is no longer open:', statusResponse.data.result.status, ); return; } try { const cancelledResponse = await wsApi.cancelSpotOrder( { order_id: orderId, currency_pair: 'BTC_USDT', account: 'spot', }, wsKey, ); console.log('Cancelled Spot order:', cancelledResponse.data.result); } catch (error) { console.error('Spot WebSocket API cancellation failed:', error); } } finally { wsApi.getWSClient().closeAll(); } } main(); ``` ### 9. Send a USDT perpetual order through the WebSocket API Futures WebSocket API commands use a product-specific WebSocket key. Pass it explicitly so the contract and connection remain clear. ```javascript import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; const rest = new RestClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); const wsApi = new WebsocketAPIClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, wsUrl: 'wss://ws-testnet.gate.com/v4/ws/futures/usdt', }); async function main() { if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); return; } if ( !process.env.GATE_TESTNET_API_KEY || !process.env.GATE_TESTNET_API_SECRET ) { console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); return; } let contract; try { contract = await rest.getFuturesContract({ settle: 'usdt', contract: 'BTC_USDT', }); } catch (error) { console.error('Contract request failed:', error); return; } let orderBook; try { orderBook = await rest.getFuturesOrderBook({ settle: 'usdt', contract: 'BTC_USDT', limit: 5, }); } catch (error) { console.error('Order book request failed:', error); return; } let account; try { account = await rest.getFuturesAccount({ settle: 'usdt', }); } catch (error) { console.error('Futures account request failed:', error); return; } const oneWayMode = account.position_mode ? account.position_mode === 'single' : !account.in_dual_mode; if (!oneWayMode) { console.error('This example requires one-way Futures position mode.'); return; } if (contract.status && contract.status !== 'trading') { console.error('BTC_USDT Futures is not currently trading.'); return; } const price = orderBook.bids[0]?.p; const size = Number(contract.order_size_min); if ( !price || !Number.isFinite(Number(price)) || Number(price) <= 0 || !Number.isFinite(size) || size <= 0 || (contract.enable_decimal === false && !Number.isInteger(size)) ) { console.error('Required contract metadata is unavailable.'); return; } const text = `t-siebly${Date.now().toString().slice(-12)}`; const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; try { let placedResponse; try { placedResponse = await wsApi.submitNewFuturesOrder( { contract: 'BTC_USDT', size, price, tif: 'poc', text, }, wsKey, ); console.log('Command status:', placedResponse.header.status); console.log('Placed Futures order:', placedResponse.data.result); } catch (error) { console.error('Futures WebSocket API placement failed:', error); return; } const orderId = String(placedResponse.data.result.id); let statusResponse; try { statusResponse = await wsApi.getFuturesOrderStatus( { order_id: orderId, }, wsKey, ); console.log('Current Futures order:', statusResponse.data.result); } catch (error) { console.error('Futures WebSocket API query failed:', error); } if (statusResponse && statusResponse.data.result.status !== 'open') { console.log( 'Order is no longer open:', statusResponse.data.result.status, ); return; } try { const cancelledResponse = await wsApi.cancelFuturesOrder( { order_id: orderId, }, wsKey, ); console.log('Cancelled Futures order:', cancelledResponse.data.result); } catch (error) { console.error('Futures WebSocket API cancellation failed:', error); } } finally { wsApi.getWSClient().closeAll(); } } main(); ``` Successful commands have `header.status === '200'`, and the endpoint result is in `data.result`. The SDK rejects a command promise when Gate returns a non-success status. An accepted command is not proof that an order later filled, remained open, or was cancelled. Treat the response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then confirm the final state through the private order stream or a REST API query. ## Work with the Gate REST API `RestClient` covers Gate's product groups through named methods. Public methods work without credentials. Private methods use the API key and secret passed to the client. ### Understand response shapes The client resolves to the endpoint's response body: ```javascript import { RestClient } from 'gateio-api'; const client = new RestClient(); async function main() { try { const result = await client.getSpotOrderBook({ currency_pair: 'BTC_USDT', }); console.log(result); } catch (error) { console.error('Order book request failed:', error); } } main(); ``` There is no shared response envelope. Check the [SDK endpoint map](./endpointFunctionList.md) before deciding how to handle `result`. | Method | Response shape | | ----------------------- | ------------------------------------------ | | `getServerTime()` | Object with `server_time` | | `getSpotCurrencyPair()` | Currency-pair object | | `getSpotTicker()` | Array of ticker objects | | `getSpotOrderBook()` | Object with tuple-array `bids` and `asks` | | `getSpotCandles()` | Array of candle tuples | | `getFuturesContract()` | Contract object | | `getFuturesTickers()` | Array of ticker objects | | `getFuturesOrderBook()` | Object with `{ p, s }` bid and ask entries | | `getFuturesAccount()` | Account object | | `getFuturesPositions()` | Array of position objects | Prices and quantities are commonly returned as strings. Keep them as strings while passing them between Gate API methods. Convert them deliberately when doing calculations, and round the result back to the product's required precision. ### Read account state An authenticated integration usually needs these views: | State | Spot method | USDT perpetual method | | ------------------- | ------------------------- | ---------------------------------------------------------- | | Balances or account | `getSpotAccounts()` | `getFuturesAccount({ settle: 'usdt' })` | | Positions | Not applicable | `getFuturesPositions({ settle: 'usdt' })` | | Open orders | `getSpotOpenOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'open' })` | | Recent orders | `getSpotOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'finished' })` | | Trades | `getSpotTradingHistory()` | `getFuturesTradingHistory({ settle: 'usdt' })` | These REST API views form a reliable [account state](https://siebly.io/reference/glossary#accountstate) baseline before stream updates are applied. ### Explore other Gate product groups The same `RestClient` also covers the following APIs. Start with read methods and check account eligibility, permissions, and product-specific rules before using any write method. | Product group | Representative SDK methods | | ----------------------- | --------------------------------------------------------------------------- | | Margin and cross margin | `getMarginAccounts()`, `getCrossMarginAccount()`, `getMarginUserAccounts()` | | Universal margin loans | `getMarginUNILoans()`, `getMarginUNIMaxBorrow()` | | Unified Account | `getUnifiedAccountInfo()`, `getUnifiedAccountMode()`, `getUnifiedLoans()` | | Delivery | `getAllDeliveryContracts()`, `getDeliveryAccount()`, `getDeliveryOrders()` | | Options | `getOptionsContracts()`, `getOptionsAccount()`, `getOptionsOrders()` | | Wallet and transfers | `getBalances()`, `submitTransfer()`, `getTransferStatus()` | | Multi-collateral loans | `getMultiLoanOrders()`, `getMultiLoanSupportedCurrencies()` | | Flash Swap | `getFlashSwapCurrencyPairs()`, `getFlashSwapOrders()` | | Earn and lending | `getEarnFixedTermProducts()`, `getEarnFixedTermLends()` | | Auto Invest | `getAutoInvestCoins()`, `getAutoInvestPlans()`, `getAutoInvestOrders()` | | Subaccounts | `getSubAccounts()`, `getSubBalance()`, `getSubFuturesBalances()` | | Rebates and partners | `getPartnerTransactionHistory()`, `getPartnerCommissionHistory()` | | OTC | `getOTCBankList()`, `getOTCFiatOrderList()` | | P2P Merchant | `getP2PMerchantUserInfo()`, `getP2PMerchantPendingTransactionList()` | | CrossEx | `getCrossExSymbols()`, `getCrossExAccounts()`, `getCrossExPositions()` | | Alpha | `getAlphaCurrencies()`, `getAlphaTickers()`, `getAlphaOrders()` | | TradFi | `getTradFiSymbols()`, `getTradFiAssets()`, `getTradFiOrders()` | See the [complete SDK endpoint map](./endpointFunctionList.md) for every supported method, its authentication requirement, HTTP method, and Gate path. ## Build with WebSocket streams Use `WebsocketClient` for ongoing market and account updates. A subscription request has two independent parts: - `topic` and `payload` select the Gate channel and its data. - `wsKey` selects the product connection that carries the subscription. One `subscribe()` call can contain several topics when they share the same `wsKey`. Use separate calls for topics on different product connections. ### Choose the correct WebSocket key | Product connection | SDK key | | ---------------------- | ---------------------------------- | | Spot | `WS_KEY_MAP.spotV4` | | USDT perpetual Futures | `WS_KEY_MAP.perpFuturesUSDTV4` | | BTC perpetual Futures | `WS_KEY_MAP.perpFuturesBTCV4` | | USDT Delivery | `WS_KEY_MAP.deliveryFuturesUSDTV4` | | BTC Delivery | `WS_KEY_MAP.deliveryFuturesBTCV4` | | Options | `WS_KEY_MAP.optionsV4` | | Announcements | `WS_KEY_MAP.announcementsV4` | Do not infer the connection from a symbol alone. `BTC_USDT` can appear in more than one product family. Useful public topics include: | Product | Starting topics | | ------- | -------------------------------------------------------------------------------------------------------------- | | Spot | `spot.tickers`, `spot.trades`, `spot.order_book`, `spot.order_book_update`, `spot.candlesticks` | | Futures | `futures.tickers`, `futures.trades`, `futures.order_book`, `futures.order_book_update`, `futures.candlesticks` | | Options | `options.tickers`, `options.trades`, `options.order_book`, `options.ul_tickers` | ### Treat responses and updates differently The `response` event tells you whether Gate accepted a subscribe, unsubscribe, or request message. Check its `error` and `result`. The `update` event carries channel data. Inspect `channel`, `event`, `result`, and the SDK-added `wsKey` before updating local state. A subscription response and a data update can have different result shapes. ### Recover after a reconnect The SDK reconnects and restores cached subscriptions. A stream gap can still hide balance, order, trade, or position changes. Reload the affected state from the REST API after `reconnected`. This Spot example reloads balances, open orders, and recent trades in sequence: ```javascript import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; const rest = new RestClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); const ws = new WebsocketClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); let recoveryRunning = false; let spotState; async function recoverSpotState() { if (recoveryRunning) { return; } recoveryRunning = true; try { let balances; try { balances = await rest.getSpotAccounts(); } catch (error) { console.error('Balance recovery failed:', error); return; } let openOrders; try { openOrders = await rest.getSpotOpenOrders({ account: 'spot', }); } catch (error) { console.error('Open-order recovery failed:', error); return; } let trades; try { trades = await rest.getSpotTradingHistory({ currency_pair: 'BTC_USDT', account: 'spot', limit: 100, }); } catch (error) { console.error('Trade recovery failed:', error); return; } spotState = { balances, openOrders, trades, recoveredAt: Date.now(), }; console.log('Recovered Spot state:', spotState); } finally { recoveryRunning = false; } } ws.on('reconnected', async ({ wsKey }) => { if (wsKey !== WS_KEY_MAP.spotV4) { return; } await recoverSpotState(); }); ws.on('update', (update) => { console.log('Private Spot update:', update); }); ws.on('exception', (error) => { console.error('WebSocket exception:', error); }); try { ws.subscribe( { topic: 'spot.balances', }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Balance subscription failed:', error); } try { ws.subscribe( { topic: 'spot.orders', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Order subscription failed:', error); } try { ws.subscribe( { topic: 'spot.usertrades', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch (error) { console.error('Trade subscription failed:', error); } process.once('SIGINT', () => { ws.closeAll(); }); ``` This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration) applied as [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery). The example replaces `spotState` only after all three reads succeed. Reload only the state that may have changed on the affected connection, then reconcile it before trusting new updates. For a wider recovery design, see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows). ## Use the Gate WebSocket API `WebsocketAPIClient` is for request and response commands over WebSocket. It is not the same as a subscription stream. The client: 1. Opens the selected WebSocket connection. 2. Authenticates automatically. 3. Adds a unique request ID. 4. Sends the command. 5. Matches Gate's response to the pending promise. 6. Resolves with `header`, `data.result`, `request_id`, and `wsKey`. Authentication happens automatically on the first command. `connectWSAPI(wsKey)` is available when an application wants to open and authenticate the connection early. Automatic WebSocket API reauthentication after a reconnect is enabled by default. Spot methods include: - `submitNewSpotOrder()` - `getSpotOrderStatus()` - `getSpotOrders()` - `updateSpotOrder()` - `cancelSpotOrder()` - `cancelSpotOrderById()` - `cancelSpotOrderForSymbol()` Futures methods include: - `submitNewFuturesOrder()` - `submitNewFuturesBatchOrder()` - `getFuturesOrderStatus()` - `getFuturesOrders()` - `updateFuturesOrder()` - `cancelFuturesOrder()` Pass a Futures `wsKey` explicitly. This keeps the settlement connection visible: ```javascript import { WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; const wsApi = new WebsocketAPIClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }); async function main() { try { const response = await wsApi.getFuturesOrders( { contract: 'BTC_USDT', status: 'open', limit: 20, }, WS_KEY_MAP.perpFuturesUSDTV4, ); console.log(response.header.status); console.log(response.data.result); } catch (error) { console.error('WebSocket API order request failed:', error); } finally { wsApi.getWSClient().closeAll(); } } main(); ``` The response confirms the command outcome. Use private order streams or a REST API query to confirm the resulting exchange state. ## Use Gate TestNet Gate TestNet is a separate environment with separate credentials. Use it for all order examples while learning the SDK. | Interface | Current TestNet host | | ------------------------ | ---------------------------------------------- | | REST API | `https://api-testnet.gateapi.io/api/v4` | | Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | | USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | Set the REST API host with `baseUrl` and the WebSocket host with `wsUrl`. Prefer explicit hosts for TestNet examples: - Spot WebSocket TestNet is not wired through `useTestnet: true` in this SDK. The Spot testnet map entry is a stub (`NoTestnetForSpotWebsockets!`), so set `wsUrl` to the Spot TestNet host above. - For Futures-only REST TestNet, the SDK also accepts `baseUrlKey: 'futuresTestnet'`, which resolves to `https://fx-api-testnet.gateio.ws/api/v4`. The Global TestNet REST host in the table is the host used by the Spot and Futures order examples in this guide. ```javascript import { RestClient, WebsocketClient } from 'gateio-api'; const rest = new RestClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); const spotWs = new WebsocketClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', }); ``` Do not send live credentials to TestNet or TestNet credentials to live hosts. TestNet balances, liquidity, and available products can differ from live trading. Fund the required Spot or Futures TestNet account with test assets before running an order example. ## Connect to Global and regional REST API hosts Use the API host associated with the Gate account and product you are integrating. Credentials and product availability are not interchangeable across account regions. | Environment or account | REST API base URL | Official reference | | ------------------------ | --------------------------------------- | -------------------------------------------------------------------- | | Global live | `https://api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | | Global TestNet | `https://api-testnet.gateapi.io/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | | Futures live alternative | `https://fx-api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | | Gate US live | `https://api.gate.us/api/v4` | [Gate US API v4](https://us.gate.com/en-us/docs/developers/apiv4/) | | Gate EU live | `https://api.gateeu.com/api/v4` | [Gate EU API v4](https://eu.gate.com/docs/developers/apiv4/en/) | Global live is the SDK default. Set `baseUrl` for another supported account host: ```javascript import { RestClient } from 'gateio-api'; const gateUs = new RestClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, baseUrl: 'https://api.gate.us/api/v4', }); const gateEu = new RestClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, baseUrl: 'https://api.gateeu.com/api/v4', }); ``` Use only the client that matches the account. Regional APIs can expose different products and endpoint sets. Check the regional documentation before calling a method, and use the region's own credentials. This guide does not assign regional WebSocket URLs. Use a regional WebSocket host only when the official documentation for that account region provides it. ## Use a proxy with the REST API and WebSockets `gateio-api` accepts standard Node.js agents. Configure the agent in both places when all Gate traffic must use the proxy: - Pass `httpsAgent` in the second `RestClient` argument and set `proxy: false`. - Pass the same agent as `wsOptions.agent` to `WebsocketClient` or `WebsocketAPIClient`. See [Using proxies with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. ### HTTP and HTTPS proxy Install the proxy agent: ```bash npm install https-proxy-agent ``` Set `GATE_PROXY_URL` to an `http://` or `https://` proxy URL. The example does not print the value because it may contain credentials. ```javascript import { HttpsProxyAgent } from 'https-proxy-agent'; import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; async function main() { const proxyUrl = process.env.GATE_PROXY_URL; if (!proxyUrl) { console.error('Set GATE_PROXY_URL.'); return; } const agent = new HttpsProxyAgent(proxyUrl); const rest = new RestClient( {}, { httpsAgent: agent, proxy: false, }, ); const ws = new WebsocketClient({ wsOptions: { agent, }, }); ws.on('open', ({ wsKey }) => { console.log('WebSocket connected through proxy:', wsKey); }); ws.on('response', (response) => { console.log('Subscription response:', response); }); ws.on('update', (update) => { console.log('Ticker update through proxy:', update); ws.closeAll(); }); ws.on('exception', () => { console.error('WebSocket proxy connection failed.'); }); try { const time = await rest.getServerTime(); console.log('Server time through proxy:', time.server_time); } catch { console.error('REST API proxy request failed.'); } try { ws.subscribe( { topic: 'spot.tickers', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch { console.error('WebSocket proxy subscription failed.'); } process.once('SIGINT', () => { ws.closeAll(); }); } main(); ``` For an authenticated HTTP or HTTPS proxy, include the username and password in `GATE_PROXY_URL`. Percent-encode reserved characters in each credential component. ### SOCKS5 proxy Install the SOCKS agent: ```bash npm install socks-proxy-agent ``` Set `GATE_SOCKS_PROXY_URL` to a `socks5://` URL: ```javascript import { SocksProxyAgent } from 'socks-proxy-agent'; import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; async function main() { const proxyUrl = process.env.GATE_SOCKS_PROXY_URL; if (!proxyUrl) { console.error('Set GATE_SOCKS_PROXY_URL.'); return; } const agent = new SocksProxyAgent(proxyUrl); const rest = new RestClient( {}, { httpsAgent: agent, proxy: false, }, ); const ws = new WebsocketClient({ wsOptions: { agent, }, }); ws.on('open', ({ wsKey }) => { console.log('WebSocket connected through SOCKS5:', wsKey); }); ws.on('response', (response) => { console.log('Subscription response:', response); }); ws.on('update', (update) => { console.log('Ticker update through SOCKS5:', update); ws.closeAll(); }); ws.on('exception', () => { console.error('SOCKS5 WebSocket connection failed.'); }); try { const time = await rest.getServerTime(); console.log('Server time through SOCKS5:', time.server_time); } catch { console.error('SOCKS5 REST API request failed.'); } try { ws.subscribe( { topic: 'spot.tickers', payload: ['BTC_USDT'], }, WS_KEY_MAP.spotV4, ); } catch { console.error('SOCKS5 WebSocket subscription failed.'); } process.once('SIGINT', () => { ws.closeAll(); }); } main(); ``` ### Private REST API, stream, and WebSocket API traffic Use the same agent and credentials for private REST API calls, private subscriptions, and WebSocket API connections: ```javascript import { HttpsProxyAgent } from 'https-proxy-agent'; import { RestClient, WebsocketAPIClient, WebsocketClient, WS_KEY_MAP, } from 'gateio-api'; async function main() { const proxyUrl = process.env.GATE_PROXY_URL; if (!proxyUrl) { console.error('Set GATE_PROXY_URL.'); return; } const agent = new HttpsProxyAgent(proxyUrl); const rest = new RestClient( { apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, }, { httpsAgent: agent, proxy: false, }, ); const streams = new WebsocketClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, wsOptions: { agent, }, }); const wsApi = new WebsocketAPIClient({ apiKey: process.env.GATE_API_KEY, apiSecret: process.env.GATE_API_SECRET, wsOptions: { agent, }, }); streams.on('authenticated', ({ wsKey }) => { console.log('Private stream authenticated:', wsKey); }); streams.on('update', (update) => { console.log('Private update through proxy:', update); }); streams.on('exception', () => { console.error('Private stream proxy connection failed.'); }); try { const balances = await rest.getSpotAccounts(); console.log('Spot balances through proxy:', balances); } catch { console.error('Private REST API proxy request failed.'); } try { streams.subscribe( { topic: 'spot.balances', }, WS_KEY_MAP.spotV4, ); } catch { console.error('Private stream subscription failed.'); } try { await wsApi.getWSClient().connectWSAPI(WS_KEY_MAP.spotV4); console.log('WebSocket API authenticated through proxy.'); } catch { console.error('WebSocket API proxy connection failed.'); } process.once('SIGINT', () => { streams.closeAll(); wsApi.getWSClient().closeAll(); }); } main(); ``` To combine a proxy with TestNet or a regional API, keep `baseUrl` or `wsUrl` in the first client argument and the agent in the same positions shown above. The proxy's egress IP is the address Gate sees. Add that address to the API key whitelist when whitelisting is enabled. Use a stable proxy endpoint, monitor its latency, and never use a proxy to bypass account or regional restrictions. A proxy changes the network path, not request signing, account eligibility, or regional product access. Test public REST API and WebSocket traffic first. Treat HTTP 407 responses, TLS failures, and repeated reconnects as network faults. The SDK does not rotate proxy endpoints. ## Production checklist ### Keep request time accurate Gate private requests and WebSocket authentication depend on timestamp checks. The gap between request time and server time must not exceed 60 seconds. Synchronize the host clock with NTP. Use `getServerTime()` for diagnosis, but fix the system clock rather than adding a permanent application offset for a drifting machine. ### Respect rate limits Rate limits vary by product and endpoint. Read the current [Gate API rate-limit documentation](https://www.gate.com/docs/developers/apiv4/en/#frequency-limit-rule) and monitor rejection labels. Retry temporary network failures and rate-limit responses with bounded exponential backoff and jitter. Do not blindly retry an order command after an ambiguous timeout. First reconcile by the order's `text` value or query current order state. ### Use custom order IDs Set a unique `text` value beginning with `t-` on each application-owned order. Store it with your local request record. This gives retries, restarts, stream updates, and REST API recovery a common identifier. ### Apply product metadata Before placing an order: - Check that the pair or contract is tradable. - Apply minimum and maximum amounts. - Round prices and quantities to the permitted increments. - Treat Futures `size` as a contract count. - Read `quanto_multiplier` before translating contract size into underlying exposure. - Keep one-way, dual-side, and split position modes explicit. Refresh metadata regularly and when Gate rejects an order for a precision or size rule. ### Confirm final state A REST API response or WebSocket API response can arrive before later fills, cancellations, or amendments. Record the command response, then confirm final state through private streams or a REST API query. After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. ### Scope credentials and network access - Use separate keys for live and TestNet. - Grant only the product permissions the process needs. - Use read-only keys for monitoring services. - Do not grant withdrawal permission. - Add IP whitelists when egress addresses are stable. - Keep secrets in a server-side secret manager or deployment environment. - Monitor proxy availability and egress IP changes. ### Shut down connections Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. ## FAQ ### Does `gateio-api` work with plain JavaScript? Yes. Every example in this guide is plain JavaScript. The examples use ESM imports, so save them as `.mjs` files or set `"type": "module"` in `package.json`. The package also includes a CommonJS build and TypeScript declarations. ### Which client should I use? Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. ### Do public Gate API calls need credentials? No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. ### Why did a REST API call return an object when another returned an array? Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. ### Why does `getSpotTicker()` return an array for one pair? That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. ### How are Spot candles structured? Spot candles are tuple arrays containing timestamp, quote volume, close, high, low, open, base volume, and a closed-window flag in that order. ### Why does Gate use `BTC_USDT`? Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. ### What do `account` and `settle` change? `account` selects the account used by a Spot order or query. `settle` selects the settlement currency and REST API path for Futures or Delivery requests. ### What is the `text` order field? `text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. ### Why am I not receiving WebSocket updates? Check the topic payload, `wsKey`, API host, credentials, and permissions. Then inspect `response`, `authenticated`, and `exception` events. A successful subscription response confirms registration, but an update only arrives when the subscribed data changes. ### Which `WS_KEY_MAP` value should I use? Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. ### Why do private Futures topics use my Gate user ID? It is part of the payload required by those channels. Retrieve it with `getAccountDetail()` instead of hardcoding it. ### What is the difference between a stream and the WebSocket API? Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. ### Does a successful WebSocket API response mean the order filled? No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. ### Why was a post-only order rejected or immediately finished? The best bid or ask can move between the order-book request and order placement. Gate will not let a post-only order take liquidity. Read the returned status and `finish_as`, then decide whether to refresh the book and submit a new order with a new `text`. ### Why does a Futures order size look too small? Futures `size` is the number of contracts. Use `quanto_multiplier` to find the underlying amount represented by one contract. ### Can live credentials be used in TestNet? No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. ### Can I use Gate US or Gate EU with the SDK? Yes, for endpoints available to that account region. Set the documented regional `baseUrl`, use credentials from the same region, and check its official API documentation for product coverage. ### Can REST API and WebSocket traffic use the same proxy? Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. ### Does a proxy change signing or account eligibility? No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. ### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? Common causes are a drifting system clock, the wrong API secret, credentials from another environment, or an API request reaching the wrong host. Verify the clock, credential source, and API host without logging the secret. ## Next steps - Browse the [Gate SDK examples](https://siebly.io/examples/Gate). - Find methods in the [complete endpoint map](./endpointFunctionList.md). - Review the [Gate SDK page](https://siebly.io/sdk/gate/javascript). - Install or update [`gateio-api` from npm](https://www.npmjs.com/package/gateio-api). - Browse the [`gateio-api` source repository](https://github.com/sieblyio/gateio-api). - Read the official [Gate REST API documentation](https://www.gate.com/docs/developers/apiv4/en/). - Read the official [Gate Spot WebSocket documentation](https://www.gate.com/docs/developers/apiv4/ws/). - Read the official [Gate Futures WebSocket documentation](https://www.gate.com/docs/developers/futures/ws/). - Review [Exchange State](https://siebly.io/reference/exchange-state) before building private state management. - Use [Runtime Workflows](https://siebly.io/reference/runtime-workflows) when designing startup, reconnect, and reconciliation behavior. - Open the [Siebly glossary](https://siebly.io/reference/glossary) for order, stream, and recovery terms. - Report SDK issues in the [`gateio-api` GitHub repository](https://github.com/sieblyio/gateio-api/issues). ================ File: src/types/request/earn.ts ================ /**========================================================================================================================== * EARN * ========================================================================================================================== */ ⋮---- /** GET /earn/dual/investment_plan */ export interface GetDualInvestmentPlansReq { plan_id?: number | string; coin?: string; type?: string; quote_currency?: string; /** `apy` | `short-period` | `multiple` */ sort?: string; page?: number; page_size?: number; } ⋮---- /** `apy` | `short-period` | `multiple` */ ⋮---- /** GET /earn/dual/orders */ export interface GetDualInvestmentOrdersReq { from?: number; to?: number; type?: string; status?: string; coin?: string; page?: number; limit?: number; } ⋮---- /** GET /earn/dual/order-refund-preview */ export interface GetDualOrderRefundPreviewReq { order_id: string; } ⋮---- /** POST /earn/dual/order-refund */ export interface SubmitDualOrderRefundParams { order_id: string; /** From order-refund-preview */ req_id: string; } ⋮---- /** From order-refund-preview */ ⋮---- /** POST /earn/dual/modify-order-reinvest */ export interface UpdateDualOrderReinvestParams { order_id?: number; /** 0 off, 1 on */ status?: number; /** Effective duration in seconds; default 86400 */ effective_time_duration?: number; } ⋮---- /** 0 off, 1 on */ ⋮---- /** Effective duration in seconds; default 86400 */ ⋮---- /** GET /earn/dual/project-recommend */ export interface GetDualProjectRecommendReq { mode?: string; coin?: string; type?: string; /** Comma-separated project IDs to exclude */ history_pids?: string; } ⋮---- /** Comma-separated project IDs to exclude */ ⋮---- /** Request params for POST /earn/dual/orders */ export interface PlaceDualInvestmentOrderParams { plan_id: string; /** Subscription amount. Mutually exclusive with copies. */ amount: string; /** Units. Mutually exclusive with amount. */ copies?: string; /** Custom order info, must start with t- */ text?: string; } ⋮---- /** Subscription amount. Mutually exclusive with copies. */ ⋮---- /** Units. Mutually exclusive with amount. */ ⋮---- /** Custom order info, must start with t- */ ⋮---- /**========================================================================================================================== * EARN FIXED-TERM * ========================================================================================================================== */ ⋮---- export interface GetEarnFixedTermProductsReq { asset?: string; type?: number; // 1 regular, 2 VIP page: number; limit: number; } ⋮---- type?: number; // 1 regular, 2 VIP ⋮---- export interface GetEarnFixedTermProductsByAssetReq { /** Product type: "" or 1 regular, 2 VIP, 0 all */ type?: string; } ⋮---- /** Product type: "" or 1 regular, 2 VIP, 0 all */ ⋮---- export interface CreateEarnFixedTermLendReq { product_id: number; amount: string; year_rate?: string; reinvest_status?: number; // 0 off, 1 on redeem_account_type?: number; // 1 spot financial_rate_id?: number; // interest boost coupon id, 0 = none sub_business?: number; } ⋮---- reinvest_status?: number; // 0 off, 1 on redeem_account_type?: number; // 1 spot financial_rate_id?: number; // interest boost coupon id, 0 = none ⋮---- export interface GetEarnFixedTermLendsReq { product_id?: number; order_id?: number; asset?: string; order_type: '1' | '2'; // 1 current, 2 historical page: number; limit: number; sub_business?: number; business_filter?: string; } ⋮---- order_type: '1' | '2'; // 1 current, 2 historical ⋮---- export interface EarnFixedTermPreRedeemReq { order_id: string; } ⋮---- export interface GetEarnFixedTermHistoryReq { product_id?: number; order_id?: string; asset?: string; type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus page: number; limit: number; start_at?: number; end_at?: number; sub_business?: number; business_filter?: string; } ⋮---- type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus ================ File: src/types/request/otc.ts ================ import { GateMultipartFile } from '../../lib/multipartUtil.js'; ⋮---- /**========================================================================================================================== * OTC * ========================================================================================================================== */ ⋮---- export interface CreateOTCQuoteReq { side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount pay_coin: string; // Currency the user pays get_coin: string; // Currency the user receives pay_amount?: string; // User payment currency amount (required if side is PAY) get_amount?: string; // Amount of currency received by user (required if side is GET) create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement promotion_code?: string; // Promotion code (optional) } ⋮---- side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount pay_coin: string; // Currency the user pays get_coin: string; // Currency the user receives pay_amount?: string; // User payment currency amount (required if side is PAY) get_amount?: string; // Amount of currency received by user (required if side is GET) create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement promotion_code?: string; // Promotion code (optional) ⋮---- export interface CreateOTCFiatOrderReq { type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) side: string; // Quote direction returned by the quote API (used for order validation) crypto_currency: string; // Cryptocurrency fiat_currency: string; // Fiat currency crypto_amount: string; // Amount of cryptocurrency fiat_amount: string; // Fiat amount promotion_code?: string; // Promotion code quote_token: string; // Parameter returned by the quote API /** From GET /otc/bank/list; default card has is_default=1 */ bank_id: string; receive_type?: string; } ⋮---- type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) side: string; // Quote direction returned by the quote API (used for order validation) crypto_currency: string; // Cryptocurrency fiat_currency: string; // Fiat currency crypto_amount: string; // Amount of cryptocurrency fiat_amount: string; // Fiat amount promotion_code?: string; // Promotion code quote_token: string; // Parameter returned by the quote API /** From GET /otc/bank/list; default card has is_default=1 */ ⋮---- export interface CreateOTCStablecoinOrderReq { pay_coin: string; // Currency paid by the user get_coin: string; // Currency to be received by the user pay_amount: string; // User payment currency amount get_amount: string; // Amount of currency received by the user side: string; // Quote direction returned by the quote API (used for order validation) quote_token: string; // Parameter returned by the quote API promotion_code?: string; // Promotion code (optional) } ⋮---- pay_coin: string; // Currency paid by the user get_coin: string; // Currency to be received by the user pay_amount: string; // User payment currency amount get_amount: string; // Amount of currency received by the user side: string; // Quote direction returned by the quote API (used for order validation) quote_token: string; // Parameter returned by the quote API promotion_code?: string; // Promotion code (optional) ⋮---- export interface MarkOTCOrderAsPaidReq { order_id: string; // Order ID client_order_id?: string; // Client order ID (gateway/Inner Pay paths) payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB payment_receipt?: string; // Alias compatible with payment_receipt_file_key } ⋮---- order_id: string; // Order ID client_order_id?: string; // Client order ID (gateway/Inner Pay paths) payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB payment_receipt?: string; // Alias compatible with payment_receipt_file_key ⋮---- export interface CancelOTCOrderReq { order_id: string; // Order ID } ⋮---- order_id: string; // Order ID ⋮---- export interface GetOTCFiatOrderListReq { type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) fiat_currency?: string; // Fiat currency crypto_currency?: string; // Digital currency start_time?: string; // Start Time end_time?: string; // End time status?: string; // DONE: Completed pn?: string; // Page number ps?: string; // Number of items per page } ⋮---- type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) fiat_currency?: string; // Fiat currency crypto_currency?: string; // Digital currency start_time?: string; // Start Time end_time?: string; // End time status?: string; // DONE: Completed pn?: string; // Page number ps?: string; // Number of items per page ⋮---- export interface GetOTCStablecoinOrderListReq { page_size?: string; // Number of records per page page_number?: string; // Page number coin_name?: string; // Order currency start_time?: string; // Start Time end_time?: string; // End time status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed } ⋮---- page_size?: string; // Number of records per page page_number?: string; // Page number coin_name?: string; // Order currency start_time?: string; // Start Time end_time?: string; // End time status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed ⋮---- export interface GetOTCFiatOrderDetailReq { order_id: string; // Order ID } ⋮---- order_id: string; // Order ID ⋮---- export interface OTCBankIdReq { bank_id: string; } ⋮---- export interface GetOTCBankSupplementChecklistReq { bank_id: string; } ⋮---- export interface CreateOTCBankReq { bank_account_name: string; bank_name: string; bank_country: string; bank_address: string; iban: string; swift: string; remittance_line_number?: string; agent_bank_name?: string; agent_bank_swift?: string; documentation_file?: GateMultipartFile; documentation_file_key?: string; file_type?: string; } ⋮---- export interface SubmitOTCBankPersonalSupplementReq { bank_id: string; id_document_front: GateMultipartFile; id_document_back: GateMultipartFile; address_proof: GateMultipartFile; } ⋮---- export interface SubmitOTCBankEnterpriseSupplementReq { bank_id: string; certificate: GateMultipartFile; share_holders: GateMultipartFile; passport: GateMultipartFile; share_holding_structure: GateMultipartFile; uid?: string; funds_statement?: GateMultipartFile; additional?: GateMultipartFile; } ⋮---- export interface CreateOTCUploadPreUploadReq { content_type: string; scene: 'general' | 'bank' | 'assessment' | 'credit'; } ================ File: src/types/request/spot.ts ================ /**========================================================================================================================== * SPOT * ========================================================================================================================== */ ⋮---- /** Limit-order take-profit / stop-loss on create */ export interface SpotOrderTPSL { trigger_price: string; order_price: string; } ⋮---- /** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; ⋮---- export interface GetSpotOrderBookReq { currency_pair: string; interval?: string; limit?: number; with_id?: boolean; } ⋮---- export interface GetSpotTradesReq { currency_pair: string; limit?: number; last_id?: string; reverse?: boolean; from?: number; to?: number; page?: number; } ⋮---- export interface GetSpotCandlesReq { currency_pair: string; limit?: number; from?: number; to?: number; interval?: | '1s' | '10s' | '1m' | '5m' | '15m' | '30m' | '1h' | '4h' | '8h' | '1d' | '7d' | '30d'; } ⋮---- export interface GetSpotAccountBookReq { currency?: string; from?: number; to?: number; page?: number; limit?: number; /** * BizType / business type filter. Sub-account transfer internal BizType values include * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. */ type?: string; code?: string; } ⋮---- /** * BizType / business type filter. Sub-account transfer internal BizType values include * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. */ ⋮---- export interface SubmitSpotClosePosCrossDisabledReq { text?: string; currency_pair: string; amount: string; price: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- export interface GetSpotOrdersReq { currency_pair: string; status: 'open' | 'finished'; page?: number; limit?: number; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; from?: number; to?: number; side?: 'buy' | 'sell'; } ⋮---- export interface CancelSpotBatchOrdersReq { currency_pair: string; id: string; account?: 'cross_margin'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- export interface DeleteSpotOrderReq { order_id: string; currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; xGateExptime?: number; } ⋮---- export interface GetSpotOrderReq { order_id: string; currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; } ⋮---- export interface GetSpotTradingHistoryReq { currency_pair?: string; limit?: number; page?: number; order_id?: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; from?: number; to?: number; } ⋮---- export interface UpdateSpotBatchOrdersReq { order_id?: string; currency_pair?: string; amount?: string; price?: string; amend_text?: string; stop_loss?: PatchSpotOrderTPSL; stop_profit?: PatchSpotOrderTPSL; } ⋮---- export interface GetSpotInsuranceHistoryReq { business: 'margin' | 'unified'; currency: string; from: number; to: number; page?: number; limit?: number; } ⋮---- export interface GetSpotAutoOrdersReq { status: 'open' | 'finished'; market?: string; account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; limit?: number; offset?: number; } ⋮---- export interface SubmitSpotOrderReq { xGateExptime?: number; side: 'buy' | 'sell'; amount: string; text?: string; currency_pair: string; type?: 'limit' | 'market'; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; price?: string; time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; iceberg?: string; auto_borrow?: boolean; auto_repay?: boolean; stp_act?: string; action_mode?: string; stop_loss?: PatchSpotOrderTPSL; stop_profit?: PatchSpotOrderTPSL; post_only?: boolean; trade_quote?: string; } ⋮---- export interface UpdateSpotOrderReq { xGateExptime?: number; order_id: string; currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; amount?: string; price?: string; amend_text?: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; stop_loss?: PatchSpotOrderTPSL; stop_profit?: PatchSpotOrderTPSL; } ⋮---- /** GET /spot/pov_orders */ export interface GetSpotPovOrdersReq { status: 'open' | 'finished'; currency_pair?: string; side?: 'buy' | 'sell'; page?: number; limit?: number; } ⋮---- /** POST /spot/pov_orders */ export interface CreateSpotPovOrderReq { currency_pair: string; side: 'buy' | 'sell'; amount: string; participation_rate: 5 | 10 | 20 | 40; ttl: '1h' | '6h' | '12h' | '1d' | '2d' | '3d' | '4d' | '5d' | '6d' | '7d'; limit_price?: string; trigger_price?: string; text?: string; } ⋮---- /** DELETE /spot/pov_orders */ export interface CancelSpotPovOrdersReq { currency_pair?: string; } ================ File: src/types/request/tradfi.ts ================ /** TradFi API request types */ ⋮---- export interface TradFiGetSymbolDetailParams { symbols: string; } ⋮---- export interface TradFiGetKlinesParams { kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; begin_time?: number; end_time?: number; limit?: number; } ⋮---- export interface TradFiCreateTransactionReq { asset: string; change: string; type: 'deposit' | 'withdraw'; } ⋮---- export interface TradFiGetTransactionsParams { begin_time?: number; end_time?: number; type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; page?: number; page_size?: number; } ⋮---- export interface TradFiCreateOrderReq { price: string; price_type: 'trigger' | 'market'; side: 1 | 2; symbol: string; volume: string; price_tp?: string; price_sl?: string; leverage?: number; } ⋮---- export interface TradFiModifyOrderReq { price: string; price_tp?: string | null; price_sl?: string | null; } ⋮---- export interface TradFiModifyPositionReq { price_tp?: string | null; price_sl?: string | null; } ⋮---- export interface TradFiClosePositionReq { close_type: 1 | 2; close_volume?: string | null; } ⋮---- export interface TradFiGetOrderHistoryParams { begin_time?: number; end_time?: number; symbol?: string; side?: 1 | 2; } ⋮---- export interface TradFiGetPositionHistoryParams { begin_time?: number; end_time?: number; symbol?: string; position_dir?: 'Long' | 'Short'; page?: number; page_size?: number; } ⋮---- /** GET /tradfi/symbols/commissions */ export interface TradFiGetSymbolCommissionsParams { symbols?: string; category_code?: string; } ================ File: src/types/request/unified.ts ================ export interface SubmitUnifiedBorrowOrRepayReq { currency: string; type: 'borrow' | 'repay'; amount: string; repaid_all?: boolean; text?: string; } ⋮---- export interface GetUnifiedLoansReq { currency?: string; page?: number; limit?: number; type?: 'platform' | 'margin'; } ⋮---- export interface GetUnifiedLoanRecordsReq { type?: 'borrow' | 'repay'; currency?: string; page?: number; limit?: number; } export interface GetUnifiedInterestRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; type?: 'platform' | 'margin'; } ⋮---- export interface SetUnifiedAccountModeReq { mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; settings?: { usdt_futures?: boolean; spot_hedge?: boolean; use_funding?: boolean; options?: boolean; }; } ⋮---- export interface PortfolioMarginCalculatorReq { spot_balances?: { currency: string; equity: string; }[]; spot_orders?: { currency_pairs: string; order_price: string; count?: string; left: string; type: 'sell' | 'buy'; }[]; futures_positions?: { contract: string; size: string; }[]; futures_orders?: { contract: string; size: string; left: string; }[]; options_positions?: { options_name: string; size: string; }[]; options_orders?: { options_name: string; size: string; left: string; }[]; spot_hedge?: boolean; } ⋮---- export interface GetUnifiedHistoryLendingRateReq { currency: string; tier?: string; page?: number; limit?: number; } ⋮---- export interface SubmitUnifiedLoanRepayReq { currency: string; amount: string; currency_pair?: string; } ⋮---- export interface SetUnifiedCollateralCurrenciesReq { collateral_type?: 0 | 1; enable_list?: string[]; disable_list?: string[]; } ⋮---- export interface CreateQuickRepaymentReq { debt_currencies: string[]; available_currencies: string[]; } ⋮---- /** POST /unified/delta_neutral — v4.106.97 */ export interface SetUnifiedDeltaNeutralReq { enabled: boolean; } ⋮---- /** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ export interface SetUserLeverageReq { leverage?: string; } ================ File: src/types/request/wallet.ts ================ /** GET /wallet/sub_account_balances */ export interface GetSubAccountBalancesReq { sub_uid?: string; page?: number; limit?: number; } ⋮---- export interface GetWithdrawalDepositRecordsReq { currency?: string; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface SubmitTransferReq { currency: string; from: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; to: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; amount: string; currency_pair?: string; settle?: string; client_order_id?: string; } ⋮---- export interface GetMainSubTransfersReq { sub_uid?: string; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface GetSavedAddressReq { currency?: string; // v4.106.94: Optional filter by currency chain?: string; limit?: string; page?: number; verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter } ⋮---- currency?: string; // v4.106.94: Optional filter by currency ⋮---- verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter ⋮---- export interface GetSmallBalanceHistoryReq { currency?: string; page?: number; limit?: number; } ⋮---- export interface ListPushOrdersReq { id?: number; from?: number; to?: number; limit?: number; offset?: number; transaction_type?: string; } ⋮---- export interface SubmitSubToSubTransferReq { currency: string; sub_account_from: string; sub_account_from_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; sub_account_to: string; sub_account_to_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; amount: string; sub_account_type?: string; } ⋮---- export interface SubmitMainSubTransferReq { currency: string; sub_account: string; direction: 'to' | 'from'; amount: string; client_order_id?: string; sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- /** GET /wallet/transfers */ export interface GetTransferReq { tx_id: string; } ================ File: src/types/response/wallet.ts ================ export interface CurrencyChain { chain: string; name_cn: string; name_en: string; contract_address: string; is_disabled: number; is_deposit_disabled: number; is_withdraw_disabled: number; decimal: string; } ⋮---- /** GET /wallet/sub_account_balances item */ export interface SubAccountBalance { uid: string; available: { [key: string]: string }; /** Locked amount per currency */ locking?: { [key: string]: string }; } ⋮---- /** Locked amount per currency */ ⋮---- export interface DepositRecord { id: string; txid: string; timestamp: string; amount: string; currency: string; address: string; memo?: string; status: | 'BLOCKED' // Deposit Blocked | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock | 'DONE' // Funds Credited to Spot Account | 'INVALID' // Invalid Transaction | 'MANUAL' // Manual Review Required | 'PEND' // Processing | 'REVIEW' // Under Compliance Review | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit chain: string; refund_status?: // v4.106.95: Blocked deposit refund status 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; } ⋮---- | 'BLOCKED' // Deposit Blocked | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock | 'DONE' // Funds Credited to Spot Account | 'INVALID' // Invalid Transaction | 'MANUAL' // Manual Review Required | 'PEND' // Processing | 'REVIEW' // Under Compliance Review | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit ⋮---- refund_status?: // v4.106.95: Blocked deposit refund status ⋮---- export interface CreateDepositAddressResp { currency: string; address: string; multichain_addresses: { chain: string; address: string; payment_id: string; payment_name: string; obtain_failed: number; }[]; } ⋮---- export interface SubAccountTransferRecord { currency: string; sub_account: string; direction: 'to' | 'from'; amount: string; uid: string; client_order_id: string; timest: string; source: string; sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- export interface WithdrawalStatus { currency: string; name: string; name_cn: string; deposit: string; withdraw_percent: string; withdraw_fix: string; withdraw_day_limit: string; withdraw_amount_mini: string; withdraw_day_limit_remain: string; withdraw_eachtime_limit: string; withdraw_fix_on_chains: { [key: string]: string }; withdraw_percent_on_chains: { [key: string]: string }; } ⋮---- export interface SubAccountMarginBalance { currency_pair: string; locked: boolean; risk: string; base: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; quote: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; } ⋮---- export interface SubAccountFuturesBalancesResp { uid: string; available: { [key: string]: { total: string; unrealised_pnl: string; position_margin: string; order_margin: string; available: string; point: string; currency: string; in_dual_mode: boolean; enable_credit: boolean; position_initial_margin: string; maintenance_margin: string; bonus: string; enable_evolved_classic: boolean; cross_order_margin: string; cross_initial_margin: string; cross_maintenance_margin: string; cross_unrealised_pnl: string; cross_available: string; isolated_position_margin: string; history: { dnw: string; pnl: string; fee: string; refr: string; fund: string; point_dnw: string; point_fee: string; point_refr: string; bonus_dnw: string; bonus_offset: string; }; }; }; } ⋮---- export interface SubAccountCrossMarginBalancesResp { uid: string; available: { user_id: number; locked: boolean; balances: { [key: string]: { available: string; freeze: string; borrowed: string; interest: string; }; }; total: string; borrowed: string; borrowed_net: string; net: string; leverage: string; interest: string; risk: string; total_initial_margin: string; total_margin_balance: string; total_maintenance_margin: string; total_initial_margin_rate: string; total_maintenance_margin_rate: string; total_available_margin: string; }; } ⋮---- export interface SavedAddress { currency: string; chain: string; address: string; name: string; tag: string; verified: string; } ⋮---- export interface TradingFees { user_id: number; taker_fee: string; maker_fee: string; gt_discount: boolean; gt_taker_fee: string; gt_maker_fee: string; loan_fee: string; point_type: string; futures_taker_fee: string; futures_maker_fee: string; delivery_taker_fee: string; delivery_maker_fee: string; debit_fee: number; } ⋮---- export interface GetBalancesResp { total: { amount: string; currency: string; unrealised_pnl?: string; borrowed?: string; }; details: { [key: string]: { amount: string; currency: string; unrealised_pnl?: string; borrowed?: string; }; }; } ⋮---- export interface SmallBalanceRecord { currency: string; available_balance: string; estimated_as_btc: string; convertible_to_gt: string; } ⋮---- export interface SmallBalanceHistoryRecord { id: string; currency: string; amount: string; gt_amount: string; create_time: number; } ⋮---- export interface PushOrder { id: string; push_uid: number; receive_uid: number; currency: string; amount: string; create_time: number; status: | 'CREATING' | 'PENDING' | 'CANCELLING' | 'CANCELLED' | 'REFUSING' | 'REFUSED' | 'RECEIVING' | 'RECEIVED'; message: string; } ⋮---- /** GET /wallet/transfers — AccountTransferDetail */ export interface AccountTransferDetail { tx_id: string; status: 'pending' | 'success' | 'fail'; currency: string; amount: string; from_account: | 'spot' | 'margin' | 'futures' | 'delivery' | 'options' | 'unknown'; to_account: | 'spot' | 'margin' | 'futures' | 'delivery' | 'options' | 'unknown'; settle?: string | null; currency_pair?: string | null; } ================ File: src/types/websockets/client.ts ================ import type { ClientRequestArgs } from 'http'; import WebSocket from 'isomorphic-ws'; ⋮---- /** * Event args for subscribing/unsubscribing */ ⋮---- // export type WsTopicSubscribePrivateArgsV2 = // | WsTopicSubscribePrivateInstIdArgsV2 // | WsTopicSubscribePrivateCoinArgsV2; ⋮---- // export type WsTopicSubscribeEventArgsV2 = // | WsTopicSubscribePublicArgsV2 // | WsTopicSubscribePrivateArgsV2; ⋮---- /** General configuration for the WebsocketClient */ export interface WSClientConfigurableOptions { /** Your API key */ apiKey?: string; /** Your API secret */ apiSecret?: string; useTestnet?: boolean; /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ recvWindow?: number; /** How often to check if the connection is alive */ pingInterval?: number; /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ pongTimeout?: number; /** Delay in milliseconds before respawning the connection */ reconnectTimeout?: number; requestOptions?: {}; wsUrl?: string; wsOptions?: { protocols?: string[]; agent?: any; } & ( | Omit, 'agent'> | Omit, 'agent'> ); /** * 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; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- /** How often to check if the connection is alive */ ⋮---- /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- /** Delay in milliseconds before respawning the connection */ ⋮---- /** * 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. */ ⋮---- /** * 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; authPrivateConnectionsOnConnect: boolean; authPrivateRequests: boolean; reauthWSAPIOnReconnect: boolean; } ================ File: webpack/webpack.config.cjs ================ function generateConfig(name) ⋮---- // Add '.ts' and '.tsx' as resolvable extensions. ⋮---- // Node.js core modules not available in browsers // The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers ⋮---- // Code is already transpiled from TypeScript, no additional loaders needed ================ File: src/types/request/crossex.ts ================ /**========================================================================================================================== * CROSSEX * ========================================================================================================================== */ ⋮---- export interface GetCrossExSymbolsReq { symbols?: string; // Trading Pair List, multiple separated by commas } ⋮---- symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- export interface GetCrossExRiskLimitsReq { symbols: string; // Trading Pair List, multiple separated by commas } ⋮---- symbols: string; // Trading Pair List, multiple separated by commas ⋮---- export interface GetCrossExTransferCoinsReq { coin?: string; // Currency } ⋮---- coin?: string; // Currency ⋮---- export interface CreateCrossExTransferReq { coin: string; // Currency amount: string; // Transfer amount from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. to: string; text?: string; // User-defined ID } ⋮---- coin: string; // Currency amount: string; // Transfer amount from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. ⋮---- text?: string; // User-defined ID ⋮---- export interface GetCrossExTransferHistoryReq { coin?: string; // Query by specified currency name order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) from?: number; // Start timestamp for the query to?: number; // End timestamp for the query, defaults to current time if not specified page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 } ⋮---- coin?: string; // Query by specified currency name order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) from?: number; // Start timestamp for the query to?: number; // End timestamp for the query, defaults to current time if not specified page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 ⋮---- export interface CreateCrossExOrderReq { text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only symbol: string; // Unique identifier Exchange_Business_Base_Counter side: 'BUY' | 'SELL'; type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement qty?: string; // Order quantity (required unless spot market buy) price?: string; // Limit Order Price (Required for Limit Orders) quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders reduce_only?: 'true' | 'false'; // Reduce-only position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified } ⋮---- text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only symbol: string; // Unique identifier Exchange_Business_Base_Counter ⋮---- type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement qty?: string; // Order quantity (required unless spot market buy) price?: string; // Limit Order Price (Required for Limit Orders) quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders reduce_only?: 'true' | 'false'; // Reduce-only position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified ⋮---- export interface GetCrossExMarketTickersReq { symbols?: string; } ⋮---- export interface GetCrossExMarketFundingInfoReq { symbols?: string; } ⋮---- /** Either order_id or text required; order_id wins if both set */ export interface CancelBatchCrossExOrdersReq { order_id?: string; text?: string; } ⋮---- export interface ModifyCrossExOrderReq { qty?: string; // modify amount price?: string; // modify price } ⋮---- qty?: string; // modify amount price?: string; // modify price ⋮---- export interface CreateCrossExConvertQuoteReq { exchange_type: string; // Exchange Type from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) from_amount: string; // Amount to sell } ⋮---- exchange_type: string; // Exchange Type from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) from_amount: string; // Amount to sell ⋮---- export interface CreateCrossExConvertOrderReq { quote_id: string; // Inquiry ID } ⋮---- quote_id: string; // Inquiry ID ⋮---- export interface UpdateCrossExAccountReq { position_mode?: string; // Futures position mode (SINGLE/DUAL) account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) } ⋮---- position_mode?: string; // Futures position mode (SINGLE/DUAL) account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) ⋮---- export interface GetCrossExAccountsReq { exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) } ⋮---- exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) ⋮---- export interface SetCrossExPositionLeverageReq { symbol: string; // Currency pair leverage: string; // leverage } ⋮---- symbol: string; // Currency pair leverage: string; // leverage ⋮---- export interface GetCrossExPositionLeverageReq { symbols?: string; // Trading Pair List, multiple separated by commas } ⋮---- symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- export interface SetCrossExMarginPositionLeverageReq { symbol: string; // Currency pair leverage: string; // leverage } ⋮---- symbol: string; // Currency pair leverage: string; // leverage ⋮---- export interface GetCrossExMarginPositionLeverageReq { symbols?: string; // Trading Pair List, multiple separated by commas } ⋮---- symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- export interface CloseCrossExPositionReq { symbol: string; // Trading Pair position_side?: string; // Position Direction } ⋮---- symbol: string; // Trading Pair position_side?: string; // Position Direction ⋮---- export interface GetCrossExInterestRateReq { coin?: string; // Currency exchange_type?: string; // Exchange } ⋮---- coin?: string; // Currency exchange_type?: string; // Exchange ⋮---- export interface GetCrossExPositionsReq { symbol?: string; // Trading Pair exchange_type?: string; // Exchange } ⋮---- symbol?: string; // Trading Pair exchange_type?: string; // Exchange ⋮---- export interface GetCrossExMarginPositionsReq { symbol?: string; // Currency pair exchange_type?: string; // Exchange } ⋮---- symbol?: string; // Currency pair exchange_type?: string; // Exchange ⋮---- export interface GetCrossExAdlRankReq { symbol: string; // Trading Pair } ⋮---- symbol: string; // Trading Pair ⋮---- export interface GetCrossExOpenOrdersReq { symbol?: string; // Trading Pair exchange_type?: string; // Exchange business_type?: string; // Business Type } ⋮---- symbol?: string; // Trading Pair exchange_type?: string; // Exchange business_type?: string; // Business Type ⋮---- export interface GetCrossExHistoryOrdersReq { page?: number; // Page number limit?: number; // Maximum number of records returned in a single list symbol?: string; from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp /** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ attributes?: string; } ⋮---- page?: number; // Page number limit?: number; // Maximum number of records returned in a single list ⋮---- from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp /** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ ⋮---- export interface GetCrossExHistoryPositionsReq { page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 symbol?: string; from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp } ⋮---- page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 ⋮---- from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp ⋮---- export interface GetCrossExHistoryMarginPositionsReq { page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 symbol?: string; from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp } ⋮---- page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 ⋮---- from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp ⋮---- export interface GetCrossExHistoryMarginInterestsReq { symbol?: string; from?: number; to?: number; page?: number; limit?: number; exchange_type?: string; } ⋮---- export interface GetCrossExHistoryTradesReq { page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 symbol?: string; from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp } ⋮---- page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 ⋮---- from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp ⋮---- export interface GetCrossExAccountBookReq { page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 coin?: string; from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp } ⋮---- page?: number; // Page number limit?: number; // Maximum number returned by list, max 1000 ⋮---- from?: number; // Start Millisecond Timestamp to?: number; // End Millisecond Timestamp ⋮---- export interface GetCrossExCoinDiscountRateReq { coin?: string; exchange_type?: string; // OKX/GATE/BINANCE/BYBIT } ⋮---- exchange_type?: string; // OKX/GATE/BINANCE/BYBIT ⋮---- export interface UpdateCrossExPositionsMarginReq { symbol: string; margin: string; position_side?: 'NONE' | 'LONG' | 'SHORT'; } ================ File: src/types/response/crossex.ts ================ /**========================================================================================================================== * CROSSEX * ========================================================================================================================== */ ⋮---- export interface CrossExSymbol { symbol: string; exchange_type: string; business_type: string; state: string; min_size: string; min_notional: string; lot_size: string; tick_size: string; max_num_orders: string; max_market_size: string; max_limit_size: string; contract_size: string; liquidation_fee: string; delist_time: string; support_rpi?: string; // true/false whether RPI orders are supported support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders } ⋮---- support_rpi?: string; // true/false whether RPI orders are supported support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders ⋮---- export interface CrossExRiskLimitTier { min_risk_limit_value: string; // Minimum risk limit value max_risk_limit_value: string; // Maximum risk limit value leverage_max: string; // Maximum leverage maintenance_rate: string; // Maintenance margin rate tier: string; // Tier quick_cal_amount: string; // Quick-calculation amount for this risk tier } ⋮---- min_risk_limit_value: string; // Minimum risk limit value max_risk_limit_value: string; // Maximum risk limit value leverage_max: string; // Maximum leverage maintenance_rate: string; // Maintenance margin rate tier: string; // Tier quick_cal_amount: string; // Quick-calculation amount for this risk tier ⋮---- export interface CrossExRiskLimit { symbol: string; tiers: CrossExRiskLimitTier[]; } ⋮---- export interface CrossExTransferCoin { coin: string; // Currency min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) est_fee: number; // Estimated Fee precision: number; // Precision is_disabled: number; // If it is disabled. 0 means NOT being disabled } ⋮---- coin: string; // Currency min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) est_fee: number; // Estimated Fee precision: number; // Precision is_disabled: number; // If it is disabled. 0 means NOT being disabled ⋮---- export interface CreateCrossExTransferResp { tx_id: string; // Order ID text: string; // User-defined Order ID } ⋮---- tx_id: string; // Order ID text: string; // User-defined Order ID ⋮---- export interface CrossExTransferHistory { id: string; // Order ID text: string; // Client Custom ID from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) to_account_type: string; coin: string; // Currency amount: string; // Transfer amount, the amount requested for the transfer actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) create_time: number; // Creation time of order update_time: number; // Order Update Time } ⋮---- id: string; // Order ID text: string; // Client Custom ID from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) ⋮---- coin: string; // Currency amount: string; // Transfer amount, the amount requested for the transfer actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) create_time: number; // Creation time of order update_time: number; // Order Update Time ⋮---- export interface CreateCrossExOrderResp { order_id: number | string; text: string; // User-defined Order ID } ⋮---- text: string; // User-defined Order ID ⋮---- export interface CancelCrossExOrderResp { order_id: number; text: string; } ⋮---- export interface ModifyCrossExOrderResp { order_id: number; text: string; } ⋮---- export interface CrossExOrder { user_id: string; // User ID order_id: string; // Order ID text: string; // Client Order ID state: string; // Order Status symbol: string; // Currency pair side: string; // direction type: string; // type attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT exchange_type: string; // Exchange business_type: string; // Business Type qty: string; // Base Currency Quantity quote_qty: string; // Quote Currency Quantity price: string; // Price time_in_force: string; // Time in Force Strategy executed_qty: string; // Filled Quantity executed_amount: string; // Filled Amount executed_avg_price: string; // Average Filled Price fee_coin: string; // Fee currency fee: string; // fee reduce_only: string; // Reduce Position Only leverage: string; // leverage reason: string; // Reason last_executed_qty: string; // Latest Filled Quantity last_executed_price: string; // Latest Filled Price last_executed_amount: string; // Latest Filled Amount position_side: string; // Position Direction create_time: string; // Created time update_time: string; // Update time } ⋮---- user_id: string; // User ID order_id: string; // Order ID text: string; // Client Order ID state: string; // Order Status symbol: string; // Currency pair side: string; // direction type: string; // type attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT exchange_type: string; // Exchange business_type: string; // Business Type qty: string; // Base Currency Quantity quote_qty: string; // Quote Currency Quantity price: string; // Price time_in_force: string; // Time in Force Strategy executed_qty: string; // Filled Quantity executed_amount: string; // Filled Amount executed_avg_price: string; // Average Filled Price fee_coin: string; // Fee currency fee: string; // fee reduce_only: string; // Reduce Position Only leverage: string; // leverage reason: string; // Reason last_executed_qty: string; // Latest Filled Quantity last_executed_price: string; // Latest Filled Price last_executed_amount: string; // Latest Filled Amount position_side: string; // Position Direction create_time: string; // Created time update_time: string; // Update time ⋮---- export interface CreateCrossExConvertQuoteResp { quote_id: string; // Quote ID valid_ms: string; // Valid time (milliseconds timestamp) from_coin: string; // Asset Sold to_coin: string; // Asset Bought from_amount: string; // Amount to sell to_amount: string; // Amount to buy price: string; // Price } ⋮---- quote_id: string; // Quote ID valid_ms: string; // Valid time (milliseconds timestamp) from_coin: string; // Asset Sold to_coin: string; // Asset Bought from_amount: string; // Amount to sell to_amount: string; // Amount to buy price: string; // Price ⋮---- export interface CreateCrossExConvertOrderResp { order_id: string; // Order ID text: string; // User-defined order ID text } ⋮---- order_id: string; // Order ID text: string; // User-defined order ID text ⋮---- export interface UpdateCrossExAccountResp { position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) } ⋮---- position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) ⋮---- export interface CrossExAccountAsset { user_id: string; // User ID coin: string; // Currency exchange_type: string; // Exchange balance: string; // Balance upnl: string; // Unrealized P&L equity: string; // Equity (only USDT has a value; other assets are 0) futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) available_balance: string; // Available Balance liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) } ⋮---- user_id: string; // User ID coin: string; // Currency exchange_type: string; // Exchange balance: string; // Balance upnl: string; // Unrealized P&L equity: string; // Equity (only USDT has a value; other assets are 0) futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) available_balance: string; // Available Balance liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) ⋮---- export interface CrossExAccount { user_id: string; // User ID available_margin: string; // Available Margin margin_balance: string; // margin balance initial_margin: string; // Initial Margin maintenance_margin: string; // Maintenance margin initial_margin_rate: string; // Initial margin rate maintenance_margin_rate: string; // Maintenance margin rate position_mode: string; // Contract Position Mode account_limit: string; // Account limit create_time: string; // Created time update_time: string; // Update time account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange assets: CrossExAccountAsset[]; } ⋮---- user_id: string; // User ID available_margin: string; // Available Margin margin_balance: string; // margin balance initial_margin: string; // Initial Margin maintenance_margin: string; // Maintenance margin initial_margin_rate: string; // Initial margin rate maintenance_margin_rate: string; // Maintenance margin rate position_mode: string; // Contract Position Mode account_limit: string; // Account limit create_time: string; // Created time update_time: string; // Update time account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange ⋮---- export interface SetCrossExPositionLeverageResp { symbol: string; // Currency pair leverage: string; // Requested Modified Leverage } ⋮---- symbol: string; // Currency pair leverage: string; // Requested Modified Leverage ⋮---- export interface CrossExPositionLeverage { symbol: string; // Currency pair leverage: number | string; } ⋮---- symbol: string; // Currency pair ⋮---- export interface SetCrossExMarginPositionLeverageResp { symbol: string; // Currency pair leverage: string; // Requested Modified Leverage } ⋮---- symbol: string; // Currency pair leverage: string; // Requested Modified Leverage ⋮---- export interface CrossExMarginPositionLeverage { symbol: string; // Currency pair leverage: number | string; } ⋮---- symbol: string; // Currency pair ⋮---- export interface CloseCrossExPositionResp { order_id: string; // Order ID text: string; // User-defined Order ID } ⋮---- order_id: string; // Order ID text: string; // User-defined Order ID ⋮---- export interface CrossExInterestRate { coin: string; // Currency exchange_type: string; // Exchange hour_interest_rate: string; // Hourly Interest Rate time: string; // Millisecond Timestamp } ⋮---- coin: string; // Currency exchange_type: string; // Exchange hour_interest_rate: string; // Hourly Interest Rate time: string; // Millisecond Timestamp ⋮---- export interface CrossExSpecialFee { symbol: string; // Currency pair taker_fee_rate: string; // Taker fee rate maker_fee_rate: string; // Maker fee rate rpi_fee_rate?: string; // RPI order maker fee rate } ⋮---- symbol: string; // Currency pair taker_fee_rate: string; // Taker fee rate maker_fee_rate: string; // Maker fee rate rpi_fee_rate?: string; // RPI order maker fee rate ⋮---- export interface CrossExFeeRate { exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) spot_maker_fee: string; // spot Maker fee rate spot_taker_fee: string; // spot Taker fee rate spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate future_maker_fee: string; // contract Maker fee rate future_taker_fee: string; // contract Taker fee rate future_rpi_maker_fee?: string; // Futures RPI order maker fee rate special_fee_list: CrossExSpecialFee[]; } ⋮---- exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) spot_maker_fee: string; // spot Maker fee rate spot_taker_fee: string; // spot Taker fee rate spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate future_maker_fee: string; // contract Maker fee rate future_taker_fee: string; // contract Taker fee rate future_rpi_maker_fee?: string; // Futures RPI order maker fee rate ⋮---- export interface CrossExMarketTicker { symbol: string; last_price: string; open_24h: string; low_24h: string; high_24h: string; volume_24h_base: string; volume_24h_quote: string; mark_price: string; index_price: string; open_interest: string; open_interest_quote: string; timestamp: string; } ⋮---- export interface CrossExMarketFundingInfo { symbol: string; funding_rate: string; funding_interval: string; funding_time: string; // Next funding time } ⋮---- funding_time: string; // Next funding time ⋮---- export interface CancelBatchCrossExOrdersResp { order_id: string; text: string; accepted: string; // "true" | "false" label: string; message: string; } ⋮---- accepted: string; // "true" | "false" ⋮---- export interface CrossExPosition { user_id: string; // User ID position_id: string; // Position ID symbol: string; // Currency pair position_side: string; // Position Direction initial_margin: string; // Initial Margin maintenance_margin: string; // Maintenance margin position_qty: string; // Position Quantity position_value: string; // Position Value upnl: string; // Unrealized P&L upnl_rate: string; // Unrealized P&L Ratio entry_price: string; // Position Average Entry Price mark_price: string; // Mark price leverage: string; // Position Leverage max_leverage: string; // Maximum leverage risk_limit: string; // Position risk limit fee: string; // Position Fee funding_fee: string; // Position Funding Fee funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) create_time: string; // Position Creation Time update_time: string; // Position Update Time closed_pnl: string; // Realized PnL } ⋮---- user_id: string; // User ID position_id: string; // Position ID symbol: string; // Currency pair position_side: string; // Position Direction initial_margin: string; // Initial Margin maintenance_margin: string; // Maintenance margin position_qty: string; // Position Quantity position_value: string; // Position Value upnl: string; // Unrealized P&L upnl_rate: string; // Unrealized P&L Ratio entry_price: string; // Position Average Entry Price mark_price: string; // Mark price leverage: string; // Position Leverage max_leverage: string; // Maximum leverage risk_limit: string; // Position risk limit fee: string; // Position Fee funding_fee: string; // Position Funding Fee funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) create_time: string; // Position Creation Time update_time: string; // Position Update Time closed_pnl: string; // Realized PnL ⋮---- export interface CrossExMarginPosition { user_id: string; // User ID position_id: string; // Leveraged Position ID symbol: string; // Trading Pair position_side: string; // Position Direction initial_margin: string; // Initial position margin maintenance_margin: string; // Position maintenance margin asset_qty: string; // Position Asset Quantity asset_coin: string; // Position Asset Currency position_value: string; // Position Value liability: string; // Debt Quantity liability_coin: string; // Debt Currency interest: string; // Deducted Interest max_position_qty: string; // Max Trade Size entry_price: string; // Position Cost Price (Average Opening Price) index_price: string; // Index price upnl: string; // Unrealized P&L upnl_rate: string; // Unrealized P&L Ratio leverage: string; // Opening Leverage max_leverage: string; // Maximum leverage create_time: string; // Created time update_time: string; // Update time } ⋮---- user_id: string; // User ID position_id: string; // Leveraged Position ID symbol: string; // Trading Pair position_side: string; // Position Direction initial_margin: string; // Initial position margin maintenance_margin: string; // Position maintenance margin asset_qty: string; // Position Asset Quantity asset_coin: string; // Position Asset Currency position_value: string; // Position Value liability: string; // Debt Quantity liability_coin: string; // Debt Currency interest: string; // Deducted Interest max_position_qty: string; // Max Trade Size entry_price: string; // Position Cost Price (Average Opening Price) index_price: string; // Index price upnl: string; // Unrealized P&L upnl_rate: string; // Unrealized P&L Ratio leverage: string; // Opening Leverage max_leverage: string; // Maximum leverage create_time: string; // Created time update_time: string; // Update time ⋮---- export interface CrossExAdlRank { user_id: string; // User ID symbol: string; // Currency pair crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) } ⋮---- user_id: string; // User ID symbol: string; // Currency pair crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) ⋮---- export interface CrossExHistoryPosition { position_id: string; // Position ID user_id: string; // User ID symbol: string; // Currency pair closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) closed_pnl: string; // Close Position P&L closed_pnl_rate: string; // Close Position P&L Ratio open_avg_price: string; // Average Opening Price closed_avg_price: string; // Average Close Price max_position_qty: string; // Max Trade Size closed_qty: string; // Close Position Quantity closed_value: string; // Close Position Value fee: string; // Position Accumulated Fees liq_fee: string; // Liquidation Fee funding_fee: string; // Funding Fee position_side: string; // Position Direction Before Close position_mode: string; // Position Mode at Close leverage: string; // Leverage at Close margin_mode?: 'CROSS' | 'ISOLATED'; business_type: string; // Business Type create_time: string; // Created time update_time: string; // Update time } ⋮---- position_id: string; // Position ID user_id: string; // User ID symbol: string; // Currency pair closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) closed_pnl: string; // Close Position P&L closed_pnl_rate: string; // Close Position P&L Ratio open_avg_price: string; // Average Opening Price closed_avg_price: string; // Average Close Price max_position_qty: string; // Max Trade Size closed_qty: string; // Close Position Quantity closed_value: string; // Close Position Value fee: string; // Position Accumulated Fees liq_fee: string; // Liquidation Fee funding_fee: string; // Funding Fee position_side: string; // Position Direction Before Close position_mode: string; // Position Mode at Close leverage: string; // Leverage at Close ⋮---- business_type: string; // Business Type create_time: string; // Created time update_time: string; // Update time ⋮---- export interface CrossExHistoryMarginPosition { position_id: string; // Position ID user_id: string; // User ID symbol: string; // Currency pair closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) closed_pnl: string; // Close Position P&L closed_pnl_rate: string; // Close Position P&L Ratio open_avg_price: string; // Average Opening Price closed_avg_price: string; // Average Close Price max_position_qty: string; // Max Trade Size closed_qty: string; // Close Position Quantity closed_value: string; // Close Position Value liq_fee: string; // Liquidation Fee position_side: string; // Position Direction Before Close leverage: string; // Leverage at Close interest: string; // Total Deducted Interest business_type: string; // Position Business Type create_time: string; // Created time update_time: string; // Update time } ⋮---- position_id: string; // Position ID user_id: string; // User ID symbol: string; // Currency pair closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) closed_pnl: string; // Close Position P&L closed_pnl_rate: string; // Close Position P&L Ratio open_avg_price: string; // Average Opening Price closed_avg_price: string; // Average Close Price max_position_qty: string; // Max Trade Size closed_qty: string; // Close Position Quantity closed_value: string; // Close Position Value liq_fee: string; // Liquidation Fee position_side: string; // Position Direction Before Close leverage: string; // Leverage at Close interest: string; // Total Deducted Interest business_type: string; // Position Business Type create_time: string; // Created time update_time: string; // Update time ⋮---- export interface CrossExHistoryMarginInterest { userId: string; // User ID symbol: string; // Trading Pair interest_id: string; // Interest Deduction ID liability_id: string; // Debt Source ID, can be Order ID or Position ID liability: string; // Debt Quantity liability_coin: string; // Debt Currency interest: string; // Interest interest_rate: string; // interest rate interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) create_time: string; // Created time exchange_type: string; // Exchange } ⋮---- userId: string; // User ID symbol: string; // Trading Pair interest_id: string; // Interest Deduction ID liability_id: string; // Debt Source ID, can be Order ID or Position ID liability: string; // Debt Quantity liability_coin: string; // Debt Currency interest: string; // Interest interest_rate: string; // interest rate interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) create_time: string; // Created time exchange_type: string; // Exchange ⋮---- export interface CrossExHistoryTrade { user_id: string; // User ID transaction_id: string; // filled records ID order_id: string; // Order ID text: string; // User Order ID symbol: string; // Currency pair exchange_type: string; // Exchange business_type: string; // Business Type side: string; // Buy/Sell Direction qty: string; // Trading size price: string; // Fill Price fee: string; // fee fee_coin: string; // Fee currency fee_rate: string; // Fee Rate match_role: string; // Filled Role rpnl: string; // Realized P&L position_mode: string; // Position Mode position_side: string; // Position Direction create_time: string; // Created time } ⋮---- user_id: string; // User ID transaction_id: string; // filled records ID order_id: string; // Order ID text: string; // User Order ID symbol: string; // Currency pair exchange_type: string; // Exchange business_type: string; // Business Type side: string; // Buy/Sell Direction qty: string; // Trading size price: string; // Fill Price fee: string; // fee fee_coin: string; // Fee currency fee_rate: string; // Fee Rate match_role: string; // Filled Role rpnl: string; // Realized P&L position_mode: string; // Position Mode position_side: string; // Position Direction create_time: string; // Created time ⋮---- export interface CrossExAccountBook { id: string; // Account Change Record ID user_id: string; // User ID business_id: string; // Business ID type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY exchange_type: string; // Exchange coin: string; // Currency change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) balance: string; // Balance after change create_time: string; // Created time } ⋮---- id: string; // Account Change Record ID user_id: string; // User ID business_id: string; // Business ID type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY exchange_type: string; // Exchange coin: string; // Currency change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) balance: string; // Balance after change create_time: string; // Created time ⋮---- export interface CrossExCoinDiscountRate { coin: string; // Currency exchange_type: string; // Exchange tier: string; // Tier min_value: string; // Minimum value max_value: string; // Maximum value discount_rate: string; // Discount rate } ⋮---- coin: string; // Currency exchange_type: string; // Exchange tier: string; // Tier min_value: string; // Minimum value max_value: string; // Maximum value discount_rate: string; // Discount rate ⋮---- export interface UpdateCrossExPositionsMarginResp { symbol?: string; margin?: string; position_side?: 'NONE' | 'LONG' | 'SHORT'; } ================ File: src/types/response/earn.ts ================ /**========================================================================================================================== * EARN * ========================================================================================================================== */ ⋮---- export interface DualInvestmentProduct { id: number; instrument_name: string; invest_currency: string; exercise_currency: string; exercise_price: number; delivery_time: number; min_amount?: string; min_copies: number; max_copies: number; /** @deprecated */ per_value: string; apy_display: string; start_time: number; end_time: number; status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; } ⋮---- /** @deprecated */ ⋮---- /** GET /earn/dual/order-refund-preview */ export interface DualOrderRefundPreview { create_timest: number; delivery_timest: number; exercise_price: string; invest_amount: string; invest_currency: string; name: string; order_id: number; req_id: string; refund_service_charge: number; settle_price: string; settlement_amount: string; settlement_currency: string; settlement_interest: string; settlement_principle: string; type: string; money_back_timest: number; } ⋮---- /** GET /earn/dual/project-recommend item */ export interface DualProjectRecommend { id: number; category: number; type: string; invest_currency: string; exercise_currency: string; apy_display: string; exercise_price: string; delivery_timest: number; min_amount: string; max_amount: string; min_copies: number; max_copies: number; invest_days: number; invest_hours: string; } ⋮---- export interface DualInvestmentOrder { id: number; plan_id: number; copies: string; invest_amount: string; settlement_amount: string; create_time: number; complete_time: number; status: | 'INIT' | 'SETTLEMENT_SUCCESS' | 'SETTLEMENT_PROCESSING' | 'CANCELED' | 'FAILED'; invest_currency: string; exercise_currency: string; exercise_price: string; settlement_price: string; settlement_currency: string; apy_display: string; apy_settlement: string; delivery_time: number; text: string; } ⋮---- /**========================================================================================================================== * EARN FIXED-TERM * ========================================================================================================================== */ ⋮---- export interface FixedTermLadderApr { apr: string; left: string; right: string; } ⋮---- export interface FixedTermProductInfo { pre_redeem: number; reinvest: number; redeem_account: number; min_vip: number; max_vip: number; } ⋮---- export interface FixedTermBonusInfo { id?: number; product_id?: number; asset?: string; bonus_asset?: string; kyc_limit?: string; ladder_apr?: FixedTermLadderApr[]; total_bonus_amount?: string; user_total_bonus_amount?: string; status?: number; start_time?: string; end_time?: string; create_time?: string; start_at?: number; end_at?: number; total_issued_amount?: string; user_total_issued_amount?: string; bonus_asset_price?: string; product_asset_price?: string; product_year_rate?: string; } ⋮---- export interface FixedTermCouponInfo { id?: number; business?: number; user_id?: number; asset?: string; order_id?: number; financial_rate_id?: number; buy_limit_low?: string; buy_limit_high?: string; rate_day?: number; rate_ratio?: string; coupon_days?: number; coupon_principal?: string; coupon_year_rate?: string; coupon_interest?: string; status?: number; finish_time?: string; create_time?: string; } ⋮---- export interface FixedTermLendOrder { id?: number; business?: number; order_id?: number; user_id?: number; asset?: string; product_id?: number; lock_up_period?: number; principal?: string; year_rate?: string; product_type?: number; interest?: string; status?: number; reinvest_status?: number; redeem_account_type?: number; origin_order?: string; redeem_type?: number; redeem_time?: string; finish_time?: string; create_time?: string; year_rate_perent?: string; total_year_rate_percent?: string; total_interest?: string; product_info?: FixedTermProductInfo; bonus_info?: FixedTermBonusInfo; coupon_info?: FixedTermCouponInfo; redeem_at?: number; finish_at?: number; create_at?: number; icon?: string; } ⋮---- export interface FixedTermProduct { id?: number; name?: string; asset?: string; lock_up_period?: number; min_lend_amount?: string; user_max_lend_amount?: string; total_lend_amount?: string; year_rate?: string; type?: number; pre_redeem?: number; reinvest?: number; redeem_account?: number; min_vip?: number; max_vip?: number; status?: number; create_time?: string; user_max_lend_volume?: string; user_total_amount?: string; sale_status?: number; } ⋮---- export interface FixedTermProductSimple { id?: number; asset?: string; lock_up_period?: number; year_rate?: string; type?: number; pre_redeem?: number; reinvest?: number; simple_earn?: number; min_vip?: number; max_vip?: number; sale_status?: number; } ⋮---- export interface GetEarnFixedTermProductsResponse { code: number; message: string; data: { list: FixedTermProduct[]; total: number; }; timestamp: number; } ⋮---- export interface GetEarnFixedTermProductsByAssetResponse { code: number; message: string; data: { list: FixedTermProductSimple[]; }; timestamp: number; } ⋮---- export interface CreateEarnFixedTermLendResponse { code?: number; message?: string; data?: { order_id?: number; }; timestamp?: number; } ⋮---- export interface GetEarnFixedTermLendsResponse { code: number; message: string; data: { list: FixedTermLendOrder[]; total: number; }; timestamp: number; } ⋮---- export interface CreateEarnFixedTermPreRedeemResponse { code?: number; message?: string; data?: Record; timestamp?: number; } ⋮---- export interface FixedTermHistoryRecord { id?: number; order_id?: number; user_id?: number; asset?: string; uniq_time?: string; bonus_id?: number; product_id?: number; bonus_asset?: string; total_principal?: string; amount?: string; asset_price?: string; status?: number; detail?: string; create_time?: string; create_at?: number; lock_up_period?: number; } ⋮---- export interface GetEarnFixedTermHistoryResponse { code?: number; message?: string; data?: { list?: FixedTermHistoryRecord[]; total?: number; }; timestamp?: number; } ================ File: src/types/response/otc.ts ================ /**========================================================================================================================== * OTC * ========================================================================================================================== */ ⋮---- export interface OTCActionResp { code: number; message: string; timestamp: number; } ⋮---- export interface CreateOTCQuoteResp { code: number; message: string; data: { type: string; // BUY (on-ramp) or SELL (off-ramp) pay_coin: string; get_coin: string; pay_amount: string; get_amount: string; rate: string; rate_reci: string; // Reciprocal of the exchange rate promotion_code: string; side: string; order_type: string; // FIAT or STABLE quote_token: string; // Quote token required when placing an order url?: string; memo?: string; has_signature?: string; validity_period?: string; ex_rate?: string; usdc_rate?: string; is_need_file?: string; gate_bank_id?: string; gate_bank_name?: string; refresh_limit?: number; refresh_limit_msg?: string; }; timestamp: number; } ⋮---- type: string; // BUY (on-ramp) or SELL (off-ramp) ⋮---- rate_reci: string; // Reciprocal of the exchange rate ⋮---- order_type: string; // FIAT or STABLE quote_token: string; // Quote token required when placing an order ⋮---- export type CreateOTCFiatOrderResp = OTCActionResp; ⋮---- export interface CreateOTCStablecoinOrderResp { code: number; message: string; timestamp: number; } ⋮---- export interface OTCBankListItem { id: string; // Bank ID (required for order placement) bank_account_name: string; bank_name: string; bank_country?: string; bank_address?: string; bank_code?: string; branch_code?: string; iban?: string; swift?: string; remittance_line_number?: string; agent_bank_name?: string; agent_bank_swift?: string; submit_time?: string; update_time?: string; status?: string; documentation_file_type?: string; memo?: string; /** 1 = default bank card, 0 = not default */ is_default?: 0 | 1; bank_id?: string; documentation_file_key_url?: string; } ⋮---- id: string; // Bank ID (required for order placement) ⋮---- /** 1 = default bank card, 0 = not default */ ⋮---- export interface GetOTCBankListResp { code: number; message: string; data: { lists: OTCBankListItem[]; }; timestamp: number; } ⋮---- export interface CreateOTCBankResp { code: number; message: string; data: { bank_id: number; status: number; }; timestamp?: number; } ⋮---- export interface OTCBankSupplementChecklistItem { description: string; code?: string; zh?: string; en?: string; required?: boolean; } ⋮---- export interface GetOTCBankSupplementChecklistResp { code: number; message: string; data: { user_type: 'personal' | 'enterprise'; items: OTCBankSupplementChecklistItem[]; }; timestamp?: number; } ⋮---- export type MarkOTCOrderAsPaidResp = OTCActionResp; ⋮---- export type CancelOTCOrderResp = OTCActionResp; ⋮---- export interface OTCFiatOrderListItem { time: string; // Current time timestamp: number; // Current timestamp order_id: string; trade_no: string; // Trade number type: string; // Quote direction buy/sell/all status: string; // Order Status (includes DISBURSED) db_status: string; fiat_currency: string; // Fiat type fiat_currency_info: { name: string; icon: string; }; fiat_amount: string; // Fiat amount crypto_currency: string; // Stablecoin crypto_currency_info: { name: string; icon: string; }; crypto_amount: string; // Stablecoin amount rate: string; // Exchange rate transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders gate_bank_account_iban: string; // Bank account promotion_code: string; // Promotion code } ⋮---- time: string; // Current time timestamp: number; // Current timestamp ⋮---- trade_no: string; // Trade number type: string; // Quote direction buy/sell/all status: string; // Order Status (includes DISBURSED) ⋮---- fiat_currency: string; // Fiat type ⋮---- fiat_amount: string; // Fiat amount crypto_currency: string; // Stablecoin ⋮---- crypto_amount: string; // Stablecoin amount rate: string; // Exchange rate transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders gate_bank_account_iban: string; // Bank account promotion_code: string; // Promotion code ⋮---- export interface GetOTCFiatOrderListResp { code: number; message: string; data: { pn: number; ps: number; total_pn: number; count: number; list: OTCFiatOrderListItem[]; }; } ⋮---- export interface OTCStablecoinOrderListItem { id: number; // Order ID trade_no: string; // Transaction reference number pay_coin: string; // Payment currency pay_amount: string; // Payment amount get_coin: string; // Received currency get_amount: string; // Received amount rate: string; // Exchange rate rate_reci: string; // Reciprocal of the exchange rate status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed create_timest: number; // Timestamp create_time: string; // Created time pay_icon?: string; get_icon?: string; } ⋮---- id: number; // Order ID trade_no: string; // Transaction reference number pay_coin: string; // Payment currency pay_amount: string; // Payment amount get_coin: string; // Received currency get_amount: string; // Received amount rate: string; // Exchange rate rate_reci: string; // Reciprocal of the exchange rate status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed create_timest: number; // Timestamp create_time: string; // Created time ⋮---- export interface GetOTCStablecoinOrderListResp { code: number; message: string; data: { total: number; page_size: number; page_number: number; total_page: number; list: OTCStablecoinOrderListItem[]; }; } ⋮---- export interface OTCFiatOrderDetail { order_id: string; // Order ID uid: string; // User ID type: string; // Order Type fiat_currency: string; // Fiat type fiat_amount: string; // Fiat amount crypto_currency: string; // Stablecoin crypto_amount: string; // Stablecoin amount rate: string; // Exchange rate transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders status: string; // Status db_status: string; create_time: string; // Created time memo: string; // Cancellation or rejection reason side: string; // Quote direction promotion_code: string; // Promotion code trade_no: string; // Trade number } ⋮---- order_id: string; // Order ID uid: string; // User ID type: string; // Order Type fiat_currency: string; // Fiat type fiat_amount: string; // Fiat amount crypto_currency: string; // Stablecoin crypto_amount: string; // Stablecoin amount rate: string; // Exchange rate transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders status: string; // Status ⋮---- create_time: string; // Created time memo: string; // Cancellation or rejection reason side: string; // Quote direction promotion_code: string; // Promotion code trade_no: string; // Trade number ⋮---- export interface GetOTCFiatOrderDetailResp { message: string; code: number; data: OTCFiatOrderDetail; } ⋮---- export interface CreateOTCUploadPreUploadFields { key?: string; content_type?: string; x_amz_credential?: string; x_amz_algorithm?: string; x_amz_date?: string; policy?: string; x_amz_signature?: string; } ⋮---- export interface CreateOTCUploadPreUploadData { file_key?: string; url?: string; fields?: CreateOTCUploadPreUploadFields; expires_in?: number; } ⋮---- export interface CreateOTCUploadPreUploadResp { code?: number; message?: string; timestamp?: number; data?: CreateOTCUploadPreUploadData; } ================ File: src/types/response/tradfi.ts ================ /** TradFi API response types */ ⋮---- export interface TradFiApiResp { timestamp?: number; data?: T; code?: number; message?: string; label?: string; } ⋮---- export interface TradFiListData { list?: T[]; total?: number; total_page?: number; } ⋮---- export interface TradFiMT5Account { mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility leverage?: number; stop_out_level?: string; status?: number; } ⋮---- mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- export interface TradFiCategoryItem { category_id?: number; is_favorite?: boolean; category_name?: string; } ⋮---- export interface TradFiSymbolItem { symbol?: string; symbol_desc?: string; category_id?: number; status?: string; trade_mode?: string; icon_link?: string; close_time?: number; open_time?: number; next_open_time?: number; settlement_currency?: string; settlement_currency_symbol?: string; price_precision?: number; } ⋮---- export interface TradFiSymbolDetailItem { symbol?: string; symbol_desc?: string; category_name?: string; contract_volume?: string; settlement_currency?: string; max_order_volume?: string; min_order_volume?: string; leverage?: string; price_precision?: number; price_sl_level?: string; swap_cost_type?: string; buy_swap_cost_rate?: string; sell_swap_cost_rate?: string; swap_cost_3day?: string; trade_timezone?: string; trade_mode?: string; icon_link?: string; [key: string]: unknown; } ⋮---- export interface TradFiKlineItem { o?: string; c?: string; h?: string; l?: string; t?: number; } ⋮---- export interface TradFiTicker { highest_price?: string; lowest_price?: string; price_change?: string; price_change_amount?: string; today_open_price?: string; last_today_close_price?: string; last_price?: string; bid_price?: string; ask_price?: string; favorite?: boolean; status?: string; close_time?: number; open_time?: number; next_open_time?: number; trade_mode?: string; category_name?: string; } ⋮---- export interface TradFiCreateUserResult { status?: number; leverage?: number; mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility } ⋮---- mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- export interface TradFiAssets { equity?: string; margin_level?: string; balance?: string; margin?: string; margin_free?: string; unrealized_pnl?: string; mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility } ⋮---- mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- export interface TradFiTransactionRecord { asset?: string; type?: string; type_desc?: string; change?: string; balance?: string; time?: number; } ⋮---- export interface TradFiTransactionListData { total?: number; total_page?: number; list?: TradFiTransactionRecord[]; } ⋮---- export interface TradFiCreateOrderResult { id?: string; } ⋮---- export interface TradFiOrderItem { order_id?: number; symbol?: string; symbol_desc?: string; price_type?: string; state?: number; state_desc?: string; finished?: number; side?: number; volume?: string; price?: string; price_tp?: string; price_sl?: string; time_setup?: number; } ⋮---- export interface TradFiOrderListData { list?: TradFiOrderItem[]; timestamp?: number; } ⋮---- export interface TradFiModifyOrderResult { order_id?: number; symbol?: string; state?: string; volume?: string; price?: string; price_tp?: string; price_sl?: string; } ⋮---- export interface TradFiOrderHistoryItem { order_id?: number; symbol?: string; symbol_desc?: string; price_type?: string; order_opt_type?: number; state?: number; state_desc?: string; side?: number; volume?: string; fill_volume?: string; close_pnl?: string; price?: string; trigger_price?: string; price_tp?: string; price_sl?: string; time_setup?: number; time_done?: number; } ⋮---- export interface TradFiPositionItem { position_id?: number; symbol?: string; symbol_desc?: string; margin?: string; unrealized_pnl?: string; unrealized_pnl_rate?: string; volume?: string; price_open?: string; position_dir?: string; price_tp?: string; price_sl?: string; counterparty_price?: string; time_create?: number; } ⋮---- export interface TradFiPositionListData { list?: TradFiPositionItem[]; timestamp?: number; } ⋮---- export interface TradFiPositionHistoryItem { position_id?: number; symbol?: string; realized_pnl?: string; realized_pnl_rate?: string; volume?: string; volume_closed?: string; price_open?: string; position_dir?: string; price_tp?: string; price_sl?: string; counterparty_price?: string; close_price?: string; time_create?: string; time_close?: string; position_status?: string; close_detail?: Record | null; realized_pnl_detail?: { closed_pnl?: string; swap?: string; fee?: string; }; } ⋮---- /** GET /tradfi/orders/log/{log_id} — v4.106.94 */ export interface TradFiOrderLog { order_id?: number; log_id?: number; symbol?: string; price_type?: 'market' | 'trigger'; state?: number; side?: number; volume?: string; price?: string; [key: string]: unknown; } ⋮---- export interface TradFiSymbolCommissionItem { category_code?: string; symbol?: string; fee_per_lot?: string; } ================ File: src/index.ts ================ // Request Types ⋮---- // Response Types ⋮---- // Websockets Types ⋮---- // Shared Types ================ File: src/types/request/futures.ts ================ /**========================================================================================================================== * FUTURES * ========================================================================================================================== */ ⋮---- export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; ⋮---- export interface GetFuturesOrderBookReq { settle: FuturesSettle; contract: string; interval?: string; limit?: number; with_id?: boolean; } ⋮---- export interface GetFuturesTradesReq { settle: FuturesSettle; contract: string; limit?: number; offset?: number; last_id?: string; from?: number; to?: number; } ⋮---- export interface GetFuturesCandlesReq { settle: FuturesSettle; contract: string; from?: number; to?: number; limit?: number; interval?: string; } ⋮---- export interface GetFuturesStatsReq { settle: FuturesSettle; contract: string; from?: number; interval?: string; limit?: number; } ⋮---- export interface GetFundingRatesReq { settle: FuturesSettle; contract: string; limit?: number; from?: number; to?: number; } ⋮---- export interface BatchFundingRatesReq { settle: 'btc' | 'usdt' | 'usd1'; contracts: string[]; } ⋮---- export interface GetLiquidationHistoryReq { settle: FuturesSettle; contract?: string; from?: number; to?: number; limit?: number; } ⋮---- export interface GetRiskLimitTiersReq { settle: FuturesSettle; contract: string; limit?: number; offset?: number; } ⋮---- export interface GetRiskLimitTableReq { settle: FuturesSettle; table_id: string; } ⋮---- export interface GetFuturesAccountBookReq { settle: FuturesSettle; contract?: string; limit?: number; offset?: number; from?: number; to?: number; type?: | 'dnw' | 'pnl' | 'fee' | 'refr' | 'fund' | 'point_dnw' | 'point_fee' | 'point_refr' | 'bonus_offset'; } ⋮---- export interface GetFuturesADLRiskStatesReq { settle: 'btc' | 'usdt' | 'usd1'; } ⋮---- export interface GetFuturesPositionsReq { settle: FuturesSettle; holding?: boolean; limit?: number; // deprecated, use positions_limit instead positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 offset?: number; position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter } ⋮---- limit?: number; // deprecated, use positions_limit instead positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 ⋮---- position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter ⋮---- export interface UpdateDualModePositionMarginReq { settle: FuturesSettle; contract: string; change: string; dual_side: 'dual_long' | 'dual_short'; } ⋮---- export interface UpdateDualModePositionLeverageReq { settle: FuturesSettle; contract: string; leverage: string; cross_leverage_limit?: string; } ⋮---- export interface SubmitFuturesOrderReq { xGateExptime?: number; settle: FuturesSettle; contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: string; text?: string; auto_size?: string; stp_act?: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; tpsl_tp_trigger_price?: string; tpsl_sl_trigger_price?: string; pos_margin_mode?: 'isolated' | 'cross'; } ⋮---- export interface GetFuturesOrdersReq { settle: FuturesSettle; contract?: string; status: string; limit?: number; offset?: number; last_id?: string; } ⋮---- export interface DeleteAllFuturesOrdersReq { xGateExptime?: number; settle: FuturesSettle; contract: string; side?: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- export interface GetFuturesOrdersByTimeRangeReq { settle: FuturesSettle; contract?: string; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface UpdateFuturesOrderReq { xGateExptime?: number; settle: FuturesSettle; order_id: string; size?: number; price?: string; amend_text?: string; } ⋮---- export interface GetFuturesTradingHistoryReq { settle: FuturesSettle; contract?: string; order?: number; limit?: number; offset?: number; last_id?: string; } ⋮---- export interface GetFuturesTradingHistoryByTimeRangeReq { settle: FuturesSettle; contract?: string; from?: number; to?: number; limit?: number; offset?: number; role?: 'maker' | 'taker'; } ⋮---- export interface GetFuturesPositionHistoryReq { settle: FuturesSettle; contract?: string; limit?: number; offset?: number; from?: number; to?: number; side?: 'long' | 'short'; pnl?: string; } ⋮---- export interface GetFuturesLiquidationHistoryReq { settle: FuturesSettle; contract?: string; limit?: number; at?: number; } ⋮---- export interface SubmitFuturesTriggeredOrderReq { initial: { contract: string; size?: number; /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ amount?: string; price: string; // Required: Order price. Set to 0 to use market price close?: boolean; tif?: 'gtc' | 'ioc'; text?: string; reduce_only?: boolean; auto_size?: string; }; trigger: { strategy_type?: 0 | 1; price_type?: 0 | 1 | 2; price: string; // Required: Price value for price trigger rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) expiration?: number; }; order_type?: | 'close-long-order' | 'close-short-order' | 'close-long-position' | 'close-short-position' | 'plan-close-long-position' | 'plan-close-short-position'; settle: FuturesSettle; } ⋮---- /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ ⋮---- price: string; // Required: Order price. Set to 0 to use market price ⋮---- price: string; // Required: Price value for price trigger rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) ⋮---- export interface GetFuturesAutoOrdersReq { settle: FuturesSettle; status: 'open' | 'finished'; contract?: string; limit?: number; offset?: number; } ⋮---- /** * Modify contract order parameters */ export interface BatchAmendOrderReq { order_id?: number; // Order id, order_id and text must contain at least one text?: string; // User-defined order text, at least one of order_id and text must be passed size?: number; // The new order size, including the executed order size price?: string; // New order price amend_text?: string; // Custom info during amending order } ⋮---- order_id?: number; // Order id, order_id and text must contain at least one text?: string; // User-defined order text, at least one of order_id and text must be passed size?: number; // The new order size, including the executed order size price?: string; // New order price amend_text?: string; // Custom info during amending order ⋮---- // v4.105.8: New GET /futures/{settle}/position_close_history endpoint request export interface GetFuturesPositionCloseHistoryReq { settle: FuturesSettle; contract?: string; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- // v4.104.6: New GET /futures/{settle}/insurance endpoint request export interface GetFuturesInsuranceReq { settle: FuturesSettle; limit?: number; } ⋮---- export interface UpdateFuturesPriceTriggeredOrderReq { settle: FuturesSettle; order_id: number | string; contract?: string; size?: number; /** Same semantics as `size` (decimal contract size) */ amount?: string; price?: string; /** When fully closing in single-position mode, set true */ close?: boolean; trigger_price?: string; price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price auto_size?: string; // Not required in single position mode } ⋮---- /** Same semantics as `size` (decimal contract size) */ ⋮---- /** When fully closing in single-position mode, set true */ ⋮---- price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price auto_size?: string; // Not required in single position mode ⋮---- /** GET /futures/{settle}/get_leverage/{contract} — v4.106.43: pos_margin_mode and dual_side required */ export interface GetFuturesContractLeverageReq { settle: FuturesSettle; contract: string; pos_margin_mode: 'isolated' | 'cross'; dual_side: 'dual_long' | 'dual_short'; } ⋮---- /** Trail order (autoorder/v1/trail) request types */ export interface CreateTrailOrderReq { settle: 'btc' | 'usdt'; contract: string; amount: string; activation_price?: string; is_gte?: boolean; price_type?: 1 | 2 | 3; price_offset?: string; reduce_only?: boolean; position_related?: boolean; text?: string; pos_margin_mode?: string; position_mode?: string; } ⋮---- export interface TerminateTrailOrderReq { settle: 'btc' | 'usdt'; id?: number; text?: string; } ⋮---- export interface BatchTerminateTrailOrdersReq { settle: 'btc' | 'usdt'; contract?: string; related_position?: 1 | 2; } ⋮---- export interface GetTrailOrderListReq { settle: 'btc' | 'usdt'; contract?: string; is_finished?: boolean; start_at?: number; end_at?: number; page_num?: number; page_size?: number; sort_by?: 1 | 2; hide_cancel?: boolean; related_position?: 1 | 2; sort_by_trigger?: boolean; reduce_only?: 1 | 2; side?: 1 | 2; } ⋮---- export interface GetTrailOrderDetailReq { settle: 'btc' | 'usdt'; id: number; } ⋮---- export interface UpdateTrailOrderReq { settle: 'btc' | 'usdt'; id: number; amount?: string; activation_price?: string; is_gte_str?: string; price_type?: 0 | 1 | 2 | 3; price_offset?: string; } ⋮---- export interface GetTrailOrderChangeLogReq { settle: 'btc' | 'usdt'; id: number; page_num?: number; page_size?: number; } ⋮---- /** Chase limit order (autoorder/v1/chase) request types */ export interface CreateChaseOrderReq { settle: FuturesSettle; contract: string; amount: string; price_limit: string; offset_limit?: string; reduce_only?: boolean; text?: string; is_dual_mode?: boolean; price_type?: number; price_gap_type?: number; price_gap_value?: string; pos_margin_mode?: 'isolated' | 'cross' | string; position_mode?: string; } ⋮---- export interface StopChaseOrderReq { settle: FuturesSettle; id?: string; text?: string; } ⋮---- export interface StopAllChaseOrdersReq { settle: FuturesSettle; contract?: string; pos_margin_mode?: 'isolated' | 'cross' | string; } ⋮---- export interface GetChaseOrdersReq { settle: FuturesSettle; contract?: string; is_finished?: boolean; start_at?: number; end_at?: number; page_num?: number; page_size?: number; /** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ sort_by: 1 | 2; hide_cancel?: boolean; reduce_only?: 0 | 1 | 2; side?: 0 | 1 | 2; } ⋮---- /** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ ⋮---- export interface GetChaseOrderDetailReq { settle: FuturesSettle; id: string; } ================ File: src/types/response/spot.ts ================ /**========================================================================================================================== * SPOT * ========================================================================================================================== */ ⋮---- /** Limit-order take-profit / stop-loss on order responses (not re-exported; use request types for submits) */ interface SpotOrderTPSL { trigger_price: string; order_price: string; } ⋮---- /** `{}` cancels TP/SL; `null` leaves unchanged */ type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; ⋮---- export interface SpotCurrencyChain { name: string; addr?: string; withdraw_disabled: boolean; withdraw_delayed: boolean; deposit_disabled: boolean; } ⋮---- export interface SpotCurrency { currency: string; name: string; delisted: boolean; withdraw_disabled: boolean; withdraw_delayed: boolean; deposit_disabled: boolean; trade_disabled: boolean; chain: string; chains: SpotCurrencyChain[]; /** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ category?: string[]; } ⋮---- /** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ ⋮---- export interface SpotTicker { currency_pair: string; last: string; lowest_ask: string; lowest_size: string; highest_bid: string; highest_size: string; change_percentage: string; change_utc0: string; change_utc8: string; base_volume: string; quote_volume: string; high_24h: string; low_24h: string; etf_net_value: string; etf_pre_net_value: string | null; etf_pre_timestamp: number | null; etf_leverage: string | null; } ⋮---- export interface SpotOrderBook { id?: number; current: number; update: number; asks: [string, string][]; bids: [string, string][]; } ⋮---- export interface SpotTrade { id: string; create_time: string; create_time_ms: string; currency_pair: string; side: 'buy' | 'sell'; role: 'taker' | 'maker'; amount: string; price: string; order_id: string; fee: string; fee_currency: string; point_fee: string; gt_fee: string; amend_text: string; sequence_id: string; text: string; trade_quote?: string; } ⋮---- export type SpotCandle = [ string, // Unix timestamp with second precision string, // Trading volume in quote currency string, // Closing price string, // Highest price string, // Lowest price string, // Opening price string, // Trading volume in base currency boolean, // Whether the window is closed ]; ⋮---- string, // Unix timestamp with second precision string, // Trading volume in quote currency string, // Closing price string, // Highest price string, // Lowest price string, // Opening price string, // Trading volume in base currency boolean, // Whether the window is closed ⋮---- export interface SpotFeeRates { user_id: number; taker_fee: string; // For spot trading maker_fee: string; // For spot trading gt_discount: boolean; gt_taker_fee: string; gt_maker_fee: string; loan_fee: string; point_type: string; currency_pair: string; debit_fee: number; } ⋮---- taker_fee: string; // For spot trading maker_fee: string; // For spot trading ⋮---- export interface SpotAccount { currency: string; available: string; locked: string; update_id: number; refresh_time: number; last_update_time?: number; trading_fee_rate?: string; } ⋮---- export interface SpotAccountBook { id: string; time: number; currency: string; change: string; balance: string; type: string; code: string; text: string; } ⋮---- export interface SubmitSpotBatchOrdersResp { order_id: string; amend_text: string; text: string; succeeded: boolean; label: string; message: string; id: string; create_time: string; update_time: string; create_time_ms: number; update_time_ms: number; status: 'open' | 'closed' | 'cancelled'; currency_pair: string; type: 'limit' | 'market'; account: 'spot' | 'margin' | 'cross_margin' | 'unified'; side: 'buy' | 'sell'; amount: string; price: string; time_in_force: 'gtc' | 'ioc' | 'poc' | 'fok'; iceberg: string; auto_repay: boolean; left: string; filled_amount: string; fill_price: string; filled_total: string; avg_deal_price: string; fee: string; fee_currency: string; point_fee: string; gt_fee: string; gt_discount: boolean; rebated_fee: string; rebated_fee_currency: string; stp_id: number; stp_act: 'cn' | 'co' | 'cb' | '-'; /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; } ⋮---- /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ ⋮---- export interface SpotOrder { id?: string; text?: string; amend_text?: string; create_time?: string; update_time?: string; create_time_ms?: number; update_time_ms?: number; status?: 'open' | 'closed' | 'cancelled'; currency_pair: string; type?: 'limit' | 'market'; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; side: 'buy' | 'sell'; amount: string; price?: string; time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; iceberg?: string; auto_borrow?: boolean; auto_repay?: boolean; left?: string; filled_amount?: string; fill_price?: string; filled_total?: string; avg_deal_price?: string; fee?: string; fee_currency?: string; point_fee?: string; gt_fee?: string; gt_maker_fee?: string; gt_taker_fee?: string; gt_discount?: boolean; rebated_fee?: string; rebated_fee_currency?: string; stp_id?: number; stp_act?: 'cn' | 'co' | 'cb' | '-'; /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; stop_loss?: PatchSpotOrderTPSL; stop_profit?: PatchSpotOrderTPSL; trade_quote?: string; } ⋮---- /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ ⋮---- export interface SpotInsuranceHistory { currency: string; balance: string; time: number; } ⋮---- export interface SpotPriceTriggeredOrder { trigger: { price: string; rule: '>=' | '<='; expiration?: number; }; put: { type?: 'limit' | 'market'; side: 'buy' | 'sell'; price: string; amount: string; account: 'normal' | 'margin' | 'cross_margin'; time_in_force: 'gtc' | 'ioc'; text?: string; }; id?: number; user?: number; market: string; ctime?: number; ftime?: number; fired_order_id?: number; status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; reason?: string; } ⋮---- export interface GetSpotOpenOrdersResp { currency_pair: string; total: number; orders: SpotOrder[]; } ⋮---- export interface DeleteSpotBatchOrdersResp { currency_pair: string; id: string; succeeded: boolean; label: string; message: string; account: string; text: string; } ⋮---- export interface SpotHistoricTradeRecord { id: string; create_time: string; create_time_ms: string; currency_pair: string; side: 'buy' | 'sell'; role: 'taker' | 'maker'; amount: string; price: string; order_id: string; fee: string; fee_currency: string; point_fee: string; gt_fee: string; amend_text: string; sequence_id: string; text: string; deal?: string; // v4.105.29: Total Executed Value trade_quote?: string; } ⋮---- deal?: string; // v4.105.29: Total Executed Value ⋮---- export type SpotPovOrderStatus = | 'CREATED' | 'CANCELING' | 'RUNNING' | 'COMPLETED' | 'EXPIRED' | 'TERMINATED'; ⋮---- export interface SpotPovOrder { id?: string; currency_pair?: string; side?: string; amount?: string; participation_rate?: number; ttl?: string; limit_price?: string; trigger_price?: string; status?: SpotPovOrderStatus | string; terminated_as?: string; start_time_ms?: number; end_time_ms?: number; expire_time_ms?: number; create_time_ms?: number; update_time_ms?: number; text?: string; } ================ File: src/types/response/unified.ts ================ export interface UnifiedAccountInfo { mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin user_id: number; refresh_time: number; locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin balances: { [key: string]: { available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode total_freeze: string; // Total frozen (deprecated, to be removed) total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin funding_version: string; // Funding version cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled balance_version?: number; // Balance version number (int64) }; }; total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled margin_mode?: string; total_balance?: string; cross_leverage?: string; portfolio_margin?: string; risk_level?: string; is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all borrow_amount?: string; cross_margin_leverage?: string; use_funding?: boolean; // Whether Earn funds are used as margin } ⋮---- mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin ⋮---- locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin ⋮---- available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode total_freeze: string; // Total frozen (deprecated, to be removed) total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin funding_version: string; // Funding version cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled balance_version?: number; // Balance version number (int64) ⋮---- total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled ⋮---- is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all ⋮---- use_funding?: boolean; // Whether Earn funds are used as margin ⋮---- export interface UnifiedLoan { currency: string; currency_pair: string; amount: string; type: 'platform' | 'margin'; create_time: number; update_time: number; } ⋮---- export interface UnifiedLoanRecord { id: number; type: 'borrow' | 'repay'; repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; currency_pair: string; currency: string; amount: string; create_time: number; borrow_type: string; } export interface UnifiedInterestRecord { currency: string; currency_pair: string; actual_rate: string; interest: string; status: number; type: 'platform' | 'margin'; create_time: number; } ⋮---- export interface UnifiedRiskUnitDetails { user_id: number; spot_hedge: boolean; risk_units: { symbol: string; spot_in_use: string; maintain_margin: string; initial_margin: string; delta: string; gamma: string; theta: string; vega: string; }[]; } ⋮---- export interface UnifiedCurrencyDiscountTiers { currency: string; discount_tiers: { tier: string; discount: string; lower_limit: string; upper_limit: string; leverage: string; }[]; } ⋮---- export interface UserCurrencyLeverageConfig { current_leverage: string; min_leverage: string; max_leverage: string; debit: string; available_margin: string; borrowable: string; except_leverage_borrowable: string; } ⋮---- export interface UnifiedLoanCurrency { name: string; prec: string; min_borrow_amount: string; user_max_borrow_amount: string; total_max_borrow_amount: string; loan_status: string; } ⋮---- export interface UnifiedHistoryLendingRate { currency: string; tier: string; tier_up_rate: string; rates: { time: number; rate: string; }[]; } ⋮---- export interface MarginTier { tier: string; margin_rate: string; lower_limit: string; upper_limit: string; } ⋮---- export interface PortfolioMarginCalculation { maintain_margin_total: string; initial_margin_total: string; calculate_time: number; risk_unit: { symbol: string; spot_in_use: string; maintain_margin: string; initial_margin: string; margin_result: { type: | 'original_position' | 'long_delta_original_position' | 'short_delta_original_position'; profit_loss_ranges: { price_percentage: string; implied_volatility_percentage: string; profit_loss: string; }[]; max_loss: { price_percentage: string; implied_volatility_percentage: string; profit_loss: string; }; mr1: string; mr2: string; mr3: string; mr4: string; delta: string; gamma: string; theta: string; vega: string; }[]; }[]; } ⋮---- export interface UnifiedCollateralCurrenciesResp { is_success: boolean; } ⋮---- export interface UnifiedQuickRepayDebtItem { currency?: string; debt_amount?: string; estimated_usd?: string; borrowed?: string; neg_balance?: string; } ⋮---- export interface UnifiedQuickRepayAvailableItem { currency?: string; available?: string; estimated_usd?: string; } ⋮---- export interface QuickEstimatedRepayment { debt_currencies?: UnifiedQuickRepayDebtItem[]; available_currencies?: UnifiedQuickRepayAvailableItem[]; } ⋮---- export interface QuickRepayRepaidInfo { currency: string; repaid: string; left: string; } ⋮---- export interface QuickRepayUsedInfo { currency: string; used: string; } ⋮---- export interface QuickRepaymentResp { order_id: string; repaid_infos: QuickRepayRepaidInfo[]; used_infos: QuickRepayUsedInfo[]; } ⋮---- /** GET/POST /unified/delta_neutral — v4.106.97 */ export interface DeltaNeutralEnabled { enabled: boolean; } ⋮---- /** POST /unified/leverage/user_setting failed currency entry */ export interface LeverageFailedCurrency { currency: string; reason: string; } ================ File: src/lib/BaseRestClient.ts ================ import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; // NOTE: https.Agent is Node.js-only and not available in browser environments // Browser builds (via webpack) exclude this module - see webpack.config.js fallback settings import https from 'https'; ⋮---- import { neverGuard } from './misc-util.js'; import { CHANNEL_ID, getRestBaseUrl, RestClientOptions, serializeParams, } from './requestUtils.js'; import { checkWebCryptoAPISupported, hashMessage, SignAlgorithm, SignEncodeMethod, signMessage, } from './webCryptoAPI.js'; ⋮---- /** * Used to switch how authentication/requests work under the hood */ ⋮---- export type RestClientType = (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- interface SignedRequest { originalParams: T; paramsWithSign?: T & { sign: string }; serializedParams: string; sign: string; queryParamsWithSign: string; timestamp: number; recvWindow: number; } ⋮---- interface UnsignedRequest { originalParams: T; paramsWithSign: T; } ⋮---- type SignMethod = 'gateV4'; ⋮---- /** * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. * This type anticipates these are possible in any combination. * * The request builder will automatically handle where parameters should go. */ type ParamsInQueryBodyOrHeader = { query?: object; body?: object; headers?: object; /** multipart/form-data body; mutually exclusive with `body` */ multipart?: FormData; }; ⋮---- /** multipart/form-data body; mutually exclusive with `body` */ ⋮---- /** * Enables: * - Detailed request/response logging * - Full request dump in any exceptions thrown from API responses */ ⋮---- // request: { // url: response.config.url, // method: response.config.method, // data: response.config.data, // headers: response.config.headers, // }, ⋮---- /** * Impure, mutates params to remove any values that have a key but are undefined. */ function deleteUndefinedValues(params?: any): void ⋮---- export abstract class BaseRestClient ⋮---- /** Defines the client type (affecting how requests & signatures behave) */ abstract getClientType(): RestClientType; ⋮---- /** * Create an instance of the REST client. Pass API credentials in the object in the first parameter. * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios */ constructor( restClientOptions: RestClientOptions = {}, networkOptions: AxiosRequestConfig = {}, ) ⋮---- /** Throw errors if any request params are empty */ ⋮---- /** in ms == 5 minutes by default */ ⋮---- /** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ ⋮---- // If enabled, configure a https agent with keepAlive enabled // NOTE: This is Node.js-only functionality. In browser environments, this code is skipped // as the 'https' module is excluded via webpack fallback configuration. // Browser connection pooling is handled automatically by the browser itself. ⋮---- // Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- // For more advanced configuration, raise an issue on GitHub or use the "networkOptions" // parameter to define a custom httpsAgent with the desired properties ⋮---- // Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- // Throw if one of the 3 values is missing, but at least one of them is set ⋮---- /** * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism */ getSignTimestampMs(): number ⋮---- protected get(endpoint: string, params?: object) ⋮---- // GET only supports params in the query string ⋮---- protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- protected getPrivate(endpoint: string, params?: object) ⋮---- // GET only supports params in the query string ⋮---- protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- /** POST private endpoint with multipart/form-data (empty body hash for signing) */ protected postPrivateMultipart( endpoint: string, formData: FormData, query?: object, ) ⋮---- protected deletePrivate( endpoint: string, params?: ParamsInQueryBodyOrHeader, ) ⋮---- protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- // protected patchPrivate(endpoint: string, params?: any) { protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- /** * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. */ private async _call( method: Method, endpoint: string, params?: ParamsInQueryBodyOrHeader, isPublicApi?: boolean, ): Promise ⋮---- // Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- // Build a request and handle signature process ⋮---- // Dispatch request ⋮---- // See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- // Throw API rejections by parsing the response code from the body ⋮---- /** * @private generic handler to parse request exceptions */ parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- // Something happened in setting up the request that triggered an error ⋮---- // request made but no response received ⋮---- // The request was made and the server responded with a status code // that falls out of the range of 2xx ⋮---- // console.error('err: ', response?.data); ⋮---- // Prevent credentials from leaking into error messages ⋮---- /** * @private sign request and set recv window */ private async signRequest< T extends ParamsInQueryBodyOrHeader | undefined = {}, >( data: T, endpoint: string, method: Method, signMethod: SignMethod, ): Promise> ⋮---- const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- // recvWindow: this.options.recvWindow, ⋮---- // It's possible to override the recv window on a per rquest level ⋮---- // console.log('sign params: ', { // requestBodyToHash, // paramsStr: toSign, // url: this.baseUrl, // urlPath: this.baseUrlPath, // }); ⋮---- private async signMessage( paramsStr: string, secret: string, method: 'hex' | 'base64', algorithm: SignAlgorithm, ): Promise ⋮---- private async prepareSignParams< TParams extends ParamsInQueryBodyOrHeader | undefined, >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: true, ): Promise>; ⋮---- private async prepareSignParams< TParams extends ParamsInQueryBodyOrHeader | undefined, >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: false | undefined, ): Promise>; ⋮---- private async prepareSignParams< TParams extends ParamsInQueryBodyOrHeader | undefined, >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: boolean, ) ⋮---- /** Returns an axios request object. Handles signing process automatically if this is a private API call */ private async buildRequest( method: Method, endpoint: string, url: string, params?: ParamsInQueryBodyOrHeader, isPublicApi?: boolean, ): Promise ================ File: src/types/response/futures.ts ================ /**========================================================================================================================== * FUTURES * ========================================================================================================================== */ ⋮---- export interface FuturesOrderBook { id?: number; current: number; update: number; asks: { p: string; s: number }[]; bids: { p: string; s: number }[]; } ⋮---- export interface FuturesTrade { id: number; create_time: number; create_time_ms: number; contract: string; size: number; price: string; is_internal?: boolean; // Deprecated } ⋮---- is_internal?: boolean; // Deprecated ⋮---- export interface FuturesCandle { t: number; v?: number; c: string; h: string; l: string; o: string; sum: string; } ⋮---- export interface PremiumIndexKLine { t: number; c: string; h: string; l: string; o: string; } ⋮---- export interface FuturesTicker { contract: string; last: string; change_percentage: string; total_size: string; low_24h: string; high_24h: string; volume_24h: string; volume_24h_btc?: string; volume_24h_usd?: string; volume_24h_base: string; volume_24h_quote: string; volume_24h_settle: string; mark_price: string; funding_rate: string; funding_rate_indicative: string; index_price: string; quanto_base_rate?: string; // Deprecated basis_rate: string; basis_value: string; lowest_ask: string; highest_bid: string; lowest_size: string; highest_size: string; } ⋮---- quanto_base_rate?: string; // Deprecated ⋮---- export interface BatchFundingRatesResponse { contract?: string; data?: { t: number; r: string }[]; } ⋮---- export interface FuturesStats { time: number; lsr_taker: number; lsr_account: number; long_liq_size: number; long_liq_amount: number; long_liq_usd: number; long_liq_usd_new?: number; short_liq_size: number; short_liq_amount: number; short_liq_usd: number; short_liq_usd_new?: number; open_interest: number; open_interest_usd: number; top_lsr_account: number; top_lsr_size: number; top_long_size?: number; top_short_size?: number; long_taker_size?: number; short_taker_size?: number; top_long_account?: number; top_short_account?: number; long_users?: number; short_users?: number; } ⋮---- export interface IndexConstituents { index: string; constituents: { exchange: string; symbols: string[]; }[]; } ⋮---- export interface LiquidationHistoryRecord { time: number; contract: string; size: number; order_size: number; order_price: string; fill_price: string; left: number; } ⋮---- export interface RiskLimitTier { tier: number; risk_limit: string; initial_rate: string; maintenance_rate: string; // First-tier maintenance margin rate requirement leverage_max: string; contract: string; } ⋮---- maintenance_rate: string; // First-tier maintenance margin rate requirement ⋮---- export interface FuturesAccount { total: string; // Balance, only applicable to classic contract account unrealised_pnl: string; position_margin?: string; // Deprecated order_margin: string; // Initial margin for all pending orders available: string; point: string; currency: string; in_dual_mode: boolean; position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) enable_credit: boolean; position_initial_margin: string; maintenance_margin: string; bonus: string; enable_evolved_classic?: boolean; // Deprecated cross_order_margin: string; cross_initial_margin: string; cross_maintenance_margin: string; cross_unrealised_pnl: string; cross_available: string; cross_margin_balance: string; cross_mmr: string; cross_imr: string; isolated_position_margin: string; enable_new_dual_mode?: boolean; // Deprecated margin_mode: number; // 0: classic future account or Classic Spot Margin Mode of unified account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode history: { dnw: string; pnl: string; fee: string; refr: string; fund: string; point_dnw: string; point_fee: string; point_refr: string; bonus_dnw: string; bonus_offset: string; }; enable_tiered_mm: boolean; funding_balance?: string; } ⋮---- total: string; // Balance, only applicable to classic contract account ⋮---- position_margin?: string; // Deprecated order_margin: string; // Initial margin for all pending orders ⋮---- position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) ⋮---- enable_evolved_classic?: boolean; // Deprecated ⋮---- enable_new_dual_mode?: boolean; // Deprecated margin_mode: number; // 0: classic future account or Classic Spot Margin Mode of unified account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode ⋮---- export interface FuturesAccountBookRecord { time: number; change: string; balance: string; type: string; text: string; contract?: string; trade_id: string; id: string; } ⋮---- export interface FuturesOrder { id?: number; user?: number; create_time?: number; finish_time?: number; /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ finish_as?: | 'filled' | 'cancelled' | 'liquidated' | 'ioc' | 'poc' | 'auto_deleveraged' | 'reduce_only' | 'position_closed' | 'stp'; status?: 'open' | 'finished'; contract: string; size: number; iceberg?: number; price?: string; close?: boolean; is_close?: boolean; reduce_only?: boolean; is_reduce_only?: boolean; is_liq?: boolean; tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; left?: number; fill_price?: string; text?: string; tkfr?: string; mkfr?: string; refu?: number; auto_size?: 'close_long' | 'close_short'; stp_id?: number; stp_act?: 'cn' | 'co' | 'cb' | '-'; amend_text?: string; biz_info?: string; /** Read-only; order notional in settle currency (API response only; omit from order requests). */ order_value?: string; /** Read-only; traded value (API response only; omit from order requests). */ trade_value?: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; tpsl_tp_trigger_price?: string; tpsl_sl_trigger_price?: string; tpsl_tp_bbo_type?: string; // v4.106.93: BBO price type for take-profit leg tpsl_sl_bbo_type?: string; // v4.106.93: BBO price type for stop-loss leg pos_margin_mode?: string; } ⋮---- /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ ⋮---- /** Read-only; order notional in settle currency (API response only; omit from order requests). */ ⋮---- /** Read-only; traded value (API response only; omit from order requests). */ ⋮---- tpsl_tp_bbo_type?: string; // v4.106.93: BBO price type for take-profit leg tpsl_sl_bbo_type?: string; // v4.106.93: BBO price type for stop-loss leg ⋮---- /** Item shape for `GET /futures/{settle}/orders_timerange` (differs from {@link FuturesOrder} in field types). */ export interface FuturesOrderTimerange { id?: number; user?: number; create_time?: number; update_time?: string; finish_time?: string; contract: string; size: string; iceberg?: string; is_close?: boolean; is_reduce_only?: boolean; is_liq?: boolean; left?: string; fill_price?: string; tkfr?: string; mkfr?: string; refu?: number; amend_text?: string; pid?: number; market_order_slip_ratio?: string; pos_margin_mode?: string; } ⋮---- export interface FuturesPosition { user?: number; contract?: string; size?: number; leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode risk_limit?: string; leverage_max?: string; // Max leverage based on current position size maintenance_rate?: string; // Tiered maintenance margin rate calculation value?: string; margin?: string; entry_price?: string; liq_price?: string; // Estimated liquidation price for reference only liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management mark_price?: string; initial_margin?: string; // Expanded scope description maintenance_margin?: string; // Expanded scope description unrealised_pnl?: string; realised_pnl?: string; // Detailed breakdown including settlement, funding fees, and trading fees pnl_pnl?: string; // Settlement P&L pnl_fund?: string; // Funding fee P&L pnl_fee?: string; // Total trading fees history_pnl?: string; // All historical settlement P&L last_close_pnl?: string; realised_point?: string; history_point?: string; adl_ranking?: number; pending_orders?: number; close_order?: { id?: number; price?: string; is_liq?: boolean; } | null; mode?: 'single' | 'dual_long' | 'dual_short'; cross_leverage_limit?: string; // Simplified description update_time?: number; update_id?: number; open_time?: number; settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support isolated_margin?: string; // v4.104.6: Add isolated_margin field pid?: number; // v4.106.0: Sub-position ID hedge_status?: 'partial_hedged' | 'full_hedged'; // v4.106.97: Delta-neutral hedging status hedged_size?: string; // v4.106.97: Hedged size under Delta-neutral strategy unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy } ⋮---- leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode ⋮---- leverage_max?: string; // Max leverage based on current position size maintenance_rate?: string; // Tiered maintenance margin rate calculation ⋮---- liq_price?: string; // Estimated liquidation price for reference only liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management ⋮---- initial_margin?: string; // Expanded scope description maintenance_margin?: string; // Expanded scope description ⋮---- realised_pnl?: string; // Detailed breakdown including settlement, funding fees, and trading fees pnl_pnl?: string; // Settlement P&L pnl_fund?: string; // Funding fee P&L pnl_fee?: string; // Total trading fees history_pnl?: string; // All historical settlement P&L ⋮---- cross_leverage_limit?: string; // Simplified description ⋮---- settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support isolated_margin?: string; // v4.104.6: Add isolated_margin field pid?: number; // v4.106.0: Sub-position ID hedge_status?: 'partial_hedged' | 'full_hedged'; // v4.106.97: Delta-neutral hedging status hedged_size?: string; // v4.106.97: Hedged size under Delta-neutral strategy unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy ⋮---- export interface FuturesTradingHistoryRecord { id: number; create_time: number; contract: string; order_id: string; size: number; price: string; role: 'taker' | 'maker'; text: string; fee: string; point_fee: string; close_size: number; } ⋮---- export interface FuturesPositionHistoryRecord { time: number; contract: string; side: 'long' | 'short'; pnl: string; pnl_pnl: string; pnl_fund: string; pnl_fee: string; text: string; max_size: string; first_open_time: number; long_price: string; short_price: string; accum_size: string; } ⋮---- export interface FuturesLiquidationHistoryRecord { time: number; contract: string; leverage: string; size: number; margin: string; entry_price: string; liq_price: string; mark_price: string; order_id: number; order_price: string; fill_price: string; left: number; } export interface FuturesAutoDeleveragingHistoryRecord { time: number; user: number; order_id: number; contract: string; leverage: string; // Clarified for better understanding of margin modes cross_leverage_limit: string; // Clarified for better understanding of margin modes entry_price: string; fill_price: string; trade_size: number; position_size: number; } ⋮---- leverage: string; // Clarified for better understanding of margin modes cross_leverage_limit: string; // Clarified for better understanding of margin modes ⋮---- export interface DeleteFuturesBatchOrdersResp { user_id: number; id: string; succeeded: boolean; message: string; } ⋮---- export interface FuturesContract { name?: string; /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ contract_type?: string; type?: 'inverse' | 'direct'; quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" leverage_min?: string; leverage_max?: string; maintenance_rate?: string; // First-tier maintenance margin rate requirement mark_type?: 'internal' | 'index'; // Deprecated mark_price?: string; index_price?: string; last_price?: string; maker_fee_rate?: string; taker_fee_rate?: string; order_price_round?: string; mark_price_round?: string; // Minimum unit of mark price order_price_deviate?: string; ref_discount_rate?: string; ref_rebate_rate?: string; funding_rate?: string; funding_rate_indicative?: string; funding_interval?: number; funding_next_apply?: number; funding_offset?: number; /** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ interest_rate?: string; risk_limit_base?: string; risk_limit_step?: string; risk_limit_max?: string; order_size_min?: string | number; // API returns string e.g. "1" order_size_max?: string | number; // API returns string e.g. "1000000" orderbook_id?: number; trade_id?: number; trade_size?: string | number; // API returns string position_size?: string | number; // API returns string short_users?: number; long_users?: number; funding_impact_value?: string; config_change_time?: number; in_delisting?: boolean; orders_limit?: number; enable_bonus?: boolean; enable_credit?: boolean; /** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ enable_decimal?: boolean; /** Whether the newly listed contract uses the mark price circuit breaker */ enable_circuit_breaker?: boolean; create_time?: number; launch_time?: number; delisting_time?: number; delisted_time?: number; status?: string; // e.g. "trading" funding_cap_ratio?: string; // Deprecated funding_rate_limit?: string; // v4.106.4: Funding rate cap value market_order_slip_ratio?: string; market_order_size_max?: string; } ⋮---- /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ ⋮---- quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" ⋮---- maintenance_rate?: string; // First-tier maintenance margin rate requirement mark_type?: 'internal' | 'index'; // Deprecated ⋮---- mark_price_round?: string; // Minimum unit of mark price ⋮---- /** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ ⋮---- order_size_min?: string | number; // API returns string e.g. "1" order_size_max?: string | number; // API returns string e.g. "1000000" ⋮---- trade_size?: string | number; // API returns string position_size?: string | number; // API returns string ⋮---- /** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ ⋮---- /** Whether the newly listed contract uses the mark price circuit breaker */ ⋮---- status?: string; // e.g. "trading" funding_cap_ratio?: string; // Deprecated funding_rate_limit?: string; // v4.106.4: Funding rate cap value ⋮---- /** GET /futures/{settle}/adl_risk_states */ export interface FuturesADLRiskState { state: 'normal' | 'warning' | 'adl_risk'; calculated_at_ms: number; } ⋮---- export interface FuturesADLRiskStates { settle: string; states: Record; } ⋮---- /** GET /futures/{settle}/get_leverage/{contract} — API field name is `Lever` */ export interface FuturesContractLeverageInfo { Lever: string; } ⋮---- /** Create/amend response for futures price-trigger orders (`/futures/{settle}/price_orders`). */ export interface TriggerOrderResponse { id?: number; /** * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. */ id_string?: string; } ⋮---- /** * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. */ ⋮---- export interface FuturesPriceTriggeredOrder { initial: { contract: string; size?: number; price?: string; close?: boolean; tif?: 'gtc' | 'ioc'; text?: string; reduce_only?: boolean; auto_size?: string; is_reduce_only?: boolean; is_close?: boolean; }; trigger: { strategy_type?: 0 | 1; price_type?: 0 | 1 | 2; price?: string; rule?: 1 | 2; expiration?: number; }; id?: number; // int64 price-triggered order id /** * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. */ id_string?: string; user?: number; create_time?: number; finish_time?: number; trade_id?: number; status?: 'open' | 'finished' | 'inactive' | 'invalid'; finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; reason?: string; order_type?: | 'close-long-order' | 'close-short-order' | 'close-long-position' | 'close-short-position' | 'plan-close-long-position' | 'plan-close-short-position'; me_order_id?: number; // int64 } ⋮---- id?: number; // int64 price-triggered order id /** * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. */ ⋮---- me_order_id?: number; // int64 ⋮---- export interface FuturesDeliveryContract { name?: string; /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ contract_type?: string; underlying?: string; cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; type?: 'inverse' | 'direct'; quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" leverage_min?: string; leverage_max?: string; maintenance_rate?: string; // First-tier maintenance margin rate requirement mark_type?: 'internal' | 'index'; // Deprecated mark_price?: string; index_price?: string; last_price?: string; maker_fee_rate?: string; taker_fee_rate?: string; order_price_round?: string; mark_price_round?: string; // Minimum unit of mark price basis_rate?: string; basis_value?: string; basis_impact_value?: string; settle_price?: string; settle_price_interval?: number; settle_price_duration?: number; expire_time?: number; risk_limit_base?: string; risk_limit_step?: string; risk_limit_max?: string; order_size_min?: number; order_size_max?: number; order_price_deviate?: string; ref_discount_rate?: string; ref_rebate_rate?: string; orderbook_id?: number; trade_id?: number; trade_size?: number; position_size?: number; config_change_time?: number; in_delisting?: boolean; orders_limit?: number; } ⋮---- /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ ⋮---- quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" ⋮---- maintenance_rate?: string; // First-tier maintenance margin rate requirement mark_type?: 'internal' | 'index'; // Deprecated ⋮---- mark_price_round?: string; // Minimum unit of mark price ⋮---- export interface BatchAmendOrderResp { succeeded: boolean; label?: string; detail?: string; id: number; user: number; create_time: number; finish_time?: number; /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ finish_as?: | 'filled' | 'cancelled' | 'liquidated' | 'ioc' | 'poc' | 'auto_deleveraged' | 'reduce_only' | 'position_closed' | 'reduce_out' | 'stp'; status: 'open' | 'finished'; contract: string; size: number; iceberg: number; price: string; is_close: boolean; is_reduce_only: boolean; is_liq: boolean; tif: 'gtc' | 'ioc' | 'poc' | 'fok'; left: number; fill_price: string; text: string; tkfr: string; mkfr: string; refu: number; stp_act: 'co' | 'cn' | 'cb' | '-'; stp_id: number; } ⋮---- /** * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ ⋮---- /** * @deprecated - Use FuturesAccount instead */ export interface UpdateFuturesDualModeResp { total: string; unrealised_pnl: string; position_margin: string; order_margin: string; available: string; point: string; currency: string; in_dual_mode: boolean; enable_credit: boolean; position_initial_margin: string; maintenance_margin: string; bonus: string; enable_evolved_classic: boolean; history: { dnw: string; pnl: string; fee: string; refr: string; fund: string; point_dnw: string; point_fee: string; point_refr: string; bonus_dnw: string; bonus_offset: string; }; } ⋮---- export interface RiskLimitTableTier { tier: number; risk_limit: string; initial_rate: string; maintenance_rate: string; // First-tier maintenance margin rate requirement leverage_max: string; deduction: string; } ⋮---- maintenance_rate: string; // First-tier maintenance margin rate requirement ⋮---- // v4.104.6: New GET /futures/{settle}/insurance endpoint types export interface FuturesInsuranceHistory { t: number; b: string; } ⋮---- /** Trail order (autoorder/v1/trail) response types */ export interface TrailOrder { id?: number | string; user_id?: number | string; user?: number | string; contract?: string; settle?: string; amount?: string; is_gte?: boolean; activation_price?: string; price_type?: number; price_offset?: string; text?: string; reduce_only?: boolean; position_related?: boolean; created_at?: number | string; activated_at?: number | string; finished_at?: number | string; create_time?: number | string; active_time?: number | string; finish_time?: number | string; reason?: string; suborder_text?: string; is_dual_mode?: boolean; trigger_price?: string; suborder_id?: number | string; side_label?: string; original_status?: number; status?: string; position_side_output?: string; updated_at?: number | string; extremum_price?: string; status_code?: string; created_at_precise?: string; finished_at_precise?: string; activated_at_precise?: string; status_label?: string; pos_margin_mode?: string; position_mode?: string; error_label?: string; leverage?: string; [key: string]: unknown; } ⋮---- export interface TrailChangeLog { updated_at?: number; amount?: string; is_gte?: boolean; activation_price?: string; price_type?: number; price_offset?: string; is_create?: boolean; } ⋮---- export interface ChaseOrder { id?: string; user?: string; contract?: string; settle?: string; amount?: string; price_limit?: string; reduce_only?: boolean; text?: string; create_time?: number; finish_time?: number; original_status?: number; status?: string; reason?: string; fill_amount?: string; average_fill_price?: string; suborder_id?: string; is_dual_mode?: boolean; side_label?: string; position_side_output?: string; chase_price?: string; interval_sec?: number; updated_at?: number; suborder_price?: string; suborder_ongoing?: boolean; suborder_finish_as?: string; price_type?: number; price_gap_type?: string; price_gap_value?: string; status_code?: string; create_time_precise?: string; finish_time_precise?: string; pos_margin_mode?: string; position_mode?: string; leverage?: string; error_label?: string; } ⋮---- export interface CreateChaseOrderResp { id?: string; } ⋮---- export interface StopChaseOrderResp { order?: ChaseOrder; } ⋮---- export interface StopAllChaseOrdersResp { orders?: ChaseOrder[]; } ⋮---- export interface GetChaseOrdersResp { orders?: ChaseOrder[]; } ⋮---- export interface GetChaseOrderDetailResp { order?: ChaseOrder; } ================ File: README.md ================ # Node.js & JavaScript SDK for Gate.com (Gate.io) REST APIs, WebSockets & WebSocket API

SDK Logo

[![npm version](https://img.shields.io/npm/v/gateio-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1] [![Build & Test](https://github.com/sieblyio/gateio-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/sieblyio/gateio-api/actions/workflows/e2etest.yml) [![last commit](https://img.shields.io/github/last-commit/sieblyio/gateio-api)][1] [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/sieblyio/gateio-api) [1]: https://www.npmjs.com/package/gateio-api Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST APIs and WebSockets: - Professional, robust & performant Gate.com SDK with extensive production use in live trading environments. - Extensive integration with Gate.com (Gate.io) REST APIs and WebSockets. - 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. - Gate.com REST APIs for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha & OTC Trading APIs. - Unified RestClient for all Gate.com trading products. - Strongly typed on most requests and responses. - Support for Cross-Exchange (CrossEx) trading across multiple exchanges - Support for Alpha account trading (meme tokens and new listings) - Support for OTC (fiat and stablecoin) trading - Support for seamless API authentication for private Gate.com REST API and WebSocket calls. - Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. - Event driven messaging. - Smart websocket persistence with automatic reconnection handling. - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - Automatically handle listenKey persistence and expiration/refresh. - Emit `reconnected` event when dropped connection is restored. - Support for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha & OTC. - WebSocket API for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures & CrossEx. - Automatic connectivity via existing WebsocketClient, just call sendWSAPIRequest to trigger a request. - Automatic authentication, just call sendWSAPIRequest with channel & parameters. - Choose between two interfaces for WS API communication: - Event-driven interface, fire & forget via sendWSAPIRequest and receive async replies via wsClient's event emitter. - Promise-driven interface, simply use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. - Heavy automated end-to-end testing with real API calls. - Proxy support via axios integration. - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). - QuickStart Guide: https://siebly.io/sdk/gate/javascript - Gate JavaScript Tutorial: https://siebly.io/sdk/gate/javascript/tutorial ## Table of Contents - [Installation](#installation) - [Examples](#examples) - [Issues & Discussion](#issues--discussion) - [Related Projects](#related-projects) - [Documentation](#documentation) - [Structure](#structure) - [Usage](#usage) - [REST API Client](#rest-api) - [WebSocket Client](#websockets) - [WebSocket Data Streams](#websocket-data-streams) - [WebSocket API](#websocket-api) - [Event Driven API](#event-driven-api) - [REST-like API](#rest-like-api) - [Customise Logging](#customise-logging) - [Browser/Frontend Usage](#browserfrontend-usage) - [Webpack](#webpack) - [LLMs & AI](#use-with-llms--ai) - [Used By](#used-by) - [Contributions & Thanks](#contributions--thanks) ## Installation `npm install --save gateio-api` ## Examples Refer to the [examples](./examples) folder for implementation demos, including: - **REST API Examples**: spot trading, futures trading, account management - **WebSocket Examples**: public market data streams, private account data, WebSocket API usage - **Spot Trading**: comprehensive spot market examples - **Futures Trading**: perpetual and delivery futures examples - **WebSocket API**: both event-driven and promise-driven approaches ## Issues & Discussion - Issues? Check the [issues tab](https://github.com/sieblyio/gateio-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 Gate.com's API documentation, or check the type definition in each class within this repository. ### API Documentation Links - [Gate.com/gate.io API Documentation](https://www.gate.com/docs/developers/apiv4/en/) - [Spot Trading API](https://www.gate.com/docs/developers/apiv4/en/#spot-new) - [Margin Trading API](https://www.gate.com/docs/developers/apiv4/en/#margin-new) - [Futures Trading API](https://www.gate.com/docs/developers/apiv4/en/#futures-new) - [Options Trading API](https://www.gate.com/docs/developers/apiv4/en/#options-new) - [CrossEx Trading API](https://www.gate.com/docs/developers/apiv4/en/#crossex) - [Alpha Trading API](https://www.gate.com/docs/developers/apiv4/en/#alpha) - [OTC Trading API](https://www.gate.com/docs/developers/apiv4/en/#otc) - [WebSocket API](https://www.gate.com/docs/developers/apiv4/en/#websocket-api) - [REST Endpoint Function List](./docs/endpointFunctionList.md) - [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/gateio-api) ## 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 Gate.com's website: - [Gate.com API Key Management](https://www.gate.com/myaccount/api_key_manage) ## REST API The SDK provides a unified `RestClient` for all Gate.com trading products including Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha, and OTC Trading. This single client handles all REST API operations across all trading markets. To use any of Gate.com's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the `RestClient`: ```javascript const { RestClient } = require('gateio-api'); const API_KEY = 'xxx'; const PRIVATE_KEY = 'yyy'; const client = new RestClient({ apiKey: API_KEY, apiSecret: PRIVATE_KEY, }); // Spot Trading Example client .getSpotTicker() .then((result) => { console.log('all spot tickers result: ', result); }) .catch((err) => { console.error('spot ticker error: ', err); }); client .getSpotOrders({ currency_pair: 'BTC_USDT', status: 'open', }) .then((result) => { console.log('getSpotOrders result: ', result); }) .catch((err) => { console.error('getSpotOrders error: ', err); }); // CrossEx Trading Example - Trade across multiple exchanges client .getCrossExSymbols() .then((result) => { console.log('CrossEx symbols: ', result); }) .catch((err) => { console.error('CrossEx error: ', err); }); // Alpha Trading Example - Trade meme tokens and new listings client .getAlphaCurrencies() .then((result) => { console.log('Alpha currencies: ', result); }) .catch((err) => { console.error('Alpha error: ', err); }); // OTC Trading Example - Fiat and stablecoin trading client .createOTCQuote({ side: 'BUY', pay_coin: 'USDT', get_coin: 'USD', pay_amount: '1000', create_quote_token: '1', }) .then((result) => { console.log('OTC quote: ', result); }) .catch((err) => { console.error('OTC error: ', err); }); ``` See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets All WebSocket functionality is supported via the unified `WebsocketClient`. This client handles all Gate.com WebSocket streams with automatic connection management and reconnection. Key WebSocket features: - Event driven messaging - Smart WebSocket persistence with automatic reconnection - Heartbeat mechanisms to detect disconnections - Automatic resubscription after reconnection - Support for all Gate.com trading products (Spot, Margin, Futures, Options) - WebSocket API support for real-time trading operations ### WebSocket Data Streams All available WebSockets can be used via a shared `WebsocketClient`. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see [WS_KEY_MAP](src/lib/websocket/websocket-util.ts) for a list of supported values). Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the [examples](./examples/) folder on GitHub. Data events are emitted from the WebsocketClient via the `update` event, see example below: ```javascript const { WebsocketClient } = require('gateio-api'); const API_KEY = 'xxx'; const PRIVATE_KEY = 'yyy'; const wsConfig = { apiKey: API_KEY, apiSecret: PRIVATE_KEY, /* The following parameters are optional: */ // Livenet is used by default, use this to enable testnet: // useTestnet: true // how long to wait (in ms) before deciding the connection should be terminated & reconnected // pongTimeout: 1000, // how often to check (in ms) that WS connection is still alive // pingInterval: 10000, // how long to wait before attempting to reconnect (in ms) after connection is closed // reconnectTimeout: 500, // config options sent to RestClient (used for time sync). See RestClient docs. // restOptions: { }, // config for axios used for HTTP requests. E.g for proxy support // requestOptions: { } }; const ws = new WebsocketClient(wsConfig); /** * Subscribing to data: **/ const userOrders = { topic: 'spot.orders', payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], }; const userTrades = { topic: 'spot.usertrades', payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], }; const userPriceOrders = { topic: 'spot.priceorders', payload: ['!all'], }; // subscribe to multiple topics at once ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4'); // and/or subscribe to individual topics on demand ws.subscribe( { topic: 'spot.priceorders', payload: ['!all'], }, 'spotV4', ); // Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above) ws.subscribe('spot.balances', 'spotV4'); /** * Handling events: **/ // Listen to events coming from websockets. This is the primary data source ws.on('update', (data) => { console.log('data', data); }); // Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) ws.on('open', ({ wsKey, event }) => { console.log('connection open for websocket with ID: ' + wsKey); }); // Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic) ws.on('response', (response) => { console.log('response', response); }); // Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected. ws.on('close', () => { console.log('connection closed'); }); // Optional: listen to internal exceptions. Useful for debugging if something weird happens ws.on('exception', (data) => { console.error('exception: ', data); }); // Optional: Listen to raw error events. ws.on('error', (err) => { console.error('ERR', err); }); ``` See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail. ### Websocket API Gate.com supports sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. The WebSocket API is available through two approaches, depending on individual preference: #### Event Driven API The WebSocket API is available in the [WebsocketClient](./src/WebsocketClient.ts) via the `sendWSAPIRequest(wsKey, channel, params)` method. Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. - event-driven: - send requests via `client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API exception for channel', channel, e))`, fire and forget, don't use await - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` - promise-driven: - send requests via `const result = await client.sendWSAPIRequest(wsKey, channel, params)`, which returns a promise - await each call - use try/catch blocks to handle promise rejections #### REST-like API The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the RestClient). It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. ```javascript const { WebsocketAPIClient } = require('gateio-api'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; async function start() { // Make an instance of the WS API Client const wsClient = new WebsocketAPIClient({ apiKey: API_KEY, apiSecret: API_SECRET, // Automatically re-auth WS API, if we were auth'd before and get reconnected reauthWSAPIOnReconnect: true, }); try { // Connection will authenticate automatically before first request // Make WebSocket API calls, very similar to a REST API: /* ============ SPOT TRADING EXAMPLES ============ */ // Submit a new spot order const newOrder = await wsClient.submitNewSpotOrder({ text: 't-my-custom-id', currency_pair: 'BTC_USDT', type: 'limit', account: 'spot', side: 'buy', amount: '1', price: '10000', }); console.log('Order result:', newOrder.data); // Cancel a spot order const cancelOrder = await wsClient.cancelSpotOrder({ order_id: '1700664330', currency_pair: 'BTC_USDT', account: 'spot', }); console.log('Cancel result:', cancelOrder.data); // Get spot order status const orderStatus = await wsClient.getSpotOrderStatus({ order_id: '1700664330', currency_pair: 'BTC_USDT', account: 'spot', }); console.log('Order status:', orderStatus.data); /* ============ FUTURES TRADING EXAMPLES ============ */ // Submit a new futures order const newFuturesOrder = await wsClient.submitNewFuturesOrder({ contract: 'BTC_USDT', size: 10, price: '31503.28', tif: 'gtc', text: 't-my-custom-id', }); console.log('Futures order result:', newFuturesOrder.data); // Cancel a futures order const cancelFuturesOrder = await wsClient.cancelFuturesOrder({ order_id: '74046514', }); console.log('Cancel futures order result:', cancelFuturesOrder.data); // Get futures order status const futuresOrderStatus = await wsClient.getFuturesOrderStatus({ order_id: '74046543', }); console.log('Futures order status:', futuresOrderStatus.data); } catch (e) { console.error('WS API Error:', e); } } start(); ``` For more detailed examples using any approach, refer to the [examples](./examples/) folder (e.g. [ws-api-client.ts](./examples/ws-api-client.ts)). --- ## Customise Logging Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired. ```javascript const { WebsocketClient, DefaultLogger } = require('gateio-api'); // Disable all logging on the silly level DefaultLogger.silly = () => {}; const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger); ``` ## Browser/Frontend Usage ### Webpack Build a bundle using webpack: - `npm install` - `npm run build` - `npm run pack` The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. ## Use with LLMs & AI This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. --- ## Used By [![Repository Users Preview Image](https://dependents.info/sieblyio/gateio-api/image)](https://github.com/sieblyio/gateio-api/network/dependents) --- ### Contributions & Thanks Have my projects helped you? Share the love, there are many ways you can show your thanks: - Star & share my projects. - Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler - Have an interesting project? Get in touch & invite me to it. - Or buy me all the coffee: - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` - Sign up with my referral links: - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 ### Contributions & Pull Requests Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) ================ File: src/RestClient.ts ================ import { AxiosRequestConfig } from 'axios'; ⋮---- import { BaseRestClient, REST_CLIENT_TYPE_ENUM, RestClientType, } from './lib/BaseRestClient.js'; import { appendGateMultipartFields, appendGateMultipartFile, } from './lib/multipartUtil.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { CreateStpGroupReq } from './types/request/account.js'; import { CreateAlphaOrderReq, CreateAlphaQuoteReq, GetAlphaAccountBookReq, GetAlphaCurrenciesReq, GetAlphaOrderReq, GetAlphaOrdersReq, GetAlphaTickersReq, } from './types/request/alpha.js'; import { ListAnnouncementArticlesReq } from './types/request/announcement.js'; import { AddAutoInvestPlanPositionReq, CreateAutoInvestPlanReq, GetAutoInvestCoinsReq, GetAutoInvestMinAmountReq, GetAutoInvestOrdersReq, GetAutoInvestPlanDetailReq, GetAutoInvestPlanRecordsReq, GetAutoInvestPlansReq, StopAutoInvestPlanReq, UpdateAutoInvestPlanReq, } from './types/request/autoinvest.js'; import { CancelBatchCrossExOrdersReq, CloseCrossExPositionReq, CreateCrossExConvertOrderReq, CreateCrossExConvertQuoteReq, CreateCrossExOrderReq, CreateCrossExTransferReq, GetCrossExAccountBookReq, GetCrossExAccountsReq, GetCrossExAdlRankReq, GetCrossExCoinDiscountRateReq, GetCrossExHistoryMarginInterestsReq, GetCrossExHistoryMarginPositionsReq, GetCrossExHistoryOrdersReq, GetCrossExHistoryPositionsReq, GetCrossExHistoryTradesReq, GetCrossExInterestRateReq, GetCrossExMarginPositionLeverageReq, GetCrossExMarginPositionsReq, GetCrossExMarketFundingInfoReq, GetCrossExMarketTickersReq, GetCrossExOpenOrdersReq, GetCrossExPositionLeverageReq, GetCrossExPositionsReq, GetCrossExRiskLimitsReq, GetCrossExSymbolsReq, GetCrossExTransferCoinsReq, GetCrossExTransferHistoryReq, ModifyCrossExOrderReq, SetCrossExMarginPositionLeverageReq, SetCrossExPositionLeverageReq, UpdateCrossExAccountReq, UpdateCrossExPositionsMarginReq, } from './types/request/crossex.js'; import { GetDeliveryAutoOrdersReq, GetDeliveryBookReq, GetDeliveryCandlesReq, GetDeliveryClosedPositionsReq, GetDeliveryLiquidationHistoryReq, GetDeliveryOrderBookReq, GetDeliveryOrdersReq, GetDeliverySettlementHistoryReq, GetDeliveryTradesReq, GetDeliveryTradingHistoryReq, SubmitDeliveryFuturesOrderReq, } from './types/request/delivery.js'; import { CreateEarnFixedTermLendReq, EarnFixedTermPreRedeemReq, GetDualInvestmentOrdersReq, GetDualInvestmentPlansReq, GetDualOrderRefundPreviewReq, GetDualProjectRecommendReq, GetEarnFixedTermHistoryReq, GetEarnFixedTermLendsReq, GetEarnFixedTermProductsByAssetReq, GetEarnFixedTermProductsReq, PlaceDualInvestmentOrderParams, SubmitDualOrderRefundParams, UpdateDualOrderReinvestParams, } from './types/request/earn.js'; import { GetLendingInterestRecordsReq, GetLendingOrdersReq, GetLendingRecordsReq, SubmitLendOrRedeemReq, } from './types/request/earnuni.js'; import { GetFlashSwapOrdersReq, SubmitFlashSwapOrderPreviewReq, SubmitFlashSwapOrderReq, } from './types/request/flashswap.js'; import { BatchAmendOrderReq, BatchFundingRatesReq, BatchTerminateTrailOrdersReq, CreateChaseOrderReq, CreateTrailOrderReq, DeleteAllFuturesOrdersReq, GetChaseOrderDetailReq, GetChaseOrdersReq, GetFundingRatesReq, GetFuturesAccountBookReq, GetFuturesADLRiskStatesReq, GetFuturesAutoOrdersReq, GetFuturesCandlesReq, GetFuturesContractLeverageReq, GetFuturesInsuranceReq, GetFuturesLiquidationHistoryReq, GetFuturesOrderBookReq, GetFuturesOrdersByTimeRangeReq, GetFuturesOrdersReq, GetFuturesPositionCloseHistoryReq, GetFuturesPositionHistoryReq, GetFuturesPositionsReq, GetFuturesStatsReq, GetFuturesTradesReq, GetFuturesTradingHistoryByTimeRangeReq, GetFuturesTradingHistoryReq, GetLiquidationHistoryReq, GetRiskLimitTableReq, GetRiskLimitTiersReq, GetTrailOrderChangeLogReq, GetTrailOrderDetailReq, GetTrailOrderListReq, StopAllChaseOrdersReq, StopChaseOrderReq, SubmitFuturesOrderReq, SubmitFuturesTriggeredOrderReq, TerminateTrailOrderReq, UpdateDualModePositionLeverageReq, UpdateDualModePositionMarginReq, UpdateFuturesOrderReq, UpdateFuturesPriceTriggeredOrderReq, UpdateTrailOrderReq, } from './types/request/futures.js'; import { GetCrossMarginAccountHistoryReq, GetCrossMarginBorrowHistoryReq, GetCrossMarginInterestRecordsReq, GetCrossMarginRepaymentsReq, GetMarginBalanceHistoryReq, SubmitCrossMarginBorrowLoanReq, } from './types/request/margin.js'; import { GetMarginUNIInterestRecordsReq, GetMarginUNILoanRecordsReq, GetMarginUNILoansReq, GetMarginUNIMaxBorrowReq, } from './types/request/marginuni.js'; import { GetMultiLoanAdjustmentRecordsReq, GetMultiLoanOrdersReq, GetMultiLoanRepayRecordsReq, RepayMultiLoanReq, SubmitMultiLoanOrderReq, UpdateMultiLoanReq, } from './types/request/multicollateralLoan.js'; import { AmendOptionsOrderReq, GetOptionsAccountChangeReq, GetOptionsCandlesReq, GetOptionsMySettlementsReq, GetOptionsOrderBookReq, GetOptionsOrdersReq, GetOptionsPersonalHistoryReq, GetOptionsSettlementHistoryReq, GetOptionsTradesReq, GetOptionsUnderlyingCandlesReq, OptionsMMPSettingsReq, SubmitOptionsOrderReq, } from './types/request/options.js'; import { CancelOTCOrderReq, CreateOTCBankReq, CreateOTCFiatOrderReq, CreateOTCQuoteReq, CreateOTCStablecoinOrderReq, CreateOTCUploadPreUploadReq, GetOTCBankSupplementChecklistReq, GetOTCFiatOrderDetailReq, GetOTCFiatOrderListReq, GetOTCStablecoinOrderListReq, MarkOTCOrderAsPaidReq, OTCBankIdReq, SubmitOTCBankEnterpriseSupplementReq, SubmitOTCBankPersonalSupplementReq, } from './types/request/otc.js'; import { P2PMerchantAdsDetailReq, P2PMerchantAdsUpdateStatusReq, P2PMerchantCancelTransactionReq, P2PMerchantConfirmPaymentReq, P2PMerchantConfirmReceiptReq, P2PMerchantGetAdsListReq, P2PMerchantGetChatsListReq, P2PMerchantGetCompletedTransactionListReq, P2PMerchantGetCounterpartyUserInfoReq, P2PMerchantGetMyselfPaymentReq, P2PMerchantGetPendingTransactionListReq, P2PMerchantGetTransactionDetailsReq, P2PMerchantMyAdsListReq, P2PMerchantPlaceBizPushOrderReq, P2PMerchantSendChatMessageReq, P2PMerchantSetMerchantWorkHoursReq, P2PMerchantUploadChatFileReq, } from './types/request/p2pMerchant.js'; import { GetAgencyCommissionHistoryReq, GetAgencyTransactionHistoryReq, GetBrokerCommissionHistoryReq, GetBrokerTransactionHistoryReq, GetPartnerAgentDataAggregatedReq, GetPartnerSubordinateListReq, PartnerTransactionReq, } from './types/request/rebate.js'; import { CancelSpotBatchOrdersReq, CancelSpotPovOrdersReq, CreateSpotPovOrderReq, DeleteSpotOrderReq, GetSpotAccountBookReq, GetSpotAutoOrdersReq, GetSpotCandlesReq, GetSpotInsuranceHistoryReq, GetSpotOrderBookReq, GetSpotOrderReq, GetSpotOrdersReq, GetSpotPovOrdersReq, GetSpotTradesReq, GetSpotTradingHistoryReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, UpdateSpotBatchOrdersReq, UpdateSpotOrderReq, } from './types/request/spot.js'; import { CloseStockPositionReq, CreateStockOrderReq, CreateStockTransactionReq, GetStockOrderHistoryReq, GetStockOrdersReq, GetStockPositionsReq, GetStockSymbolDetailReq, GetStockSymbolsReq, GetStockTransactionsReq, GetStockUserAssetsReq, UpdateStockOrderReq, } from './types/request/stock.js'; import { CreateSubAccountApiKeyReq, CreateSubAccountReq, UpdateSubAccountApiKeyReq, } from './types/request/subaccount.js'; import { TradFiClosePositionReq, TradFiCreateOrderReq, TradFiCreateTransactionReq, TradFiGetKlinesParams, TradFiGetOrderHistoryParams, TradFiGetPositionHistoryParams, TradFiGetSymbolCommissionsParams, TradFiGetSymbolDetailParams, TradFiGetTransactionsParams, TradFiModifyOrderReq, TradFiModifyPositionReq, } from './types/request/tradfi.js'; import { CreateQuickRepaymentReq, GetUnifiedHistoryLendingRateReq, GetUnifiedInterestRecordsReq, GetUnifiedLoanRecordsReq, GetUnifiedLoansReq, PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, SetUnifiedDeltaNeutralReq, SetUserLeverageReq, SubmitUnifiedBorrowOrRepayReq, SubmitUnifiedLoanRepayReq, } from './types/request/unified.js'; import { GetMainSubTransfersReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, GetSubAccountBalancesReq, GetTransferReq, GetWithdrawalDepositRecordsReq, ListPushOrdersReq, SubmitMainSubTransferReq, SubmitSubToSubTransferReq, SubmitTransferReq, } from './types/request/wallet.js'; import { SubmitWithdrawalReq } from './types/request/withdrawal.js'; import { AccountDetail, AccountMainKey, AccountRateLimit, StpGroup, StpGroupUser, } from './types/response/account.js'; import { AlphaAccount, AlphaAccountBook, AlphaCurrency, AlphaOrder, AlphaTicker, CreateAlphaOrderResp, CreateAlphaQuoteResp, } from './types/response/alpha.js'; import { AnnouncementArticleListResponse } from './types/response/announcement.js'; import { AutoInvestCoinItem, AutoInvestConfigItem, AutoInvestMinAmountResp, AutoInvestOrderItem, AutoInvestPlanDetail, AutoInvestPlanExecutionRecordsPaginated, AutoInvestPlansListResp, CreateAutoInvestPlanResp, } from './types/response/autoinvest.js'; import { CancelBatchCrossExOrdersResp, CancelCrossExOrderResp, CloseCrossExPositionResp, CreateCrossExConvertOrderResp, CreateCrossExConvertQuoteResp, CreateCrossExOrderResp, CreateCrossExTransferResp, CrossExAccount, CrossExAccountBook, CrossExAdlRank, CrossExCoinDiscountRate, CrossExFeeRate, CrossExHistoryMarginInterest, CrossExHistoryMarginPosition, CrossExHistoryPosition, CrossExHistoryTrade, CrossExInterestRate, CrossExMarginPosition, CrossExMarginPositionLeverage, CrossExMarketFundingInfo, CrossExMarketTicker, CrossExOrder, CrossExPosition, CrossExPositionLeverage, CrossExRiskLimit, CrossExSymbol, CrossExTransferCoin, CrossExTransferHistory, ModifyCrossExOrderResp, SetCrossExMarginPositionLeverageResp, SetCrossExPositionLeverageResp, UpdateCrossExAccountResp, UpdateCrossExPositionsMarginResp, } from './types/response/crossex.js'; import { DeliveryAccount, DeliveryBook, DeliveryCandle, DeliveryClosedPosition, DeliveryLiquidationHistoryRecord, DeliveryOrderBook, DeliverySettlementHistoryRecord, DeliveryTicker, DeliveryTrade, DeliveryTradingHistoryRecord, } from './types/response/delivery.js'; import { CreateEarnFixedTermLendResponse, CreateEarnFixedTermPreRedeemResponse, DualInvestmentOrder, DualInvestmentProduct, DualOrderRefundPreview, DualProjectRecommend, GetEarnFixedTermHistoryResponse, GetEarnFixedTermLendsResponse, GetEarnFixedTermProductsByAssetResponse, GetEarnFixedTermProductsResponse, } from './types/response/earn.js'; import { LendingCurrency, LendingInterestRecord, LendingOrder, LendingRecord, } from './types/response/earnuni.js'; import { FlashSwapCurrencyPair, FlashSwapOrder, SubmitFlashSwapOrderPreviewResp, } from './types/response/flashswap.js'; import { BatchAmendOrderResp, BatchFundingRatesResponse, CreateChaseOrderResp, DeleteFuturesBatchOrdersResp, FuturesAccount, FuturesAccountBookRecord, FuturesADLRiskStates, FuturesAutoDeleveragingHistoryRecord, FuturesCandle, FuturesContract, FuturesContractLeverageInfo, FuturesDeliveryContract, FuturesInsuranceHistory, FuturesLiquidationHistoryRecord, FuturesOrder, FuturesOrderBook, FuturesOrderTimerange, FuturesPosition, FuturesPositionHistoryRecord, FuturesPriceTriggeredOrder, FuturesStats, FuturesTicker, FuturesTrade, FuturesTradingHistoryRecord, GetChaseOrderDetailResp, GetChaseOrdersResp, IndexConstituents, LiquidationHistoryRecord, PremiumIndexKLine, RiskLimitTableTier, RiskLimitTier, StopAllChaseOrdersResp, StopChaseOrderResp, TrailChangeLog, TrailOrder, TriggerOrderResponse, } from './types/response/futures.js'; import { CrossMarginAccount, CrossMarginAccountHistoryRecord, CrossMarginCurrency, CrossMarginMorrowLoanRecord, MarginAccount, MarginBalanceHistoryRecord, MarginUserAccount, } from './types/response/margin.js'; import { LendingMarket, MarginUNIInterestRecord, MarginUNILoan, MarginUNILoanRecord, MarginUNIMaxBorrowable, } from './types/response/marginuni.js'; import { MultiLoanAdjustmentRecord, MultiLoanCurrencyQuota, MultiLoanFixedRate, MultiLoanOrder, MultiLoanRatio, MultiLoanRepayRecord, MultiLoanSupportedCurrencies, RepayMultiLoanResp, UpdateMultiLoanResp, } from './types/response/multicollateralLoan.js'; import { GetOptionsLiquidationResp, OptionsAccount, OptionsAccountChangeRecord, OptionsCandle, OptionsContract, OptionsMMPSettings, OptionsOrderBook, OptionsPositionsUnderlying, OptionsSettlementHistoryRecord, OptionsTicker, OptionsTrade, OptionsUnderlyingCandle, OptionsUserHistoryRecord, OptionsUserSettlement, SubmitOptionsOrderResp, } from './types/response/options.js'; import { CancelOTCOrderResp, CreateOTCBankResp, CreateOTCFiatOrderResp, CreateOTCQuoteResp, CreateOTCStablecoinOrderResp, CreateOTCUploadPreUploadResp, GetOTCBankListResp, GetOTCBankSupplementChecklistResp, GetOTCFiatOrderDetailResp, GetOTCFiatOrderListResp, GetOTCStablecoinOrderListResp, MarkOTCOrderAsPaidResp, OTCActionResp, } from './types/response/otc.js'; import { P2PMerchantAdsDetail, P2PMerchantAdsListItem, P2PMerchantApiResp, P2PMerchantChatsListData, P2PMerchantCounterpartyUserInfo, P2PMerchantMyAdsListData, P2PMerchantPaymentMethod, P2PMerchantTransactionDetails, P2PMerchantTransactionListData, P2PMerchantUserInfo, } from './types/response/p2pMerchant.js'; import { AgencyCommissionHistoryRecord, AgencyTransactionHistoryRecord, BrokerCommissionHistoryRecord, BrokerTransactionHistoryRecord, PartnerCommission, PartnerDataAggregatedResponse, PartnerSubordinate, PartnerTransaction, } from './types/response/rebate.js'; import { DeleteSpotBatchOrdersResp, GetSpotOpenOrdersResp, SpotAccount, SpotAccountBook, SpotCandle, SpotCurrency, SpotFeeRates, SpotHistoricTradeRecord, SpotInsuranceHistory, SpotOrder, SpotOrderBook, SpotPovOrder, SpotPriceTriggeredOrder, SpotTicker, SpotTrade, SubmitSpotBatchOrdersResp, } from './types/response/spot.js'; import { StockApiResp, StockClosePositionResult, StockCreateOrderResult, StockExchangeItem, StockFeeRateItem, StockListData, StockOrderBook, StockOrderHistoryItem, StockOrderItem, StockPositionItem, StockSymbolDetailItem, StockSymbolItem, StockTransactionItem, StockUpdateOrderResult, StockUserAssets, } from './types/response/stock.js'; import { CreatedSubAccountAPIKey, SubAccount, SubAccountAPIKey, SubAccountMode, } from './types/response/subaccount.js'; import { TradFiApiResp, TradFiAssets, TradFiCategoryItem, TradFiCreateOrderResult, TradFiCreateUserResult, TradFiKlineItem, TradFiListData, TradFiModifyOrderResult, TradFiMT5Account, TradFiOrderHistoryItem, TradFiOrderItem, TradFiOrderLog, TradFiPositionHistoryItem, TradFiPositionItem, TradFiSymbolCommissionItem, TradFiSymbolDetailItem, TradFiSymbolItem, TradFiTicker, TradFiTransactionListData, } from './types/response/tradfi.js'; import { DeltaNeutralEnabled, LeverageFailedCurrency, MarginTier, PortfolioMarginCalculation, QuickEstimatedRepayment, QuickRepaymentResp, UnifiedAccountInfo, UnifiedCurrencyDiscountTiers, UnifiedHistoryLendingRate, UnifiedInterestRecord, UnifiedLoan, UnifiedLoanCurrency, UnifiedLoanRecord, UnifiedRiskUnitDetails, UserCurrencyLeverageConfig, } from './types/response/unified.js'; import { AccountTransferDetail, CreateDepositAddressResp, CurrencyChain, DepositRecord, GetBalancesResp, PushOrder, SavedAddress, SmallBalanceHistoryRecord, SmallBalanceRecord, SubAccountBalance, SubAccountCrossMarginBalancesResp, SubAccountFuturesBalancesResp, SubAccountMarginBalance, SubAccountTransferRecord, TradingFees, WithdrawalStatus, } from './types/response/wallet.js'; import { WithdrawalRecord } from './types/response/withdrawal.js'; import { CurrencyPair } from './types/shared.js'; ⋮---- /** * Unified REST API client for all of Gate's REST APIs */ export class RestClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- /** * * Custom SDK functions * */ ⋮---- /** * This method is used to get the latency and time sync between the client and the server. * This is not official API endpoint and is only used for internal testing purposes. * Use this method to check the latency and time sync between the client and the server. * Final values might vary slightly, but it should be within few ms difference. * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. */ async fetchLatencySummary(): Promise ⋮---- // Adjust server time by adding estimated one-way latency ⋮---- // Calculate time difference between adjusted server time and local time ⋮---- /** * * Gate.io misc endpoints * */ ⋮---- getClientType(): RestClientType ⋮---- getSystemMaintenanceStatus(): Promise ⋮---- listAnnouncementArticles( params?: ListAnnouncementArticlesReq, ): Promise ⋮---- /**================================================================================================================================ * WITHDRAW * ========================================================================================================================== */ ⋮---- /** * Withdraw * * Withdrawals to Gate addresses do not incur transaction fees. * * @param params Withdrawal parameters * @returns Promise */ submitWithdrawal(params: SubmitWithdrawalReq): Promise ⋮---- /** * Transfer between spot main accounts * * Both parties cannot be sub-accounts. * * @param params Transfer parameters * @returns Promise<{ * id: number; * }> */ submitSpotMainAccountTransfer(params: { receive_uid: number; currency: string; amount: string; }): Promise< ⋮---- /** * Cancel withdrawal with specified ID * * @param params Parameters containing the withdrawal ID * @returns Promise */ cancelWithdrawal(params: { withdrawal_id: string; }): Promise ⋮---- /**========================================================================================================================== * WALLET * ========================================================================================================================== */ ⋮---- /** * List chains supported for specified currency * * @param params Parameters containing the currency name * @returns Promise */ getCurrencyChains(params: ⋮---- /** * Generate currency deposit address * * @param params Parameters containing the currency name * @returns Promise */ createDepositAddress(params: { currency: string; }): Promise ⋮---- /** * Retrieve withdrawal records * * Record time range cannot exceed 30 days * * @param params Parameters for filtering withdrawal records * @returns Promise */ getWithdrawalRecords( params?: GetWithdrawalDepositRecordsReq, ): Promise ⋮---- /** * Retrieve deposit records * * Record time range cannot exceed 30 days * * @param params Parameters for filtering deposit records * @returns Promise */ getDepositRecords( params?: GetWithdrawalDepositRecordsReq, ): Promise ⋮---- /** * Transfer between trading accounts * * Transfer between different accounts. Currently support transfers between the following: * - spot - margin * - spot - futures(perpetual) * - spot - delivery * - spot - cross margin * - spot - options * * @param params Transfer parameters * @returns Promise */ submitTransfer(params: SubmitTransferReq): Promise< ⋮---- /** * Get trading account transfer details * * Retrieve the current user's trading account transfer details by tx_id. Response includes transfer status, currency, amount, source and destination account types, and applicable settlement currency or margin currency pair. * * @param params Parameters containing the transfer transaction ID * @returns Promise */ getTransfer(params: GetTransferReq): Promise ⋮---- /** * Transfer between main and sub accounts * * Support transferring with sub user's spot or futures account. Note that only main user's spot account is used no matter which sub user's account is operated. * * @param params Transfer parameters * @returns Promise */ submitMainSubTransfer(params: SubmitMainSubTransferReq): Promise ⋮---- /** * Retrieve transfer records between main and sub accounts * * Record time range cannot exceed 30 days * * Note: only records after 2020-04-10 can be retrieved * * @param params Parameters for filtering transfer records * @returns Promise */ getMainSubTransfers( params?: GetMainSubTransfersReq, ): Promise ⋮---- /** * Sub-account transfers to sub-account * * It is possible to perform balance transfers between two sub-accounts under the same main account. You can use either the API Key of the main account or the API Key of the sub-account to initiate the transfer. * * @param params Transfer parameters * @returns Promise */ submitSubToSubTransfer(params: SubmitSubToSubTransferReq): Promise ⋮---- /** * Query transfer status based on client_order_id or tx_id * * @param params Parameters for querying transfer status * @returns Promise<{ * tx_id: string; * status: 'PENDING' | 'SUCCESS' | 'FAIL' | 'PARTIAL_SUCCESS'; * }> */ getTransferStatus(params: { client_order_id?: string; tx_id?: string; }): Promise< ⋮---- /** * Retrieve withdrawal status * * @param params Parameters for retrieving withdrawal status * @returns Promise */ getWithdrawalStatus(params?: { currency?: string; }): Promise ⋮---- /** * Retrieve sub account balances * * @param params Parameters for retrieving sub account balances * @returns Promise */ getSubBalance( params?: GetSubAccountBalancesReq, ): Promise ⋮---- /** * Query sub accounts' margin balances * * @param params Parameters for querying sub accounts' margin balances * @returns Promise */ getSubMarginBalances(params?: { sub_uid?: string; }): Promise< ⋮---- /** * Query sub accounts' futures account balances * * @param params Parameters for querying sub accounts' futures account balances * @returns Promise */ getSubFuturesBalances(params?: { sub_uid?: string; settle?: string; }): Promise ⋮---- /** * Query subaccount's cross_margin account info * * @param params Parameters for querying subaccount's cross_margin account info * @returns Promise */ getSubCrossMarginBalances(params?: { sub_uid?: string; }): Promise ⋮---- /** * Query saved addresses * * @param params Parameters for querying saved address * @returns Promise */ getSavedAddresses(params: GetSavedAddressReq): Promise ⋮---- /** * Retrieve personal trading fee * * @param params Parameters for retrieving personal trading fee * @returns Promise */ getTradingFees(params?: { currency_pair?: string; settle?: 'BTC' | 'USDT' | 'USD'; }): Promise ⋮---- /** * Retrieve user's total balances * * This endpoint returns an approximate sum of exchanged amount from all currencies to input currency for each account. * The exchange rate and account balance could have been cached for at most 1 minute. It is not recommended to use its result for any trading calculation. * * For trading calculation, use the corresponding account query endpoint for each account type. For example: * - GET /spot/accounts to query spot account balance * - GET /margin/accounts to query margin account balance * - GET /futures/{settle}/accounts to query futures account balance * * @param params Parameters for retrieving total balances * @returns Promise */ getBalances(params?: ⋮---- /** * List small balance * * @returns Promise */ getSmallBalances(): Promise ⋮---- /** * Convert small balance * * @param params Parameters for converting small balance * @returns Promise */ convertSmallBalance(params?: { currency?: string[]; is_all?: boolean; }): Promise ⋮---- /** * List small balance history * * @param params Parameters for listing small balance history * @returns Promise */ getSmallBalanceHistory( params?: GetSmallBalanceHistoryReq, ): Promise ⋮---- /** * List push orders * * @param params Parameters for listing push orders * @returns Promise */ getPushOrders(params?: ListPushOrdersReq): Promise ⋮---- /** * Retrieve the list of low-liquidity or low-cap tokens * * @returns Promise */ getLowCapExchangeList(): Promise ⋮---- /**========================================================================================================================== * SUBACCOUNT * ========================================================================================================================== */ ⋮---- /** * Create a new sub-account * * @param params Parameters for creating a new sub-account * @returns Promise */ createSubAccount(params: CreateSubAccountReq): Promise ⋮---- /** * List sub-accounts * * @param params Parameters for listing sub-accounts * @returns Promise */ ⋮---- getSubAccounts(params?: ⋮---- /** * Get the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ getSubAccount(params: ⋮---- /** * Create API Key of the sub-account * * @param params Parameters for creating API Key of the sub-account * @returns Promise */ createSubAccountApiKey( params: CreateSubAccountApiKeyReq, ): Promise ⋮---- /** * List all API Key of the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ getSubAccountApiKeys(params: { user_id: number; }): Promise ⋮---- /** * Update API key of the sub-account * * Note: This interface cannot modify the mode account type attribute * * @param params Parameters for updating API key of the sub-account * @returns Promise */ updateSubAccountApiKey(params: UpdateSubAccountApiKeyReq): Promise ⋮---- /** * Delete API key of the sub-account * * @param params Parameters for deleting API key of the sub-account * @returns Promise */ deleteSubAccountApiKey(params: { user_id: number; key: string; }): Promise ⋮---- /** * Get the API Key of the sub-account * * @param params Parameters containing the sub-account user ID and API key * @returns Promise */ getSubAccountApiKey(params: { user_id: number; key: string; }): Promise ⋮---- /** * Lock the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ lockSubAccount(params: ⋮---- /** * Unlock the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ unlockSubAccount(params: ⋮---- /** * Get sub-account mode * * Unified account mode: * - classic: Classic account mode * - multi_currency: Multi-currency margin mode * - portfolio: Portfolio margin mode * * @returns Promise */ getSubAccountMode(): Promise ⋮---- /**========================================================================================================================== * UNIFIED * ========================================================================================================================== */ ⋮---- /** * Get unified account information * * The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account. * * For specific formulas, please refer to Margin Formula * * @param params Parameters for retrieving unified account information * @returns Promise */ getUnifiedAccountInfo(params?: { currency?: string; sub_uid?: string; }): Promise ⋮---- /** * Query about the maximum borrowing for the unified account * * @param params Parameters for querying the maximum borrowing for the unified account * @returns Promise<{ * currency: string; * amount: string; * }> */ getUnifiedMaxBorrow(params: ⋮---- /** * Query about the maximum transferable for the unified account * * @param params Parameters for querying the maximum transferable for the unified account * @returns Promise<{ * currency: string; * amount: string; * }> */ getUnifiedMaxTransferable(params: ⋮---- /** * Batch query maximum transferable amounts for unified accounts * * After withdrawing currency, the transferable amount will change. * * @param params Parameters containing currencies to query (up to 100 at once) * @returns Promise with array of currency and maximum transferable amount */ getUnifiedMaxTransferables(params: { currencies: string }): Promise< { currency: string; amount: string; }[] > { return this.getPrivate('/unified/transferables', params); ⋮---- getUnifiedBatchMaxBorrowable(params: ⋮---- /** * Borrow or repay * * When borrowing, it is essential to ensure that the borrowed amount is not below the minimum borrowing threshold for the specific cryptocurrency and does not exceed the maximum borrowing limit set by the platform and the user. * * The interest on the loan will be automatically deducted from the account at regular intervals. It is the user's responsibility to manage the repayment of the borrowed amount. * * For repayment, the option to repay the entire borrowed amount is available by setting the parameter repaid_all=true * * @param params Parameters for borrowing or repaying * @returns Promise */ submitUnifiedBorrowOrRepay( params: SubmitUnifiedBorrowOrRepayReq, ): Promise ⋮---- /** * List loans * * @param params Parameters for listing loans * @returns Promise */ getUnifiedLoans(params?: GetUnifiedLoansReq): Promise ⋮---- /** * Get loan records * * @param params Parameters for getting loan records * @returns Promise */ getUnifiedLoanRecords( params?: GetUnifiedLoanRecordsReq, ): Promise ⋮---- /** * List interest records * * @param params Parameters for listing interest records * @returns Promise */ getUnifiedInterestRecords( params?: GetUnifiedInterestRecordsReq, ): Promise ⋮---- /** * Retrieve user risk unit details, only valid in portfolio margin mode * * @returns Promise */ getUnifiedRiskUnitDetails(): Promise ⋮---- /** * Set mode of the unified account * * Switching between different account modes requires only passing the parameters corresponding to the target account mode. It also supports opening or closing configuration switches for the corresponding account mode when switching. * * @param params Parameters for setting the mode of the unified account * @returns Promise */ setUnifiedAccountMode(params: SetUnifiedAccountModeReq): Promise ⋮---- /** * Query mode of the unified account * * @returns Promise */ getUnifiedAccountMode(): Promise ⋮---- /** * Get unified estimate rate * * Due to fluctuations in lending depth, hourly interest rates may vary, and thus, I cannot provide exact rates. When a currency is not supported, the interest rate returned will be an empty string. * * @param params Parameters for querying estimate rates * @returns Promise<{ [key: string]: string }> */ getUnifiedEstimateRate(params: { currencies: string[]; }): Promise< ⋮---- /** * List currency discount tiers * * @returns Promise */ getUnifiedCurrencyDiscountTiers(): Promise ⋮---- /** * List loan margin tiers * * @returns Promise<{ * currency: string; * margin_tiers: MarginTier[]; * }[]> */ getLoanMarginTiers(): Promise< { currency: string; margin_tiers: MarginTier[]; }[] > { return this.get('/unified/loan_margin_tiers'); ⋮---- /** * Portfolio margin calculator * * Portfolio Margin Calculator When inputting a simulated position portfolio, each position includes the position name and quantity held, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. When inputting simulated orders, each order includes the market identifier, order price, and order quantity, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. Market orders are not included. * * @param params Parameters for portfolio margin calculator * @returns Promise */ portfolioMarginCalculate( params: PortfolioMarginCalculatorReq, ): Promise ⋮---- /** * Set leverage for all borrowed currencies * * Set leverage for all of a user's borrowed currencies. Currencies with outstanding loans cannot be changed. Values above a currency's leverage limit are capped. The response lists currencies whose updates failed together with the failure reason. * * @param params Parameters containing the leverage value * @returns Promise */ setUserLeverage( params: SetUserLeverageReq, ): Promise ⋮---- /** * Query user currency leverage configuration * * Get the maximum and minimum leverage multiples that users can set for a currency type * * @param params Parameters containing the currency * @returns Promise */ getUserCurrencyLeverageConfig(params: { currency: string; }): Promise ⋮---- /** * Get the user's currency leverage * * If currency is not passed, query all currencies. * * @param params Optional parameters containing the currency * @returns Promise */ getUserCurrencyLeverageSettings(params?: { currency?: string }): Promise< { currency: string; leverage: string; }[] > { return this.getPrivate('/unified/leverage/user_currency_setting', params); ⋮---- /** * Set the currency leverage ratio * * @param params Parameters for setting currency leverage ratio * @returns Promise Returns nothing on success (204 No Content) */ updateUserCurrencyLeverage(params: { currency: string; leverage: string; }): Promise ⋮---- /** * List loan currencies supported by unified account * * @param params Optional parameters for filtering * @returns Promise with array of loan currencies */ getUnifiedLoanCurrencies(params?: { currency?: string; }): Promise ⋮---- /** * Get historical lending rates * * @param params Parameters for retrieving historical lending rates * @returns Promise */ getHistoricalLendingRates( params: GetUnifiedHistoryLendingRateReq, ): Promise ⋮---- submitUnifiedLoanRepay(params: SubmitUnifiedLoanRepayReq): Promise ⋮---- /** * Get estimated quick repayment data (unified account, cross-currency or portfolio margin mode) */ getEstimatedQuickRepayment(): Promise ⋮---- /** * Execute quick repayment */ createQuickRepayment( params: CreateQuickRepaymentReq, ): Promise ⋮---- /** * Set Delta-neutral strategy mode (v4.106.97) * * Requires VIP level >= 4 and cross-currency margin mode. */ setUnifiedDeltaNeutral( params: SetUnifiedDeltaNeutralReq, ): Promise ⋮---- /** * Query Delta-neutral strategy mode setting (v4.106.97) */ getUnifiedDeltaNeutral(): Promise ⋮---- /**========================================================================================================================== * SPOT * ========================================================================================================================== */ ⋮---- /** * List all currencies' details * * Currency has two forms: * - Only currency name, e.g., BTC, USDT * - _, e.g., HT_ETH * * The latter one occurs when one currency has multiple chains. Currency detail contains a chain field whatever the form is. To retrieve all chains of one currency, you can use all the details which have the name of the currency or name starting with _. * * @returns Promise */ getSpotCurrencies(): Promise ⋮---- /** * Get details of a specific currency * * @param params Parameters for retrieving details of a specific currency * @returns Promise */ getSpotCurrency(params: ⋮---- /** * List all currency pairs supported * * @returns Promise */ getSpotCurrencyPairs(): Promise ⋮---- /** * Get details of a specific currency pair * * @param params Parameters for retrieving details of a specific currency pair * @returns Promise */ getSpotCurrencyPair(params: { currency_pair: string; }): Promise ⋮---- /** * Retrieve ticker information * * Return only related data if currency_pair is specified; otherwise return all of them. * * @param params Parameters for retrieving ticker information * @returns Promise */ getSpotTicker(params?: { currency_pair?: string; timezone?: 'utc0' | 'utc8' | 'all'; }): Promise ⋮---- /** * Retrieve order book * * Order book will be sorted by price from high to low on bids; low to high on asks. * * @param params Parameters for retrieving order book * @returns Promise */ getSpotOrderBook(params: GetSpotOrderBookReq): Promise ⋮---- /** * Retrieve market trades * * You can use from and to to query by time range, or use last_id by scrolling page. The default behavior is by time range. * Scrolling query using last_id is not recommended any more. If last_id is specified, time range query parameters will be ignored. * * @param params Parameters for retrieving market trades * @returns Promise */ getSpotTrades(params: GetSpotTradesReq): Promise ⋮---- /** * Market Candles * * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving market Candles * @returns Promise */ getSpotCandles(params: GetSpotCandlesReq): Promise ⋮---- /** * Query user trading fee rates * * This API is deprecated in favour of new fee retrieving API /wallet/fee. * * @param params Parameters for querying user trading fee rates * @returns Promise */ getSpotFeeRates(params?: ⋮---- /** * Query a batch of user trading fee rates * * @param params Parameters for querying a batch of user trading fee rates */ getSpotBatchFeeRates(params: { currency_pairs: string; }): Promise> ⋮---- /** * List spot accounts * * @param params Parameters for listing spot accounts * @returns Promise */ getSpotAccounts(params?: ⋮---- /** * Query account book * * Record time range cannot exceed 30 days. * * @param params Parameters for querying account book * @returns Promise */ getSpotAccountBook( params?: GetSpotAccountBookReq, ): Promise ⋮---- /** * Create a batch of orders * * Batch orders requirements: * - custom order field text is required * - At most 4 currency pairs, maximum 10 orders each, are allowed in one request * - No mixture of spot orders and margin orders, i.e. account must be identical for all orders * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating a batch of orders * @returns Promise */ submitSpotBatchOrders( body: SpotOrder[], params?: { xGateExptime?: number; }, ): Promise ⋮---- /** * List all open orders * * List open orders in all currency pairs. * Note that pagination parameters affect record number in each currency pair's open order list. No pagination is applied to the number of currency pairs returned. All currency pairs with open orders will be returned. * Spot, portfolio, and margin orders are returned by default. To list cross margin orders, account must be set to cross_margin. * * @param params Parameters for listing all open orders * @returns Promise */ getSpotOpenOrders(params?: { page?: number; limit?: number; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; }): Promise ⋮---- /** * Close position when cross-currency is disabled * * Currently, only cross-margin accounts are supported to close position when cross currencies are disabled. Maximum buy quantity = (unpaid principal and interest - currency balance - the amount of the currency in the order book) / 0.998 * * @param params Parameters for closing position when cross-currency is disabled * @returns Promise */ submitSpotClosePosCrossDisabled( params: SubmitSpotClosePosCrossDisabledReq, ): Promise ⋮---- /** * Create an order * * You can place orders with spot, portfolio, margin or cross margin account through setting the account field. It defaults to spot, which means spot account is used to place orders. If the user is using unified account, it defaults to the unified account. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating an order * @returns Promise */ submitSpotOrder(params: SubmitSpotOrderReq): Promise ⋮---- /** * List orders * * Spot, portfolio and margin orders are returned by default. If cross margin orders are needed, account must be set to cross_margin. * * @param params Parameters for listing orders * @returns Promise */ getSpotOrders(params: GetSpotOrdersReq): Promise ⋮---- /** * Cancel all open orders in specified currency pair * * If account is not set, all open orders, including spot, portfolio, margin and cross margin ones, will be cancelled. * You can set account to cancel only orders within the specified account. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling all open orders in specified currency pair * @returns Promise */ cancelSpotOpenOrders(params: { currency_pair: string; side?: 'buy' | 'sell'; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; trade_quote?: string; xGateExptime?: number; }): Promise ⋮---- /** * Cancel a batch of orders with an ID list * * Multiple currency pairs can be specified, but maximum 20 orders are allowed per request. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a batch of orders * @returns Promise */ batchCancelSpotOrders( body: CancelSpotBatchOrdersReq[], params?: { xGateExptime?: number; }, ): Promise ⋮---- /** * Get a single order * * Spot, portfolio and margin orders are queried by default. If cross margin orders are needed or portfolio margin account are used, account must be set to cross_margin. * * @param params Parameters for getting a single order * @returns Promise */ getSpotOrder(params: GetSpotOrderReq): Promise ⋮---- /** * Amend an order * * By default, the orders of spot, portfolio and margin account are updated. If you need to modify orders of the cross-margin account, you must specify account as cross_margin. For portfolio margin account, only cross_margin account is supported. * * Currently, only supports modification of price or amount fields. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for amending an order * @returns Promise */ updateSpotOrder(params: UpdateSpotOrderReq): Promise ⋮---- /** * Cancel a single order * * Spot, portfolio and margin orders are cancelled by default. If trying to cancel cross margin orders or portfolio margin account are used, account must be set to cross_margin. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a single order * @returns Promise */ cancelSpotOrder(params: DeleteSpotOrderReq): Promise ⋮---- /** * List personal trading history * * By default query of transaction records for spot, unified account and warehouse-by-site leverage accounts. * * The history within a specified time range can be queried by specifying from or (and) to. * * If no time parameters are specified, only data for the last 7 days can be obtained. * If only any parameter of from or to is specified, only 7-day data from the start (or end) of the specified time is returned. * The range not allowed to exceed 30 days. * The parameters of the time range filter are processed according to the order end time. * * The maximum number of pages when searching data using limit&page paging function is 100,0, that is, limit * (page - 1) <= 100,0. * * @param params Parameters for listing personal trading history * @returns Promise */ getSpotTradingHistory( params?: GetSpotTradingHistoryReq, ): Promise ⋮---- /** * Get server current time * * @returns Promise<{ * server_time: number; * }> */ getServerTime(): Promise< ⋮---- /** * Countdown cancel orders * * When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown. * * @param params Parameters for setting countdown cancel orders * @returns Promise<{ * triggerTime: number; * }> */ submitSpotCountdownOrders(params: { timeout: number; currency_pair?: string; }): Promise< ⋮---- /** * Batch modification of orders * * Default modification of orders for spot, portfolio, and margin accounts. To modify orders for a cross margin account, the account parameter must be specified as cross_margin. For portfolio margin accounts, the account parameter can only be specified as cross_margin. Currently, only modifications to price or quantity (choose one) are supported. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for batch modification of orders * @returns Promise */ batchUpdateSpotOrders( body: UpdateSpotBatchOrdersReq[], params?: { xGateExptime?: number; }, ): Promise ⋮---- /** * Query spot insurance fund historical data * * @param params Parameters for querying spot insurance fund history * @returns Promise<{ * currency: string; * balance: string; * time: number; * }[]> */ getSpotInsuranceHistory( params: GetSpotInsuranceHistoryReq, ): Promise ⋮---- /** * Create a price-triggered order * * @param params Parameters for creating a price-triggered order * @returns Promise<{ * id: number; * }> */ submitSpotPriceTriggerOrder(params: SpotPriceTriggeredOrder): Promise< ⋮---- /** * Retrieve running auto order list * * @param params Parameters for retrieving running auto order list * @returns Promise */ getSpotAutoOrders( params: GetSpotAutoOrdersReq, ): Promise ⋮---- /** * Cancel all open orders * * @param params Parameters for cancelling all open orders * @returns Promise */ cancelAllOpenSpotOrders(params?: { market?: string; account?: 'normal' | 'margin' | 'cross_margin'; }): Promise ⋮---- /** * Get a price-triggered order * * @param params Parameters for getting a price-triggered order * @returns Promise */ getPriceTriggeredOrder(params: { order_id: string; }): Promise ⋮---- /** * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order * @returns Promise */ cancelSpotTriggeredOrder(params: { order_id: string; }): Promise ⋮---- /** * List Spot POV orders * * List percentage-of-volume strategy orders. Status defaults to open when listing active orders. * * @param params Parameters for listing Spot POV orders * @returns Promise */ getSpotPovOrders(params: GetSpotPovOrdersReq): Promise ⋮---- /** * Create a Spot POV order * * Create a percentage-of-volume strategy order with a target participation rate, validity period, and optional limit/trigger prices. * * @param params Parameters for creating a Spot POV order * @returns Promise */ createSpotPovOrder(params: CreateSpotPovOrderReq): Promise ⋮---- /** * Cancel Spot POV orders * * Cancel Spot POV orders in bulk. Optionally filter by currency pair. * * @param params Optional parameters for cancelling Spot POV orders * @returns Promise */ cancelSpotPovOrders( params?: CancelSpotPovOrdersReq, ): Promise ⋮---- /** * Query Spot POV order details * * Supports the order ID returned after creation, or the custom ID specified in the text field. * * @param params Parameters containing the order ID * @returns Promise */ getSpotPovOrder(params: ⋮---- /** * Cancel a Spot POV order * * Supports the order ID returned after creation, or the custom ID specified in the text field. * * @param params Parameters containing the order ID * @returns Promise */ cancelSpotPovOrder(params: ⋮---- /** * Set collateral currency * * @param params Parameters for setting collateral currency * @returns Promise<{ * is_success: boolean; * }> */ setCollateralCurrency(params: { collateral_type: 0 | 1; enable_list?: string[]; disable_list?: string[]; }): Promise< ⋮---- /**========================================================================================================================== * MARGIN * ========================================================================================================================== */ ⋮---- /** * Margin account list * * @param params Parameters for listing margin accounts * @returns Promise */ getMarginAccounts(params?: { currency_pair?: string; }): Promise ⋮---- /** * List margin account balance change history * * Only transferals from and to margin account are provided for now. Time range allows 30 days at most. * * @param params Parameters for listing margin account balance change history * @returns Promise */ getMarginBalanceHistory( params?: GetMarginBalanceHistoryReq, ): Promise ⋮---- /** * Funding account list * * @param params Parameters for listing funding accounts * @returns Promise<{ * currency: string; * available: string; * locked: string; * lent: string; * total_lent: string; * }[]> */ getFundingAccounts(params?: { currency?: string }): Promise< { currency: string; available: string; locked: string; lent: string; total_lent: string; }[] > { return this.getPrivate('/margin/funding_accounts', params); ⋮---- /** * Update user's auto repayment setting * * @param params Parameters for updating auto repayment setting * @returns Promise<{ status: 'on' | 'off' }> */ updateAutoRepaymentSetting(params: { status: 'on' | 'off'; }): Promise< ⋮---- /** * Retrieve user auto repayment setting * * @returns Promise<{ status: 'on' | 'off' }> */ getAutoRepaymentSetting(): Promise< ⋮---- /** * Get the max transferable amount for a specific margin currency * * @param params Parameters for retrieving the max transferable amount * @returns Promise<{ * currency: string; * currency_pair?: string; * amount: string; * }> */ getMarginTransferableAmount(params: { currency: string; currency_pair?: string; }): Promise< ⋮---- /** * @deprecated as of 2025-02-10 * Currencies supported by cross margin * * @returns Promise */ getCrossMarginCurrencies(): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve detail of one single currency supported by cross margin * * @param params Parameters containing the currency name * @returns Promise */ getCrossMarginCurrency(params: { currency: string; }): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve cross margin account * * @returns Promise */ getCrossMarginAccount(): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve cross margin account change history * * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving cross margin account change history * @returns Promise */ getCrossMarginAccountHistory( params?: GetCrossMarginAccountHistoryReq, ): Promise ⋮---- /** * * @deprecated as of 2025-02-10 * Create a cross margin borrow loan * * Borrow amount cannot be less than currency minimum borrow amount. * * @param params Parameters for creating a cross margin borrow loan * @returns Promise * */ submitCrossMarginBorrowLoan( params: SubmitCrossMarginBorrowLoanReq, ): Promise ⋮---- /** * * List cross margin borrow history * * Sort by creation time in descending order by default. Set reverse=false to return ascending results. * * @param params Parameters for listing cross margin borrow history * @returns Promise */ getCrossMarginBorrowHistory( params: GetCrossMarginBorrowHistoryReq, ): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve single borrow loan detail * * @param params Parameters containing the borrow loan ID * @returns Promise */ getCrossMarginBorrowLoan(params: { loan_id: string; }): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Cross margin repayments * * When the liquidity of the currency is insufficient and the transaction risk is high, the currency will be disabled, and funds cannot be transferred. When the available balance of cross-margin is insufficient, the balance of the spot account can be used for repayment. Please ensure that the balance of the spot account is sufficient, and system uses cross-margin account for repayment first. * * @param params Parameters for cross margin repayments * @returns Promise */ submitCrossMarginRepayment(params: { currency: string; amount: string; }): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve cross margin repayments * * Sort by creation time in descending order by default. Set reverse=false to return ascending results. * * @param params Parameters for retrieving cross margin repayments * @returns Promise */ getCrossMarginRepayments( params?: GetCrossMarginRepaymentsReq, ): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Interest records for the cross margin account * * @param params Parameters for retrieving interest records * @returns Promise */ getCrossMarginInterestRecords( params?: GetCrossMarginInterestRecordsReq, ): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Get the max transferable amount for a specific cross margin currency * * @param params Parameters for retrieving the max transferable amount * @returns Promise<{ * currency: string; * amount: string; * }> */ getCrossMarginTransferableAmount(params: ⋮---- /** * @deprecated as of 2025-02-10 * Estimated interest rates * * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. * * @param params Parameters for retrieving estimated interest rates * @returns Promise */ getEstimatedInterestRates(params: ⋮---- /** * @deprecated as of 2025-02-10 * Get the max borrowable amount for a specific cross margin currency * * @param params Parameters for retrieving the max borrowable amount * @returns Promise<{ * currency: string; * amount: string; * }> */ getCrossMarginBorrowableAmount(params: ⋮---- /** * Check the user's own leverage lending gradient in the current market * * @param params Parameters containing currency pair to query * @returns Promise with array of market gradient information */ getMarginUserLoanTiers(params: { currency_pair: string }): Promise< { tier_amount: string; mmr: string; leverage: string; }[] > { return this.getPrivate('/margin/user/loan_margin_tiers', params); ⋮---- /** * Query the current market leverage lending gradient * * @param params Parameters containing currency pair to query * @returns Promise with array of market gradient information */ getMarginPublicLoanTiers(params: { currency_pair: string }): Promise< { tier_amount: string; mmr: string; leverage: string; }[] > { return this.get('/margin/loan_margin_tiers', params); ⋮---- /** * Set the user market leverage multiple * * @param params Parameters containing currency pair and leverage value * @returns Promise - Returns nothing on success (204 No Content) */ setMarginUserLeverage(params: { currency_pair: string; leverage: string; }): Promise ⋮---- /** * Query the user's leverage account list * * Supports querying risk rate per position account and margin rate per position account * * @param params Optional parameters for filtering by currency pair * @returns Promise with array of margin account details */ getMarginUserAccounts(params?: { currency_pair?: string; }): Promise ⋮---- /**========================================================================================================================== * MARGIN UNI * ========================================================================================================================== */ /** * List lending markets * * @returns Promise */ getLendingMarkets(): Promise ⋮---- /** * Get detail of lending market * * @param params Parameters containing the currency pair * @returns Promise<{ * currency_pair: string; * base_min_borrow_amount: string; * quote_min_borrow_amount: string; * leverage: string; * }> */ getLendingMarket(params: ⋮---- /** * Estimate interest rate * * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. * * @param params Parameters for retrieving estimated interest rates * @returns Promise */ getEstimatedInterestRate(params: ⋮---- /** * Borrow or repay * * @param params Parameters for borrowing or repaying * @returns Promise */ submitMarginUNIBorrowOrRepay(params: { currency: string; type: 'borrow' | 'repay'; amount: string; currency_pair: string; repaid_all?: boolean; }): Promise ⋮---- /** * List loans * * @param params Parameters for listing loans * @returns Promise */ getMarginUNILoans(params?: GetMarginUNILoansReq): Promise ⋮---- /** * Get loan records * * @param params Parameters for retrieving loan records * @returns Promise */ getMarginUNILoanRecords( params?: GetMarginUNILoanRecordsReq, ): Promise ⋮---- /** * List interest records * * @param params Parameters for listing interest records * @returns Promise */ getMarginUNIInterestRecords( params?: GetMarginUNIInterestRecordsReq, ): Promise ⋮---- /** * Get maximum borrowable * * @param params Parameters for retrieving the maximum borrowable amount * @returns Promise */ getMarginUNIMaxBorrow( params: GetMarginUNIMaxBorrowReq, ): Promise /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== */ ⋮---- /** * List All Supported Currency Pairs In Flash Swap * * @param params Parameters for retrieving data of the specified currency * @returns Promise */ getFlashSwapCurrencyPairs(params?: { currency?: string; page?: number; limit?: number; }): Promise ⋮---- /** * Create a flash swap order * * Initiate a flash swap preview in advance because order creation requires a preview result. * * @param params Parameters for creating a flash swap order * @returns Promise */ submitFlashSwapOrder( params: SubmitFlashSwapOrderReq, ): Promise ⋮---- /** * List all flash swap orders * * @param params Parameters for listing flash swap orders * @returns Promise */ getFlashSwapOrders( params?: GetFlashSwapOrdersReq, ): Promise ⋮---- /** * Get a single flash swap order's detail * * @param params Parameters containing the flash swap order ID * @returns Promise */ getFlashSwapOrder(params: ⋮---- /** * Initiate a flash swap order preview * * @param params Parameters for initiating a flash swap order preview * @returns Promise */ submitFlashSwapOrderPreview( params: SubmitFlashSwapOrderPreviewReq, ): Promise ⋮---- /**========================================================================================================================== * FUTURES * ========================================================================================================================== */ ⋮---- /** * List all futures contracts * * @param params Parameters for listing futures contracts * @returns Promise */ getFuturesContracts(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; limit?: number; offset?: number; }): Promise ⋮---- /** * Get a single contract * * @param params Parameters for retrieving a single contract * @returns Promise */ getFuturesContract(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; }): Promise ⋮---- listFuturesADLRiskStates( params: GetFuturesADLRiskStatesReq, ): Promise ⋮---- /** * Futures order book * * Bids will be sorted by price from high to low, while asks sorted reversely. * * @param params Parameters for retrieving the futures order book * @returns Promise */ getFuturesOrderBook( params: GetFuturesOrderBookReq, ): Promise ⋮---- /** * Futures trading history * * @param params Parameters for retrieving futures trading history * @returns Promise */ getFuturesTrades(params: GetFuturesTradesReq): Promise ⋮---- /** * Get futures Candles * * Return specified contract Candles. If prefix contract with mark_, the contract's mark price Candles are returned; if prefix with index_, index price Candles will be returned. * * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving futures Candles * @returns Promise */ getFuturesCandles(params: GetFuturesCandlesReq): Promise ⋮---- /** * Premium Index K-Line * * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving premium index K-Line * @returns Promise */ getPremiumIndexKLines( params: GetFuturesCandlesReq, ): Promise ⋮---- /** * List futures tickers * * @param params Parameters for listing futures tickers * @returns Promise */ getFuturesTickers(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract?: string; }): Promise ⋮---- /** * Funding rate history * * @param params Parameters for retrieving funding rate history * @returns Promise<{ * t: number; * r: string; * }[]> */ getFundingRates(params: GetFundingRatesReq): Promise< { t: number; r: string; }[] > { const { settle, ...query } = params; return this.get(`/futures/$ ⋮---- /** * Batch query historical funding rate data for perpetual contracts * * @param params settle and array of contract names * @returns Promise */ getBatchFundingRates( params: BatchFundingRatesReq, ): Promise ⋮---- /** * Futures insurance balance history * * @param params Parameters for retrieving futures insurance balance history * @returns Promise<{ * t: number; * b: string; * }[]> */ getFuturesInsuranceBalanceHistory(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; limit?: number; }): Promise< { t: number; b: string; }[] > { const { settle, ...query } = params; return this.get(`/futures/$ ⋮---- /** * Futures stats * * @param params Parameters for retrieving futures stats * @returns Promise */ getFuturesStats(params: GetFuturesStatsReq): Promise ⋮---- /** * Get index constituents * * @param params Parameters for retrieving index constituents * @returns Promise */ getIndexConstituents(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; index: string; }): Promise ⋮---- /** * Retrieve liquidation history * * Interval between from and to cannot exceed 3600. Some private fields will not be returned in public endpoints. Refer to field description for detail. * * @param params Parameters for retrieving liquidation history * @returns Promise */ getLiquidationHistory( params: GetLiquidationHistoryReq, ): Promise ⋮---- /** * List risk limit tiers * * When the 'contract' parameter is not passed, the default is to query the risk limits for the top 100 markets. * 'Limit' and 'offset' correspond to pagination queries at the market level, not to the length of the returned array. * This only takes effect when the 'contract' parameter is empty. * * @param params Parameters for listing risk limit tiers * @returns Promise */ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise ⋮---- /** * Query futures account * * Query account information for classic future account and unified account * * @param params Parameters for querying futures account * @returns Promise */ getFuturesAccount(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; }): Promise ⋮---- /** * Query account book * * If the contract field is provided, it can only filter records that include this field after 2023-10-30. * * @param params Parameters for querying account book * @returns Promise */ getFuturesAccountBook( params: GetFuturesAccountBookReq, ): Promise ⋮---- /** * List all positions of a user * * @param params Parameters for listing all positions of a user * @returns Promise */ getFuturesPositions( params: GetFuturesPositionsReq, ): Promise ⋮---- /** * Get single position * * Clarifies dual-position query method when holding both long and short positions in the same contract market * * @param params Parameters for retrieving a single position * @returns Promise */ getFuturesPosition(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; }): Promise ⋮---- /** * Update position margin * * Under the new risk limit rules, the position limit is related to the leverage you set; a lower leverage will result in a higher position limit. Please use the leverage adjustment api to adjust the position limit. * * @param params Parameters for updating position margin * @returns Promise */ updateFuturesMargin(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; change: string; }): Promise ⋮---- /** * Update position leverage * * Position Mode Switching Rules: * - leverage ≠ 0: Isolated Margin Mode (Regardless of whether cross_leverage_limit is filled, this parameter will be ignored) * - leverage = 0: Cross Margin Mode (Use cross_leverage_limit to set the leverage multiple) * * Examples: * - Set isolated margin with 10x leverage: leverage=10 * - Set cross margin with 10x leverage: leverage=0&cross_leverage_limit=10 * - leverage=5&cross_leverage_limit=10 → Result: Isolated margin with 5x leverage (cross_leverage_limit is ignored) * * Warning: Incorrect settings may cause unexpected position mode switching, affecting risk management. * * @param params Parameters for updating position leverage * @returns Promise */ updateFuturesLeverage(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; leverage: string; cross_leverage_limit?: string; pid?: number; // Product ID }): Promise ⋮---- pid?: number; // Product ID ⋮---- /** * Get leverage for a contract in split / dual-side mode (requires pos_margin_mode and dual_side). * * @param params settle, contract, pos_margin_mode, dual_side * @returns Promise — response field `Lever` is the leverage string */ getFuturesContractLeverage( params: GetFuturesContractLeverageReq, ): Promise ⋮---- /** * Update position by store mode * * @param params Parameters for updating position by store mode * @returns Promise */ updateFuturesPositionMode(params: { settle: 'btc' | 'usdt'; mode: 'ISOLATED' | 'CROSS'; contract: string; }): Promise ⋮---- /** * Update position risk limit * * @param params Parameters for updating position risk limit * @returns Promise */ updatePositionRiskLimit(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; risk_limit: string; }): Promise ⋮---- /** * Enable or disable dual mode * * Before setting dual mode, make sure all positions are closed and no orders are open. * * @param params Parameters for enabling or disabling dual mode * @returns Promise */ updateFuturesDualMode(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; dual_mode: boolean; }): Promise ⋮---- /** * Retrieve position detail in dual mode * * @param params Parameters for retrieving position detail in dual mode * @returns Promise */ getDualModePosition(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; }): Promise ⋮---- /** * Update position margin in dual mode * * @param params Parameters for updating position margin in dual mode * @returns Promise */ updateDualModePositionMargin( params: UpdateDualModePositionMarginReq, ): Promise ⋮---- /** * Update position leverage in dual mode * * @param params Parameters for updating position leverage in dual mode * @returns Promise */ updateDualModePositionLeverage( params: UpdateDualModePositionLeverageReq, ): Promise ⋮---- /** * Update position risk limit in dual mode * * @param params Parameters for updating position risk limit in dual mode * @returns Promise */ /** * Update position risk limit in dual mode * * See risk limit rules for more information * * @param params Parameters for updating position risk limit in dual mode * @returns Promise */ updateDualModePositionRiskLimit(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; risk_limit: string; }): Promise ⋮---- /** * Create a futures order * * Creating futures orders requires size, which is the number of contracts instead of currency amount. You can use quanto_multiplier in the contract detail response to know how much currency 1 size contract represents. * Zero-filled order cannot be retrieved 10 minutes after order cancellation. You will get a 404 not found for such orders. * Set reduce_only to true to keep the position from changing side when reducing position size. * In single position mode, to close a position, you need to set size to 0 and close to true. * In dual position mode, to close one side position, you need to set auto_size side, reduce_only to true, and size to 0. * Set stp_act to decide the strategy of self-trade prevention. For detailed usage, refer to the stp_act parameter in the request body. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating a futures order * @returns Promise */ submitFuturesOrder(params: SubmitFuturesOrderReq): Promise ⋮---- /** * List futures orders * * Zero-fill order cannot be retrieved for 10 minutes after cancellation. * Historical orders, by default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/orders_timerange. * * @param params Parameters for listing futures orders * @returns Promise */ getFuturesOrders(params: GetFuturesOrdersReq): Promise ⋮---- /** * Cancel all open orders matched * * Zero-filled order cannot be retrieved 10 minutes after order cancellation. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling all open orders matched * @returns Promise */ cancelAllFuturesOrders( params: DeleteAllFuturesOrdersReq, ): Promise ⋮---- /** * List Futures Orders By Time Range * * @param params Parameters for listing futures orders by time range * @returns Promise */ getFuturesOrdersByTimeRange( params: GetFuturesOrdersByTimeRangeReq, ): Promise ⋮---- /** * Create a batch of futures orders * * Up to 10 orders per request. * If any of the order's parameters are missing or in the wrong format, all of them will not be executed, and a http status 400 error will be returned directly. * If the parameters are checked and passed, all are executed. Even if there is a business logic error in the middle (such as insufficient funds), it will not affect other execution orders. * The returned result is in array format, and the order corresponds to the orders in the request body. * In the returned result, the succeeded field of type bool indicates whether the execution was successful or not. * If the execution is successful, the normal order content is included; if the execution fails, the label field is included to indicate the cause of the error. * In the rate limiting, each order is counted individually. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating a batch of futures orders * @returns Promise */ submitFuturesBatchOrders(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd' | 'usd1'; orders: SubmitFuturesOrderReq[]; }): Promise ⋮---- /** * Get a single order * * Zero-fill order cannot be retrieved for 10 minutes after cancellation. * Historical orders, by default, only data within the past 6 months is supported. * * @param params.order_id Exchange order id (numeric), **or** the order's custom client id from the `text` field — same path segment as in `GET /futures/{settle}/orders/{order_id}`. * @returns Promise */ getFuturesOrder(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; order_id: string; }): Promise ⋮---- /** * Cancel a single order * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a single order * @returns Promise */ cancelFuturesOrder(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd' | 'usd1'; order_id: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise ⋮---- /** * Amend an order * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for amending an order * @returns Promise */ updateFuturesOrder(params: UpdateFuturesOrderReq): Promise ⋮---- /** * List personal trading history * * By default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/my_trades_timerange. * * @param params Parameters for listing personal trading history * @returns Promise */ getFuturesTradingHistory( params: GetFuturesTradingHistoryReq, ): Promise ⋮---- /** * List personal trading history * * This endpoint is for data longer than 6 months. * * @param params Parameters for listing personal trading history * @returns Promise */ getFuturesTradingHistoryByTimeRange( params: GetFuturesTradingHistoryByTimeRangeReq, ): Promise ⋮---- /** * List position close history * * @param params Parameters for listing position close history * @returns Promise */ getFuturesPositionHistory( params: GetFuturesPositionHistoryReq, ): Promise ⋮---- /** * List liquidation history * * @param params Parameters for listing liquidation history * @returns Promise */ getFuturesLiquidationHistory( params: GetFuturesLiquidationHistoryReq, ): Promise ⋮---- /** * List Auto-Deleveraging History * * @param params Parameters for listing auto-deleveraging history * @returns Promise */ getFuturesAutoDeleveragingHistory( params: GetFuturesLiquidationHistoryReq, ): Promise ⋮---- /** * Countdown cancel orders * * When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown. * For example, call this endpoint at 30s intervals, each countdown timeout is set to 30s. If this endpoint is not called again within 30 seconds, all pending orders on the specified market will be automatically cancelled, if no market is specified, all market pending orders will be cancelled. * If the timeout is set to 0 within 30 seconds, the countdown timer will expire and the cancel function will be cancelled. * * @param params Parameters for setting countdown cancel orders * @returns Promise<{ triggerTime: number }> */ setFuturesOrderCancelCountdown(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; timeout: number; contract?: string; }): Promise< ⋮---- /** * Query user trading fee rates * * @param params Parameters for querying user trading fee rates * @returns Promise */ getFuturesUserTradingFees(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract?: string; }): Promise ⋮---- /** * Cancel a batch of orders with an ID list * * Multiple distinct order ID list can be specified. Each request can cancel a maximum of 20 records. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a batch of orders with an ID list * @returns Promise */ batchCancelFuturesOrders(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd' | 'usd1'; orderIds: string[]; }): Promise ⋮---- /** * Batch modify orders with specified IDs * * You can specify multiple different order IDs. You can only modify up to 10 orders in one request. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Array of BatchAmendOrderReq objects * @param settle Settlement currency (e.g., 'btc', 'usdt', 'usd') * @returns Promise */ batchUpdateFuturesOrders(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd' | 'usd1'; orders: BatchAmendOrderReq[]; }): Promise ⋮---- /** * Query risk limit table by table_id * * @param params Parameters for querying risk limit table * @returns Promise */ getRiskLimitTable( params: GetRiskLimitTableReq, ): Promise ⋮---- /** * Create a price-triggered order * * @param params Parameters for creating a price-triggered order * @returns Promise */ submitFuturesPriceTriggeredOrder( params: SubmitFuturesTriggeredOrderReq, ): Promise ⋮---- /** * List all auto orders * * @param params Parameters for listing all auto orders * @returns Promise */ getFuturesAutoOrders( params: GetFuturesAutoOrdersReq, ): Promise ⋮---- /** * Cancel all open orders * * @param params Parameters for cancelling all open orders * @returns Promise */ cancelAllOpenFuturesOrders(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; contract: string; }): Promise ⋮---- /** * Get a price-triggered order * * @param params Parameters for retrieving a price-triggered order * @returns Promise */ getFuturesPriceTriggeredOrder(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; order_id: number; }): Promise ⋮---- /** * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order * @returns Promise */ cancelFuturesPriceTriggeredOrder(params: { settle: 'btc' | 'usdt' | 'usd' | 'usd1'; order_id: number; }): Promise ⋮---- /** * Update a single price-triggered order * * @param params Parameters for updating a price-triggered order * @returns Promise */ updateFuturesPriceTriggeredOrder( params: UpdateFuturesPriceTriggeredOrderReq, ): Promise ⋮---- /** * Create trail order * * @param params settle and trail order parameters * @returns Promise with code, message, data containing id and timestamp */ createTrailOrder(params: CreateTrailOrderReq): Promise< ⋮---- /** * Terminate trail order * * @param params settle and id or text * @returns Promise */ terminateTrailOrder(params: TerminateTrailOrderReq): Promise ⋮---- /** * Batch terminate trail orders * * @param params settle and optional contract, related_position * @returns Promise<{ orders: TrailOrder[] }> */ batchTerminateTrailOrders( params: BatchTerminateTrailOrdersReq, ): Promise< ⋮---- /** * Get trail order list * * @param params query parameters * @returns Promise<{ orders: TrailOrder[] }> */ getTrailOrderList( params: GetTrailOrderListReq, ): Promise< ⋮---- /** * Get trail order details * * @param params settle and order id * @returns Promise with code, message, data.order */ getTrailOrderDetail(params: GetTrailOrderDetailReq): Promise< ⋮---- /** * Update trail order * * @param params settle, id and fields to update * @returns Promise */ updateTrailOrder(params: UpdateTrailOrderReq): Promise ⋮---- /** * Get trail order user modification records * * @param params settle, id and optional pagination * @returns Promise<{ change_log: TrailChangeLog[] }> */ getTrailOrderChangeLog( params: GetTrailOrderChangeLogReq, ): Promise< ⋮---- /** * Create a chase limit order */ createChaseOrder(params: CreateChaseOrderReq): Promise ⋮---- /** * Stop a chase order */ stopChaseOrder(params: StopChaseOrderReq): Promise ⋮---- /** * Stop chase orders in batch */ stopAllChaseOrders( params: StopAllChaseOrdersReq, ): Promise ⋮---- /** * List chase orders */ getChaseOrders(params: GetChaseOrdersReq): Promise ⋮---- /** * Get chase order detail */ getChaseOrderDetail( params: GetChaseOrderDetailReq, ): Promise ⋮---- getFuturesPositionCloseHistory( params: GetFuturesPositionCloseHistoryReq, ): Promise ⋮---- getFuturesInsuranceHistory( params: GetFuturesInsuranceReq, ): Promise ⋮---- /**========================================================================================================================== * DELIVERY * ========================================================================================================================== */ ⋮---- /** * List all futures contracts * * @param params Parameters for listing all futures contracts * @returns Promise */ getAllDeliveryContracts(params: { settle: 'usdt'; }): Promise ⋮---- /** * Get a single contract * * @param params Parameters for retrieving a single contract * @returns Promise */ getDeliveryContract(params: { settle: 'usdt'; contract: string; }): Promise ⋮---- /** * Futures order book * * Bids will be sorted by price from high to low, while asks sorted reversely * * @param params Parameters for retrieving the futures order book * @returns Promise */ getDeliveryOrderBook( params: GetDeliveryOrderBookReq, ): Promise ⋮---- /** * Futures trading history * * @param params Parameters for retrieving the futures trading history * @returns Promise */ getDeliveryTrades(params: GetDeliveryTradesReq): Promise ⋮---- /** * Get futures Candles * * Return specified contract Candles. If prefix contract with mark_, the contract's mark price Candles are returned; if prefix with index_, index price Candles will be returned. * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving futures Candles * @returns Promise */ getDeliveryCandles(params: GetDeliveryCandlesReq): Promise ⋮---- /** * List futures tickers * * @param params Parameters for listing futures tickers * @returns Promise */ getDeliveryTickers(params: { settle: 'usdt'; contract?: string; }): Promise ⋮---- /** * Futures insurance balance history * * @param params Parameters for retrieving the futures insurance balance history * @returns Promise<{ * t: number; * b: string; * }[]> */ getDeliveryInsuranceBalanceHistory(params: { settle: 'usdt'; limit?: number; }): Promise< { t: number; b: string; }[] > { const { settle, ...query } = params; return this.get(`/delivery/$ ⋮---- /** * Query futures account * * @param params Parameters for querying futures account * @returns Promise */ getDeliveryAccount(params: ⋮---- /** * Query account book * * @param params Parameters for querying account book * @returns Promise */ getDeliveryBook(params: GetDeliveryBookReq): Promise ⋮---- /** * List all positions of a user * * @param params Parameters for listing all positions of a user * @returns Promise */ getDeliveryPositions(params: ⋮---- /** * Get single position * * @param params Parameters for retrieving a single position * @returns Promise */ getDeliveryPosition(params: { settle: 'usdt'; contract: string; }): Promise ⋮---- /** * Update position margin * * @param params Parameters for updating position margin * @returns Promise */ updateDeliveryMargin(params: { settle: 'usdt'; contract: string; change: string; }): Promise ⋮---- /** * Update position leverage * * @param params Parameters for updating position leverage * @returns Promise */ updateDeliveryLeverage(params: { settle: 'usdt'; contract: string; leverage: string; }): Promise ⋮---- /** * Update position risk limit * * @param params Parameters for updating position risk limit * @returns Promise */ updateDeliveryRiskLimit(params: { settle: 'usdt'; contract: string; risk_limit: string; }): Promise ⋮---- /** * Create a futures order * * Zero-filled order cannot be retrieved 10 minutes after order cancellation * * @param params Parameters for creating a futures order * @returns Promise */ submitDeliveryOrder( params: SubmitDeliveryFuturesOrderReq, ): Promise ⋮---- /** * List futures orders * * Zero-fill order cannot be retrieved 10 minutes after order cancellation. * * @param params Parameters for listing futures orders * @returns Promise */ getDeliveryOrders(params: GetDeliveryOrdersReq): Promise ⋮---- /** * Cancel all open orders matched * * Zero-filled order cannot be retrieved 10 minutes after order cancellation * * @param params Parameters for cancelling all open orders matched * @returns Promise */ cancelAllDeliveryOrders(params: { settle: 'usdt'; contract: string; side?: 'ask' | 'bid'; }): Promise ⋮---- /** * Get a single order * * Zero-filled order cannot be retrieved 10 minutes after order cancellation * * @param params Parameters for retrieving a single order * @returns Promise */ getDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /** * Cancel a single order * * @param params Parameters for cancelling a single order * @returns Promise */ cancelDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /** * List personal trading history * * @param params Parameters for listing personal trading history * @returns Promise */ getDeliveryTradingHistory( params: GetDeliveryTradingHistoryReq, ): Promise ⋮---- /** * List position close history * * @param params Parameters for listing position close history * @returns Promise */ getDeliveryClosedPositions( params: GetDeliveryClosedPositionsReq, ): Promise ⋮---- /** * List liquidation history * * @param params Parameters for listing liquidation history * @returns Promise */ getDeliveryLiquidationHistory( params: GetDeliveryLiquidationHistoryReq, ): Promise ⋮---- /** * List settlement history * * @param params Parameters for listing settlement history * @returns Promise */ getDeliverySettlementHistory( params: GetDeliverySettlementHistoryReq, ): Promise ⋮---- /** * Create a price-triggered order * * @param params Parameters for creating a price-triggered order * @returns Promise */ submitDeliveryTriggeredOrder( params: SubmitFuturesTriggeredOrderReq, ): Promise ⋮---- /** * List all auto orders * * @param params Parameters for listing all auto orders * @returns Promise */ getDeliveryAutoOrders( params: GetDeliveryAutoOrdersReq, ): Promise ⋮---- /** * Cancel all open orders * * @param params Parameters for cancelling all open orders * @returns Promise */ cancelAllOpenDeliveryOrders(params: { settle: 'usdt'; contract: string; }): Promise ⋮---- /** * Get a price-triggered order * * @param params Parameters for retrieving a price-triggered order * @returns Promise */ getDeliveryTriggeredOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /** * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order * @returns Promise */ cancelTriggeredDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /**========================================================================================================================== * OPTIONS * ========================================================================================================================== */ ⋮---- /** * List all underlyings * * @returns Promise<{ name: string; index_price: string }[]> */ getOptionsUnderlyings(): Promise< ⋮---- /** * List all expiration times * * @param params Parameters for listing expiration times * @returns Promise */ getOptionsExpirationTimes(params: ⋮---- /** * List all the contracts with specified underlying and expiration time * * @param params Parameters for listing contracts * @returns Promise */ getOptionsContracts(params: { underlying: string; expiration?: number; }): Promise ⋮---- /** * Query specified contract detail * * @param params Parameters for querying specified contract detail * @returns Promise */ getOptionsContract(params: ⋮---- /** * List settlement history * * @param params Parameters for listing settlement history * @returns Promise */ getOptionsSettlementHistory( params: GetOptionsSettlementHistoryReq, ): Promise ⋮---- /** * Get specified contract's settlement * * @param params Parameters for retrieving specified contract's settlement * @returns Promise */ getOptionsContractSettlement(params: { contract: string; underlying: string; at: number; }): Promise ⋮---- /** * List my options settlements * * @param params Parameters for listing my options settlements * @returns Promise */ getOptionsMySettlements( params: GetOptionsMySettlementsReq, ): Promise ⋮---- /** * Options order book * * Bids will be sorted by price from high to low, while asks sorted reversely * * @param params Parameters for retrieving options order book * @returns Promise */ getOptionsOrderBook( params: GetOptionsOrderBookReq, ): Promise ⋮---- /** * List tickers of options contracts * * @param params Parameters for listing tickers of options contracts * @returns Promise */ getOptionsTickers(params: ⋮---- /** * Get underlying ticker * * @param params Parameters for retrieving underlying ticker * @returns Promise<{ * trade_put: number; * trade_call: number; * index_price: string; * }> */ getOptionsUnderlyingTicker(params: ⋮---- /** * Get options Candles * * @param params Parameters for retrieving options Candles * @returns Promise */ getOptionsCandles(params: GetOptionsCandlesReq): Promise ⋮---- /** * Mark price Candles of an underlying * * @param params Parameters for retrieving mark price Candles of an underlying * @returns Promise */ getOptionsUnderlyingCandles( params: GetOptionsUnderlyingCandlesReq, ): Promise ⋮---- /** * Options trade history * * @param params Parameters for retrieving options trade history * @returns Promise */ getOptionsTrades(params: GetOptionsTradesReq): Promise ⋮---- /** * List options account * * Indicates support for querying both classic options accounts and unified accounts * * @returns Promise */ getOptionsAccount(): Promise ⋮---- /** * List account changing history * * @param params Parameters for listing account changing history * @returns Promise */ getOptionsAccountChange( params?: GetOptionsAccountChangeReq, ): Promise ⋮---- /** * List user's positions of specified underlying * * @param params Parameters for listing user's positions of specified underlying * @returns Promise */ getOptionsPositionsUnderlying(params: { underlying?: string; }): Promise ⋮---- /** * Get specified contract position * * @param params Parameters for retrieving specified contract position * @returns Promise */ getOptionsPositionContract(params: { contract: string; }): Promise ⋮---- /** * List user's liquidation history of specified underlying * * @param params Parameters for listing user's liquidation history of specified underlying * @returns Promise */ getOptionsLiquidation(params: { underlying: string; contract?: string; }): Promise ⋮---- /** * Create an options order * * @param params Parameters for creating an options order * @returns Promise */ submitOptionsOrder( params: SubmitOptionsOrderReq, ): Promise ⋮---- /** * List options orders * * @param params Parameters for listing options orders * @returns Promise */ getOptionsOrders( params: GetOptionsOrdersReq, ): Promise ⋮---- /** * Cancel all open orders matched * * @param params Parameters for canceling all open orders matched * @returns Promise */ cancelAllOpenOptionsOrders(params: { contract?: string; underlying?: string; side?: 'ask' | 'bid'; }): Promise ⋮---- /** * Get a single order * * @param params Parameters for retrieving a single order * @returns Promise */ getOptionsOrder(params: { order_id: number; }): Promise ⋮---- /** * Amend an options order (modify price and/or size). Only orders with status `open` are supported. * * @param params order_id and amendment body (`contract` is required) * @returns Promise */ amendOptionsOrder( params: { order_id: number; } & AmendOptionsOrderReq, ): Promise ⋮---- /** * Cancel a single order * * @param params Parameters for canceling a single order * @returns Promise */ cancelOptionsOrder(params: { order_id: number; }): Promise ⋮---- /** * Countdown cancel orders for options * * Option order heartbeat detection. When the timeout set by the user is reached, * if there is no cancel or new countdown set, related pending orders will be * automatically cancelled. This endpoint can be called repeatedly to set a new * countdown or cancel the countdown. * * @param params Parameters for setting countdown cancel orders * @returns Promise<{ * triggerTime: number; * }> */ submitOptionsCountdownCancel(params: { timeout: number; contract?: string; underlying?: string; }): Promise< ⋮---- /** * List personal trading history * * @param params Parameters for listing personal trading history * @returns Promise */ getOptionsPersonalHistory( params: GetOptionsPersonalHistoryReq, ): Promise ⋮---- /** * Set MMP (Market Maker Protection) settings * * @param params Parameters for setting MMP settings * @returns Promise */ setOptionsMMPSettings( params: OptionsMMPSettingsReq, ): Promise ⋮---- /** * Query MMP (Market Maker Protection) settings * * @param params Parameters for querying MMP settings * @returns Promise */ getOptionsMMPSettings(params?: { underlying?: string; }): Promise ⋮---- /** * Reset MMP (Market Maker Protection) settings * * @param params Parameters for resetting MMP settings * @returns Promise */ resetOptionsMMPSettings(params: { underlying: string; }): Promise ⋮---- /**========================================================================================================================== * EARN UNI * ========================================================================================================================== */ ⋮---- /** * List currencies for lending * * @returns Promise */ getLendingCurrencies(): Promise ⋮---- /** * Get currency detail for lending * * @param params Parameters for retrieving currency detail for lending * @returns Promise */ getLendingCurrency(params: ⋮---- /** * Lend or redeem * * @param params Parameters for lending or redeeming * @returns Promise */ submitLendOrRedeemOrder(params: SubmitLendOrRedeemReq): Promise ⋮---- /** * List user's lending orders * * @param params Parameters for listing user's lending orders * @returns Promise */ getLendingOrders(params?: GetLendingOrdersReq): Promise ⋮---- /** * Amend lending order * * Currently only supports amending the minimum interest rate (hour) * * @param params Parameters for amending lending order * @returns Promise */ updateLendingOrder(params: { currency?: string; min_rate?: string; }): Promise ⋮---- /** * List records of lending * * @param params Parameters for listing records of lending * @returns Promise */ getLendingRecords(params?: GetLendingRecordsReq): Promise ⋮---- /** * Get the user's total interest income of specified currency * * @param params Parameters for retrieving the user's total interest income of specified currency * @returns Promise<{ * currency: string; * interest: string; * }> */ getLendingTotalInterest(params: ⋮---- /** * List interest records * * @param params Parameters for listing interest records * @returns Promise */ getLendingInterestRecords( params?: GetLendingInterestRecordsReq, ): Promise ⋮---- /** * Set interest reinvestment toggle * @deprecated as of v4.99.0, 23-06-2025 * * @param params Parameters for setting interest reinvestment toggle * @returns Promise */ updateInterestReinvestment(params: { currency: string; status: boolean; }): Promise ⋮---- /** * Query currency interest compounding status * * @param params Parameters for querying currency interest compounding status * @returns Promise<{ * currency: string; * interest_status: string; * }> */ getLendingInterestStatus(params: ⋮---- /** * UniLoan currency annualized trend chart * * Get the annualized interest rate trend chart data for a specific currency * * @param params Parameters for retrieving the annualized trend chart * @returns Promise<{ time: number; value: string }[]> */ getLendingAnnualizedTrendChart(params: { from: number; to: number; asset: string; }): Promise< ⋮---- getLendingEstimatedRates(): Promise< { currency: string; est_rate: string }[] > { return this.getPrivate('/earn/uni/rate'); ⋮---- /**========================================================================================================================== * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- /** * Create Multi-Collateral Order * * @param params Parameters for creating a multi-collateral order * @returns Promise<{ order_id: number }> */ submitMultiLoanOrder( params: SubmitMultiLoanOrderReq, ): Promise< ⋮---- /** * List Multi-Collateral Orders * * @param params Parameters for listing multi-collateral orders * @returns Promise */ getMultiLoanOrders( params?: GetMultiLoanOrdersReq, ): Promise ⋮---- /** * Get Multi-Collateral Order Detail * * @param params Parameters for retrieving a multi-collateral order detail * @returns Promise */ getMultiLoanOrder(params: ⋮---- /** * Repay Multi-Collateral Loan * * @param params Parameters for repaying a multi-collateral loan * @returns Promise */ repayMultiLoan(params: RepayMultiLoanReq): Promise ⋮---- /** * List Multi-Collateral Repay Records * * @param params Parameters for listing multi-collateral repay records * @returns Promise */ getMultiLoanRepayRecords( params: GetMultiLoanRepayRecordsReq, ): Promise ⋮---- /** * Operate Multi-Collateral * * @param params Parameters for operating multi-collateral * @returns Promise */ updateMultiLoan(params: UpdateMultiLoanReq): Promise ⋮---- /** * Query collateral adjustment records * * @param params Parameters for querying collateral adjustment records * @returns Promise */ getMultiLoanAdjustmentRecords( params?: GetMultiLoanAdjustmentRecordsReq, ): Promise ⋮---- /** * List User Currency Quota * * @param params Parameters for listing user currency quota * @returns Promise */ getMultiLoanCurrencyQuota(params: { type: 'collateral' | 'borrow'; currency: string; }): Promise ⋮---- /** * Query supported borrowing and collateral currencies in Multi-Collateral * * @returns Promise */ getMultiLoanSupportedCurrencies(): Promise ⋮---- /** * Get Multi-Collateral ratio * * @returns Promise */ getMultiLoanRatio(): Promise ⋮---- /** * Query fixed interest rates for the currency for 7 days and 30 days * * @returns Promise */ getMultiLoanFixedRates(): Promise ⋮---- /** * Query the current interest rate of currencies * * Query the current interest rate of currencies in the last hour. * The current interest rate is updated every hour. * * @param params Parameters containing currencies to query and optional VIP level * @returns Promise */ getMultiLoanCurrentRates(params: { currencies: string[]; vip_level?: string; }): Promise< { currency: string; current_rate: string; }[] > { return this.get('/loan/multi_collateral/current_rate', params); ⋮---- /**========================================================================================================================== * EARN * ========================================================================================================================== */ ⋮---- /** * Dual Investment product list * * @returns Promise */ getDualInvestmentProducts( params?: GetDualInvestmentPlansReq, ): Promise ⋮---- /** * Dual Investment order list * * @returns Promise */ getDualInvestmentOrders( params?: GetDualInvestmentOrdersReq, ): Promise ⋮---- /** * Place Dual Investment order * * @param params plan_id, amount (or copies), optional text * @returns Promise */ submitDualInvestmentOrder( params: PlaceDualInvestmentOrderParams, ): Promise ⋮---- /** * Dual-currency early redemption preview */ getDualOrderRefundPreview( params: GetDualOrderRefundPreviewReq, ): Promise ⋮---- /** * Dual-currency order early redemption */ submitDualOrderRefund( params: SubmitDualOrderRefundParams, ): Promise ⋮---- /** * Update dual-currency order reinvest settings */ updateDualOrderReinvest( params: UpdateDualOrderReinvestParams, ): Promise ⋮---- /** * Dual-currency recommended projects */ getDualProjectRecommend( params?: GetDualProjectRecommendReq, ): Promise ⋮---- /** * List fixed-term earn products (public). */ getEarnFixedTermProducts( params: GetEarnFixedTermProductsReq, ): Promise ⋮---- /** * List fixed-term earn products for one asset (public). */ getEarnFixedTermProductsByAsset( asset: string, params?: GetEarnFixedTermProductsByAssetReq, ): Promise ⋮---- /** * Subscribe to a fixed-term earn product. */ createEarnFixedTermLend( params: CreateEarnFixedTermLendReq, ): Promise ⋮---- /** * List fixed-term earn subscriptions. */ getEarnFixedTermLends( params: GetEarnFixedTermLendsReq, ): Promise ⋮---- /** * Early redeem a fixed-term earn order. */ createEarnFixedTermPreRedeem( params: EarnFixedTermPreRedeemReq, ): Promise ⋮---- /** * Fixed-term earn subscription history. */ getEarnFixedTermHistory( params: GetEarnFixedTermHistoryReq, ): Promise ⋮---- /** * Create auto invest plan */ createAutoInvestPlan( params: CreateAutoInvestPlanReq, ): Promise ⋮---- /** * Update auto invest plan */ updateAutoInvestPlan(params: UpdateAutoInvestPlanReq): Promise ⋮---- /** * Stop auto invest plan */ stopAutoInvestPlan(params: StopAutoInvestPlanReq): Promise ⋮---- /** * Add position immediately (auto invest) */ addAutoInvestPlanPosition( params: AddAutoInvestPlanPositionReq, ): Promise ⋮---- /** * List currencies supporting auto invest */ getAutoInvestCoins( params?: GetAutoInvestCoinsReq, ): Promise ⋮---- /** * Get minimum investment amount for a portfolio */ getAutoInvestMinAmount( params: GetAutoInvestMinAmountReq, ): Promise ⋮---- /** * List plan execution records */ getAutoInvestPlanRecords( params: GetAutoInvestPlanRecordsReq, ): Promise ⋮---- /** * List plan execution order details */ getAutoInvestOrders( params: GetAutoInvestOrdersReq, ): Promise ⋮---- /** * List investment currency configuration */ getAutoInvestConfig(): Promise ⋮---- /** * Get auto invest plan details */ getAutoInvestPlanDetail( params: GetAutoInvestPlanDetailReq, ): Promise ⋮---- /** * List auto invest plans */ getAutoInvestPlans( params: GetAutoInvestPlansReq, ): Promise ⋮---- /** * List staking coins * * @param params Parameters for listing staking coins * @returns Promise */ getStakingCoins(params?: { coin?: string; cointype?: string; }): Promise ⋮---- /** * On-chain Token Swap for Earned Coins * * @param params Parameters for staking swap * @returns Promise */ submitStakingSwap(params: { coin: string; side: '0' | '1'; // 0 - Stake, 1 - Redeem amount: string; pid?: number; }): Promise ⋮---- side: '0' | '1'; // 0 - Stake, 1 - Redeem ⋮---- /**========================================================================================================================== * ACCOUNT * ========================================================================================================================== */ ⋮---- /** * Get account detail * * @returns Promise */ getAccountDetail(): Promise ⋮---- /** * Get user transaction rate limit information * * @returns Promise */ getAccountRateLimit(): Promise ⋮---- /** * Create STP Group * * @param params Parameters for creating an STP group * @returns Promise */ createStpGroup(params: CreateStpGroupReq): Promise ⋮---- /** * List STP Groups * * @param params Parameters for listing STP groups * @returns Promise */ getStpGroups(params?: ⋮---- /** * List users of the STP group * * @param params Parameters for listing users of the STP group * @returns Promise */ getStpGroupUsers(params: ⋮---- /** * Add users to the STP group * * @param params Parameters for adding users to the STP group * @returns Promise */ addUsersToStpGroup(params: { stp_id: number; body: number[]; }): Promise ⋮---- /** * Delete the user in the STP group * * @param params Parameters for deleting users from the STP group * @returns Promise */ deleteUserFromStpGroup(params: { stp_id: number; user_id: number; }): Promise ⋮---- /** * Set GT deduction * * Enable or disable GT deduction for the current account. * * @param params Parameters for setting GT deduction * @returns Promise */ setGTDeduction(params: ⋮---- /** * Query GT deduction configuration * * Query the current GT deduction configuration for the account. * * @returns Promise<{ enabled: boolean }> */ getGTDeduction(): Promise< ⋮---- /** * Query all main account API key information * * @returns Promise */ getAccountMainKeys(): Promise ⋮---- /**========================================================================================================================== * REBATES * ========================================================================================================================== */ ⋮---- /** * The agency obtains the transaction history of the recommended user. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving transaction history * @returns Promise */ getAgencyTransactionHistory( params: GetAgencyTransactionHistoryReq, ): Promise< ⋮---- /** * The agency obtains the commission history of the recommended user. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving commission history * @returns Promise */ getAgencyCommissionHistory( params: GetAgencyCommissionHistoryReq, ): Promise< ⋮---- /** * Partner obtains transaction records of recommended users * * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving transaction records * @returns Promise */ getPartnerTransactionHistory(params?: PartnerTransactionReq): Promise< ⋮---- /** * Partner obtains commission records of recommended users * * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving commission records * @returns Promise */ getPartnerCommissionHistory(params?: PartnerTransactionReq): Promise< ⋮---- /** * Partner subordinate list * * Including sub-agents, direct customers, indirect customers * * @param params Parameters for retrieving partner subordinate list * @returns Promise<{ * total: number; * list: { * user_id: number; * user_join_time: number; * type: number; * desc: string; * }[]; * }> */ getPartnerSubordinateList(params?: GetPartnerSubordinateListReq): Promise< ⋮---- /** * Aggregated partner agent statistics (rebate amount, volume, net fee, customer count; optional trading user count by business type). */ getPartnerAgentDataAggregated( params?: GetPartnerAgentDataAggregatedReq, ): Promise ⋮---- /** * The broker obtains the user's commission rebate records. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving commission rebate records * @returns Promise */ getBrokerCommissionHistory( params: GetBrokerCommissionHistoryReq, ): Promise< ⋮---- /** * The broker obtains the user's trading history. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving trading history * @returns Promise */ getBrokerTransactionHistory( params: GetBrokerTransactionHistoryReq, ): Promise< ⋮---- /** * User retrieves rebate information. */ getUserRebateInfo(): Promise< ⋮---- /** * Query user-subordinate relationship * * Checks whether specified users are in the system and their relationship status */ getUserSubordinateRelationships(params: { user_id_list: string; // Comma-separated list of user IDs (max 100) }): Promise< ⋮---- user_id_list: string; // Comma-separated list of user IDs (max 100) ⋮---- /**========================================================================================================================== * OTC * ========================================================================================================================== */ ⋮---- /** * Fiat and stablecoin quote * * Create fiat and stablecoin quotes, supporting both PAY and GET directions * * @param params Quote parameters * @returns Promise with quote details including rate, amounts, and quote_token */ createOTCQuote(params: CreateOTCQuoteReq): Promise ⋮---- /** * Create fiat order * * Create a fiat order, supporting BUY for on-ramp and SELL for off-ramp * * @param params Fiat order parameters * @returns Promise with order creation confirmation */ createOTCFiatOrder( params: CreateOTCFiatOrderReq, ): Promise ⋮---- /** * Create stablecoin order * * Create stablecoin order * * @param params Stablecoin order parameters * @returns Promise with order creation confirmation */ createOTCStablecoinOrder( params: CreateOTCStablecoinOrderReq, ): Promise ⋮---- /** * Get user bank card list (use is_default=1 for default card) */ getOTCBankList(): Promise ⋮---- /** * Get user bank card list (Inner-aligned alias of getOTCBankList) */ getOTCBankListLegacy(): Promise ⋮---- createOTCUploadPreUpload( params: CreateOTCUploadPreUploadReq, ): Promise ⋮---- /** * Create / bind a bank card (multipart/form-data) */ createOTCBank(params: CreateOTCBankReq): Promise ⋮---- /** * Delete a bank card */ deleteOTCBank(params: OTCBankIdReq): Promise ⋮---- /** * Set default bank card */ setDefaultOTCBank(params: OTCBankIdReq): Promise ⋮---- /** * Bank card supplement checklist */ getOTCBankSupplementChecklist( params: GetOTCBankSupplementChecklistReq, ): Promise ⋮---- /** * Submit personal bank card supplement materials (multipart/form-data) */ submitOTCBankPersonalSupplement( params: SubmitOTCBankPersonalSupplementReq, ): Promise ⋮---- /** * Submit enterprise bank card supplement materials (multipart/form-data) */ submitOTCBankEnterpriseSupplement( params: SubmitOTCBankEnterpriseSupplementReq, ): Promise ⋮---- /** * Mark fiat order as paid * * Mark fiat order as paid * * @param params Parameters with order_id * @returns Promise with confirmation */ markOTCOrderAsPaid( params: MarkOTCOrderAsPaidReq, ): Promise ⋮---- /** * Fiat order cancellation * * Cancel fiat order * * @param params Parameters with order_id * @returns Promise with cancellation confirmation */ cancelOTCOrder(params: CancelOTCOrderReq): Promise ⋮---- /** * Fiat order list * * Query the fiat order list with filters such as type, currency, time range, and status * * @param params Filter parameters for fiat order list * @returns Promise with paginated fiat order list */ getOTCFiatOrderList( params?: GetOTCFiatOrderListReq, ): Promise ⋮---- /** * Stablecoin order list * * Query stablecoin order list with filtering by currency, time range, status, etc. * * @param params Filter parameters for stablecoin order list * @returns Promise with paginated stablecoin order list */ getOTCStablecoinOrderList( params?: GetOTCStablecoinOrderListReq, ): Promise ⋮---- /** * Fiat order details * * Query fiat order details * * @param params Parameters with order_id * @returns Promise with fiat order details */ getOTCFiatOrderDetail( params: GetOTCFiatOrderDetailReq, ): Promise ⋮---- /**========================================================================================================================== * P2P MERCHANT * ========================================================================================================================== */ ⋮---- /** * Get account information */ getP2PMerchantUserInfo(): Promise> ⋮---- /** * Get counterparty information */ getP2PMerchantCounterpartyUserInfo( params: P2PMerchantGetCounterpartyUserInfoReq, ): Promise> ⋮---- /** * Get payment method list */ getP2PMerchantMyselfPayment( params?: P2PMerchantGetMyselfPaymentReq, ): Promise> ⋮---- /** * Query spot account balance for P2P merchant (v4.106.103) * * Guide entry — uses Spot API GET /spot/accounts. */ getP2PMerchantSpotBalance(params?: { currency?: string; }): Promise ⋮---- /** * Set merchant working status and custom working hours (v4.106.96) */ setP2PMerchantWorkHours( params: P2PMerchantSetMerchantWorkHoursReq, ): Promise> ⋮---- /** * Get completed/historical orders */ getP2PMerchantCompletedTransactionList( params: P2PMerchantGetCompletedTransactionListReq, ): Promise> ⋮---- /** * Get order details */ getP2PMerchantTransactionDetails( params: P2PMerchantGetTransactionDetailsReq, ): Promise> ⋮---- /** * Confirm payment */ confirmP2PMerchantPayment( params: P2PMerchantConfirmPaymentReq, ): Promise>> ⋮---- /** * Confirm receipt */ confirmP2PMerchantReceipt( params: P2PMerchantConfirmReceiptReq, ): Promise>> ⋮---- /** * Cancel order */ cancelP2PMerchantTransaction( params: P2PMerchantCancelTransactionReq, ): Promise>> ⋮---- /** * Place ad order */ placeP2PMerchantBizPushOrder( params: P2PMerchantPlaceBizPushOrderReq, ): Promise>> ⋮---- /** * Update ad status */ updateP2PMerchantAdsStatus( params: P2PMerchantAdsUpdateStatusReq, ): Promise> ⋮---- /** * Get my ads list */ getP2PMerchantMyAdsList( params?: P2PMerchantMyAdsListReq, ): Promise> ⋮---- /** * Get advertisement list */ getP2PMerchantAdsList( params: P2PMerchantGetAdsListReq, ): Promise> ⋮---- /** * Get chat history */ getP2PMerchantChatsList( params: P2PMerchantGetChatsListReq, ): Promise> ⋮---- /** * Send chat message */ sendP2PMerchantChatMessage( params: P2PMerchantSendChatMessageReq, ): Promise ⋮---- /** * Query Risk Limit Information * * Query risk limit information for futures/margin trading pairs * * @param params Parameters with required symbols * @returns Promise with array of risk limit information */ getCrossExRiskLimits( params: GetCrossExRiskLimitsReq, ): Promise ⋮---- /** * Query Supported Transfer Currencies * * Query supported transfer currencies for cross-exchange * * @param params Optional currency filter * @returns Promise with array of transfer coin information */ getCrossExTransferCoins( params?: GetCrossExTransferCoinsReq, ): Promise ⋮---- /** * Fund Transfer * * Transfer funds between accounts. Rate limit: 10 requests per 10 seconds * * @param params Transfer parameters * @returns Promise with transfer confirmation */ createCrossExTransfer( params: CreateCrossExTransferReq, ): Promise ⋮---- /** * Query Fund Transfer History * * Query fund transfer history. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of transfer history records */ getCrossExTransferHistory( params?: GetCrossExTransferHistoryReq, ): Promise ⋮---- /** * Create an order * * Create an order for cross-exchange trading. Rate Limit: 100 requests per 10 seconds * * @param params Order parameters * @returns Promise with order creation response */ createCrossExOrder( params: CreateCrossExOrderReq, ): Promise ⋮---- /** * Batch cancel CrossEx orders * * Cancel multiple CrossEx orders by order_id or custom text. When both are provided, order_id takes precedence. Each result reports whether the request was accepted plus any error label and message. Rate Limit: 100 requests per 10 seconds * * @param params Array of cancel requests (order_id and/or text) * @returns Promise with array of batch cancel results */ cancelBatchCrossExOrders( params: CancelBatchCrossExOrdersReq[], ): Promise ⋮---- /** * Cancel Order * * Cancel an order. Rate Limit: 100 requests per 10 seconds * * @param order_id Order ID or Text for Cancel Order * @returns Promise with cancellation confirmation */ cancelCrossExOrder(order_id: string): Promise ⋮---- /** * Modify Order * * Modify an existing order. Rate Limit: 100 requests per 10 seconds * * @param order_id Order ID or Text for Modify Order * @param params Modification parameters * @returns Promise with modification confirmation */ modifyCrossExOrder( order_id: string, params: ModifyCrossExOrderReq, ): Promise ⋮---- /** * Query order details * * Query order details by order ID or custom text. Rate Limit: 200 requests per 10 seconds * * @param order_id Order ID or custom text * @returns Promise with order details */ getCrossExOrder(order_id: string): Promise ⋮---- /** * Flash Swap Inquiry * * Create a flash swap quote. Rate Limit: 100 requests per day * * @param params Quote parameters * @returns Promise with quote details */ createCrossExConvertQuote( params: CreateCrossExConvertQuoteReq, ): Promise ⋮---- /** * Flash Swap Transaction * * Execute a flash swap transaction. Rate limit: 10 requests per 10 seconds * * @param params Parameters with quote_id * @returns Promise with transaction confirmation */ createCrossExConvertOrder( params: CreateCrossExConvertOrderReq, ): Promise ⋮---- /** * Modify Account Contract Position Mode and Account Mode * * Modify account settings. Rate Limit: 100 requests per 60 seconds * * @param params Account modification parameters * @returns Promise with update confirmation */ updateCrossExAccount( params: UpdateCrossExAccountReq, ): Promise ⋮---- /** * Query Account Assets * * Query account assets and balances. Rate Limit: 200 requests per 10 seconds * * @param params Optional exchange_type filter * @returns Promise with account information */ getCrossExAccounts(params?: GetCrossExAccountsReq): Promise ⋮---- /** * Modify Contract Trading Pair Leverage Multiplier * * Modify leverage for contract trading pair. Rate Limit: 100 requests per 10 seconds * * @param params Leverage modification parameters * @returns Promise with leverage update confirmation */ setCrossExPositionLeverage( params: SetCrossExPositionLeverageReq, ): Promise ⋮---- /** * Query Contract Trading Pair Leverage Multiplier * * Query leverage for contract trading pairs. Rate Limit: 200 requests per 10 seconds * * @param params Optional symbols filter * @returns Promise with array of leverage information */ getCrossExPositionLeverage( params?: GetCrossExPositionLeverageReq, ): Promise ⋮---- /** * Modify Leveraged Trading Pair Leverage Multiplier * * Modify leverage for margin trading pair. Rate Limit: 100 requests per 10 seconds * * @param params Leverage modification parameters * @returns Promise with leverage update confirmation */ setCrossExMarginPositionLeverage( params: SetCrossExMarginPositionLeverageReq, ): Promise ⋮---- /** * Query Leveraged Trading Pair Leverage Multiplier * * Query leverage for margin trading pairs. Rate Limit: 200 requests per 10 seconds * * @param params Optional symbols filter * @returns Promise with array of leverage information */ getCrossExMarginPositionLeverage( params?: GetCrossExMarginPositionLeverageReq, ): Promise ⋮---- /** * Full Close Position * * Fully close a position. Rate Limit: 100 requests per day * * @param params Position close parameters * @returns Promise with close position confirmation */ closeCrossExPosition( params: CloseCrossExPositionReq, ): Promise ⋮---- updateCrossExPositionsMargin( params: UpdateCrossExPositionsMarginReq, ): Promise ⋮---- /** * Query margin asset interest rates * * Query interest rates for margin assets. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of interest rates */ getCrossExInterestRate( params?: GetCrossExInterestRateReq, ): Promise ⋮---- /** * Query User Fee Rates * * Query user fee rates. Rate Limit: 200 requests per 10 seconds * * @returns Promise with fee rates per exchange */ getCrossExFeeRate(): Promise ⋮---- /** * Query Contract Positions * * Query contract positions. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of positions */ getCrossExPositions( params?: GetCrossExPositionsReq, ): Promise ⋮---- /** * Query Leveraged Positions * * Query margin/leveraged positions. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of margin positions */ getCrossExMarginPositions( params?: GetCrossExMarginPositionsReq, ): Promise ⋮---- /** * Query ADL Position Reduction Ranking * * Query ADL position reduction ranking. Rate Limit: 200 requests per 10 seconds * * @param params Parameters with required symbol * @returns Promise with array of ADL rankings */ getCrossExAdlRank(params: GetCrossExAdlRankReq): Promise ⋮---- /** * Query All Current Open Orders * * Query all current open orders. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of open orders */ getCrossExOpenOrders( params?: GetCrossExOpenOrdersReq, ): Promise ⋮---- /** * Query order history * * Query historical orders. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of historical orders */ getCrossExHistoryOrders( params?: GetCrossExHistoryOrdersReq, ): Promise ⋮---- /** * Query Contract Position History * * Query contract position history. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of historical positions */ getCrossExHistoryPositions( params?: GetCrossExHistoryPositionsReq, ): Promise ⋮---- /** * Query Leveraged Position History * * Query margin position history. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of historical margin positions */ getCrossExHistoryMarginPositions( params?: GetCrossExHistoryMarginPositionsReq, ): Promise ⋮---- /** * Query Leveraged Interest Deduction History * * Query margin interest deduction history. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of interest deduction records */ getCrossExHistoryMarginInterests( params?: GetCrossExHistoryMarginInterestsReq, ): Promise ⋮---- /** * Query filled history * * Query trade execution history. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of trade records */ getCrossExHistoryTrades( params?: GetCrossExHistoryTradesReq, ): Promise ⋮---- /** * Query Account Asset Change History * * Query account balance change history. Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of account book records */ getCrossExAccountBook( params?: GetCrossExAccountBookReq, ): Promise ⋮---- /** * Query currency discount rate * * Query currency discount rate (for margin currency in isolated exchange mode). Rate Limit: 200 requests per 10 seconds * * @param params Optional filter parameters * @returns Promise with array of coin discount rates */ getCrossExCoinDiscountRate( params?: GetCrossExCoinDiscountRateReq, ): Promise ⋮---- /** * Query CrossEx market tickers * * Query exchange market tickers, optionally filtered by a comma-separated list of symbols. * * @param params Optional parameters to filter symbols * @returns Promise with array of market tickers */ getCrossExMarketTickers( params?: GetCrossExMarketTickersReq, ): Promise ⋮---- /** * Query CrossEx market funding info * * Query futures funding rates, funding intervals, and next funding timestamps across exchanges. * * @param params Optional parameters to filter symbols * @returns Promise with array of funding info records */ getCrossExMarketFundingInfo( params?: GetCrossExMarketFundingInfoReq, ): Promise ⋮---- /**========================================================================================================================== * ALPHA * ========================================================================================================================== */ ⋮---- /** * Query position assets * * Query alpha account position assets * * @returns Promise with array of account balances */ getAlphaAccounts(): Promise ⋮---- /** * Query asset transactions * * Query alpha account transaction history * * @param params Parameters with required from timestamp * @returns Promise with array of transaction records */ getAlphaAccountBook( params: GetAlphaAccountBookReq, ): Promise ⋮---- /** * Alpha Quote API * * Get a quote for alpha trading. Quote is valid for 1 minute. Rate-limited at 10 requests per second per user. * * @param params Quote parameters * @returns Promise with quote details */ createAlphaQuote(params: CreateAlphaQuoteReq): Promise ⋮---- /** * Alpha Order API * * Create an alpha order. Rate-limited at 5 requests per second per user. * * @param params Order parameters including quote_id * @returns Promise with order details */ createAlphaOrder(params: CreateAlphaOrderReq): Promise ⋮---- /** * Alpha Order List API * * Query alpha order list with filters * * @param params Filter parameters * @returns Promise with array of orders */ getAlphaOrders(params?: GetAlphaOrdersReq): Promise ⋮---- /** * Alpha Single Order Query API * * Query a single alpha order by order ID * * @param params Parameters with order_id * @returns Promise with order details */ getAlphaOrder(params: GetAlphaOrderReq): Promise ⋮---- /** * Query currency information * * Query alpha currency information. When currency is provided, returns specific currency info; otherwise returns paginated list. * * @param params Optional filter parameters * @returns Promise with array of currency information */ getAlphaCurrencies(params?: GetAlphaCurrenciesReq): Promise ⋮---- /** * Query currency ticker * * Query alpha currency ticker. When currency is provided, returns specific ticker; otherwise returns paginated list. * * @param params Optional filter parameters * @returns Promise with array of ticker information */ getAlphaTickers(params?: GetAlphaTickersReq): Promise ⋮---- // ============ TradFi ============ ⋮---- getTradFiMT5Account(): Promise> ⋮---- getTradFiSymbolCategories(): Promise< TradFiApiResp> > { return this.get('/tradfi/symbols/categories'); ⋮---- getTradFiSymbols(): Promise>> ⋮---- /** * Query CFD symbol commission rates * * At least one of symbols or category_code is required. When both are provided, symbols are filtered by category. * * @param params Optional filters for symbols and/or category codes * @returns Promise with list of symbol commission rates */ getTradFiSymbolCommissions( params?: TradFiGetSymbolCommissionsParams, ): Promise>> ⋮---- getTradFiSymbolDetail( params: TradFiGetSymbolDetailParams, ): Promise>> ⋮---- getTradFiKlines( symbol: string, params: TradFiGetKlinesParams, ): Promise>> ⋮---- getTradFiTicker(symbol: string): Promise> ⋮---- createTradFiUser(): Promise> ⋮---- getTradFiAssets(): Promise> ⋮---- createTradFiTransaction( params: TradFiCreateTransactionReq, ): Promise>> ⋮---- getTradFiTransactions( params?: TradFiGetTransactionsParams, ): Promise> ⋮---- createTradFiOrder( params: TradFiCreateOrderReq, ): Promise> ⋮---- getTradFiOrders(): Promise>> ⋮---- modifyTradFiOrder( orderId: number, params: TradFiModifyOrderReq, ): Promise> ⋮---- cancelTradFiOrder(orderId: number): Promise> ⋮---- getTradFiOrderHistory( params?: TradFiGetOrderHistoryParams, ): Promise>> ⋮---- getTradFiPositions(): Promise< TradFiApiResp> > { return this.getPrivate('/tradfi/positions'); ⋮---- modifyTradFiPosition( positionId: number, params: TradFiModifyPositionReq, ): Promise>> ⋮---- closeTradFiPosition( positionId: number, params: TradFiClosePositionReq, ): Promise>> ⋮---- getTradFiPositionHistory( params?: TradFiGetPositionHistoryParams, ): Promise>> ⋮---- /** * Query order details by log_id from order placement (v4.106.94) */ getTradFiOrderLog(params: { log_id: number | string; }): Promise> ⋮---- // ============ Stock ============ ⋮---- /** * Query user stock assets * * @param params Optional PnL calculation parameters * @returns Promise with user asset details */ getStockUserAssets( params?: GetStockUserAssetsReq, ): Promise> ⋮---- /** * Query stock symbol list * * @param params Optional filters for symbols, exchange, and pagination * @returns Promise with paginated symbol list */ getStockSymbols( params?: GetStockSymbolsReq, ): Promise>> ⋮---- /** * Query stock symbol details * * @param params Optional filters for symbols, exchange, and pagination * @returns Promise with paginated symbol detail list */ getStockSymbolDetail( params?: GetStockSymbolDetailReq, ): Promise>> ⋮---- /** * Query stock market order book * * @param symbol Symbol * @returns Promise with order book data */ getStockOrderBook(symbol: string): Promise> ⋮---- /** * Query open stock orders * * @param params Optional symbol filter * @returns Promise with open order list */ getStockOrders( params?: GetStockOrdersReq, ): Promise>> ⋮---- /** * Create a stock order * * Limit orders support only the all trading session; market orders support only regular. time_in_force supports day only. * * @param params Order parameters * @returns Promise with created order ID */ createStockOrder( params: CreateStockOrderReq, ): Promise> ⋮---- /** * Cancel all open stock orders * * @returns Promise with empty data on success */ cancelAllStockOrders(): Promise>> ⋮---- /** * Query stock order history * * @param params Optional filters for symbol, order IDs, time range, side, and pagination * @returns Promise with paginated historical order list */ getStockOrderHistory( params?: GetStockOrderHistoryReq, ): Promise>> ⋮---- /** * Modify a stock order * * @param orderId Order ID * @param params Modified volume and price * @returns Promise with updated order ID */ updateStockOrder( orderId: number, params: UpdateStockOrderReq, ): Promise> ⋮---- /** * Cancel a stock order * * @param orderId Order ID * @returns Promise with empty data on success */ cancelStockOrder( orderId: number, ): Promise>> ⋮---- /** * Query current stock positions * * @param params Optional filters for PnL calc, symbol, and exchange * @returns Promise with position list */ getStockPositions( params?: GetStockPositionsReq, ): Promise>> ⋮---- /** * Close a stock position * * @param params Close parameters (partial or full) * @returns Promise with close order ID */ closeStockPosition( params: CloseStockPositionReq, ): Promise> ⋮---- /** * Query stock transaction records * * @param params Optional filters for time range, ref_id, type, and pagination * @returns Promise with paginated transaction list */ getStockTransactions( params?: GetStockTransactionsReq, ): Promise>> ⋮---- /** * Fund transfer for stock account * * Transfer funds in or out of the stock account (USDT only). * * @param params Transfer parameters including ref_id for idempotency * @returns Promise with empty data on success */ createStockTransaction( params: CreateStockTransactionReq, ): Promise>> ⋮---- /** * Query supported stock exchanges * * @returns Promise with exchange list */ getStockExchanges(): Promise>> ⋮---- /** * Query stock fee rates * * Maker/taker fee fields apply to Japanese and Korean stocks. * * @returns Promise with fee rate list by VIP level */ getStockFeeRate(): Promise>> ================ File: package.json ================ { "name": "gateio-api", "version": "1.6.4", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", "build": "rm -fr dist/* && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", "pack": "webpack --config webpack/webpack.config.cjs", "test": "jest --passWithNoTests", "lint": "eslint src" }, "main": "dist/cjs/index.js", "module": "dist/mjs/index.js", "types": "dist/mjs/index.d.ts", "exports": { ".": { "import": "./dist/mjs/index.js", "require": "./dist/cjs/index.js", "types": "./dist/mjs/index.d.ts" } }, "type": "module", "files": [ "dist/*", "llms.txt" ], "author": "Tiago Siebler (https://siebly.io)", "contributors": [ "Jerko J (https://github.com/JJ-Cro)" ], "dependencies": { "@types/ws": "8.18.1", "axios": "1.18.1", "isomorphic-ws": "4.0.1", "ws": "8.21.1" }, "devDependencies": { "@types/jest": "^29.5.12", "@types/node": "^22.10.2", "@typescript-eslint/eslint-plugin": "^8.18.0", "@typescript-eslint/parser": "^8.18.0", "eslint": "^8.29.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.1.3", "eslint-plugin-require-extensions": "^0.1.3", "eslint-plugin-simple-import-sort": "^12.1.1", "jest": "^29.7.0", "ts-jest": "^29.1.2", "ts-node": "^10.9.2", "typescript": "^5.7.3", "webpack": "^5.0.0", "webpack-cli": "^4.0.0" }, "overrides": { "brace-expansion@<2": "1.1.18", "brace-expansion@>=2 <3": "2.1.4", "brace-expansion@>=5 <6": "5.0.9", "fast-uri@>=3 <4": "3.1.5", "js-yaml@>=3 <4": "3.15.1", "js-yaml@>=4 <5": "4.3.1" }, "keywords": [ "Gate", "Gate.io", "Gate.com", "Gate api", "Gate.io api", "Gate.com api", "Gate nodejs", "Gate javascript", "Gate javascript websocket api", "Gate typescript", "Gate js", "Gate ts", "Gate api node", "Gate sdk javascript", "algo trading", "api", "websocket", "rest", "rest api", "ccxt", "trading bots", "nodejs", "node", "trading", "cryptocurrency", "bitcoin", "best", "siebly.io" ], "funding": { "type": "individual", "url": "https://github.com/sponsors/tiagosiebler" }, "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/sieblyio/gateio-api.git" }, "bugs": { "url": "https://github.com/sieblyio/gateio-api/issues" }, "homepage": "https://siebly.io/sdk/gate/javascript" } ================================================================ End of Codebase ================================================================