From e6b950f964f4fe1acb767634eed41fa30ebc8ffe Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 10:14:31 +0000 Subject: [PATCH 1/7] feat(1.6.5): sync Gate API through v4.106.160 and fix TestNet hosts TestNet REST `futuresTestnet` now uses https://api-testnet.gateapi.io/api/v4. `baseUrlKey: 'testnet'` is the same host for spot and futures. `futuresTestnet` stays as an alias. WebSocket TestNet: - spot: wss://ws-testnet.gate.com/v4/ws/spot - options: wss://ws-testnet.gate.com/v4/ws/options - USDT perpetual, BTC perpetual, and delivery hosts still match current Gate docs Changelog: - v4.106.160: updateFuturesPriceTriggeredOrder uses PUT /futures/{settle}/price_orders/amend/{order_id}; order_id stays in the body - v4.106.159: stock trade_status is pre_market | open | post_market - v4.106.158: OTC fiat and stablecoin order lists use data.lists - v4.106.148: stock trade_mode, order status, and finish_as enums - v4.106.147: futures account_book type dividend - Futures place-order requests accept tpsl_tp_bbo_type and tpsl_sl_bbo_type Skipped: - stock time_in_force GTC: docs only list day - stock client_order_id: already on CreateStockOrderReq - tpsl bbo fields on FuturesOrder responses: already present Co-authored-by: Jerko J --- README.md | 2 ++ docs/GATE_SDK_QUICKSTART_GUIDE.md | 7 +++-- examples/Rest/futures/testnet.ts | 6 ++-- package-lock.json | 4 +-- package.json | 2 +- src/RestClient.ts | 14 ++++++--- src/lib/requestUtils.ts | 13 ++++++-- src/lib/websocket/websocket-util.ts | 6 ++-- src/types/request/futures.ts | 28 +++++++++++------- src/types/response/futures.ts | 5 +++- src/types/response/otc.ts | 6 ++-- src/types/response/stock.ts | 46 ++++++++++++++++++++++------- src/types/shared.ts | 6 ++++ test/REST/baseUrl.test.ts | 24 +++++++++++++++ test/REST/priceOrderAmend.test.ts | 32 ++++++++++++++++++++ 15 files changed, 162 insertions(+), 39 deletions(-) create mode 100644 test/REST/baseUrl.test.ts create mode 100644 test/REST/priceOrderAmend.test.ts diff --git a/README.md b/README.md index 4dfcf2e..231477e 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,8 @@ client }); ``` +TestNet REST for spot and futures is `baseUrlKey: 'testnet'` (`https://api-testnet.gateapi.io/api/v4`). `baseUrlKey: 'futuresTestnet'` is that same host, kept so older configs keep working. WebSocket TestNet is `useTestnet: true` on `WebsocketClient`. + See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets diff --git a/docs/GATE_SDK_QUICKSTART_GUIDE.md b/docs/GATE_SDK_QUICKSTART_GUIDE.md index 5aaf489..e3fa34b 100644 --- a/docs/GATE_SDK_QUICKSTART_GUIDE.md +++ b/docs/GATE_SDK_QUICKSTART_GUIDE.md @@ -1738,11 +1738,12 @@ Gate TestNet is a separate environment with separate credentials. Use it for all | 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` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | -Set the REST API host with `baseUrl` and the WebSocket host with `wsUrl`. Prefer explicit hosts for TestNet examples: +Set the REST API host with `baseUrl` or `baseUrlKey`, and the WebSocket host with `wsUrl` or `useTestnet: true`. 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. +- `baseUrlKey: 'testnet'` uses `https://api-testnet.gateapi.io/api/v4` for spot and futures. `baseUrlKey: 'futuresTestnet'` is the same host, kept so older configs keep working. +- `useTestnet: true` selects the TestNet WebSocket host for that connection, including Spot and Options. BTC perpetual and delivery TestNet hosts stay on the URLs in the current Gate docs (`wss://fx-ws-testnet.gateio.ws/...`). Announcements still have no TestNet host. ```javascript import { RestClient, WebsocketClient } from 'gateio-api'; diff --git a/examples/Rest/futures/testnet.ts b/examples/Rest/futures/testnet.ts index 8fb22c4..a2709af 100644 --- a/examples/Rest/futures/testnet.ts +++ b/examples/Rest/futures/testnet.ts @@ -19,8 +19,10 @@ const gateRestClient = new RestClient({ */ /* - * Futures TestNet trading: - * 'https://fx-api-testnet.gateio.ws/api/v4' + * Futures TestNet trading (alias of `testnet`, spot and futures): + * 'https://api-testnet.gateapi.io/api/v4' + * Older host https://fx-api-testnet.gateio.ws/api/v4 now returns 502. + * baseUrlKey: 'testnet' is the same host. */ baseUrlKey: 'futuresTestnet', diff --git a/package-lock.json b/package-lock.json index f876e20..78c0677 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 7df721f..e527c0d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", diff --git a/src/RestClient.ts b/src/RestClient.ts index 66d6c04..aba932c 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -3548,16 +3548,22 @@ export class RestClient extends BaseRestClient { /** * Update a single price-triggered order * + * v4.106.160: `PUT /futures/{settle}/price_orders/amend/{order_id}`. + * `order_id` is required in the path and is still sent in the JSON body. + * * @param params Parameters for updating a price-triggered order * @returns Promise */ updateFuturesPriceTriggeredOrder( params: UpdateFuturesPriceTriggeredOrderReq, ): Promise { - const { settle, ...body } = params; - return this.putPrivate(`/futures/${settle}/price_orders/amend`, { - body: body, - }); + const { settle, order_id, ...rest } = params; + return this.putPrivate( + `/futures/${settle}/price_orders/amend/${order_id}`, + { + body: { order_id, ...rest }, + }, + ); } /** diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index ae40631..ac2eae6 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -24,7 +24,11 @@ export interface RestClientOptions { **/ baseUrl?: string; - // manually override with one of the known base URLs in the library + /** + * Built-in Gate API v4 host. + * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 + * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. + */ baseUrlKey?: GateBaseUrlKey; /** Default: true. whether to try and post-process request exceptions (and throw them). */ @@ -79,10 +83,15 @@ export function serializeParams | undefined = {}>( return queryString ? prefixWith + queryString : queryString; } +/** Global TestNet REST host. Gate docs: spot and futures. */ +const GATE_TESTNET_REST_URL = 'https://api-testnet.gateapi.io/api/v4'; + const GATE_BASE_URLS: Record = { live: 'https://api.gateio.ws/api/v4', futuresLiveAlternative: 'https://fx-api.gateio.ws/api/v4', - futuresTestnet: 'https://fx-api-testnet.gateio.ws/api/v4', + testnet: GATE_TESTNET_REST_URL, + // Alias of `testnet`. Previously https://fx-api-testnet.gateio.ws/api/v4 (HTTP 502). + futuresTestnet: GATE_TESTNET_REST_URL, }; export function getRestBaseUrl(restClientOptions: RestClientOptions): string { diff --git a/src/lib/websocket/websocket-util.ts b/src/lib/websocket/websocket-util.ts index e6d1dab..3f938b4 100644 --- a/src/lib/websocket/websocket-util.ts +++ b/src/lib/websocket/websocket-util.ts @@ -101,7 +101,8 @@ export const WS_BASE_URL_MAP: Record< > = { spotV4: { livenet: 'wss://api.gateio.ws/ws/v4/', - testnet: 'NoTestnetForSpotWebsockets!', + // https://www.gate.com/docs/developers/apiv4/ws/en/ + testnet: 'wss://ws-testnet.gate.com/v4/ws/spot', }, perpFuturesUSDTV4: { livenet: 'wss://fx-ws.gateio.ws/v4/ws/usdt', @@ -121,7 +122,8 @@ export const WS_BASE_URL_MAP: Record< }, optionsV4: { livenet: 'wss://op-ws.gateio.live/v4/ws', - testnet: 'wss://op-ws-testnet.gateio.live/v4/ws', + // https://www.gate.com/docs/developers/options/ws/en/ + testnet: 'wss://ws-testnet.gate.com/v4/ws/options', }, announcementsV4: { livenet: 'wss://api.gateio.ws/ws/v4/ann', diff --git a/src/types/request/futures.ts b/src/types/request/futures.ts index 7753669..1007c36 100644 --- a/src/types/request/futures.ts +++ b/src/types/request/futures.ts @@ -73,6 +73,19 @@ export interface GetRiskLimitTableReq { table_id: string; } +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout + export interface GetFuturesAccountBookReq { settle: FuturesSettle; contract?: string; @@ -80,16 +93,7 @@ export interface GetFuturesAccountBookReq { offset?: number; from?: number; to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; + type?: FuturesAccountBookType; } export interface GetFuturesADLRiskStatesReq { @@ -136,6 +140,10 @@ export interface SubmitFuturesOrderReq { action_mode?: 'ACK' | 'RESULT' | 'FULL'; tpsl_tp_trigger_price?: string; tpsl_sl_trigger_price?: string; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; pos_margin_mode?: 'isolated' | 'cross'; } diff --git a/src/types/response/futures.ts b/src/types/response/futures.ts index 4a936c8..3ae3c8c 100644 --- a/src/types/response/futures.ts +++ b/src/types/response/futures.ts @@ -3,6 +3,8 @@ * ========================================================================================================================== */ +import type { FuturesAccountBookType } from '../request/futures.js'; + export interface FuturesOrderBook { id?: number; current: number; @@ -169,7 +171,8 @@ export interface FuturesAccountBookRecord { time: number; change: string; balance: string; - type: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookType; text: string; contract?: string; trade_id: string; diff --git a/src/types/response/otc.ts b/src/types/response/otc.ts index ce6319f..c022716 100644 --- a/src/types/response/otc.ts +++ b/src/types/response/otc.ts @@ -147,7 +147,8 @@ export interface GetOTCFiatOrderListResp { ps: number; total_pn: number; count: number; - list: OTCFiatOrderListItem[]; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; }; } @@ -175,7 +176,8 @@ export interface GetOTCStablecoinOrderListResp { page_size: number; page_number: number; total_page: number; - list: OTCStablecoinOrderListItem[]; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; }; } diff --git a/src/types/response/stock.ts b/src/types/response/stock.ts index 3770646..4b8058a 100644 --- a/src/types/response/stock.ts +++ b/src/types/response/stock.ts @@ -11,6 +11,32 @@ export type StockCategory = export type StockAssetType = 'STOCK' | 'ETF'; +/** v4.106.159: `closed` and `gt_lp` removed. */ +export type StockTradeStatus = 'pre_market' | 'open' | 'post_market'; + +/** + * v4.106.148. + * 0 disabled, 1 buy only, 2 sell only, 4 buy and sell, + * 5 manual suspension, 6 strategy exception, 7 stock halt, 8 circuit breaker halt. + */ +export type StockTradeMode = 0 | 1 | 2 | 4 | 5 | 6 | 7 | 8; + +/** + * `GET /stock/orders` and `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 new, 2 partial, 3 filled, 4 canceled, 5 rejected, + * 6 cancel rejected, 7 update succeeded, 8 update rejected. + */ +export type StockOrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + +/** + * `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 no quote, 2 no match, 3 trigger price exceeded, + * 4 order value exceeds limit, 5 unknown rejection, 6 unknown cancellation, + * 7 canceled by user, 8 time in force expired, 9 session unsupported, + * 13 canceled due to corporate action. + */ +export type StockOrderFinishAs = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13; + export interface StockApiResp { timestamp?: number; data?: T; @@ -53,8 +79,8 @@ export interface StockSymbolItem { symbol_desc?: string; category?: StockCategory | string; asset_type?: StockAssetType; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; order_fill_timing?: number; icon_link?: string; quote_currency_symbol?: string; @@ -91,8 +117,8 @@ export interface StockSymbolDetailItem { buy_price_protection?: string; slippage_rate?: string; commission_rate?: string; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; order_fill_timing?: number; symbol_descs?: StockSymbolDescI18n[]; [key: string]: unknown; @@ -118,11 +144,11 @@ export interface StockOrderItem { quote_currency?: string; fx_rate?: string; symbol_desc?: string; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; price_type?: string; side?: number; - status?: number; + status?: StockOrderStatus; volume?: string; fill_volume?: string; price?: string; @@ -152,10 +178,10 @@ export interface StockOrderHistoryItem { fx_rate?: string; symbol_desc?: string; price_type?: string; - status?: number; + status?: StockOrderStatus; status_desc?: string; status_detail?: { title?: string; message?: string } | null; - finish_as?: number; + finish_as?: StockOrderFinishAs; side?: number; time_in_force?: string; volume?: string; @@ -178,7 +204,7 @@ export interface StockPositionItem { quote_currency?: string; quote_currency_precision?: number; fx_rate?: string; - trade_status?: string; + trade_status?: StockTradeStatus; symbol_desc?: string; position_pnl?: string; today_pnl?: string; diff --git a/src/types/shared.ts b/src/types/shared.ts index d451367..c4c095e 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -1,6 +1,12 @@ +/** + * Built-in Gate API v4 hosts. + * `testnet` is the global TestNet host (spot and futures). + * `futuresTestnet` is the same host, kept so older `baseUrlKey` values keep working. + */ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' + | 'testnet' | 'futuresTestnet'; // interfaces diff --git a/test/REST/baseUrl.test.ts b/test/REST/baseUrl.test.ts new file mode 100644 index 0000000..007a5d1 --- /dev/null +++ b/test/REST/baseUrl.test.ts @@ -0,0 +1,24 @@ +import { getRestBaseUrl } from '../../src/lib/requestUtils.js'; + +const GATE_TESTNET_REST_URL = 'https://api-testnet.gateapi.io/api/v4'; + +describe('REST base URL', () => { + it('uses the global testnet host for testnet and futuresTestnet', () => { + expect(getRestBaseUrl({ baseUrlKey: 'testnet' })).toBe( + GATE_TESTNET_REST_URL, + ); + expect(getRestBaseUrl({ baseUrlKey: 'futuresTestnet' })).toBe( + GATE_TESTNET_REST_URL, + ); + }); + + it('keeps live as the default and prefers an explicit baseUrl', () => { + expect(getRestBaseUrl({})).toBe('https://api.gateio.ws/api/v4'); + expect( + getRestBaseUrl({ + baseUrl: 'https://example.test/api/v4', + baseUrlKey: 'testnet', + }), + ).toBe('https://example.test/api/v4'); + }); +}); diff --git a/test/REST/priceOrderAmend.test.ts b/test/REST/priceOrderAmend.test.ts new file mode 100644 index 0000000..8e68480 --- /dev/null +++ b/test/REST/priceOrderAmend.test.ts @@ -0,0 +1,32 @@ +import { RestClient } from '../../src/index.js'; + +class CapturingRestClient extends RestClient { + public lastCall?: { endpoint: string; params?: unknown }; + + protected putPrivate(endpoint: string, params?: unknown): Promise { + this.lastCall = { endpoint, params }; + return Promise.resolve({ id: 1, id_string: '1' }); + } +} + +describe('updateFuturesPriceTriggeredOrder', () => { + it('puts order_id in the path and the body', async () => { + const rest = new CapturingRestClient(); + + await rest.updateFuturesPriceTriggeredOrder({ + settle: 'usdt', + order_id: 42, + price: '1', + }); + + expect(rest.lastCall).toEqual({ + endpoint: '/futures/usdt/price_orders/amend/42', + params: { + body: { + order_id: 42, + price: '1', + }, + }, + }); + }); +}); From c0980301a8935bc474ff78ff0525384cb6a8c73e Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Fri, 16 Oct 2026 12:17:27 +0200 Subject: [PATCH 2/7] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 896 +- .../updateFuturesPriceTriggeredOrder.js | 2 +- llms.txt | 12730 ++++++++-------- 3 files changed, 6855 insertions(+), 6773 deletions(-) diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index efece8f..ea6ec2e 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -49,454 +49,454 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getSystemMaintenanceStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L711) | | GET | `/v1/public/system_info` | -| [listAnnouncementArticles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L715) | | POST | `/ann/list_article` | -| [submitWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L734) | :closed_lock_with_key: | POST | `/withdrawals` | -| [submitSpotMainAccountTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L748) | :closed_lock_with_key: | POST | `/withdrawals/push` | -| [cancelWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L764) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | -| [getCurrencyChains()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L781) | | GET | `/wallet/currency_chains` | -| [createDepositAddress()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L791) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | -| [getWithdrawalRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L805) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | -| [getDepositRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L819) | :closed_lock_with_key: | GET | `/wallet/deposits` | -| [submitTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L838) | :closed_lock_with_key: | POST | `/wallet/transfers` | -| [getTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L850) | :closed_lock_with_key: | GET | `/wallet/transfers` | -| [submitMainSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L862) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | -| [getMainSubTransfers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L876) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | -| [submitSubToSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L890) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | -| [getTransferStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L905) | :closed_lock_with_key: | GET | `/wallet/order_status` | -| [getWithdrawalStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L921) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | -| [getSubBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L933) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | -| [getSubMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L945) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | -| [getSubFuturesBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L957) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | -| [getSubCrossMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L970) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | -| [getSavedAddresses()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L982) | :closed_lock_with_key: | GET | `/wallet/saved_address` | -| [getTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L992) | :closed_lock_with_key: | GET | `/wallet/fee` | -| [getBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1013) | :closed_lock_with_key: | GET | `/wallet/total_balance` | -| [getSmallBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1022) | :closed_lock_with_key: | GET | `/wallet/small_balance` | -| [convertSmallBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1032) | :closed_lock_with_key: | POST | `/wallet/small_balance` | -| [getSmallBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1045) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | -| [getPushOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1057) | :closed_lock_with_key: | GET | `/wallet/push` | -| [getLowCapExchangeList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1066) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | -| [createSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1081) | :closed_lock_with_key: | POST | `/sub_accounts` | -| [getSubAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1092) | :closed_lock_with_key: | GET | `/sub_accounts` | -| [getSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1102) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | -| [createSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1112) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | -| [getSubAccountApiKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1125) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | -| [updateSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1139) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | -| [deleteSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1150) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | -| [getSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1165) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | -| [lockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1180) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | -| [unlockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1190) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | -| [getSubAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1204) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | -| [getUnifiedAccountInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1223) | :closed_lock_with_key: | GET | `/unified/accounts` | -| [getUnifiedMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1239) | :closed_lock_with_key: | GET | `/unified/borrowable` | -| [getUnifiedMaxTransferable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1255) | :closed_lock_with_key: | GET | `/unified/transferable` | -| [getUnifiedMaxTransferables()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1270) | :closed_lock_with_key: | GET | `/unified/transferables` | -| [getUnifiedBatchMaxBorrowable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1279) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | -| [submitUnifiedBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1297) | :closed_lock_with_key: | POST | `/unified/loans` | -| [getUnifiedLoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1309) | :closed_lock_with_key: | GET | `/unified/loans` | -| [getUnifiedLoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1319) | :closed_lock_with_key: | GET | `/unified/loan_records` | -| [getUnifiedInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1331) | :closed_lock_with_key: | GET | `/unified/interest_records` | -| [getUnifiedRiskUnitDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1342) | :closed_lock_with_key: | GET | `/unified/risk_units` | -| [setUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1354) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | -| [getUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1363) | :closed_lock_with_key: | GET | `/unified/unified_mode` | -| [getUnifiedEstimateRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1375) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | -| [getUnifiedCurrencyDiscountTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1386) | | GET | `/unified/currency_discount_tiers` | -| [getLoanMarginTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1398) | | GET | `/unified/loan_margin_tiers` | -| [portfolioMarginCalculate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1415) | | POST | `/unified/portfolio_calculator` | -| [setUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1429) | :closed_lock_with_key: | POST | `/unified/leverage/user_setting` | -| [getUserCurrencyLeverageConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1443) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | -| [getUserCurrencyLeverageSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1457) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | -| [updateUserCurrencyLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1472) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | -| [getUnifiedLoanCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1487) | :closed_lock_with_key: | GET | `/unified/currencies` | -| [getHistoricalLendingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1499) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | -| [submitUnifiedLoanRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1505) | :closed_lock_with_key: | POST | `/unified/loans/repay` | -| [getEstimatedQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1512) | :closed_lock_with_key: | GET | `/unified/estimated_quick_repayment` | -| [createQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1519) | :closed_lock_with_key: | POST | `/unified/quick_repayment` | -| [setUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1530) | :closed_lock_with_key: | POST | `/unified/delta_neutral` | -| [getUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1539) | :closed_lock_with_key: | GET | `/unified/delta_neutral` | -| [getSpotCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1559) | | GET | `/spot/currencies` | -| [getSpotCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1569) | | GET | `/spot/currencies/{currency}` | -| [getSpotCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1578) | | GET | `/spot/currency_pairs` | -| [getSpotCurrencyPair()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1588) | | GET | `/spot/currency_pairs/{currency_pair}` | -| [getSpotTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1602) | | GET | `/spot/tickers` | -| [getSpotOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1617) | | GET | `/spot/order_book` | -| [getSpotTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1630) | | GET | `/spot/trades` | -| [getSpotCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1642) | | GET | `/spot/candlesticks` | -| [getSpotFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1654) | :closed_lock_with_key: | GET | `/spot/fee` | -| [getSpotBatchFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1663) | :closed_lock_with_key: | GET | `/spot/batch_fee` | -| [getSpotAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1675) | :closed_lock_with_key: | GET | `/spot/accounts` | -| [getSpotAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1687) | :closed_lock_with_key: | GET | `/spot/account_book` | -| [submitSpotBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1706) | :closed_lock_with_key: | POST | `/spot/batch_orders` | -| [getSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1733) | :closed_lock_with_key: | GET | `/spot/open_orders` | -| [submitSpotClosePosCrossDisabled()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1749) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | -| [submitSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1765) | :closed_lock_with_key: | POST | `/spot/orders` | -| [getSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1782) | :closed_lock_with_key: | GET | `/spot/orders` | -| [cancelSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1797) | :closed_lock_with_key: | DELETE | `/spot/orders` | -| [batchCancelSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1826) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | -| [getSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1851) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | -| [updateSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1868) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | -| [cancelSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1896) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | -| [getSpotTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1925) | :closed_lock_with_key: | GET | `/spot/my_trades` | -| [submitSpotCountdownOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1954) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | -| [batchUpdateSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1973) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | -| [getSpotInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2000) | :closed_lock_with_key: | GET | `/spot/insurance_history` | -| [submitSpotPriceTriggerOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2014) | :closed_lock_with_key: | POST | `/spot/price_orders` | -| [getSpotAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2026) | :closed_lock_with_key: | GET | `/spot/price_orders` | -| [cancelAllOpenSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2038) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | -| [getPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2051) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | -| [cancelSpotTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2063) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | -| [getSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2077) | :closed_lock_with_key: | GET | `/spot/pov_orders` | -| [createSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2089) | :closed_lock_with_key: | POST | `/spot/pov_orders` | -| [cancelSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2101) | :closed_lock_with_key: | DELETE | `/spot/pov_orders` | -| [getSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2115) | :closed_lock_with_key: | GET | `/spot/pov_orders/{order_id}` | -| [cancelSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2127) | :closed_lock_with_key: | DELETE | `/spot/pov_orders/{order_id}` | -| [setCollateralCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2139) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | -| [getMarginAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2160) | :closed_lock_with_key: | GET | `/margin/accounts` | -| [getMarginBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2174) | :closed_lock_with_key: | GET | `/margin/account_book` | -| [getFundingAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2192) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | -| [updateAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2210) | :closed_lock_with_key: | POST | `/margin/auto_repay` | -| [getAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2221) | :closed_lock_with_key: | GET | `/margin/auto_repay` | -| [getMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2235) | :closed_lock_with_key: | GET | `/margin/transferable` | -| [getCrossMarginCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2252) | | GET | `/margin/cross/currencies` | -| [getCrossMarginCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2263) | | GET | `/margin/cross/currencies/{currency}` | -| [getCrossMarginAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2275) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | -| [getCrossMarginAccountHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2288) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | -| [submitCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2305) | :closed_lock_with_key: | POST | `/margin/cross/loans` | -| [getCrossMarginBorrowHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2320) | :closed_lock_with_key: | GET | `/margin/cross/loans` | -| [getCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2333) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | -| [submitCrossMarginRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2348) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | -| [getCrossMarginRepayments()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2364) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | -| [getCrossMarginInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2377) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | -| [getCrossMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2393) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | -| [getEstimatedInterestRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2409) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | -| [getCrossMarginBorrowableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2423) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | -| [getMarginUserLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2436) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | -| [getMarginPublicLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2452) | | GET | `/margin/loan_margin_tiers` | -| [setMarginUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2468) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | -| [getMarginUserAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2485) | :closed_lock_with_key: | GET | `/margin/user/account` | -| [getLendingMarkets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2500) | | GET | `/margin/uni/currency_pairs` | -| [getLendingMarket()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2515) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | -| [getEstimatedInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2527) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | -| [submitMarginUNIBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2537) | :closed_lock_with_key: | POST | `/margin/uni/loans` | -| [getMarginUNILoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2553) | :closed_lock_with_key: | GET | `/margin/uni/loans` | -| [getMarginUNILoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2563) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | -| [getMarginUNIInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2575) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | -| [getMarginUNIMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2587) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | -| [getFlashSwapCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2603) | | GET | `/flash_swap/currency_pairs` | -| [submitFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2619) | :closed_lock_with_key: | POST | `/flash_swap/orders` | -| [getFlashSwapOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2631) | :closed_lock_with_key: | GET | `/flash_swap/orders` | -| [getFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2643) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | -| [submitFlashSwapOrderPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2653) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | -| [getFuturesContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2670) | | GET | `/futures/{settle}/contracts` | -| [getFuturesContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2685) | | GET | `/futures/{settle}/contracts/{contract}` | -| [listFuturesADLRiskStates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2692) | | GET | `/futures/{settle}/adl_risk_states` | -| [getFuturesOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2706) | | GET | `/futures/{settle}/order_book` | -| [getFuturesTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2719) | | GET | `/futures/{settle}/trades` | -| [getFuturesCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2734) | | GET | `/futures/{settle}/candlesticks` | -| [getPremiumIndexKLines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2747) | | GET | `/futures/{settle}/premium_index` | -| [getFuturesTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2760) | | GET | `/futures/{settle}/tickers` | -| [getFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2777) | | GET | `/futures/{settle}/funding_rate` | -| [getBatchFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2793) | | POST | `/futures/{settle}/funding_rates` | -| [getFuturesInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2811) | | GET | `/futures/{settle}/insurance` | -| [getFuturesStats()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2830) | | GET | `/futures/{settle}/contract_stats` | -| [getIndexConstituents()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2841) | | GET | `/futures/{settle}/index_constituents/{index}` | -| [getLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2858) | | GET | `/futures/{settle}/liq_orders` | -| [getRiskLimitTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2875) | | GET | `/futures/{settle}/risk_limit_tiers` | -| [getFuturesAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2888) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | -| [getFuturesAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2902) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | -| [getFuturesPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2915) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | -| [getFuturesPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2930) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | -| [updateFuturesMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2947) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | -| [updateFuturesLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2975) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | -| [getFuturesContractLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2995) | :closed_lock_with_key: | GET | `/futures/{settle}/get_leverage/{contract}` | -| [updateFuturesPositionMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3011) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | -| [updatePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3028) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | -| [updateFuturesDualMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3048) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | -| [getDualModePosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3064) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | -| [updateDualModePositionMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3079) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | -| [updateDualModePositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3095) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | -| [updateDualModePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3119) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | -| [submitFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3146) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | -| [getFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3167) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | -| [cancelAllFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3182) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | -| [getFuturesOrdersByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3202) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | -| [submitFuturesBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3225) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | -| [getFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3250) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | -| [cancelFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3267) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | -| [updateFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3292) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | -| [getFuturesTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3313) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | -| [getFuturesTradingHistoryByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3328) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | -| [getFuturesPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3341) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | -| [getFuturesLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3354) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | -| [getFuturesAutoDeleveragingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3367) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | -| [setFuturesOrderCancelCountdown()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3384) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | -| [getFuturesUserTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3401) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | -| [batchCancelFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3419) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | -| [batchUpdateFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3446) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | -| [getRiskLimitTable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3468) | | GET | `/futures/{settle}/risk_limit_table` | -| [submitFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3481) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | -| [getFuturesAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3494) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | -| [cancelAllOpenFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3507) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | -| [getFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3523) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | -| [cancelFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3538) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | -| [updateFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3553) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend` | -| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3568) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | -| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3586) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | -| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3599) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | -| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3614) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | -| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3627) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | -| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3645) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | -| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3658) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | -| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3671) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | -| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3681) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | -| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3691) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | -| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3703) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | -| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3711) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | -| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3720) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | -| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3729) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | -| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3746) | | GET | `/delivery/{settle}/contracts` | -| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3758) | | GET | `/delivery/{settle}/contracts/{contract}` | -| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3773) | | GET | `/delivery/{settle}/order_book` | -| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3786) | | GET | `/delivery/{settle}/trades` | -| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3800) | | GET | `/delivery/{settle}/candlesticks` | -| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3811) | | GET | `/delivery/{settle}/tickers` | -| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3828) | | GET | `/delivery/{settle}/insurance` | -| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3847) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | -| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3858) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | -| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3869) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | -| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3879) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | -| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3894) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | -| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3912) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | -| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3930) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | -| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3950) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | -| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3965) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | -| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3978) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | -| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3997) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | -| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4012) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | -| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4027) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | -| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4040) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | -| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4053) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | -| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4066) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | -| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4079) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | -| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4094) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | -| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4107) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | -| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4123) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | -| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4138) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | -| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4157) | | GET | `/options/underlyings` | -| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4167) | | GET | `/options/expirations` | -| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4177) | | GET | `/options/contracts` | -| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4190) | | GET | `/options/contracts/{contract}` | -| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4200) | | GET | `/options/settlements` | -| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4212) | | GET | `/options/settlements/{contract}` | -| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4227) | :closed_lock_with_key: | GET | `/options/my_settlements` | -| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4241) | | GET | `/options/order_book` | -| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4253) | | GET | `/options/tickers` | -| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4267) | | GET | `/options/underlying/tickers/{underlying}` | -| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4281) | | GET | `/options/candlesticks` | -| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4291) | | GET | `/options/underlying/candlesticks` | -| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4303) | | GET | `/options/trades` | -| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4314) | :closed_lock_with_key: | GET | `/options/accounts` | -| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4324) | :closed_lock_with_key: | GET | `/options/account_book` | -| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4336) | :closed_lock_with_key: | GET | `/options/positions` | -| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4348) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | -| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4360) | :closed_lock_with_key: | GET | `/options/position_close` | -| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4373) | :closed_lock_with_key: | POST | `/options/orders` | -| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4385) | :closed_lock_with_key: | GET | `/options/orders` | -| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4397) | :closed_lock_with_key: | DELETE | `/options/orders` | -| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4411) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | -| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4423) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | -| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4438) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | -| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4457) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | -| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4473) | :closed_lock_with_key: | GET | `/options/my_trades` | -| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4485) | :closed_lock_with_key: | POST | `/options/mmp` | -| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4497) | :closed_lock_with_key: | GET | `/options/mmp` | -| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4509) | :closed_lock_with_key: | POST | `/options/mmp/reset` | -| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4525) | | GET | `/earn/uni/currencies` | -| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4535) | | GET | `/earn/uni/currencies/{currency}` | -| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4545) | :closed_lock_with_key: | POST | `/earn/uni/lends` | -| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4555) | :closed_lock_with_key: | GET | `/earn/uni/lends` | -| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4567) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | -| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4580) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | -| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4593) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | -| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4606) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | -| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4619) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | -| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4635) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | -| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4650) | :closed_lock_with_key: | GET | `/earn/uni/chart` | -| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4658) | :closed_lock_with_key: | GET | `/earn/uni/rate` | -| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4675) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | -| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4687) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | -| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4699) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | -| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4709) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | -| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4719) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | -| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4731) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | -| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4743) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | -| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4755) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | -| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4767) | | GET | `/loan/multi_collateral/currencies` | -| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4776) | | GET | `/loan/multi_collateral/ltv` | -| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4785) | | GET | `/loan/multi_collateral/fixed_rate` | -| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4798) | | GET | `/loan/multi_collateral/current_rate` | -| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4820) | | GET | `/earn/dual/investment_plan` | -| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4831) | :closed_lock_with_key: | GET | `/earn/dual/orders` | -| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4843) | :closed_lock_with_key: | POST | `/earn/dual/orders` | -| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4852) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | -| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4861) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | -| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4870) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | -| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4881) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | -| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4890) | | GET | `/earn/fixed-term/product` | -| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4899) | | GET | `/earn/fixed-term/product/{asset}/list` | -| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4909) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | -| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4918) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | -| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4927) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | -| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4938) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | -| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4947) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | -| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4956) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | -| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4963) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | -| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4970) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | -| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4981) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | -| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4990) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | -| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5001) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | -| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5010) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | -| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5019) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | -| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5026) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | -| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5035) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | -| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5047) | :closed_lock_with_key: | GET | `/earn/staking/coins` | -| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5060) | :closed_lock_with_key: | POST | `/earn/staking/swap` | -| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5079) | :closed_lock_with_key: | GET | `/account/detail` | -| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5088) | :closed_lock_with_key: | GET | `/account/rate_limit` | -| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5098) | :closed_lock_with_key: | POST | `/account/stp_groups` | -| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5108) | :closed_lock_with_key: | GET | `/account/stp_groups` | -| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5118) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | -| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5128) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | -| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5144) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | -| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5162) | :closed_lock_with_key: | POST | `/account/debit_fee` | -| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5173) | :closed_lock_with_key: | GET | `/account/debit_fee` | -| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5182) | :closed_lock_with_key: | GET | `/account/main_keys` | -| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5198) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | -| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5211) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | -| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5225) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | -| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5240) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | -| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5263) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | -| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5273) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | -| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5286) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | -| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5299) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | -| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5308) | :closed_lock_with_key: | GET | `/rebate/user/info` | -| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5343) | :closed_lock_with_key: | POST | `/otc/quote` | -| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5355) | :closed_lock_with_key: | POST | `/otc/order/create` | -| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5369) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | -| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5378) | :closed_lock_with_key: | GET | `/otc/bank/list` | -| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5385) | :closed_lock_with_key: | GET | `/otc/bank_list` | -| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5389) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | -| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5398) | :closed_lock_with_key: | POST | `/otc/bank/create` | -| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5412) | :closed_lock_with_key: | POST | `/otc/bank/delete` | -| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5419) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | -| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5426) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | -| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5435) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5454) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5490) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5504) | :closed_lock_with_key: | POST | `/otc/order/cancel` | -| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5516) | :closed_lock_with_key: | GET | `/otc/order/list` | -| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5530) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | -| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5544) | :closed_lock_with_key: | GET | `/otc/order/detail` | -| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5558) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | -| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5567) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | -| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5579) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | -| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5592) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | -| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5601) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | -| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5612) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | -| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5624) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | -| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5636) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | -| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5648) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | -| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5659) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | -| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5670) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | -| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5681) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | -| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5692) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | -| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5705) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | -| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5714) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | -| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5725) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | -| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5734) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | -| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5745) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | -| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5756) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | -| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5777) | | GET | `/crossex/rule/symbols` | -| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5789) | | GET | `/crossex/rule/risk_limits` | -| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5803) | | GET | `/crossex/transfers/coin` | -| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5817) | :closed_lock_with_key: | POST | `/crossex/transfers` | -| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5831) | :closed_lock_with_key: | GET | `/crossex/transfers` | -| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5845) | :closed_lock_with_key: | POST | `/crossex/orders` | -| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5859) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | -| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5873) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | -| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5886) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | -| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5901) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | -| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5913) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | -| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5927) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | -| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5941) | :closed_lock_with_key: | PUT | `/crossex/accounts` | -| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5955) | :closed_lock_with_key: | GET | `/crossex/accounts` | -| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5967) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | -| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5981) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | -| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5995) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | -| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6011) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | -| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6025) | :closed_lock_with_key: | POST | `/crossex/position` | -| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6031) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | -| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6045) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | -| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6058) | :closed_lock_with_key: | GET | `/crossex/fee` | -| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6070) | :closed_lock_with_key: | GET | `/crossex/positions` | -| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6084) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | -| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6098) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | -| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6110) | :closed_lock_with_key: | GET | `/crossex/open_orders` | -| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6124) | :closed_lock_with_key: | GET | `/crossex/history_orders` | -| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6138) | :closed_lock_with_key: | GET | `/crossex/history_positions` | -| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6152) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | -| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6166) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | -| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6180) | :closed_lock_with_key: | GET | `/crossex/history_trades` | -| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6194) | :closed_lock_with_key: | GET | `/crossex/account_book` | -| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6208) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | -| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6222) | | GET | `/crossex/market/tickers` | -| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6236) | | GET | `/crossex/market/funding_info` | -| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6254) | :closed_lock_with_key: | GET | `/alpha/accounts` | -| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6266) | :closed_lock_with_key: | GET | `/alpha/account_book` | -| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6280) | :closed_lock_with_key: | POST | `/alpha/quote` | -| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6292) | :closed_lock_with_key: | POST | `/alpha/orders` | -| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6304) | :closed_lock_with_key: | GET | `/alpha/orders` | -| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6316) | :closed_lock_with_key: | GET | `/alpha/order` | -| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6328) | | GET | `/alpha/currencies` | -| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6340) | | GET | `/alpha/tickers` | -| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6346) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | -| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6350) | | GET | `/tradfi/symbols/categories` | -| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6356) | | GET | `/tradfi/symbols` | -| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6368) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | -| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6374) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | -| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6380) | | GET | `/tradfi/symbols/{symbol}/klines` | -| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6387) | | GET | `/tradfi/symbols/{symbol}/tickers` | -| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6391) | :closed_lock_with_key: | POST | `/tradfi/users` | -| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6395) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | -| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6399) | :closed_lock_with_key: | POST | `/tradfi/transactions` | -| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6405) | :closed_lock_with_key: | GET | `/tradfi/transactions` | -| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6411) | :closed_lock_with_key: | POST | `/tradfi/orders` | -| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6417) | :closed_lock_with_key: | GET | `/tradfi/orders` | -| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6421) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | -| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6428) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | -| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6432) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | -| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6438) | :closed_lock_with_key: | GET | `/tradfi/positions` | -| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6444) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | -| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6453) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | -| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6462) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | -| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6471) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | -| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6485) | :closed_lock_with_key: | GET | `/stock/users/assets` | -| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6497) | | GET | `/stock/symbols` | -| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6509) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | -| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6521) | | GET | `/stock/market/{symbol}/orderbook` | -| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6531) | :closed_lock_with_key: | GET | `/stock/orders` | -| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6545) | :closed_lock_with_key: | POST | `/stock/orders` | -| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6556) | :closed_lock_with_key: | DELETE | `/stock/orders` | -| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6566) | :closed_lock_with_key: | GET | `/stock/orders/history` | -| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6579) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | -| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6592) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | -| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6604) | :closed_lock_with_key: | GET | `/stock/positions` | -| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6616) | :closed_lock_with_key: | POST | `/stock/positions/close` | -| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6628) | :closed_lock_with_key: | GET | `/stock/transactions` | -| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6642) | :closed_lock_with_key: | POST | `/stock/transactions` | -| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6653) | | GET | `/stock/exchanges` | -| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6664) | | GET | `/stock/fee-rate` | +| [getSystemMaintenanceStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L712) | | GET | `/v1/public/system_info` | +| [listAnnouncementArticles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L716) | | POST | `/ann/list_article` | +| [submitWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L735) | :closed_lock_with_key: | POST | `/withdrawals` | +| [submitSpotMainAccountTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L749) | :closed_lock_with_key: | POST | `/withdrawals/push` | +| [cancelWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L765) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | +| [getCurrencyChains()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L782) | | GET | `/wallet/currency_chains` | +| [createDepositAddress()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L792) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | +| [getWithdrawalRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L806) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | +| [getDepositRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L820) | :closed_lock_with_key: | GET | `/wallet/deposits` | +| [submitTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L839) | :closed_lock_with_key: | POST | `/wallet/transfers` | +| [getTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L851) | :closed_lock_with_key: | GET | `/wallet/transfers` | +| [submitMainSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L863) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | +| [getMainSubTransfers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L877) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | +| [submitSubToSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L891) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | +| [getTransferStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L906) | :closed_lock_with_key: | GET | `/wallet/order_status` | +| [getWithdrawalStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L922) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | +| [getSubBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L934) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | +| [getSubMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L946) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | +| [getSubFuturesBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L958) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | +| [getSubCrossMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L971) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | +| [getSavedAddresses()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L983) | :closed_lock_with_key: | GET | `/wallet/saved_address` | +| [getTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L993) | :closed_lock_with_key: | GET | `/wallet/fee` | +| [getBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1014) | :closed_lock_with_key: | GET | `/wallet/total_balance` | +| [getSmallBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1023) | :closed_lock_with_key: | GET | `/wallet/small_balance` | +| [convertSmallBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1033) | :closed_lock_with_key: | POST | `/wallet/small_balance` | +| [getSmallBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1046) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | +| [getPushOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1058) | :closed_lock_with_key: | GET | `/wallet/push` | +| [getLowCapExchangeList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1067) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | +| [createSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1082) | :closed_lock_with_key: | POST | `/sub_accounts` | +| [getSubAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1093) | :closed_lock_with_key: | GET | `/sub_accounts` | +| [getSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1103) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | +| [createSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1113) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | +| [getSubAccountApiKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1126) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | +| [updateSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1140) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | +| [deleteSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1151) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | +| [getSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1166) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | +| [lockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1181) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | +| [unlockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1191) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | +| [getSubAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1205) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | +| [getUnifiedAccountInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1224) | :closed_lock_with_key: | GET | `/unified/accounts` | +| [getUnifiedMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1240) | :closed_lock_with_key: | GET | `/unified/borrowable` | +| [getUnifiedMaxTransferable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1256) | :closed_lock_with_key: | GET | `/unified/transferable` | +| [getUnifiedMaxTransferables()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1271) | :closed_lock_with_key: | GET | `/unified/transferables` | +| [getUnifiedBatchMaxBorrowable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1280) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | +| [submitUnifiedBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1298) | :closed_lock_with_key: | POST | `/unified/loans` | +| [getUnifiedLoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1310) | :closed_lock_with_key: | GET | `/unified/loans` | +| [getUnifiedLoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1320) | :closed_lock_with_key: | GET | `/unified/loan_records` | +| [getUnifiedInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1332) | :closed_lock_with_key: | GET | `/unified/interest_records` | +| [getUnifiedRiskUnitDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1343) | :closed_lock_with_key: | GET | `/unified/risk_units` | +| [setUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1355) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | +| [getUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1364) | :closed_lock_with_key: | GET | `/unified/unified_mode` | +| [getUnifiedEstimateRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1376) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | +| [getUnifiedCurrencyDiscountTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1387) | | GET | `/unified/currency_discount_tiers` | +| [getLoanMarginTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1399) | | GET | `/unified/loan_margin_tiers` | +| [portfolioMarginCalculate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1416) | | POST | `/unified/portfolio_calculator` | +| [setUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1430) | :closed_lock_with_key: | POST | `/unified/leverage/user_setting` | +| [getUserCurrencyLeverageConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1444) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | +| [getUserCurrencyLeverageSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1458) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | +| [updateUserCurrencyLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1473) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | +| [getUnifiedLoanCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1488) | :closed_lock_with_key: | GET | `/unified/currencies` | +| [getHistoricalLendingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1500) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | +| [submitUnifiedLoanRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1506) | :closed_lock_with_key: | POST | `/unified/loans/repay` | +| [getEstimatedQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1513) | :closed_lock_with_key: | GET | `/unified/estimated_quick_repayment` | +| [createQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1520) | :closed_lock_with_key: | POST | `/unified/quick_repayment` | +| [setUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1531) | :closed_lock_with_key: | POST | `/unified/delta_neutral` | +| [getUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1540) | :closed_lock_with_key: | GET | `/unified/delta_neutral` | +| [getSpotCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1560) | | GET | `/spot/currencies` | +| [getSpotCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1570) | | GET | `/spot/currencies/{currency}` | +| [getSpotCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1579) | | GET | `/spot/currency_pairs` | +| [getSpotCurrencyPair()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1589) | | GET | `/spot/currency_pairs/{currency_pair}` | +| [getSpotTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1603) | | GET | `/spot/tickers` | +| [getSpotOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1618) | | GET | `/spot/order_book` | +| [getSpotTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1631) | | GET | `/spot/trades` | +| [getSpotCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1643) | | GET | `/spot/candlesticks` | +| [getSpotFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1655) | :closed_lock_with_key: | GET | `/spot/fee` | +| [getSpotBatchFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1664) | :closed_lock_with_key: | GET | `/spot/batch_fee` | +| [getSpotAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1676) | :closed_lock_with_key: | GET | `/spot/accounts` | +| [getSpotAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1688) | :closed_lock_with_key: | GET | `/spot/account_book` | +| [submitSpotBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1707) | :closed_lock_with_key: | POST | `/spot/batch_orders` | +| [getSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1734) | :closed_lock_with_key: | GET | `/spot/open_orders` | +| [submitSpotClosePosCrossDisabled()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1750) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | +| [submitSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1766) | :closed_lock_with_key: | POST | `/spot/orders` | +| [getSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1783) | :closed_lock_with_key: | GET | `/spot/orders` | +| [cancelSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1798) | :closed_lock_with_key: | DELETE | `/spot/orders` | +| [batchCancelSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1827) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | +| [getSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1852) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | +| [updateSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1869) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | +| [cancelSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1897) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | +| [getSpotTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1926) | :closed_lock_with_key: | GET | `/spot/my_trades` | +| [submitSpotCountdownOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1955) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | +| [batchUpdateSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1974) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | +| [getSpotInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2001) | :closed_lock_with_key: | GET | `/spot/insurance_history` | +| [submitSpotPriceTriggerOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2015) | :closed_lock_with_key: | POST | `/spot/price_orders` | +| [getSpotAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2027) | :closed_lock_with_key: | GET | `/spot/price_orders` | +| [cancelAllOpenSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2039) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | +| [getPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2052) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | +| [cancelSpotTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2064) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | +| [getSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2078) | :closed_lock_with_key: | GET | `/spot/pov_orders` | +| [createSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2090) | :closed_lock_with_key: | POST | `/spot/pov_orders` | +| [cancelSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2102) | :closed_lock_with_key: | DELETE | `/spot/pov_orders` | +| [getSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2116) | :closed_lock_with_key: | GET | `/spot/pov_orders/{order_id}` | +| [cancelSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2128) | :closed_lock_with_key: | DELETE | `/spot/pov_orders/{order_id}` | +| [setCollateralCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2140) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | +| [getMarginAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2161) | :closed_lock_with_key: | GET | `/margin/accounts` | +| [getMarginBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2175) | :closed_lock_with_key: | GET | `/margin/account_book` | +| [getFundingAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2193) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | +| [updateAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2211) | :closed_lock_with_key: | POST | `/margin/auto_repay` | +| [getAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2222) | :closed_lock_with_key: | GET | `/margin/auto_repay` | +| [getMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2236) | :closed_lock_with_key: | GET | `/margin/transferable` | +| [getCrossMarginCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2253) | | GET | `/margin/cross/currencies` | +| [getCrossMarginCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2264) | | GET | `/margin/cross/currencies/{currency}` | +| [getCrossMarginAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2276) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | +| [getCrossMarginAccountHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2289) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | +| [submitCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2306) | :closed_lock_with_key: | POST | `/margin/cross/loans` | +| [getCrossMarginBorrowHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2321) | :closed_lock_with_key: | GET | `/margin/cross/loans` | +| [getCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2334) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | +| [submitCrossMarginRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2349) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | +| [getCrossMarginRepayments()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2365) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | +| [getCrossMarginInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2378) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | +| [getCrossMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2394) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | +| [getEstimatedInterestRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2410) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | +| [getCrossMarginBorrowableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2424) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | +| [getMarginUserLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2437) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | +| [getMarginPublicLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2453) | | GET | `/margin/loan_margin_tiers` | +| [setMarginUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2469) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | +| [getMarginUserAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2486) | :closed_lock_with_key: | GET | `/margin/user/account` | +| [getLendingMarkets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2501) | | GET | `/margin/uni/currency_pairs` | +| [getLendingMarket()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2516) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | +| [getEstimatedInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2528) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | +| [submitMarginUNIBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2538) | :closed_lock_with_key: | POST | `/margin/uni/loans` | +| [getMarginUNILoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2554) | :closed_lock_with_key: | GET | `/margin/uni/loans` | +| [getMarginUNILoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2564) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | +| [getMarginUNIInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2576) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | +| [getMarginUNIMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2588) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | +| [getFlashSwapCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2604) | | GET | `/flash_swap/currency_pairs` | +| [submitFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2620) | :closed_lock_with_key: | POST | `/flash_swap/orders` | +| [getFlashSwapOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2632) | :closed_lock_with_key: | GET | `/flash_swap/orders` | +| [getFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2644) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | +| [submitFlashSwapOrderPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2654) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | +| [getFuturesContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2671) | | GET | `/futures/{settle}/contracts` | +| [getFuturesContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2686) | | GET | `/futures/{settle}/contracts/{contract}` | +| [listFuturesADLRiskStates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2693) | | GET | `/futures/{settle}/adl_risk_states` | +| [getFuturesOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2707) | | GET | `/futures/{settle}/order_book` | +| [getFuturesTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2720) | | GET | `/futures/{settle}/trades` | +| [getFuturesCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2735) | | GET | `/futures/{settle}/candlesticks` | +| [getPremiumIndexKLines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2748) | | GET | `/futures/{settle}/premium_index` | +| [getFuturesTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2761) | | GET | `/futures/{settle}/tickers` | +| [getFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2778) | | GET | `/futures/{settle}/funding_rate` | +| [getBatchFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2794) | | POST | `/futures/{settle}/funding_rates` | +| [getFuturesInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2812) | | GET | `/futures/{settle}/insurance` | +| [getFuturesStats()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2831) | | GET | `/futures/{settle}/contract_stats` | +| [getIndexConstituents()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2842) | | GET | `/futures/{settle}/index_constituents/{index}` | +| [getLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2859) | | GET | `/futures/{settle}/liq_orders` | +| [getRiskLimitTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2876) | | GET | `/futures/{settle}/risk_limit_tiers` | +| [getFuturesAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2889) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | +| [getFuturesAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2903) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | +| [getFuturesPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2916) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | +| [getFuturesPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2931) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | +| [updateFuturesMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2948) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | +| [updateFuturesLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2976) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | +| [getFuturesContractLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2996) | :closed_lock_with_key: | GET | `/futures/{settle}/get_leverage/{contract}` | +| [updateFuturesPositionMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3012) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | +| [updatePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3029) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | +| [updateFuturesDualMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3049) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | +| [getDualModePosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3065) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | +| [updateDualModePositionMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3080) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | +| [updateDualModePositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3096) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | +| [updateDualModePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3120) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | +| [submitFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3147) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | +| [getFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3168) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | +| [cancelAllFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3183) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | +| [getFuturesOrdersByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3203) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | +| [submitFuturesBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3226) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | +| [getFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3251) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | +| [cancelFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3268) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | +| [updateFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3293) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | +| [getFuturesTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3314) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | +| [getFuturesTradingHistoryByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3329) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | +| [getFuturesPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3342) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | +| [getFuturesLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3355) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | +| [getFuturesAutoDeleveragingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3368) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | +| [setFuturesOrderCancelCountdown()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3385) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | +| [getFuturesUserTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3402) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | +| [batchCancelFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3420) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | +| [batchUpdateFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3447) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | +| [getRiskLimitTable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3469) | | GET | `/futures/{settle}/risk_limit_table` | +| [submitFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3482) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | +| [getFuturesAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3495) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | +| [cancelAllOpenFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3508) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | +| [getFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3524) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | +| [cancelFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3539) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | +| [updateFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3557) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend/{order_id}` | +| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3575) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | +| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3593) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | +| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3606) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | +| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3621) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | +| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3634) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | +| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3652) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | +| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3665) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | +| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3678) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | +| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3688) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | +| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3698) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | +| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3710) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | +| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3718) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | +| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3727) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | +| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3736) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | +| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3753) | | GET | `/delivery/{settle}/contracts` | +| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3765) | | GET | `/delivery/{settle}/contracts/{contract}` | +| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3780) | | GET | `/delivery/{settle}/order_book` | +| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3793) | | GET | `/delivery/{settle}/trades` | +| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3807) | | GET | `/delivery/{settle}/candlesticks` | +| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3818) | | GET | `/delivery/{settle}/tickers` | +| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3835) | | GET | `/delivery/{settle}/insurance` | +| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3854) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | +| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3865) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | +| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3876) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | +| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3886) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | +| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3901) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | +| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3919) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | +| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3937) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | +| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3957) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | +| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3972) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | +| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3985) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | +| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4004) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | +| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4019) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | +| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4034) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | +| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4047) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | +| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4060) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | +| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4073) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | +| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4086) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | +| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4101) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | +| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4114) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | +| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4130) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | +| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4145) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | +| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4164) | | GET | `/options/underlyings` | +| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4174) | | GET | `/options/expirations` | +| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4184) | | GET | `/options/contracts` | +| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4197) | | GET | `/options/contracts/{contract}` | +| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4207) | | GET | `/options/settlements` | +| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4219) | | GET | `/options/settlements/{contract}` | +| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4234) | :closed_lock_with_key: | GET | `/options/my_settlements` | +| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4248) | | GET | `/options/order_book` | +| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4260) | | GET | `/options/tickers` | +| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4274) | | GET | `/options/underlying/tickers/{underlying}` | +| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4288) | | GET | `/options/candlesticks` | +| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4298) | | GET | `/options/underlying/candlesticks` | +| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4310) | | GET | `/options/trades` | +| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4321) | :closed_lock_with_key: | GET | `/options/accounts` | +| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4331) | :closed_lock_with_key: | GET | `/options/account_book` | +| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4343) | :closed_lock_with_key: | GET | `/options/positions` | +| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4355) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | +| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4367) | :closed_lock_with_key: | GET | `/options/position_close` | +| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4380) | :closed_lock_with_key: | POST | `/options/orders` | +| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4392) | :closed_lock_with_key: | GET | `/options/orders` | +| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4404) | :closed_lock_with_key: | DELETE | `/options/orders` | +| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4418) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | +| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4430) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | +| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4445) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | +| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4464) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | +| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4480) | :closed_lock_with_key: | GET | `/options/my_trades` | +| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4492) | :closed_lock_with_key: | POST | `/options/mmp` | +| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4504) | :closed_lock_with_key: | GET | `/options/mmp` | +| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4516) | :closed_lock_with_key: | POST | `/options/mmp/reset` | +| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4532) | | GET | `/earn/uni/currencies` | +| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4542) | | GET | `/earn/uni/currencies/{currency}` | +| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4552) | :closed_lock_with_key: | POST | `/earn/uni/lends` | +| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4562) | :closed_lock_with_key: | GET | `/earn/uni/lends` | +| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4574) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | +| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4587) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | +| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4600) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | +| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4613) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | +| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4626) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | +| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4642) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | +| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4657) | :closed_lock_with_key: | GET | `/earn/uni/chart` | +| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4665) | :closed_lock_with_key: | GET | `/earn/uni/rate` | +| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4682) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | +| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4694) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | +| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4706) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | +| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4716) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | +| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4726) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | +| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4738) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | +| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4750) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | +| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4762) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | +| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4774) | | GET | `/loan/multi_collateral/currencies` | +| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4783) | | GET | `/loan/multi_collateral/ltv` | +| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4792) | | GET | `/loan/multi_collateral/fixed_rate` | +| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4805) | | GET | `/loan/multi_collateral/current_rate` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4827) | | GET | `/earn/dual/investment_plan` | +| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4838) | :closed_lock_with_key: | GET | `/earn/dual/orders` | +| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4850) | :closed_lock_with_key: | POST | `/earn/dual/orders` | +| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4859) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | +| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4868) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | +| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4877) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | +| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4888) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | +| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4897) | | GET | `/earn/fixed-term/product` | +| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4906) | | GET | `/earn/fixed-term/product/{asset}/list` | +| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4916) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | +| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4925) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | +| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4934) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | +| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4945) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | +| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4954) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | +| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4963) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | +| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4970) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | +| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4977) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | +| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4988) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | +| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4997) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | +| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5008) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | +| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5017) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | +| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5026) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | +| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5033) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | +| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5042) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | +| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5054) | :closed_lock_with_key: | GET | `/earn/staking/coins` | +| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5067) | :closed_lock_with_key: | POST | `/earn/staking/swap` | +| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5086) | :closed_lock_with_key: | GET | `/account/detail` | +| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5095) | :closed_lock_with_key: | GET | `/account/rate_limit` | +| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5105) | :closed_lock_with_key: | POST | `/account/stp_groups` | +| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5115) | :closed_lock_with_key: | GET | `/account/stp_groups` | +| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5125) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | +| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5135) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | +| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5151) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | +| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5169) | :closed_lock_with_key: | POST | `/account/debit_fee` | +| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5180) | :closed_lock_with_key: | GET | `/account/debit_fee` | +| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5189) | :closed_lock_with_key: | GET | `/account/main_keys` | +| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5205) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | +| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5218) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | +| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5232) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | +| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5247) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | +| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5270) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | +| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5280) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | +| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5293) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | +| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5306) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | +| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5315) | :closed_lock_with_key: | GET | `/rebate/user/info` | +| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5350) | :closed_lock_with_key: | POST | `/otc/quote` | +| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5362) | :closed_lock_with_key: | POST | `/otc/order/create` | +| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5376) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | +| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5385) | :closed_lock_with_key: | GET | `/otc/bank/list` | +| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5392) | :closed_lock_with_key: | GET | `/otc/bank_list` | +| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5396) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | +| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5405) | :closed_lock_with_key: | POST | `/otc/bank/create` | +| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5419) | :closed_lock_with_key: | POST | `/otc/bank/delete` | +| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5426) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | +| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5433) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | +| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5442) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5461) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5497) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5511) | :closed_lock_with_key: | POST | `/otc/order/cancel` | +| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5523) | :closed_lock_with_key: | GET | `/otc/order/list` | +| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5537) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | +| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5551) | :closed_lock_with_key: | GET | `/otc/order/detail` | +| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5565) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | +| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5574) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | +| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5586) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | +| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5599) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5608) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5619) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | +| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5631) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | +| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5643) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | +| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5655) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | +| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5666) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | +| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5677) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | +| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5688) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | +| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5699) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | +| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5712) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | +| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5721) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | +| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5732) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | +| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5741) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | +| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5752) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | +| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5763) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | +| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5784) | | GET | `/crossex/rule/symbols` | +| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5796) | | GET | `/crossex/rule/risk_limits` | +| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5810) | | GET | `/crossex/transfers/coin` | +| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5824) | :closed_lock_with_key: | POST | `/crossex/transfers` | +| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5838) | :closed_lock_with_key: | GET | `/crossex/transfers` | +| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5852) | :closed_lock_with_key: | POST | `/crossex/orders` | +| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5866) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | +| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5880) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | +| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5893) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | +| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5908) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | +| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5920) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | +| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5934) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | +| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5948) | :closed_lock_with_key: | PUT | `/crossex/accounts` | +| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5962) | :closed_lock_with_key: | GET | `/crossex/accounts` | +| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5974) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | +| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5988) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | +| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6002) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | +| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6018) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | +| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6032) | :closed_lock_with_key: | POST | `/crossex/position` | +| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6038) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | +| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6052) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | +| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6065) | :closed_lock_with_key: | GET | `/crossex/fee` | +| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6077) | :closed_lock_with_key: | GET | `/crossex/positions` | +| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6091) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | +| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6105) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | +| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6117) | :closed_lock_with_key: | GET | `/crossex/open_orders` | +| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6131) | :closed_lock_with_key: | GET | `/crossex/history_orders` | +| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6145) | :closed_lock_with_key: | GET | `/crossex/history_positions` | +| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6159) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | +| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6173) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | +| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6187) | :closed_lock_with_key: | GET | `/crossex/history_trades` | +| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6201) | :closed_lock_with_key: | GET | `/crossex/account_book` | +| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6215) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | +| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6229) | | GET | `/crossex/market/tickers` | +| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6243) | | GET | `/crossex/market/funding_info` | +| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6261) | :closed_lock_with_key: | GET | `/alpha/accounts` | +| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6273) | :closed_lock_with_key: | GET | `/alpha/account_book` | +| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6287) | :closed_lock_with_key: | POST | `/alpha/quote` | +| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6299) | :closed_lock_with_key: | POST | `/alpha/orders` | +| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6311) | :closed_lock_with_key: | GET | `/alpha/orders` | +| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6323) | :closed_lock_with_key: | GET | `/alpha/order` | +| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6335) | | GET | `/alpha/currencies` | +| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6347) | | GET | `/alpha/tickers` | +| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6353) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | +| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6357) | | GET | `/tradfi/symbols/categories` | +| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6363) | | GET | `/tradfi/symbols` | +| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6375) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | +| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6381) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | +| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6387) | | GET | `/tradfi/symbols/{symbol}/klines` | +| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6394) | | GET | `/tradfi/symbols/{symbol}/tickers` | +| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6398) | :closed_lock_with_key: | POST | `/tradfi/users` | +| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6402) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | +| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6406) | :closed_lock_with_key: | POST | `/tradfi/transactions` | +| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6412) | :closed_lock_with_key: | GET | `/tradfi/transactions` | +| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6418) | :closed_lock_with_key: | POST | `/tradfi/orders` | +| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6424) | :closed_lock_with_key: | GET | `/tradfi/orders` | +| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6428) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | +| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6435) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | +| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6439) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | +| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6445) | :closed_lock_with_key: | GET | `/tradfi/positions` | +| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6451) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | +| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6460) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | +| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6469) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | +| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6478) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | +| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6492) | :closed_lock_with_key: | GET | `/stock/users/assets` | +| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6504) | | GET | `/stock/symbols` | +| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6516) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | +| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6528) | | GET | `/stock/market/{symbol}/orderbook` | +| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6538) | :closed_lock_with_key: | GET | `/stock/orders` | +| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6552) | :closed_lock_with_key: | POST | `/stock/orders` | +| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6563) | :closed_lock_with_key: | DELETE | `/stock/orders` | +| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6573) | :closed_lock_with_key: | GET | `/stock/orders/history` | +| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6586) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | +| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6599) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | +| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6611) | :closed_lock_with_key: | GET | `/stock/positions` | +| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6623) | :closed_lock_with_key: | POST | `/stock/positions/close` | +| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6635) | :closed_lock_with_key: | GET | `/stock/transactions` | +| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6649) | :closed_lock_with_key: | POST | `/stock/transactions` | +| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6660) | | GET | `/stock/exchanges` | +| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6671) | | GET | `/stock/fee-rate` | # WebsocketAPIClient.ts diff --git a/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js b/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js index a211c1f..48dc1d7 100644 --- a/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js +++ b/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js @@ -4,7 +4,7 @@ import { RestClient } from 'gateio-api'; // This example shows how to call this Gate.io API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "gateio-api" for Gate.io exchange // This Gate.io API SDK is available on npm via "npm install gateio-api" -// ENDPOINT: /futures/{settle}/price_orders/amend +// ENDPOINT: /futures/{settle}/price_orders/amend/{order_id} // METHOD: PUT // PUBLIC: NO diff --git a/llms.txt b/llms.txt index a13ad5e..5169453 100644 --- a/llms.txt +++ b/llms.txt @@ -196,136 +196,6 @@ Most examples also have minimal typescript, so if you rename them to "js" they s 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 ================ @@ -441,118 +311,6 @@ 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 ================ @@ -600,32 +358,12 @@ export interface CreateStpGroupReq { } ================ -File: src/types/request/announcement.ts +File: src/types/request/collateralLoan.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 - * ========================================================================================================================== - */ +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ ⋮---- export interface SubmitLoanOrderReq { collateral_amount: string; @@ -1146,44 +884,6 @@ export interface AccountMainKey { 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 ================ @@ -3034,53 +2734,6 @@ 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 ================ @@ -3714,6 +3367,140 @@ async function start() // 'spotV4', // ); +================ +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); +⋮---- +// https://www.gate.com/docs/developers/apiv4/ws/en/ +⋮---- +// https://www.gate.com/docs/developers/options/ws/en/ +⋮---- +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.ts ================ @@ -4344,33 +4131,177 @@ export function appendGateMultipartFields( ): void ================ -File: src/types/request/options.ts +File: src/lib/requestUtils.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; -} +import WebSocket from 'isomorphic-ws'; ⋮---- -export interface GetOptionsOrderBookReq { - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; +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; + + /** + * Built-in Gate API v4 host. + * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 + * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. + */ + 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' + **/ +⋮---- +/** + * Built-in Gate API v4 host. + * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 + * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. + */ +⋮---- +/** 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 +⋮---- +/** Global TestNet REST host. Gate docs: spot and futures. */ +⋮---- +// Alias of `testnet`. Previously https://fx-api-testnet.gateio.ws/api/v4 (HTTP 502). +⋮---- +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/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/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 { @@ -4534,99 +4465,6 @@ export interface GetPartnerAgentDataAggregatedReq { * 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 ================ @@ -4770,10 +4608,48 @@ volume: string; // 24h Trading Volume (USDT) market_cap: string; // Current Token Market Cap ================ -File: src/types/response/autoinvest.ts +File: src/types/response/announcement.ts ================ -/**========================================================================================================================== - * EARN AUTO INVEST +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/autoinvest.ts +================ +/**========================================================================================================================== + * EARN AUTO INVEST * ========================================================================================================================== */ ⋮---- @@ -5213,60 +5089,6 @@ 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 ================ @@ -5821,388 +5643,151 @@ export interface PartnerDataAggregatedResponse { } ================ -File: src/types/response/stock.ts +File: src/types/response/withdrawal.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 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; } ⋮---- -export interface StockListData { - list?: T[]; - total?: number; - total_page?: number; -} +/** When `status` is DONE, withdrawal success time (not conditioned on `block_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; -} +| '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: .npmrc +================ +min-release-age=30 +save-exact=true + +================ +File: .nvmrc +================ +v24.18.0 + +================ +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) ⋮---- -export interface StockSymbolDescI18n { - lang?: string; - value?: string; -} +// Define the account object with API key and secret ⋮---- -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; -} +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 ⋮---- -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; -} +// Initialize the RestClient with the API credentials ⋮---- -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; -} +/** + * 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. + */ ⋮---- -export interface StockCreateOrderResult { - id?: string; -} +/* + * Futures TestNet trading (alias of `testnet`, spot and futures): + * 'https://api-testnet.gateapi.io/api/v4' + * Older host https://fx-api-testnet.gateio.ws/api/v4 now returns 502. + * baseUrlKey: 'testnet' is the same host. + */ ⋮---- -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; -} +/** + * Futures live trading alternative (futures only): + * 'https://fx-api.gateio.ws/api/v4' + */ +// baseUrlKey: 'futuresLiveAlternative' ⋮---- -export interface StockUpdateOrderResult { - order_id?: number; -} +async function submitFuturesOrder() ⋮---- -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; -} +// Submit a market order for futures trading ⋮---- -export interface StockClosePositionResult { - order_id?: number; -} +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) ⋮---- -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; -} +console.log('Response: ', result); // Log the response to the console ⋮---- -export interface StockExchangeItem { - exchange?: string; - exchange_desc?: string; - icon_link?: string; - support_transfer?: boolean; -} +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -export interface StockFeeRateItem { - vip_level?: number; - maker_fee?: string; - taker_fee?: string; -} +// Execute the function to submit a futures order ================ -File: src/types/response/withdrawal.ts +File: examples/Rest/otc/submitOTCBankPersonalSupplement.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; -} +import { readFileSync } from 'fs'; ⋮---- -/** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; ⋮---- -| '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 +async function submitOTCBankPersonalSupplementExample() ================ -File: src/types/shared.ts +File: src/types/request/alpha.ts ================ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'futuresTestnet'; -⋮---- -// interfaces +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; +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 } ⋮---- -// 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 +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 @@ -6539,6 +6124,153 @@ export interface P2PMerchantUploadChatFileReq { base64_img: string; } +================ +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/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/p2pMerchant.ts ================ @@ -6835,3456 +6567,4069 @@ restClientRegex.ts testfile.ts ================ -File: docs/GATE_SDK_QUICKSTART_GUIDE.md +File: src/types/request/earn.ts ================ - - -# 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(); - } +/**========================================================================================================================== + * 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 -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); - } +================ +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; +} - if (statusResponse && statusResponse.data.result.status !== 'open') { - console.log( - 'Order is no longer open:', - statusResponse.data.result.status, - ); - return; - } +================ +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; +} - 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(); - } +================ +File: src/types/response/stock.ts +================ +export type StockCategory = + | 'CS' + | 'ETF' + | 'ADRC' + | 'ADR' + | 'ETV' + | 'PFD' + | 'ETS' + | 'ETN' + | 'FUND'; +⋮---- +export type StockAssetType = 'STOCK' | 'ETF'; +⋮---- +/** v4.106.159: `closed` and `gt_lp` removed. */ +export type StockTradeStatus = 'pre_market' | 'open' | 'post_market'; +⋮---- +/** + * v4.106.148. + * 0 disabled, 1 buy only, 2 sell only, 4 buy and sell, + * 5 manual suspension, 6 strategy exception, 7 stock halt, 8 circuit breaker halt. + */ +export type StockTradeMode = 0 | 1 | 2 | 4 | 5 | 6 | 7 | 8; +⋮---- +/** + * `GET /stock/orders` and `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 new, 2 partial, 3 filled, 4 canceled, 5 rejected, + * 6 cancel rejected, 7 update succeeded, 8 update rejected. + */ +export type StockOrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; +⋮---- +/** + * `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 no quote, 2 no match, 3 trigger price exceeded, + * 4 order value exceeds limit, 5 unknown rejection, 6 unknown cancellation, + * 7 canceled by user, 8 time in force expired, 9 session unsupported, + * 13 canceled due to corporate action. + */ +export type StockOrderFinishAs = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13; +⋮---- +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?: StockTradeStatus; + trade_mode?: StockTradeMode; + 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?: StockTradeStatus; + trade_mode?: StockTradeMode; + 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?: StockTradeStatus; + trade_mode?: StockTradeMode; + price_type?: string; + side?: number; + status?: StockOrderStatus; + 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?: StockOrderStatus; + status_desc?: string; + status_detail?: { title?: string; message?: string } | null; + finish_as?: StockOrderFinishAs; + 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; } - -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); - } +⋮---- +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?: StockTradeStatus; + 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; } -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(), +================ +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; + }; }; - - 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); +⋮---- +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; + }; + }; } - -try { - ws.subscribe( - { - topic: 'spot.orders', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Order subscription failed:', error); +⋮---- +export interface SmallBalanceRecord { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; } - -try { - ws.subscribe( - { - topic: 'spot.usertrades', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Trade subscription failed:', error); +⋮---- +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; } -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. +================ +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; -The client: + /** Your API secret */ + apiSecret?: string; -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`. + useTestnet?: boolean; -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. + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; -Spot methods include: + /** How often to check if the connection is alive */ + pingInterval?: number; -- `submitNewSpotOrder()` -- `getSpotOrderStatus()` -- `getSpotOrders()` -- `updateSpotOrder()` -- `cancelSpotOrder()` -- `cancelSpotOrderById()` -- `cancelSpotOrderForSymbol()` + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; -Futures methods include: + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; -- `submitNewFuturesOrder()` -- `submitNewFuturesBatchOrder()` -- `getFuturesOrderStatus()` -- `getFuturesOrders()` -- `updateFuturesOrder()` -- `cancelFuturesOrder()` + requestOptions?: {}; -Pass a Futures `wsKey` explicitly. This keeps the settlement connection visible: + wsUrl?: string; -```javascript -import { WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + wsOptions?: { + protocols?: string[]; + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); + /** + * 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; -async function main() { - try { - const response = await wsApi.getFuturesOrders( - { - contract: 'BTC_USDT', - status: 'open', - limit: 20, - }, - WS_KEY_MAP.perpFuturesUSDTV4, - ); + /** + * 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; +} - console.log(response.header.status); - console.log(response.data.result); - } catch (error) { - console.error('WebSocket API order request failed:', error); - } finally { - wsApi.getWSClient().closeAll(); - } +================ +File: src/types/shared.ts +================ +/** + * Built-in Gate API v4 hosts. + * `testnet` is the global TestNet host (spot and futures). + * `futuresTestnet` is the same host, kept so older `baseUrlKey` values keep working. + */ +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'testnet' + | '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 -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 +================ +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 -Gate TestNet is a separate environment with separate credentials. Use it for all order examples while learning the SDK. +================ +File: docs/GATE_SDK_QUICKSTART_GUIDE.md +================ + -| 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` | +# Gate API JavaScript Tutorial for Node.js -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. +> [!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) -```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', -}); +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. -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', -}); -``` +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. -Do not send live credentials to TestNet or TestNet credentials to live hosts. TestNet balances, liquidity, and available products can differ from live trading. +**Key links** -Fund the required Spot or Futures TestNet account with test assets before running an order example. +- 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`? -## Connect to Global and regional REST API hosts +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. -Use the API host associated with the Gate account and product you are integrating. Credentials and product availability are not interchangeable across account regions. +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. -| 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/) | +`gateio-api` handles those mechanics and gives each job a focused client: -Global live is the SDK default. Set `baseUrl` for another supported account host: +| 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 | -```javascript -import { RestClient } from 'gateio-api'; +`WebsocketClient` also handles heartbeats, reconnects, cached subscriptions, and resubscription. `WebsocketAPIClient` adds login, request IDs, response matching, and promise resolution. -const gateUs = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - baseUrl: 'https://api.gate.us/api/v4', -}); +## Install the SDK -const gateEu = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - baseUrl: 'https://api.gateeu.com/api/v4', -}); +```bash +npm install gateio-api ``` -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: +The package includes CommonJS, ESM, and TypeScript declarations. Every example below is plain JavaScript using ESM imports. -```bash -npm install https-proxy-agent -``` +## Create Gate API keys -Set `GATE_PROXY_URL` to an `http://` or `https://` proxy URL. The example does not print the value because it may contain credentials. +Public market data does not require credentials. Private REST API calls, private streams, and WebSocket API commands require an API key and secret. -```javascript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; +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: -async function main() { - const proxyUrl = process.env.GATE_PROXY_URL; +- 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. - if (!proxyUrl) { - console.error('Set GATE_PROXY_URL.'); - return; - } +Set these live credential names in your shell, secret manager, or deployment environment: - const agent = new HttpsProxyAgent(proxyUrl); +- `GATE_API_KEY` +- `GATE_API_SECRET` - const rest = new RestClient( - {}, - { - httpsAgent: agent, - proxy: false, - }, - ); +Use separate names for TestNet: - const ws = new WebsocketClient({ - wsOptions: { - agent, - }, - }); +- `GATE_TESTNET_API_KEY` +- `GATE_TESTNET_API_SECRET` +- `GATE_PLACE_TESTNET_ORDER=true` - ws.on('open', ({ wsKey }) => { - console.log('WebSocket connected through proxy:', wsKey); - }); +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. - ws.on('response', (response) => { - console.log('Subscription response:', response); - }); +## Gate products and request vocabulary - ws.on('update', (update) => { - console.log('Ticker update through proxy:', update); - ws.closeAll(); - }); +Several short fields determine where a request goes and what its values mean: - ws.on('exception', () => { - console.error('WebSocket proxy connection failed.'); - }); +| 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 | - try { - const time = await rest.getServerTime(); - console.log('Server time through proxy:', time.server_time); - } catch { - console.error('REST API proxy request failed.'); - } +For Spot orders, `account` can be `spot`, `margin`, `cross_margin`, or `unified`, depending on the account and endpoint. This tutorial uses `spot`. - try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('WebSocket proxy subscription failed.'); - } +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. - process.once('SIGINT', () => { - ws.closeAll(); - }); -} +Keep these routing values visible in code and logs. They are part of the request, not interchangeable labels. -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. +## Start building: first calls and streams -### SOCKS5 proxy +Run each example on its own. Start with public data, then add authenticated account state and live streams. -Install the SOCKS agent: +### 1. Make public REST API calls -```bash -npm install socks-proxy-agent -``` +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. -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'; +import { RestClient } from 'gateio-api'; -async function main() { - const proxyUrl = process.env.GATE_SOCKS_PROXY_URL; +const client = new RestClient(); - if (!proxyUrl) { - console.error('Set GATE_SOCKS_PROXY_URL.'); - return; +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); } - 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 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 time = await rest.getServerTime(); - console.log('Server time through SOCKS5:', time.server_time); - } catch { - console.error('SOCKS5 REST API request failed.'); + 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 { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('SOCKS5 WebSocket subscription failed.'); + 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); } - process.once('SIGINT', () => { - ws.closeAll(); - }); + 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(); ``` -### 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; +The SDK returns the endpoint body directly. There is no shared result wrapper to unwrap. - if (!proxyUrl) { - console.error('Set GATE_PROXY_URL.'); - return; - } +Each Spot candle is a tuple: - const agent = new HttpsProxyAgent(proxyUrl); +```text +[ + timestamp, + quoteVolume, + close, + high, + low, + open, + baseVolume, + closed +] +``` - const rest = new RestClient( - { - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - }, - { - httpsAgent: agent, - proxy: false, - }, - ); +Use the [SDK endpoint map](./endpointFunctionList.md) or the official endpoint documentation when reading tuple positions and endpoint-specific objects. - const streams = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - wsOptions: { - agent, - }, - }); +### 2. Make private REST API calls - const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - wsOptions: { - agent, - }, - }); +Private calls use the same `RestClient`. Add your key and secret, then call private methods normally. The SDK adds the required timestamp and signature. - streams.on('authenticated', ({ wsKey }) => { - console.log('Private stream authenticated:', wsKey); - }); + - streams.on('update', (update) => { - console.log('Private update through proxy:', update); - }); +```javascript +import { RestClient } from 'gateio-api'; - streams.on('exception', () => { - console.error('Private stream proxy connection failed.'); - }); +const client = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); +async function main() { try { - const balances = await rest.getSpotAccounts(); - console.log('Spot balances through proxy:', balances); - } catch { - console.error('Private REST API proxy request failed.'); + const balances = await client.getSpotAccounts(); + console.log('Spot balances:', balances); + } catch (error) { + console.error('Balance request failed:', error); } try { - streams.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('Private stream subscription failed.'); + 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 { - await wsApi.getWSClient().connectWSAPI(WS_KEY_MAP.spotV4); - console.log('WebSocket API authenticated through proxy.'); - } catch { - console.error('WebSocket API proxy connection failed.'); + 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); } - process.once('SIGINT', () => { - streams.closeAll(); - wsApi.getWSClient().closeAll(); - }); + 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(); ``` -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. +`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. -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. +### 3. Subscribe to public WebSocket streams -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. +Every subscription includes both a topic and an explicit `wsKey`. The key tells the SDK which Gate connection should carry the subscription. - + -## Production checklist +```javascript +import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; -### Keep request time accurate +const ws = new WebsocketClient(); -Gate private requests and WebSocket authentication depend on timestamp checks. The gap between request time and server time must not exceed 60 seconds. +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. -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. +### 4. Subscribe to private Spot streams -### Respect rate limits +Private streams use the same client with credentials. This example follows Spot balances, orders, and user trades. -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. +```javascript +import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; -### Use custom order IDs +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); -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. +ws.on('authenticated', ({ wsKey }) => { + console.log('Authenticated:', wsKey); +}); -### Apply product metadata +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); -Before placing an order: +ws.on('update', (update) => { + console.log('Private Spot update:', update); +}); -- 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. +ws.on('reconnected', (event) => { + console.log('Reconnected:', event.wsKey); +}); -Refresh metadata regularly and when Gate rejects an order for a precision or size rule. +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); -### Confirm final state +try { + ws.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Balance subscription failed:', error); +} -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. +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); +} -After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); +} -### Scope credentials and network access +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` -- 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. +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. -### Shut down connections +Other private Spot topics include `spot.margin_balances` and `spot.cross_balances`. Check each channel's payload rules before subscribing. -Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. +### 5. Subscribe to private Futures streams -## FAQ +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. -### Does `gateio-api` work with plain JavaScript? +```javascript +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; -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. +const rest = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); -### Which client should I use? +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); -Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. +ws.on('authenticated', ({ wsKey }) => { + console.log('Authenticated:', wsKey); +}); -### Do public Gate API calls need credentials? +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); -No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. +ws.on('update', (update) => { + console.log('Private Futures update:', update); +}); -### Why did a REST API call return an object when another returned an array? +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); -Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. +async function main() { + let account; -### Why does `getSpotTicker()` return an array for one pair? + try { + account = await rest.getAccountDetail(); + console.log('Gate user ID:', account.user_id); + } catch (error) { + console.error('Account detail request failed:', error); + return; + } -That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. + const userId = String(account.user_id); + const payload = [userId, 'BTC_USDT']; + const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; -### How are Spot candles structured? + try { + ws.subscribe( + { + topic: 'futures.orders', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Order subscription failed:', error); + } -Spot candles are tuple arrays containing timestamp, quote volume, close, high, low, open, base volume, and a closed-window flag in that order. + try { + ws.subscribe( + { + topic: 'futures.usertrades', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Trade subscription failed:', error); + } -### Why does Gate use `BTC_USDT`? + try { + ws.subscribe( + { + topic: 'futures.balances', + payload: [userId], + }, + wsKey, + ); + } catch (error) { + console.error('Balance subscription failed:', error); + } -Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. + try { + ws.subscribe( + { + topic: 'futures.positions', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Position subscription failed:', error); + } +} -### What do `account` and `settle` change? +process.once('SIGINT', () => { + ws.closeAll(); +}); -`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. +main(); +``` -### What is the `text` order field? +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`. -`text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. +Gate also provides private Futures channels such as `futures.autoorders`. Use the payload documented for that specific channel. -### Why am I not receiving WebSocket updates? +### 6. Place and cancel a Spot order in TestNet -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. +Gate TestNet uses separate credentials and API hosts. This example: -### Which `WS_KEY_MAP` value should I use? +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. -Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. +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. -### 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. +```javascript +import { RestClient } from 'gateio-api'; -### What is the difference between a stream and the WebSocket 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', +}); -Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } -### Does a successful WebSocket API response mean the order filled? + 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; + } -No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. + let pair; -### Why was a post-only order rejected or immediately finished? + try { + pair = await client.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + } catch (error) { + console.error('Currency pair request failed:', error); + return; + } -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`. + let orderBook; -### Why does a Futures order size look too small? + try { + orderBook = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } -Futures `size` is the number of contracts. Use `quanto_multiplier` to find the underlying amount represented by one contract. + if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { + console.error('BTC_USDT is not currently buyable.'); + return; + } -### Can live credentials be used in TestNet? + 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); -No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. + if ( + !price || + amountPrecision === undefined || + !Number.isFinite(minBase) || + !Number.isFinite(minQuote) || + !Number.isFinite(priceNumber) || + priceNumber <= 0 + ) { + console.error('Required market metadata is unavailable.'); + return; + } -### Can I use Gate US or Gate EU with the SDK? + const amountStep = 10 ** -amountPrecision; + const minimumAmount = Math.max(minBase, minQuote / priceNumber); + const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; + const amount = amountNumber.toFixed(amountPrecision); -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. + if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { + console.error('Could not derive a valid TestNet order.'); + return; + } -### Can REST API and WebSocket traffic use the same proxy? + const maxBase = Number(pair.max_base_amount); + const maxQuote = Number(pair.max_quote_amount); -Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. + if ( + (Number.isFinite(maxBase) && amountNumber > maxBase) || + (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) + ) { + console.error('Derived amount exceeds the pair limits.'); + return; + } -### Does a proxy change signing or account eligibility? + const text = `t-siebly${Date.now().toString().slice(-12)}`; + let placedOrder; -No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. + 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; + } -### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? + if (!placedOrder.id) { + console.error('Gate did not return an order ID.'); + return; + } -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. + let currentOrder; -## Next steps + 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); + } -- 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). + if (currentOrder && currentOrder.status !== 'open') { + console.log('Order is no longer open:', currentOrder.status); + return; + } -================ -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; + 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); + } } -⋮---- -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; +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); + } } -⋮---- -export interface SubmitOTCBankEnterpriseSupplementReq { - bank_id: string; - certificate: GateMultipartFile; - share_holders: GateMultipartFile; - passport: GateMultipartFile; - share_holding_structure: GateMultipartFile; - uid?: string; - funds_statement?: GateMultipartFile; - additional?: GateMultipartFile; + +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(); + } } -⋮---- -export interface CreateOTCUploadPreUploadReq { - content_type: string; - scene: 'general' | 'bank' | 'assessment' | 'credit'; + +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); + } } -================ -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; +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; + } } -⋮---- -export interface GetSpotTradesReq { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; + +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); } -⋮---- -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'; + +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); } -⋮---- -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; + +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); } -⋮---- -/** - * 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'; + +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(); + } } -⋮---- -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'; + +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` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | + +Set the REST API host with `baseUrl` or `baseUrlKey`, and the WebSocket host with `wsUrl` or `useTestnet: true`. Prefer explicit hosts for TestNet examples: + +- `baseUrlKey: 'testnet'` uses `https://api-testnet.gateapi.io/api/v4` for spot and futures. `baseUrlKey: 'futuresTestnet'` is the same host, kept so older configs keep working. +- `useTestnet: true` selects the TestNet WebSocket host for that connection, including Spot and Options. BTC perpetual and delivery TestNet hosts stay on the URLs in the current Gate docs (`wss://fx-ws-testnet.gateio.ws/...`). Announcements still have no TestNet host. + +```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(); + }); } -⋮---- -export interface CancelSpotBatchOrdersReq { - currency_pair: string; - id: string; - account?: 'cross_margin'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; + +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(); + }); } -⋮---- -export interface DeleteSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - xGateExptime?: number; + +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/otc.ts +================ +import { GateMultipartFile } from '../../lib/multipartUtil.js'; ⋮---- -export interface GetSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; -} +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ ⋮---- -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 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) } ⋮---- -export interface UpdateSpotBatchOrdersReq { - order_id?: string; - currency_pair?: string; - amount?: string; - price?: string; - amend_text?: string; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; -} +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 GetSpotInsuranceHistoryReq { - business: 'margin' | 'unified'; - currency: string; - from: number; - to: number; - page?: number; - limit?: number; +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; } ⋮---- -export interface GetSpotAutoOrdersReq { - status: 'open' | 'finished'; - market?: string; - account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; - limit?: number; - offset?: number; -} +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 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 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) } ⋮---- -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; -} +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) ⋮---- -/** GET /spot/pov_orders */ -export interface GetSpotPovOrdersReq { - status: 'open' | 'finished'; - currency_pair?: string; - side?: 'buy' | 'sell'; - page?: number; - limit?: number; +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 } ⋮---- -/** 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; -} +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 ⋮---- -/** DELETE /spot/pov_orders */ -export interface CancelSpotPovOrdersReq { - currency_pair?: string; +export interface CancelOTCOrderReq { + order_id: string; // Order ID } - -================ -File: src/types/request/tradfi.ts -================ -/** TradFi API request types */ ⋮---- -export interface TradFiGetSymbolDetailParams { - symbols: string; -} +order_id: string; // Order ID ⋮---- -export interface TradFiGetKlinesParams { - kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; - begin_time?: number; - end_time?: number; - limit?: number; +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 } ⋮---- -export interface TradFiCreateTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; -} +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 TradFiGetTransactionsParams { - begin_time?: number; - end_time?: number; - type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; - page?: number; - page_size?: number; +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 } ⋮---- -export interface TradFiCreateOrderReq { - price: string; - price_type: 'trigger' | 'market'; - side: 1 | 2; - symbol: string; - volume: string; - price_tp?: string; - price_sl?: string; - leverage?: number; +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 } ⋮---- -export interface TradFiModifyOrderReq { - price: string; - price_tp?: string | null; - price_sl?: string | null; +order_id: string; // Order ID +⋮---- +export interface OTCBankIdReq { + bank_id: string; } ⋮---- -export interface TradFiModifyPositionReq { - price_tp?: string | null; - price_sl?: string | null; +export interface GetOTCBankSupplementChecklistReq { + bank_id: string; } ⋮---- -export interface TradFiClosePositionReq { - close_type: 1 | 2; - close_volume?: string | null; +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 TradFiGetOrderHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - side?: 1 | 2; +export interface SubmitOTCBankPersonalSupplementReq { + bank_id: string; + id_document_front: GateMultipartFile; + id_document_back: GateMultipartFile; + address_proof: GateMultipartFile; } ⋮---- -export interface TradFiGetPositionHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - position_dir?: 'Long' | 'Short'; - page?: number; - page_size?: number; +export interface SubmitOTCBankEnterpriseSupplementReq { + bank_id: string; + certificate: GateMultipartFile; + share_holders: GateMultipartFile; + passport: GateMultipartFile; + share_holding_structure: GateMultipartFile; + uid?: string; + funds_statement?: GateMultipartFile; + additional?: GateMultipartFile; } ⋮---- -/** GET /tradfi/symbols/commissions */ -export interface TradFiGetSymbolCommissionsParams { - symbols?: string; - category_code?: string; +export interface CreateOTCUploadPreUploadReq { + content_type: string; + scene: 'general' | 'bank' | 'assessment' | 'credit'; } ================ -File: src/types/request/unified.ts +File: src/types/request/spot.ts ================ -export interface SubmitUnifiedBorrowOrRepayReq { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; -} +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ ⋮---- -export interface GetUnifiedLoansReq { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; +/** Limit-order take-profit / stop-loss on create */ +export interface SpotOrderTPSL { + trigger_price: string; + order_price: string; } ⋮---- -export interface GetUnifiedLoanRecordsReq { - type?: 'borrow' | 'repay'; - currency?: string; - page?: number; +/** 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 GetUnifiedInterestRecordsReq { - currency?: string; - page?: number; +⋮---- +export interface GetSpotTradesReq { + currency_pair: string; limit?: number; + last_id?: string; + reverse?: boolean; 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; - }; + page?: number; } ⋮---- -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 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 GetUnifiedHistoryLendingRateReq { - currency: string; - tier?: string; +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; } ⋮---- -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; -} +/** + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. + */ ⋮---- -/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ -export interface SetUserLeverageReq { - leverage?: string; +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } - -================ -File: src/types/request/wallet.ts -================ -/** GET /wallet/sub_account_balances */ -export interface GetSubAccountBalancesReq { - sub_uid?: string; +⋮---- +export interface GetSpotOrdersReq { + currency_pair: string; + status: 'open' | 'finished'; page?: number; limit?: number; -} -⋮---- -export interface GetWithdrawalDepositRecordsReq { - currency?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; from?: number; to?: number; - limit?: number; - offset?: number; + side?: 'buy' | 'sell'; } ⋮---- -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 CancelSpotBatchOrdersReq { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -export interface GetMainSubTransfersReq { - sub_uid?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + xGateExptime?: 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 +export interface GetSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; } ⋮---- -currency?: string; // v4.106.94: Optional filter by currency +export interface GetSpotTradingHistoryReq { + currency_pair?: string; + limit?: number; + page?: number; + order_id?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; +} ⋮---- -verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +export interface UpdateSpotBatchOrdersReq { + order_id?: string; + currency_pair?: string; + amount?: string; + price?: string; + amend_text?: string; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; +} ⋮---- -export interface GetSmallBalanceHistoryReq { - currency?: string; +export interface GetSpotInsuranceHistoryReq { + business: 'margin' | 'unified'; + currency: string; + from: number; + to: number; page?: number; limit?: number; } ⋮---- -export interface ListPushOrdersReq { - id?: number; - from?: number; - to?: number; +export interface GetSpotAutoOrdersReq { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; 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'; +export interface SubmitSpotOrderReq { + xGateExptime?: number; + side: 'buy' | 'sell'; amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; + 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; } ⋮---- -/** 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; +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 /wallet/sub_account_balances item */ -export interface SubAccountBalance { - uid: string; - available: { [key: string]: string }; - /** Locked amount per currency */ - locking?: { [key: string]: string }; +/** GET /spot/pov_orders */ +export interface GetSpotPovOrdersReq { + status: 'open' | 'finished'; + currency_pair?: string; + side?: 'buy' | 'sell'; + page?: number; + limit?: number; } ⋮---- -/** Locked amount per currency */ -⋮---- -export interface DepositRecord { - id: string; - txid: string; - timestamp: string; +/** POST /spot/pov_orders */ +export interface CreateSpotPovOrderReq { + currency_pair: string; + side: 'buy' | 'sell'; 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'; + 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; } ⋮---- -| '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 +/** DELETE /spot/pov_orders */ +export interface CancelSpotPovOrdersReq { + currency_pair?: string; +} + +================ +File: src/types/request/tradfi.ts +================ +/** TradFi API request types */ ⋮---- -export interface CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; +export interface TradFiGetSymbolDetailParams { + symbols: string; } ⋮---- -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 TradFiGetKlinesParams { + kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; + begin_time?: number; + end_time?: number; + limit?: number; } ⋮---- -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 TradFiCreateTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; } ⋮---- -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 TradFiGetTransactionsParams { + begin_time?: number; + end_time?: number; + type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; + page?: number; + page_size?: number; } ⋮---- -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 TradFiCreateOrderReq { + price: string; + price_type: 'trigger' | 'market'; + side: 1 | 2; + symbol: string; + volume: string; + price_tp?: string; + price_sl?: string; + leverage?: number; } ⋮---- -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 TradFiModifyOrderReq { + price: string; + price_tp?: string | null; + price_sl?: string | null; } ⋮---- -export interface SavedAddress { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; +export interface TradFiModifyPositionReq { + price_tp?: string | null; + price_sl?: string | null; } ⋮---- -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 TradFiClosePositionReq { + close_type: 1 | 2; + close_volume?: string | null; } ⋮---- -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 TradFiGetOrderHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + side?: 1 | 2; } ⋮---- -export interface SmallBalanceRecord { - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; +export interface TradFiGetPositionHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + position_dir?: 'Long' | 'Short'; + page?: number; + page_size?: number; } ⋮---- -export interface SmallBalanceHistoryRecord { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; +/** GET /tradfi/symbols/commissions */ +export interface TradFiGetSymbolCommissionsParams { + symbols?: string; + category_code?: string; } + +================ +File: src/types/response/earn.ts +================ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ ⋮---- -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; +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'; } ⋮---- -/** 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; +/** @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; } - -================ -File: src/types/websockets/client.ts -================ -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; ⋮---- -/** - * Event args for subscribing/unsubscribing - */ +/** 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 type WsTopicSubscribePrivateArgsV2 = -// | WsTopicSubscribePrivateInstIdArgsV2 -// | WsTopicSubscribePrivateCoinArgsV2; +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; +} ⋮---- -// export type WsTopicSubscribeEventArgsV2 = -// | WsTopicSubscribePublicArgsV2 -// | WsTopicSubscribePrivateArgsV2; +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ ⋮---- -/** 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; +export interface FixedTermLadderApr { + apr: string; + left: string; + right: string; } ⋮---- -/** Your API key */ +export interface FixedTermProductInfo { + pre_redeem: number; + reinvest: number; + redeem_account: number; + min_vip: number; + max_vip: number; +} ⋮---- -/** Your API secret */ +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; +} ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +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; +} ⋮---- -/** How often to check if the connection is alive */ +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; +} ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +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; +} ⋮---- -/** Delay in milliseconds before respawning the connection */ +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; +} ⋮---- -/** - * 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 interface GetEarnFixedTermProductsResponse { + code: number; + message: string; + data: { + list: FixedTermProduct[]; + total: number; + }; + timestamp: number; +} ⋮---- -/** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ +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; +} ⋮---- -/** - * 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; +export interface GetEarnFixedTermLendsResponse { + code: number; + message: string; + data: { + list: FixedTermLendOrder[]; + total: number; + }; + timestamp: number; } - -================ -File: webpack/webpack.config.cjs -================ -function generateConfig(name) ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +export interface CreateEarnFixedTermPreRedeemResponse { + code?: number; + message?: string; + data?: Record; + timestamp?: number; +} ⋮---- -// 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 +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; +} ⋮---- -// Code is already transpiled from TypeScript, no additional loaders needed +export interface GetEarnFixedTermHistoryResponse { + code?: number; + message?: string; + data?: { + list?: FixedTermHistoryRecord[]; + total?: number; + }; + timestamp?: number; +} ================ File: src/types/request/crossex.ts @@ -10776,1346 +11121,1041 @@ export interface CreateCrossExConvertQuoteResp { 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 + price: string; // Price } ⋮---- -funding_time: string; // Next funding time +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 CancelBatchCrossExOrdersResp { - order_id: string; - text: string; - accepted: string; // "true" | "false" - label: string; - message: string; +export interface CreateCrossExConvertOrderResp { + order_id: string; // Order ID + text: string; // User-defined order ID text } ⋮---- -accepted: string; // "true" | "false" +order_id: string; // Order ID +text: string; // User-defined order ID text ⋮---- -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 +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) } ⋮---- -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 +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 CrossExMarginPosition { +export interface CrossExAccountAsset { 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 + coin: string; // Currency + exchange_type: string; // Exchange + balance: string; // Balance 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 + 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 -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 +coin: string; // Currency +exchange_type: string; // Exchange +balance: string; // Balance 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) +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 CrossExHistoryPosition { - position_id: string; // Position ID +export interface CrossExAccount { 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 + 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[]; } ⋮---- -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 +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 CrossExHistoryMarginPosition { - position_id: string; // Position ID - user_id: string; // User ID +export interface SetCrossExPositionLeverageResp { 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 + leverage: string; // Requested Modified Leverage } ⋮---- -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 +leverage: string; // Requested Modified Leverage ⋮---- -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 +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 } ⋮---- -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 +symbol: string; // Currency pair +leverage: string; // Requested Modified Leverage ⋮---- -export interface CrossExHistoryTrade { - user_id: string; // User ID - transaction_id: string; // filled records ID - order_id: string; // Order ID - text: string; // User Order ID +export interface CrossExMarginPositionLeverage { 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 + leverage: number | string; } ⋮---- -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 +export interface CloseCrossExPositionResp { + order_id: string; // Order ID + text: string; // User-defined Order ID } ⋮---- -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 +order_id: string; // Order ID +text: string; // User-defined Order ID ⋮---- -export interface CrossExCoinDiscountRate { +export interface CrossExInterestRate { 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 + hour_interest_rate: string; // Hourly Interest Rate + time: string; // Millisecond Timestamp } ⋮---- 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 +hour_interest_rate: string; // Hourly Interest Rate +time: string; // Millisecond Timestamp ⋮---- -export interface UpdateCrossExPositionsMarginResp { - symbol?: string; - margin?: string; - position_side?: 'NONE' | 'LONG' | 'SHORT'; +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 } - -================ -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'; +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[]; } ⋮---- -/** @deprecated */ +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 ⋮---- -/** 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; +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; } ⋮---- -/** 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 CrossExMarketFundingInfo { + symbol: string; + funding_rate: string; + funding_interval: string; + funding_time: string; // Next funding time } ⋮---- -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; +funding_time: string; // Next funding time +⋮---- +export interface CancelBatchCrossExOrdersResp { + order_id: string; text: string; + accepted: string; // "true" | "false" + label: string; + message: string; } ⋮---- -/**========================================================================================================================== - * EARN FIXED-TERM - * ========================================================================================================================== - */ +accepted: string; // "true" | "false" ⋮---- -export interface FixedTermLadderApr { - apr: string; - left: string; - right: string; +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 } ⋮---- -export interface FixedTermProductInfo { - pre_redeem: number; - reinvest: number; - redeem_account: number; - min_vip: number; - max_vip: number; -} +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 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 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 } ⋮---- -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; -} +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 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 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) } ⋮---- -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; -} +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 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 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 } ⋮---- -export interface GetEarnFixedTermProductsResponse { - code: number; - message: string; - data: { - list: FixedTermProduct[]; - total: number; - }; - timestamp: number; +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 } ⋮---- -export interface GetEarnFixedTermProductsByAssetResponse { - code: number; - message: string; - data: { - list: FixedTermProductSimple[]; - }; - timestamp: number; -} +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 CreateEarnFixedTermLendResponse { - code?: number; - message?: string; - data?: { - order_id?: number; - }; - timestamp?: number; +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 } ⋮---- -export interface GetEarnFixedTermLendsResponse { - code: number; - message: string; - data: { - list: FixedTermLendOrder[]; - total: number; - }; - timestamp: number; -} +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 CreateEarnFixedTermPreRedeemResponse { - code?: number; - message?: string; - data?: Record; - timestamp?: number; +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 } ⋮---- -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; -} +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 GetEarnFixedTermHistoryResponse { - code?: number; - message?: string; - data?: { - list?: FixedTermHistoryRecord[]; - total?: number; - }; - timestamp?: number; +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 } - -================ -File: src/types/response/otc.ts -================ -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ ⋮---- -export interface OTCActionResp { - code: number; - message: string; - timestamp: number; -} +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 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; +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 } ⋮---- -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; +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 CreateOTCStablecoinOrderResp { - code: number; - message: string; - timestamp: number; +export interface UpdateCrossExPositionsMarginResp { + symbol?: string; + margin?: string; + position_side?: 'NONE' | 'LONG' | 'SHORT'; } + +================ +File: src/types/response/tradfi.ts +================ +/** TradFi API response types */ ⋮---- -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; +export interface TradFiApiResp { + timestamp?: number; + data?: T; + code?: number; + message?: string; + label?: 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 TradFiListData { + list?: T[]; + total?: number; + total_page?: number; } ⋮---- -export interface CreateOTCBankResp { - code: number; - message: string; - data: { - bank_id: number; - status: number; - }; - timestamp?: 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; } ⋮---- -export interface OTCBankSupplementChecklistItem { - description: string; - code?: string; - zh?: string; - en?: string; - required?: boolean; +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 GetOTCBankSupplementChecklistResp { - code: number; - message: string; - data: { - user_type: 'personal' | 'enterprise'; - items: OTCBankSupplementChecklistItem[]; - }; - timestamp?: number; +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 type MarkOTCOrderAsPaidResp = OTCActionResp; +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 type CancelOTCOrderResp = OTCActionResp; +export interface TradFiKlineItem { + o?: string; + c?: string; + h?: string; + l?: string; + t?: number; +} ⋮---- -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 +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; } ⋮---- -time: string; // Current time -timestamp: number; // Current timestamp +export interface TradFiCreateUserResult { + status?: number; + leverage?: number; + mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +} ⋮---- -trade_no: string; // Trade number -type: string; // Quote direction buy/sell/all -status: string; // Order Status (includes DISBURSED) +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- -fiat_currency: string; // Fiat type +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 +} ⋮---- -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- -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 TradFiTransactionRecord { + asset?: string; + type?: string; + type_desc?: string; + change?: string; + balance?: string; + time?: number; +} ⋮---- -export interface GetOTCFiatOrderListResp { - code: number; - message: string; - data: { - pn: number; - ps: number; - total_pn: number; - count: number; - list: OTCFiatOrderListItem[]; - }; +export interface TradFiTransactionListData { + total?: number; + total_page?: number; + list?: TradFiTransactionRecord[]; } ⋮---- -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; +export interface TradFiCreateOrderResult { + id?: 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 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 GetOTCStablecoinOrderListResp { - code: number; - message: string; - data: { - total: number; - page_size: number; - page_number: number; - total_page: number; - list: OTCStablecoinOrderListItem[]; - }; +export interface TradFiOrderListData { + list?: TradFiOrderItem[]; + timestamp?: number; } ⋮---- -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 +export interface TradFiModifyOrderResult { + order_id?: number; + symbol?: string; + state?: string; + volume?: string; + price?: string; + price_tp?: string; + price_sl?: string; } ⋮---- -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 +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; +} ⋮---- -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 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 GetOTCFiatOrderDetailResp { - message: string; - code: number; - data: OTCFiatOrderDetail; +export interface TradFiPositionListData { + list?: TradFiPositionItem[]; + timestamp?: number; } ⋮---- -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 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; + }; } ⋮---- -export interface CreateOTCUploadPreUploadData { - file_key?: string; - url?: string; - fields?: CreateOTCUploadPreUploadFields; - expires_in?: number; +/** 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 CreateOTCUploadPreUploadResp { - code?: number; - message?: string; - timestamp?: number; - data?: CreateOTCUploadPreUploadData; +export interface TradFiSymbolCommissionItem { + category_code?: string; + symbol?: string; + fee_per_lot?: string; } ================ -File: src/types/response/tradfi.ts +File: src/types/response/unified.ts ================ -/** TradFi API response types */ -⋮---- -export interface TradFiApiResp { - timestamp?: number; - data?: T; - code?: number; - message?: string; - label?: string; +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 } ⋮---- -export interface TradFiListData { - list?: T[]; - total?: number; - total_page?: number; -} +mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin ⋮---- -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; -} +locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin ⋮---- -mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility +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) ⋮---- -export interface TradFiCategoryItem { - category_id?: number; - is_favorite?: boolean; - category_name?: string; -} +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 ⋮---- -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; -} +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 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 UnifiedLoan { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; } ⋮---- -export interface TradFiKlineItem { - o?: string; - c?: string; - h?: string; - l?: string; - t?: 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 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 UnifiedInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; } ⋮---- -export interface TradFiCreateUserResult { - status?: number; - leverage?: number; - mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +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; + }[]; } ⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +export interface UnifiedCurrencyDiscountTiers { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + leverage: string; + }[]; +} ⋮---- -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 +export interface UserCurrencyLeverageConfig { + current_leverage: string; + min_leverage: string; + max_leverage: string; + debit: string; + available_margin: string; + borrowable: string; + except_leverage_borrowable: string; } ⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +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 TradFiTransactionRecord { - asset?: string; - type?: string; - type_desc?: string; - change?: string; - balance?: string; - time?: number; +export interface UnifiedHistoryLendingRate { + currency: string; + tier: string; + tier_up_rate: string; + rates: { + time: number; + rate: string; + }[]; } ⋮---- -export interface TradFiTransactionListData { - total?: number; - total_page?: number; - list?: TradFiTransactionRecord[]; +export interface MarginTier { + tier: string; + margin_rate: string; + lower_limit: string; + upper_limit: string; } ⋮---- -export interface TradFiCreateOrderResult { - id?: 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 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 UnifiedCollateralCurrenciesResp { + is_success: boolean; } ⋮---- -export interface TradFiOrderListData { - list?: TradFiOrderItem[]; - timestamp?: number; +export interface UnifiedQuickRepayDebtItem { + currency?: string; + debt_amount?: string; + estimated_usd?: string; + borrowed?: string; + neg_balance?: string; } ⋮---- -export interface TradFiModifyOrderResult { - order_id?: number; - symbol?: string; - state?: string; - volume?: string; - price?: string; - price_tp?: string; - price_sl?: string; +export interface UnifiedQuickRepayAvailableItem { + currency?: string; + available?: string; + estimated_usd?: 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 QuickEstimatedRepayment { + debt_currencies?: UnifiedQuickRepayDebtItem[]; + available_currencies?: UnifiedQuickRepayAvailableItem[]; } ⋮---- -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 QuickRepayRepaidInfo { + currency: string; + repaid: string; + left: string; } ⋮---- -export interface TradFiPositionListData { - list?: TradFiPositionItem[]; - timestamp?: number; +export interface QuickRepayUsedInfo { + currency: string; + used: string; } ⋮---- -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; - }; +export interface QuickRepaymentResp { + order_id: string; + repaid_infos: QuickRepayRepaidInfo[]; + used_infos: QuickRepayUsedInfo[]; } ⋮---- -/** 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; +/** GET/POST /unified/delta_neutral — v4.106.97 */ +export interface DeltaNeutralEnabled { + enabled: boolean; } ⋮---- -export interface TradFiSymbolCommissionItem { - category_code?: string; - symbol?: string; - fee_per_lot?: string; +/** POST /unified/leverage/user_setting failed currency entry */ +export interface LeverageFailedCurrency { + currency: string; + reason: string; } ================ @@ -12130,1329 +12170,1360 @@ File: src/index.ts // Shared Types ================ -File: src/types/request/futures.ts +File: src/lib/BaseRestClient.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; -} +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'; ⋮---- -export interface GetFuturesStatsReq { - settle: FuturesSettle; - contract: string; - from?: number; - interval?: string; - limit?: number; -} +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getRestBaseUrl, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; ⋮---- -export interface GetFundingRatesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - from?: number; - to?: number; -} +/** + * Used to switch how authentication/requests work under the hood + */ ⋮---- -export interface BatchFundingRatesReq { - settle: 'btc' | 'usdt' | 'usd1'; - contracts: string[]; -} +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -export interface GetLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; +interface SignedRequest { + originalParams: T; + paramsWithSign?: T & { sign: string }; + serializedParams: string; + sign: string; + queryParamsWithSign: string; + timestamp: number; + recvWindow: number; } ⋮---- -export interface GetRiskLimitTiersReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; } ⋮---- -export interface GetRiskLimitTableReq { - settle: FuturesSettle; - table_id: string; -} +type SignMethod = 'gateV4'; ⋮---- -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'; -} +/** + * 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; +}; ⋮---- -export interface GetFuturesADLRiskStatesReq { - settle: 'btc' | 'usdt' | 'usd1'; -} +/** multipart/form-data body; mutually exclusive with `body` */ ⋮---- -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 -} +/** + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses + */ ⋮---- -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 +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, ⋮---- -position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support -hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void ⋮---- -export interface UpdateDualModePositionMarginReq { - settle: FuturesSettle; - contract: string; - change: string; - dual_side: 'dual_long' | 'dual_short'; -} +export abstract class BaseRestClient ⋮---- -export interface UpdateDualModePositionLeverageReq { - settle: FuturesSettle; - contract: string; - leverage: string; - cross_leverage_limit?: string; -} +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; ⋮---- -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'; -} +/** + * 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 = {}, +) ⋮---- -export interface GetFuturesOrdersReq { - settle: FuturesSettle; - contract?: string; - status: string; - limit?: number; - offset?: number; - last_id?: string; -} +/** Throw errors if any request params are empty */ ⋮---- -export interface DeleteAllFuturesOrdersReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - side?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} +/** in ms == 5 minutes by default */ ⋮---- -export interface GetFuturesOrdersByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} +/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ ⋮---- -export interface UpdateFuturesOrderReq { - xGateExptime?: number; - settle: FuturesSettle; - order_id: string; - size?: number; - price?: string; - amend_text?: string; -} +// 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. ⋮---- -export interface GetFuturesTradingHistoryReq { - settle: FuturesSettle; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; -} +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- -export interface GetFuturesTradingHistoryByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - role?: 'maker' | 'taker'; -} +// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" +// parameter to define a custom httpsAgent with the desired properties ⋮---- -export interface GetFuturesPositionHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; -} +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -export interface GetFuturesLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - at?: number; -} +// Throw if one of the 3 values is missing, but at least one of them is set ⋮---- -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; -} +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number ⋮---- -/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ +protected get(endpoint: string, params?: object) ⋮---- -price: string; // Required: Order price. Set to 0 to use market price +// GET only supports params in the query string ⋮---- -price: string; // Required: Price value for price trigger -rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface GetFuturesAutoOrdersReq { - settle: FuturesSettle; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} +protected getPrivate(endpoint: string, params?: object) ⋮---- -/** - * 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 -} +// GET only supports params in the query string ⋮---- -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 +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -// 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; -} +/** POST private endpoint with multipart/form-data (empty body hash for signing) */ +protected postPrivateMultipart( + endpoint: string, + formData: FormData, + query?: object, +) ⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint request -export interface GetFuturesInsuranceReq { - settle: FuturesSettle; - limit?: number; -} +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, +) ⋮---- -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 -} +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -/** Same semantics as `size` (decimal contract size) */ +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -/** When fully closing in single-position mode, set true */ +/** + * @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 ⋮---- -price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price -auto_size?: string; // Not required in single position mode +// Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- -/** 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'; -} +// Build a request and handle signature process ⋮---- -/** 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; -} +// Dispatch request ⋮---- -export interface TerminateTrailOrderReq { - settle: 'btc' | 'usdt'; - id?: number; - text?: string; -} +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- -export interface BatchTerminateTrailOrdersReq { - settle: 'btc' | 'usdt'; - contract?: string; - related_position?: 1 | 2; -} +// Throw API rejections by parsing the response code from the body ⋮---- -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; -} +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- -export interface GetTrailOrderDetailReq { - settle: 'btc' | 'usdt'; - id: number; -} +// Something happened in setting up the request that triggered an error ⋮---- -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; -} +// request made but no response received ⋮---- -export interface GetTrailOrderChangeLogReq { - settle: 'btc' | 'usdt'; - id: number; - page_num?: number; - page_size?: number; -} +// The request was made and the server responded with a status code +// that falls out of the range of 2xx ⋮---- -/** 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; -} +// console.error('err: ', response?.data); ⋮---- -export interface StopChaseOrderReq { - settle: FuturesSettle; - id?: string; - text?: string; -} +// Prevent credentials from leaking into error messages ⋮---- -export interface StopAllChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - pos_margin_mode?: 'isolated' | 'cross' | string; -} +/** + * @private sign request and set recv window + */ +private async signRequest< + T extends ParamsInQueryBodyOrHeader | undefined = {}, + >( + data: T, + endpoint: string, + method: Method, + signMethod: SignMethod, +): Promise> ⋮---- -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; -} +const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- -/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ +// recvWindow: this.options.recvWindow, ⋮---- -export interface GetChaseOrderDetailReq { - settle: FuturesSettle; - id: string; -} +// 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/spot.ts +File: src/types/response/otc.ts ================ /**========================================================================================================================== - * SPOT + * OTC * ========================================================================================================================== */ ⋮---- -/** 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; +export interface OTCActionResp { + code: number; + message: string; + timestamp: number; } ⋮---- -/** `{}` 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 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; } ⋮---- -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[]; -} +type: string; // BUY (on-ramp) or SELL (off-ramp) ⋮---- -/** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ +rate_reci: string; // Reciprocal of the exchange rate ⋮---- -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; -} +order_type: string; // FIAT or STABLE +quote_token: string; // Quote token required when placing an order ⋮---- -export interface SpotOrderBook { - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; +export type CreateOTCFiatOrderResp = OTCActionResp; +⋮---- +export interface CreateOTCStablecoinOrderResp { + code: number; + message: string; + timestamp: number; } ⋮---- -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 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; } ⋮---- -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 -]; +id: string; // Bank ID (required for order placement) ⋮---- -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 +/** 1 = default bank card, 0 = not default */ ⋮---- -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; +export interface GetOTCBankListResp { + code: number; + message: string; + data: { + lists: OTCBankListItem[]; + }; + timestamp: 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 CreateOTCBankResp { + code: number; + message: string; + data: { + bank_id: number; + status: number; + }; + timestamp?: number; } ⋮---- -export interface SpotAccountBook { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - code: string; - text: string; +export interface OTCBankSupplementChecklistItem { + description: string; + code?: string; + zh?: string; + en?: string; + required?: boolean; } ⋮---- -export interface SubmitSpotBatchOrdersResp { - order_id: string; - amend_text: string; - text: string; - succeeded: boolean; - label: string; +export interface GetOTCBankSupplementChecklistResp { + code: number; 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'; + data: { + user_type: 'personal' | 'enterprise'; + items: OTCBankSupplementChecklistItem[]; + }; + timestamp?: number; } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +export type MarkOTCOrderAsPaidResp = OTCActionResp; ⋮---- -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; +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 } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +time: string; // Current time +timestamp: number; // Current timestamp ⋮---- -export interface SpotInsuranceHistory { - currency: string; - balance: string; - time: number; -} +trade_no: string; // Trade number +type: string; // Quote direction buy/sell/all +status: string; // Order Status (includes DISBURSED) ⋮---- -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; +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; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; }; - 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[]; +/** v4.106.158: was `list` */ +⋮---- +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; } ⋮---- -export interface DeleteSpotBatchOrdersResp { - currency_pair: string; - id: string; - succeeded: boolean; - label: 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; - account: string; - text: string; + data: { + total: number; + page_size: number; + page_number: number; + total_page: number; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; + }; } ⋮---- -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; +/** v4.106.158: was `list` */ +⋮---- +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 } ⋮---- -deal?: string; // v4.105.29: Total Executed Value +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 ⋮---- -export type SpotPovOrderStatus = - | 'CREATED' - | 'CANCELING' - | 'RUNNING' - | 'COMPLETED' - | 'EXPIRED' - | 'TERMINATED'; +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 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 +export interface GetOTCFiatOrderDetailResp { + message: string; + code: number; + data: OTCFiatOrderDetail; } ⋮---- -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 +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; +} ⋮---- -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) +export interface CreateOTCUploadPreUploadData { + file_key?: string; + url?: string; + fields?: CreateOTCUploadPreUploadFields; + expires_in?: number; +} ⋮---- -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 +export interface CreateOTCUploadPreUploadResp { + code?: number; + message?: string; + timestamp?: number; + data?: CreateOTCUploadPreUploadData; +} + +================ +File: src/types/response/spot.ts +================ +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ ⋮---- -is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all +/** 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; +} ⋮---- -use_funding?: boolean; // Whether Earn funds are used as margin +/** `{}` cancels TP/SL; `null` leaves unchanged */ +type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; ⋮---- -export interface UnifiedLoan { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; +export interface SpotCurrencyChain { + name: string; + addr?: string; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; } ⋮---- -export interface UnifiedLoanRecord { - id: number; - type: 'borrow' | 'repay'; - repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; - currency_pair: string; +export interface SpotCurrency { currency: string; - amount: string; - create_time: number; - borrow_type: 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[]; } -export interface UnifiedInterestRecord { - currency: string; +⋮---- +/** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ +⋮---- +export interface SpotTicker { currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: 'platform' | 'margin'; - create_time: number; + 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 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 SpotOrderBook { + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; } ⋮---- -export interface UnifiedCurrencyDiscountTiers { - currency: string; - discount_tiers: { - tier: string; - discount: string; - lower_limit: string; - upper_limit: string; - leverage: 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 interface UserCurrencyLeverageConfig { - current_leverage: string; - min_leverage: string; - max_leverage: string; - debit: string; - available_margin: string; - borrowable: string; - except_leverage_borrowable: 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 +]; ⋮---- -export interface UnifiedLoanCurrency { - name: string; - prec: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - loan_status: string; +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; } ⋮---- -export interface UnifiedHistoryLendingRate { +taker_fee: string; // For spot trading +maker_fee: string; // For spot trading +⋮---- +export interface SpotAccount { currency: string; - tier: string; - tier_up_rate: string; - rates: { - time: number; - rate: string; - }[]; + available: string; + locked: string; + update_id: number; + refresh_time: number; + last_update_time?: number; + trading_fee_rate?: string; } ⋮---- -export interface MarginTier { - tier: string; - margin_rate: string; - lower_limit: string; - upper_limit: string; +export interface SpotAccountBook { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + code: string; + text: 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 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'; } ⋮---- -export interface UnifiedCollateralCurrenciesResp { - is_success: boolean; -} +/** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ ⋮---- -export interface UnifiedQuickRepayDebtItem { - currency?: string; - debt_amount?: string; - estimated_usd?: string; - borrowed?: string; - neg_balance?: string; +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; } ⋮---- -export interface UnifiedQuickRepayAvailableItem { - currency?: string; - available?: string; - estimated_usd?: 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 QuickEstimatedRepayment { - debt_currencies?: UnifiedQuickRepayDebtItem[]; - available_currencies?: UnifiedQuickRepayAvailableItem[]; +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 QuickRepayRepaidInfo { - currency: string; - repaid: string; - left: string; +export interface GetSpotOpenOrdersResp { + currency_pair: string; + total: number; + orders: SpotOrder[]; } ⋮---- -export interface QuickRepayUsedInfo { - currency: string; - used: string; +export interface DeleteSpotBatchOrdersResp { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; + text: string; } ⋮---- -export interface QuickRepaymentResp { +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; - repaid_infos: QuickRepayRepaidInfo[]; - used_infos: QuickRepayUsedInfo[]; + 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; } ⋮---- -/** GET/POST /unified/delta_neutral — v4.106.97 */ -export interface DeltaNeutralEnabled { - enabled: boolean; -} +deal?: string; // v4.105.29: Total Executed Value ⋮---- -/** POST /unified/leverage/user_setting failed currency entry */ -export interface LeverageFailedCurrency { - currency: string; - reason: string; +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/lib/BaseRestClient.ts +File: src/types/request/futures.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'; +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ ⋮---- -import { neverGuard } from './misc-util.js'; -import { - CHANNEL_ID, - getRestBaseUrl, - RestClientOptions, - serializeParams, -} from './requestUtils.js'; -import { - checkWebCryptoAPISupported, - hashMessage, - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './webCryptoAPI.js'; +export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; ⋮---- -/** - * Used to switch how authentication/requests work under the hood - */ +export interface GetFuturesOrderBookReq { + settle: FuturesSettle; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; +} ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +export interface GetFuturesTradesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; +} ⋮---- -interface SignedRequest { - originalParams: T; - paramsWithSign?: T & { sign: string }; - serializedParams: string; - sign: string; - queryParamsWithSign: string; - timestamp: number; - recvWindow: 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; } ⋮---- -interface UnsignedRequest { - originalParams: T; - paramsWithSign: T; +export interface GetFundingRatesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + from?: number; + to?: number; } ⋮---- -type SignMethod = 'gateV4'; +export interface BatchFundingRatesReq { + settle: 'btc' | 'usdt' | 'usd1'; + contracts: string[]; +} ⋮---- -/** - * 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; -}; +export interface GetLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; +} ⋮---- -/** multipart/form-data body; mutually exclusive with `body` */ +export interface GetRiskLimitTiersReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; +} ⋮---- -/** - * Enables: - * - Detailed request/response logging - * - Full request dump in any exceptions thrown from API responses - */ +export interface GetRiskLimitTableReq { + settle: FuturesSettle; + table_id: string; +} ⋮---- -// request: { -// url: response.config.url, -// method: response.config.method, -// data: response.config.data, -// headers: response.config.headers, -// }, +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout ⋮---- -/** - * Impure, mutates params to remove any values that have a key but are undefined. - */ -function deleteUndefinedValues(params?: any): void +| 'dividend'; // v4.106.147: dividend payout ⋮---- -export abstract class BaseRestClient +export interface GetFuturesAccountBookReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: FuturesAccountBookType; +} ⋮---- -/** Defines the client type (affecting how requests & signatures behave) */ -abstract getClientType(): RestClientType; +export interface GetFuturesADLRiskStatesReq { + settle: 'btc' | 'usdt' | 'usd1'; +} ⋮---- -/** - * 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 = {}, -) +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 +} ⋮---- -/** Throw errors if any request params are empty */ +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 ⋮---- -/** in ms == 5 minutes by default */ +position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support +hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter ⋮---- -/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ +export interface UpdateDualModePositionMarginReq { + settle: FuturesSettle; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; +} ⋮---- -// 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. +export interface UpdateDualModePositionLeverageReq { + settle: FuturesSettle; + contract: string; + leverage: string; + cross_leverage_limit?: string; +} ⋮---- -// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely +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; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; + pos_margin_mode?: 'isolated' | 'cross'; +} ⋮---- -// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" -// parameter to define a custom httpsAgent with the desired properties +/** BBO price type for the take-profit leg */ ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +/** BBO price type for the stop-loss leg */ ⋮---- -// Throw if one of the 3 values is missing, but at least one of them is set +export interface GetFuturesOrdersReq { + settle: FuturesSettle; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; +} ⋮---- -/** - * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism - */ -getSignTimestampMs(): number +export interface DeleteAllFuturesOrdersReq { + xGateExptime?: number; + settle: FuturesSettle; + contract: string; + side?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} ⋮---- -protected get(endpoint: string, params?: object) +export interface GetFuturesOrdersByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -// GET only supports params in the query string +export interface UpdateFuturesOrderReq { + xGateExptime?: number; + settle: FuturesSettle; + order_id: string; + size?: number; + price?: string; + amend_text?: string; +} ⋮---- -protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetFuturesTradingHistoryReq { + settle: FuturesSettle; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; +} ⋮---- -protected getPrivate(endpoint: string, params?: object) +export interface GetFuturesTradingHistoryByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + role?: 'maker' | 'taker'; +} ⋮---- -// GET only supports params in the query string +export interface GetFuturesPositionHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; +} ⋮---- -protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetFuturesLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + at?: number; +} ⋮---- -/** POST private endpoint with multipart/form-data (empty body hash for signing) */ -protected postPrivateMultipart( - endpoint: string, - formData: FormData, - query?: object, -) +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; +} ⋮---- -protected deletePrivate( - endpoint: string, - params?: ParamsInQueryBodyOrHeader, -) +/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ ⋮---- -protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +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: <=) ⋮---- -// protected patchPrivate(endpoint: string, params?: any) { -protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetFuturesAutoOrdersReq { + settle: FuturesSettle; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} ⋮---- /** - * @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 + * 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 +} ⋮---- -// Sanity check to make sure it's only ever prefixed by one forward slash +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 ⋮---- -// Build a request and handle signature process +// 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; +} ⋮---- -// Dispatch request +// v4.104.6: New GET /futures/{settle}/insurance endpoint request +export interface GetFuturesInsuranceReq { + settle: FuturesSettle; + limit?: number; +} ⋮---- -// See: https://www.gate.io/docs/developers/apiv4/en/#return-format +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 +} ⋮---- -// Throw API rejections by parsing the response code from the body +/** Same semantics as `size` (decimal contract size) */ ⋮---- -/** - * @private generic handler to parse request exceptions - */ -parseException(e: any, request: AxiosRequestConfig): unknown +/** When fully closing in single-position mode, set true */ ⋮---- -// Something happened in setting up the request that triggered an error +price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price +auto_size?: string; // Not required in single position mode ⋮---- -// request made but no response received +/** 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'; +} ⋮---- -// The request was made and the server responded with a status code -// that falls out of the range of 2xx +/** 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; +} ⋮---- -// console.error('err: ', response?.data); +export interface TerminateTrailOrderReq { + settle: 'btc' | 'usdt'; + id?: number; + text?: string; +} ⋮---- -// Prevent credentials from leaking into error messages +export interface BatchTerminateTrailOrdersReq { + settle: 'btc' | 'usdt'; + contract?: string; + related_position?: 1 | 2; +} ⋮---- -/** - * @private sign request and set recv window - */ -private async signRequest< - T extends ParamsInQueryBodyOrHeader | undefined = {}, - >( - data: T, - endpoint: string, - method: Method, - signMethod: SignMethod, -): Promise> +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; +} ⋮---- -const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds +export interface GetTrailOrderDetailReq { + settle: 'btc' | 'usdt'; + id: number; +} ⋮---- -// recvWindow: this.options.recvWindow, +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; +} ⋮---- -// It's possible to override the recv window on a per rquest level +export interface GetTrailOrderChangeLogReq { + settle: 'btc' | 'usdt'; + id: number; + page_num?: number; + page_size?: number; +} ⋮---- -// console.log('sign params: ', { -// requestBodyToHash, -// paramsStr: toSign, -// url: this.baseUrl, -// urlPath: this.baseUrlPath, -// }); +/** 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; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +export interface StopChaseOrderReq { + settle: FuturesSettle; + id?: string; + text?: string; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: true, - ): Promise>; +export interface StopAllChaseOrdersReq { + settle: FuturesSettle; + contract?: string; + pos_margin_mode?: 'isolated' | 'cross' | string; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: false | undefined, - ): Promise>; +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; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: boolean, -) +/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ ⋮---- -/** 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 +export interface GetChaseOrderDetailReq { + settle: FuturesSettle; + id: string; +} ================ File: src/types/response/futures.ts @@ -13462,6 +13533,8 @@ File: src/types/response/futures.ts * ========================================================================================================================== */ ⋮---- +import type { FuturesAccountBookType } from '../request/futures.js'; +⋮---- export interface FuturesOrderBook { id?: number; current: number; @@ -13646,13 +13719,16 @@ export interface FuturesAccountBookRecord { time: number; change: string; balance: string; - type: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookType; text: string; contract?: string; trade_id: string; id: string; } ⋮---- +/** v4.106.147: includes `dividend` (dividend payout) */ +⋮---- export interface FuturesOrder { id?: number; user?: number; @@ -14530,6 +14606,8 @@ client }); ``` +TestNet REST for spot and futures is `baseUrlKey: 'testnet'` (`https://api-testnet.gateapi.io/api/v4`). `baseUrlKey: 'futuresTestnet'` is that same host, kept so older configs keep working. WebSocket TestNet is `useTestnet: true` on `WebsocketClient`. + See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets @@ -14968,6 +15046,7 @@ import { CreateChaseOrderReq, CreateTrailOrderReq, DeleteAllFuturesOrdersReq, + FuturesSettle, GetChaseOrderDetailReq, GetChaseOrdersReq, GetFundingRatesReq, @@ -17098,7 +17177,7 @@ submitFlashSwapOrderPreview( * @returns Promise */ getFuturesContracts(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; offset?: number; }): Promise @@ -17110,7 +17189,7 @@ getFuturesContracts(params: { * @returns Promise */ getFuturesContract(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17169,7 +17248,7 @@ getPremiumIndexKLines( * @returns Promise */ getFuturesTickers(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17211,7 +17290,7 @@ getBatchFundingRates( * }[]> */ getFuturesInsuranceBalanceHistory(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; }): Promise< { @@ -17237,7 +17316,7 @@ getFuturesStats(params: GetFuturesStatsReq): Promise * @returns Promise */ getIndexConstituents(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; index: string; }): Promise ⋮---- @@ -17274,7 +17353,7 @@ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise * @returns Promise */ getFuturesAccount(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; }): Promise ⋮---- /** @@ -17308,7 +17387,7 @@ getFuturesPositions( * @returns Promise */ getFuturesPosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17321,7 +17400,7 @@ getFuturesPosition(params: { * @returns Promise */ updateFuturesMargin(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; change: string; }): Promise @@ -17344,7 +17423,7 @@ updateFuturesMargin(params: { * @returns Promise */ updateFuturesLeverage(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; leverage: string; cross_leverage_limit?: string; @@ -17382,7 +17461,7 @@ updateFuturesPositionMode(params: { * @returns Promise */ updatePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17396,7 +17475,7 @@ updatePositionRiskLimit(params: { * @returns Promise */ updateFuturesDualMode(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; dual_mode: boolean; }): Promise ⋮---- @@ -17407,7 +17486,7 @@ updateFuturesDualMode(params: { * @returns Promise */ getDualModePosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17446,7 +17525,7 @@ updateDualModePositionLeverage( * @returns Promise */ updateDualModePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17521,7 +17600,7 @@ getFuturesOrdersByTimeRange( */ submitFuturesBatchOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: SubmitFuturesOrderReq[]; }): Promise ⋮---- @@ -17535,7 +17614,7 @@ submitFuturesBatchOrders(params: { * @returns Promise */ getFuturesOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; }): Promise ⋮---- @@ -17549,7 +17628,7 @@ getFuturesOrder(params: { */ cancelFuturesOrder(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise @@ -17629,7 +17708,7 @@ getFuturesAutoDeleveragingHistory( * @returns Promise<{ triggerTime: number }> */ setFuturesOrderCancelCountdown(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; timeout: number; contract?: string; }): Promise< @@ -17641,7 +17720,7 @@ setFuturesOrderCancelCountdown(params: { * @returns Promise */ getFuturesUserTradingFees(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17657,7 +17736,7 @@ getFuturesUserTradingFees(params: { */ batchCancelFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orderIds: string[]; }): Promise ⋮---- @@ -17674,7 +17753,7 @@ batchCancelFuturesOrders(params: { */ batchUpdateFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: BatchAmendOrderReq[]; }): Promise ⋮---- @@ -17715,7 +17794,7 @@ getFuturesAutoOrders( * @returns Promise */ cancelAllOpenFuturesOrders(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17726,7 +17805,7 @@ cancelAllOpenFuturesOrders(params: { * @returns Promise */ getFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- @@ -17737,13 +17816,16 @@ getFuturesPriceTriggeredOrder(params: { * @returns Promise */ cancelFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- /** * Update a single price-triggered order * + * v4.106.160: `PUT /futures/{settle}/price_orders/amend/{order_id}`. + * `order_id` is required in the path and is still sent in the JSON body. + * * @param params Parameters for updating a price-triggered order * @returns Promise */ @@ -20138,7 +20220,7 @@ File: package.json ================ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", From 916c60af6f2d94b043b30b3eef246173c1b02fc7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 12:06:34 +0000 Subject: [PATCH 3/7] fix: give futures account book responses their own type Stop importing FuturesAccountBookType from request types. Response records use FuturesAccountBookRecordType. Co-authored-by: Jerko J --- src/types/response/futures.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/types/response/futures.ts b/src/types/response/futures.ts index 3ae3c8c..46d330c 100644 --- a/src/types/response/futures.ts +++ b/src/types/response/futures.ts @@ -3,8 +3,6 @@ * ========================================================================================================================== */ -import type { FuturesAccountBookType } from '../request/futures.js'; - export interface FuturesOrderBook { id?: number; current: number; @@ -167,12 +165,25 @@ export interface FuturesAccount { funding_balance?: string; } +/** v4.106.147: includes `dividend` (dividend payout) */ +export type FuturesAccountBookRecordType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; + export interface FuturesAccountBookRecord { time: number; change: string; balance: string; /** v4.106.147: includes `dividend` (dividend payout) */ - type: FuturesAccountBookType; + type: FuturesAccountBookRecordType; text: string; contract?: string; trade_id: string; From eb7bfef16fa1fa865a9a962a73c3d873388bb69d Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:29:03 +0200 Subject: [PATCH 4/7] Delete test/REST/baseUrl.test.ts --- test/REST/baseUrl.test.ts | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 test/REST/baseUrl.test.ts diff --git a/test/REST/baseUrl.test.ts b/test/REST/baseUrl.test.ts deleted file mode 100644 index 007a5d1..0000000 --- a/test/REST/baseUrl.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { getRestBaseUrl } from '../../src/lib/requestUtils.js'; - -const GATE_TESTNET_REST_URL = 'https://api-testnet.gateapi.io/api/v4'; - -describe('REST base URL', () => { - it('uses the global testnet host for testnet and futuresTestnet', () => { - expect(getRestBaseUrl({ baseUrlKey: 'testnet' })).toBe( - GATE_TESTNET_REST_URL, - ); - expect(getRestBaseUrl({ baseUrlKey: 'futuresTestnet' })).toBe( - GATE_TESTNET_REST_URL, - ); - }); - - it('keeps live as the default and prefers an explicit baseUrl', () => { - expect(getRestBaseUrl({})).toBe('https://api.gateio.ws/api/v4'); - expect( - getRestBaseUrl({ - baseUrl: 'https://example.test/api/v4', - baseUrlKey: 'testnet', - }), - ).toBe('https://example.test/api/v4'); - }); -}); From e4061fbf1f2ebcfd7928c6adedfcf61acc01b1f9 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:29:13 +0200 Subject: [PATCH 5/7] Delete test/REST/priceOrderAmend.test.ts --- test/REST/priceOrderAmend.test.ts | 32 ------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 test/REST/priceOrderAmend.test.ts diff --git a/test/REST/priceOrderAmend.test.ts b/test/REST/priceOrderAmend.test.ts deleted file mode 100644 index 8e68480..0000000 --- a/test/REST/priceOrderAmend.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { RestClient } from '../../src/index.js'; - -class CapturingRestClient extends RestClient { - public lastCall?: { endpoint: string; params?: unknown }; - - protected putPrivate(endpoint: string, params?: unknown): Promise { - this.lastCall = { endpoint, params }; - return Promise.resolve({ id: 1, id_string: '1' }); - } -} - -describe('updateFuturesPriceTriggeredOrder', () => { - it('puts order_id in the path and the body', async () => { - const rest = new CapturingRestClient(); - - await rest.updateFuturesPriceTriggeredOrder({ - settle: 'usdt', - order_id: 42, - price: '1', - }); - - expect(rest.lastCall).toEqual({ - endpoint: '/futures/usdt/price_orders/amend/42', - params: { - body: { - order_id: 42, - price: '1', - }, - }, - }); - }); -}); From afa1bb52a7c16334a6afe2736b99d58561d9c137 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 20 Oct 2026 12:22:45 +0000 Subject: [PATCH 6/7] docs: describe TestNet with useTestnet WebSocket TestNet is useTestnet: true. Drop the baseUrlKey TestNet write-up from the README, quickstart, and option comments. Co-authored-by: Jerko J --- README.md | 2 +- docs/GATE_SDK_QUICKSTART_GUIDE.md | 7 ++----- examples/Rest/futures/testnet.ts | 21 +-------------------- src/lib/requestUtils.ts | 8 ++------ src/types/shared.ts | 5 ----- src/types/websockets/client.ts | 1 + 6 files changed, 7 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 231477e..5ff029d 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,7 @@ client }); ``` -TestNet REST for spot and futures is `baseUrlKey: 'testnet'` (`https://api-testnet.gateapi.io/api/v4`). `baseUrlKey: 'futuresTestnet'` is that same host, kept so older configs keep working. WebSocket TestNet is `useTestnet: true` on `WebsocketClient`. +WebSocket TestNet: set `useTestnet: true` on `WebsocketClient`. See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. diff --git a/docs/GATE_SDK_QUICKSTART_GUIDE.md b/docs/GATE_SDK_QUICKSTART_GUIDE.md index e3fa34b..1de6cb3 100644 --- a/docs/GATE_SDK_QUICKSTART_GUIDE.md +++ b/docs/GATE_SDK_QUICKSTART_GUIDE.md @@ -1740,10 +1740,7 @@ Gate TestNet is a separate environment with separate credentials. Use it for all | USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | | Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | -Set the REST API host with `baseUrl` or `baseUrlKey`, and the WebSocket host with `wsUrl` or `useTestnet: true`. Prefer explicit hosts for TestNet examples: - -- `baseUrlKey: 'testnet'` uses `https://api-testnet.gateapi.io/api/v4` for spot and futures. `baseUrlKey: 'futuresTestnet'` is the same host, kept so older configs keep working. -- `useTestnet: true` selects the TestNet WebSocket host for that connection, including Spot and Options. BTC perpetual and delivery TestNet hosts stay on the URLs in the current Gate docs (`wss://fx-ws-testnet.gateio.ws/...`). Announcements still have no TestNet host. +For WebSocket TestNet, set `useTestnet: true`. ```javascript import { RestClient, WebsocketClient } from 'gateio-api'; @@ -1757,7 +1754,7 @@ const rest = new RestClient({ 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', + useTestnet: true, }); ``` diff --git a/examples/Rest/futures/testnet.ts b/examples/Rest/futures/testnet.ts index a2709af..2e30082 100644 --- a/examples/Rest/futures/testnet.ts +++ b/examples/Rest/futures/testnet.ts @@ -11,26 +11,7 @@ const account = { const gateRestClient = new RestClient({ apiKey: account.key, apiSecret: account.secret, - /** - * 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 (alias of `testnet`, spot and futures): - * 'https://api-testnet.gateapi.io/api/v4' - * Older host https://fx-api-testnet.gateio.ws/api/v4 now returns 502. - * baseUrlKey: 'testnet' is the same host. - */ - baseUrlKey: 'futuresTestnet', - - /** - * Futures live trading alternative (futures only): - * 'https://fx-api.gateio.ws/api/v4' - */ - // baseUrlKey: 'futuresLiveAlternative' + baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); async function submitFuturesOrder() { diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index ac2eae6..f2a0cbb 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -24,11 +24,7 @@ export interface RestClientOptions { **/ baseUrl?: string; - /** - * Built-in Gate API v4 host. - * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 - * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. - */ + // 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). */ @@ -90,7 +86,7 @@ const GATE_BASE_URLS: Record = { live: 'https://api.gateio.ws/api/v4', futuresLiveAlternative: 'https://fx-api.gateio.ws/api/v4', testnet: GATE_TESTNET_REST_URL, - // Alias of `testnet`. Previously https://fx-api-testnet.gateio.ws/api/v4 (HTTP 502). + // Same host as testnet. The old fx-api-testnet.gateio.ws host returns 502. futuresTestnet: GATE_TESTNET_REST_URL, }; diff --git a/src/types/shared.ts b/src/types/shared.ts index c4c095e..0ce4210 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -1,8 +1,3 @@ -/** - * Built-in Gate API v4 hosts. - * `testnet` is the global TestNet host (spot and futures). - * `futuresTestnet` is the same host, kept so older `baseUrlKey` values keep working. - */ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' diff --git a/src/types/websockets/client.ts b/src/types/websockets/client.ts index 7485936..0175304 100644 --- a/src/types/websockets/client.ts +++ b/src/types/websockets/client.ts @@ -21,6 +21,7 @@ export interface WSClientConfigurableOptions { /** Your API secret */ apiSecret?: string; + /** Use the Gate TestNet WebSocket hosts. */ useTestnet?: boolean; /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ From 020031f599da89e35c700dd1a225479ba79249a2 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Tue, 20 Oct 2026 14:26:55 +0200 Subject: [PATCH 7/7] chore: regenerate endpoint docs and examples --- llms.txt | 17820 ++++++++++++++++++++++++++--------------------------- 1 file changed, 8899 insertions(+), 8921 deletions(-) diff --git a/llms.txt b/llms.txt index 5169453..12027b0 100644 --- a/llms.txt +++ b/llms.txt @@ -950,6 +950,193 @@ export interface LoanCollateralRatio { left_borrowable_amount: string; } +================ +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/earnuni.ts ================ @@ -1038,1188 +1225,1578 @@ export interface SubmitFlashSwapOrderPreviewResp { } ================ -File: src/types/response/subaccount.ts +File: src/types/response/margin.ts ================ -export interface SubAccount { - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; +/**========================================================================================================================== + * 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 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 MarginBalanceHistoryRecord { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; } ⋮---- -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 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 SubAccountMode { +export interface CrossMarginAccount { 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; + 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 WsRequestPing { +export interface CrossMarginAccountHistoryRecord { + id: string; time: number; - channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; + currency: string; + change: string; + balance: string; + type: string; } ⋮---- -export interface WsRequestOperationGate< - TWSTopic extends string, - TWSPayload = any, -> { - time: number; - id?: number; - channel: TWSTopic; - auth?: WsRequestAuthGate; - event?: WsOperation; - payload?: TWSPayload; +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 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; +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/websockets/wsAPI.ts +File: src/types/response/options.ts ================ -import { WsKey } from '../../lib/websocket/websocket-util.js'; +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ ⋮---- -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 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 +} ⋮---- -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'; +tag: string; // Expiry period: day, week, month ⋮---- -export interface WsAPIWsKeyTopicMap { - spotV4: SpotWSAPITopic; - perpFuturesUSDTV4: FuturesWSAPITopic; - perpFuturesBTCV4: FuturesWSAPITopic; - deliveryFuturesUSDTV4: FuturesWSAPITopic; - deliveryFuturesBTCV4: FuturesWSAPITopic; - // optionsV4: never; - // announcementsV4: never; -} +trade_id?: number; // Deprecated ⋮---- -// optionsV4: never; -// announcementsV4: never; +underlying_price: string; // Forward futures price for the delivery date +multiplier: string; // Option contract multiplier ⋮---- -export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; -export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; +mark_price_round: string; // Minimum unit of mark price ⋮---- -// ==================================== -// Spot WebSocket API Request Types -// ==================================== +order_price_deviate?: string; // Deprecated ⋮---- -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'; +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 WSAPISpotOrderCancelReq { - order_id: string; - currency_pair: string; - account?: 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 WSAPISpotOrderCancelIdsReq { - currency_pair: string; - id: string; - account?: string; +export interface OptionsOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; } ⋮---- -export interface WSAPISpotOrderCancelCPReq { - currency_pair: string; - side?: 'buy' | 'sell'; - account?: string; +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; } ⋮---- -export interface WSAPISpotOrderAmendReq { - amount?: string; - price?: string; - amend_text?: string; - order_id: string; - currency_pair: string; - account?: string; -} +leverage: string; // Leverage calculation formula updated with reference note ⋮---- -export interface WSAPISpotOrderStatusReq { - order_id: string; - currency_pair: string; - account?: string; +export interface OptionsCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; } ⋮---- -export interface WSAPISpotOrderListReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: string; - from?: number; - to?: number; - side?: 'buy' | 'sell'; +export interface OptionsUnderlyingCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; } ⋮---- -// ==================================== -// Futures WebSocket API Request Types -// ==================================== -⋮---- -export interface WSAPIFuturesOrderPlaceReq { +export interface OptionsTrade { + id: number; + create_time: number; + create_time_ms: number; 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; + price: string; + is_internal?: boolean; // Deprecated } ⋮---- -export interface WSAPIFuturesOrderCancelCPReq { - contract: string; - side?: 'bid' | 'ask'; -} +is_internal?: boolean; // Deprecated ⋮---- -export interface WSAPIFuturesOrderAmendReq { - order_id: string; - price?: string; - size?: number; - amend_text?: string; +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 } ⋮---- -export interface WSAPIFuturesOrderListReq { - contract: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: number; -} +total?: string; // Only applicable to classic options accounts (unified account limitation) +equity?: string; // Only applicable to classic options accounts (unified account limitation) ⋮---- -export interface WSAPIFuturesOrderStatusReq { - order_id: string; -} +unrealised_pnl: string; // Enhanced with calculation formula ⋮---- -// ==================================== -// Spot WebSocket API Response Types -// ==================================== +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 WSAPISpotOrder { - id: string; +export interface OptionsAccountChangeRecord { + time: number; + change: string; + balance: string; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; 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; +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; } ⋮---- -// ==================================== -// Futures WebSocket API Response Types -// ==================================== +underlying_price: string; // Forward futures price for the delivery date ⋮---- -export interface WSAPIFuturesOrder { +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; - update_time?: number; - finish_as?: string; - status: string; + 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; - tif: string; - left?: number; + 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; - stp_id?: number; - stp_act?: string; - amend_text?: string; + refu: number; + refr: string; } ⋮---- -export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { - succeeded: boolean; +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'; } ⋮---- -export interface WSAPIFuturesOrderCancelIdsRespItem { - id: string; - user_id: number; - succeeded?: boolean; - message?: string; -} +underlying_price: string; // Forward futures price for the delivery date ⋮---- -// ==================================== -// Request Parameter Mapping -// ==================================== +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 +} ⋮---- -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; +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 - '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; +================ +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 type WsAPITopicRequestParams = - WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; -⋮---- -// ==================================== -// Response Headers and Base Response -// ==================================== +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 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; +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; } ⋮---- -/** String timestamp as ms */ +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'; ⋮---- -/** Status of WS API call. "200" if successful, else exception is thrown */ +export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; ⋮---- -export interface WSAPILoginResponse { - api_key: string; - uid: string; +export interface WsRequestAuthGate { + method: 'api_key'; + KEY: string; + SIGN: 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 interface WsRequestPing { + time: number; + channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; } ⋮---- -export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; +export interface WsRequestOperationGate< + TWSTopic extends string, + TWSPayload = any, +> { + time: number; + id?: number; + channel: TWSTopic; + auth?: WsRequestAuthGate; + event?: WsOperation; + payload?: TWSPayload; +} ⋮---- -export interface WSAPIResponse< - TResponseData extends object = WSAPIResponseData | object, - TChannel extends WSAPITopic = WSAPITopic, +export interface WSAPIRequest< + TRequestParams = any, + TWSChannel extends WSAPITopic = any, > { - wsKey: WsKey; - header: WSAPIResponseHeader; - data: { - result: TResponseData; + 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; }; - /** Auto-generated */ - request_id: string; } + +================ +File: src/types/websockets/wsAPI.ts +================ +import { WsKey } from '../../lib/websocket/websocket-util.js'; ⋮---- -/** Auto-generated */ +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'; ⋮---- -// ==================================== -// Response Type Mapping -// ==================================== +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 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 WsAPIWsKeyTopicMap { + spotV4: SpotWSAPITopic; + perpFuturesUSDTV4: FuturesWSAPITopic; + perpFuturesBTCV4: FuturesWSAPITopic; + deliveryFuturesUSDTV4: FuturesWSAPITopic; + deliveryFuturesBTCV4: FuturesWSAPITopic; + // optionsV4: never; + // announcementsV4: never; } ⋮---- -// 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'; +// optionsV4: never; +// announcementsV4: never; ⋮---- -/** - * 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; +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'; } ⋮---- -/** - * 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(....)`. - */ +export interface WSAPISpotOrderCancelReq { + order_id: string; + currency_pair: string; + account?: string; +} ⋮---- -/** - * 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 +export interface WSAPISpotOrderCancelIdsReq { + currency_pair: string; + id: string; + account?: string; +} ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +export interface WSAPISpotOrderCancelCPReq { + currency_pair: string; + side?: 'buy' | 'sell'; + account?: string; +} ⋮---- -public getWSClient(): WebsocketClient +export interface WSAPISpotOrderAmendReq { + amount?: string; + price?: string; + amend_text?: string; + order_id: string; + currency_pair: string; + account?: string; +} ⋮---- -public setTimeOffsetMs(newOffset: number): void +export interface WSAPISpotOrderStatusReq { + order_id: string; + currency_pair: string; + account?: string; +} ⋮---- -/* - * - * SPOT - Trading requests - * - */ +export interface WSAPISpotOrderListReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: string; + from?: number; + to?: number; + side?: 'buy' | 'sell'; +} ⋮---- -/** - * Submit a spot order - */ -submitNewSpotOrder( - params: WSAPISpotOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +// ==================================== +// Futures WebSocket API Request Types +// ==================================== ⋮---- -/** - * Cancel a spot order - */ -cancelSpotOrder( - params: WSAPISpotOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +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'; +} ⋮---- -/** - * Cancel all spot orders with the given id list - */ -cancelSpotOrderById( - params: WSAPISpotOrderCancelIdsReq[], - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderCancelReq { + order_id: string; +} ⋮---- -/** - * Cancel a spot order for a given symbol - */ -cancelSpotOrderForSymbol( - params: WSAPISpotOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderCancelCPReq { + contract: string; + side?: 'bid' | 'ask'; +} ⋮---- -/** - * Update a spot order - */ -updateSpotOrder( - params: WSAPISpotOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderAmendReq { + order_id: string; + price?: string; + size?: number; + amend_text?: string; +} ⋮---- -/** - * Get the status of a spot order - */ -getSpotOrderStatus( - params: WSAPISpotOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderListReq { + contract: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: number; +} ⋮---- -/** - * Get all spot orders - */ -getSpotOrders( - params: WSAPISpotOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderStatusReq { + order_id: string; +} ⋮---- -/* - * - * Futures - Trading requests - * - */ +// ==================================== +// Spot WebSocket API Response Types +// ==================================== ⋮---- -/** - * Submit a futures order. - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -submitNewFuturesOrder( - params: WSAPIFuturesOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +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; +} ⋮---- -/** - * Submit a batch of futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -submitNewFuturesBatchOrder( - params: WSAPIFuturesOrderPlaceReq[], - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPISpotOrderCancelIdsRespItem { + currency_pair: string; + id: string; + succeeded: boolean; +} ⋮---- -/** - * Cancel a futures order - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesOrder( - params: WSAPIFuturesOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +// ==================================== +// Futures WebSocket API Response Types +// ==================================== ⋮---- -/** - * Cancel futures orders by id list - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesOrderById( - params: string[], - wsKey?: WSAPIWsKey, -): Promise> +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; +} ⋮---- -/** - * Cancel all open futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesAllOpenOrders( - params: WSAPIFuturesOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { + succeeded: boolean; +} ⋮---- -/** - * Update a futures order - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -updateFuturesOrder( - params: WSAPIFuturesOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPIFuturesOrderCancelIdsRespItem { + id: string; + user_id: number; + succeeded?: boolean; + message?: string; +} ⋮---- -/** - * Get all futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -getFuturesOrders( - params: WSAPIFuturesOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> +// ==================================== +// Request Parameter Mapping +// ==================================== ⋮---- -/** - * Get futures order status - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -getFuturesOrderStatus( - params: WSAPIFuturesOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> +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; +} ⋮---- -/** - * - * - * - * - * - * - * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * - * - */ +export type WsAPITopicRequestParams = + WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; ⋮---- -private setupDefaultEventListeners() +// ==================================== +// Response Headers and Base Response +// ==================================== ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +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; +} ⋮---- -// Blind JSON.stringify can fail on circular references +/** String timestamp as ms */ ⋮---- -// 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'; +/** Status of WS API call. "200" if successful, else exception is thrown */ ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; +export interface WSAPILoginResponse { + api_key: string; + uid: string; } ⋮---- -/** If true, will skip auth requirement for WS API connection */ +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; +} ⋮---- -/** - * WS topics are always a string for gate. Some exchanges use complex objects - */ -export type WsTopic = string; +export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; ⋮---- -export class WebsocketClient extends BaseWebsocketClient +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'; ⋮---- /** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true * - * Returns array of promises that individually resolve when each connection is successfully opened. + * 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(....)`. */ -public connectAll(): Promise[] + attachEventListeners: boolean; +} ⋮---- /** - * Ensures the WS API connection is active and ready. + * Default: true * - * 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). + * 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(....)`. */ -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}. + * 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 +⋮---- +/* * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. + * SPOT - Trading requests * - * 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. + * Submit a spot order */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) +submitNewSpotOrder( + params: WSAPISpotOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * WS API Methods - similar to the REST API, but via WebSockets + * Cancel a spot order */ +cancelSpotOrder( + params: WSAPISpotOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * 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 + * Cancel all spot orders with the given id list */ -⋮---- -// 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, +cancelSpotOrderById( + params: WSAPISpotOrderCancelIdsReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * 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; + * Cancel a spot order for a given symbol + */ +cancelSpotOrderForSymbol( + params: WSAPISpotOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// Send event +/** + * Update a spot order + */ +updateSpotOrder( + params: WSAPISpotOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// Return deferred promise, so caller can await this call +/** + * Get the status of a spot order + */ +getSpotOrderStatus( + params: WSAPISpotOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** + * Get all spot orders + */ +getSpotOrders( + params: WSAPISpotOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> +⋮---- +/* * - * Internal methods - not intended for public use + * Futures - Trading requests * */ ⋮---- -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 + * Submit a futures order. + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -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 +submitNewFuturesOrder( + params: WSAPIFuturesOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Determines if a topic is for a private channel, using a hardcoded list of strings + * Submit a batch of futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -protected isPrivateTopicRequest( - request: WsTopicRequest, - wsKey: WsKey, -): boolean -⋮---- -// No private announcements channels +submitNewFuturesBatchOrder( + params: WSAPIFuturesOrderPlaceReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Not in use for gate.io + * Cancel a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket +cancelFuturesOrder( + params: WSAPIFuturesOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Not in use for gate.io + * Cancel futures orders by id list + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -protected getPrivateWSKeys(): WsKey[] -⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +cancelFuturesOrderById( + params: string[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** 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 +/** + * Cancel all open futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesAllOpenOrders( + params: WSAPIFuturesOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) + * Update a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -protected async getWsOperationEventsForTopics( - topics: WsTopicRequest[], - wsKey: WsKey, - operation: WsOperation, -): Promise +updateFuturesOrder( + params: WSAPIFuturesOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); -// console.trace(); +/** + * Get all futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrders( + params: WSAPIFuturesOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// Events that are ready to send (usually stringified JSON) +/** + * Get futures order status + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrderStatus( + params: WSAPIFuturesOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * */ -private async getWsRequestEvents( - market: WsMarket, - operation: WsOperation, - requests: WsTopicRequest[], - wsKey: WsKey, -): Promise[]> ⋮---- -// If private topic request, build auth part for request +private setupDefaultEventListeners() ⋮---- -// No key or secret, push event as failed +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise -⋮---- -protected async getWsAuthRequestEvent(wsKey: WsKey): Promise -⋮---- -// id: timeInSeconds, +// Blind JSON.stringify can fail on circular references ⋮---- -/** - * - * @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'], +// JSON.stringify({ ...data, target: 'WebSocket' }), ================ -File: .prettierrc +File: src/WebsocketClient.ts ================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" +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; } - -================ -File: jest.config.ts -================ +⋮---- +/** If true, will skip auth requirement for WS API connection */ +⋮---- /** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration + * WS topics are always a string for gate. Some exchanges use complex objects */ +export type WsTopic = string; ⋮---- -import type { Config } from 'jest'; +export class WebsocketClient extends BaseWebsocketClient ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +/** + * 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[] ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +/** + * 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 ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +/** + * 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, +) ⋮---- -// Indicates whether the coverage information should be collected while executing the test +/** + * 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, +) ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +/** + * WS API Methods - similar to the REST API, but via WebSockets + */ ⋮---- -// The directory where Jest should output its coverage files +/** + * 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 + */ ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +// 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; ⋮---- -// Indicates which provider should be used to instrument code for coverage +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 ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +// Some commands don't require authentication. ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, +// id: timeInSeconds, ⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, +/** + * 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. + */ ⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], +// Sign request ⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, +// Store deferred promise ⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, +// Enrich returned promise with request context for easier debugging ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +// throw e; ⋮---- -// 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%", +// Send event ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +// Return deferred promise, so caller can await this call ⋮---- -// An array of file extensions your modules use +/** + * + * Internal methods - not intended for public use + * + */ ⋮---- -// modulePaths: ['src'], +protected getWsUrl(wsKey: WsKey): string ⋮---- -// 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: {}, +protected sendPingEvent(wsKey: WsKey) ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +protected sendPongEvent(wsKey: WsKey) ⋮---- -// Activates notifications for test results -// notify: false, +// Send a protocol layer pong ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +// 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, @@ -4131,148 +4708,24 @@ export function appendGateMultipartFields( ): void ================ -File: src/lib/requestUtils.ts +File: src/types/request/announcement.ts ================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { GateBaseUrlKey } from '../types/shared.js'; +/** POST /ann/list_article */ ⋮---- -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; - - /** - * Built-in Gate API v4 host. - * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 - * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. - */ - 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' - **/ -⋮---- -/** - * Built-in Gate API v4 host. - * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 - * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. - */ -⋮---- -/** 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 -⋮---- -/** Global TestNet REST host. Gate docs: spot and futures. */ -⋮---- -// Alias of `testnet`. Previously https://fx-api-testnet.gateio.ws/api/v4 (HTTP 502). -⋮---- -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/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; -} +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/options.ts @@ -4769,361 +5222,94 @@ export interface AutoInvestPlansListResp { } ================ -File: src/types/response/delivery.ts +File: src/types/response/marginuni.ts ================ /**========================================================================================================================== - * DELIVERY + * MARGIN UNI * ========================================================================================================================== */ ⋮---- -export interface DeliveryOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; +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 DeliveryTrade { - id: number; +export interface MarginUNILoan { + currency: string; + currency_pair: string; + amount: string; + type: string; // Lending type, margin indicates margin borrowing create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; // Deprecated + update_time: number; } ⋮---- -is_internal?: boolean; // Deprecated +type: string; // Lending type, margin indicates margin borrowing ⋮---- -export interface DeliveryCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; +export interface MarginUNILoanRecord { + type: string; + currency_pair: string; + currency: string; + amount: string; + create_time: number; } ⋮---- -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; +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; } ⋮---- -quanto_base_rate?: string; // Deprecated +type: string; // Lending type, margin indicates margin borrowing ⋮---- -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; +export interface MarginUNIMaxBorrowable { 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; + currency_pair: string; + borrowable: string; } + +================ +File: src/types/response/multicollateralLoan.ts +================ +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ ⋮---- -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/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 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; @@ -5262,263 +5448,7 @@ export interface MultiLoanFixedRate { } ================ -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 +File: src/types/response/rebate.ts ================ export interface AgencyTransactionHistoryRecord { transaction_time: number; @@ -5711,63 +5641,130 @@ File: .nvmrc v24.18.0 ================ -File: examples/Rest/futures/testnet.ts +File: examples/Rest/otc/submitOTCBankPersonalSupplement.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 +import { readFileSync } from 'fs'; ⋮---- -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 +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; ⋮---- -// Initialize the RestClient with the API credentials +async function submitOTCBankPersonalSupplementExample() + +================ +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 */ ⋮---- /** - * 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. + * 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 */ ⋮---- -/* - * Futures TestNet trading (alias of `testnet`, spot and futures): - * 'https://api-testnet.gateapi.io/api/v4' - * Older host https://fx-api-testnet.gateio.ws/api/v4 now returns 502. - * baseUrlKey: 'testnet' is the same host. +/** 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 */ ⋮---- /** - * Futures live trading alternative (futures only): - * 'https://fx-api.gateio.ws/api/v4' + * 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) */ -// baseUrlKey: 'futuresLiveAlternative' ⋮---- -async function submitFuturesOrder() +/** + * 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. + */ ⋮---- -// Submit a market order for futures trading +export function serializeParams | undefined = {}>( + params: T, + strict_validation: boolean | undefined, + encodeValues: boolean, + prefixWith: string, +): string ⋮---- -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) +// Only prefix if there's a value ⋮---- -console.log('Response: ', result); // Log the response to the console +/** Global TestNet REST host. Gate docs: spot and futures. */ ⋮---- -console.error('Error in execution: ', e); // Log any errors that occur +// Same host as testnet. The old fx-api-testnet.gateio.ws host returns 502. ⋮---- -// Execute the function to submit a futures order - -================ -File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts -================ -import { readFileSync } from 'fs'; +export function getRestBaseUrl(restClientOptions: RestClientOptions): string ⋮---- -import { RestClient } from '../../../src/index.js'; -// import { RestClient } from 'gateio-api'; +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} ⋮---- -async function submitOTCBankPersonalSupplementExample() +export function isMessageEvent(msg: unknown): msg is MessageEventLike ================ File: src/types/request/alpha.ts @@ -6217,60 +6214,6 @@ export interface CreateStockTransactionReq { ref_id: string; } -================ -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/p2pMerchant.ts ================ @@ -6566,6 +6509,35 @@ restClientRegex.ts testfile.ts +================ +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 +⋮---- +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: src/types/request/earn.ts ================ @@ -7468,7465 +7440,6916 @@ export interface AccountTransferDetail { } ================ -File: src/types/websockets/client.ts +File: src/types/shared.ts ================ -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'testnet' + | 'futuresTestnet'; ⋮---- -/** - * Event args for subscribing/unsubscribing - */ +// interfaces ⋮---- -// export type WsTopicSubscribePrivateArgsV2 = -// | WsTopicSubscribePrivateInstIdArgsV2 -// | WsTopicSubscribePrivateCoinArgsV2; +export interface FromToPageLimit { + from: number; + to: number; + page: number; + limit: number; +} ⋮---- -// export type WsTopicSubscribeEventArgsV2 = -// | WsTopicSubscribePublicArgsV2 -// | WsTopicSubscribePrivateArgsV2; +// 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; +} ⋮---- -/** 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'> - ); +up_rate?: string; // v4.106.4: Maximum price increase percentage +down_rate?: string; // v4.106.4: Maximum price decrease percentage - /** - * 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; +================ +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 - /** - * 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; -} +================ +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'; ⋮---- -/** Your API key */ +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getRestBaseUrl, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; ⋮---- -/** Your API secret */ +/** + * Used to switch how authentication/requests work under the hood + */ ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -/** How often to check if the connection is alive */ +interface SignedRequest { + originalParams: T; + paramsWithSign?: T & { sign: string }; + serializedParams: string; + sign: string; + queryParamsWithSign: string; + timestamp: number; + recvWindow: number; +} ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; +} ⋮---- -/** Delay in milliseconds before respawning the connection */ +type SignMethod = 'gateV4'; ⋮---- /** - * 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. - */ + * 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; +}; ⋮---- -/** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ +/** multipart/form-data body; mutually exclusive with `body` */ ⋮---- /** - * WS configuration that's always defined, regardless of user configuration - * (usually comes from defaults if there's no user-provided values) + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses */ -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - pingInterval: number; - pongTimeout: number; - reconnectTimeout: number; - recvWindow: number; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequests: boolean; - reauthWSAPIOnReconnect: boolean; -} - -================ -File: src/types/shared.ts -================ +⋮---- +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, +⋮---- /** - * Built-in Gate API v4 hosts. - * `testnet` is the global TestNet host (spot and futures). - * `futuresTestnet` is the same host, kept so older `baseUrlKey` values keep working. + * Impure, mutates params to remove any values that have a key but are undefined. */ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'testnet' - | 'futuresTestnet'; +function deleteUndefinedValues(params?: any): void ⋮---- -// interfaces +export abstract class BaseRestClient ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; -} +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; ⋮---- -// 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; -} +/** + * 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 = {}, +) ⋮---- -up_rate?: string; // v4.106.4: Maximum price increase percentage -down_rate?: string; // v4.106.4: Maximum price decrease percentage - -================ -File: webpack/webpack.config.cjs -================ -function generateConfig(name) +/** Throw errors if any request params are empty */ ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +/** in ms == 5 minutes by default */ ⋮---- -// 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 +/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ ⋮---- -// Code is already transpiled from TypeScript, no additional loaders needed - -================ -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` | -| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | - -Set the REST API host with `baseUrl` or `baseUrlKey`, and the WebSocket host with `wsUrl` or `useTestnet: true`. Prefer explicit hosts for TestNet examples: - -- `baseUrlKey: 'testnet'` uses `https://api-testnet.gateapi.io/api/v4` for spot and futures. `baseUrlKey: 'futuresTestnet'` is the same host, kept so older configs keep working. -- `useTestnet: true` selects the TestNet WebSocket host for that connection, including Spot and Options. BTC perpetual and delivery TestNet hosts stay on the URLs in the current Gate docs (`wss://fx-ws-testnet.gateio.ws/...`). Announcements still have no TestNet host. - -```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/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/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/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/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/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/index.ts -================ -// Request Types -⋮---- -// Response Types -⋮---- -// Websockets Types -⋮---- -// Shared Types - -================ -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, -) +// 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. ⋮---- -/** 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/otc.ts -================ -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- -export interface OTCActionResp { - code: number; - message: string; - timestamp: number; -} +// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" +// parameter to define a custom httpsAgent with the desired properties ⋮---- -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; -} +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -type: string; // BUY (on-ramp) or SELL (off-ramp) +// Throw if one of the 3 values is missing, but at least one of them is set ⋮---- -rate_reci: string; // Reciprocal of the exchange rate +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number ⋮---- -order_type: string; // FIAT or STABLE -quote_token: string; // Quote token required when placing an order +protected get(endpoint: string, params?: object) ⋮---- -export type CreateOTCFiatOrderResp = OTCActionResp; +// GET only supports params in the query string ⋮---- -export interface CreateOTCStablecoinOrderResp { - code: number; - message: string; - timestamp: number; -} +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -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; -} +protected getPrivate(endpoint: string, params?: object) ⋮---- -id: string; // Bank ID (required for order placement) +// GET only supports params in the query string ⋮---- -/** 1 = default bank card, 0 = not default */ +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface GetOTCBankListResp { - code: number; - message: string; - data: { - lists: OTCBankListItem[]; - }; - timestamp: number; -} +/** POST private endpoint with multipart/form-data (empty body hash for signing) */ +protected postPrivateMultipart( + endpoint: string, + formData: FormData, + query?: object, +) ⋮---- -export interface CreateOTCBankResp { - code: number; - message: string; - data: { - bank_id: number; - status: number; - }; - timestamp?: number; -} +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, +) ⋮---- -export interface OTCBankSupplementChecklistItem { - description: string; - code?: string; - zh?: string; - en?: string; - required?: boolean; -} +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface GetOTCBankSupplementChecklistResp { - code: number; - message: string; - data: { - user_type: 'personal' | 'enterprise'; - items: OTCBankSupplementChecklistItem[]; - }; - timestamp?: number; -} +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export type MarkOTCOrderAsPaidResp = OTCActionResp; +/** + * @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 ⋮---- -export type CancelOTCOrderResp = OTCActionResp; +// Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- -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 -} +// Build a request and handle signature process ⋮---- -time: string; // Current time -timestamp: number; // Current timestamp +// Dispatch request ⋮---- -trade_no: string; // Trade number -type: string; // Quote direction buy/sell/all -status: string; // Order Status (includes DISBURSED) +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- -fiat_currency: string; // Fiat type +// Throw API rejections by parsing the response code from the body ⋮---- -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- -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 +// Something happened in setting up the request that triggered an error ⋮---- -export interface GetOTCFiatOrderListResp { - code: number; - message: string; - data: { - pn: number; - ps: number; - total_pn: number; - count: number; - /** v4.106.158: was `list` */ - lists: OTCFiatOrderListItem[]; - }; -} +// request made but no response received ⋮---- -/** v4.106.158: was `list` */ +// The request was made and the server responded with a status code +// that falls out of the range of 2xx ⋮---- -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; -} +// console.error('err: ', response?.data); ⋮---- -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 +// Prevent credentials from leaking into error messages ⋮---- -export interface GetOTCStablecoinOrderListResp { - code: number; - message: string; - data: { - total: number; - page_size: number; - page_number: number; - total_page: number; - /** v4.106.158: was `list` */ - lists: OTCStablecoinOrderListItem[]; - }; -} +/** + * @private sign request and set recv window + */ +private async signRequest< + T extends ParamsInQueryBodyOrHeader | undefined = {}, + >( + data: T, + endpoint: string, + method: Method, + signMethod: SignMethod, +): Promise> ⋮---- -/** v4.106.158: was `list` */ +const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- -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 -} +// recvWindow: this.options.recvWindow, ⋮---- -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 +// It's possible to override the recv window on a per rquest level ⋮---- -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 +// console.log('sign params: ', { +// requestBodyToHash, +// paramsStr: toSign, +// url: this.baseUrl, +// urlPath: this.baseUrlPath, +// }); ⋮---- -export interface GetOTCFiatOrderDetailResp { - message: string; - code: number; - data: OTCFiatOrderDetail; -} +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise ⋮---- -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; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: true, + ): Promise>; ⋮---- -export interface CreateOTCUploadPreUploadData { - file_key?: string; - url?: string; - fields?: CreateOTCUploadPreUploadFields; - expires_in?: number; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: false | undefined, + ): Promise>; ⋮---- -export interface CreateOTCUploadPreUploadResp { - code?: number; - message?: string; - timestamp?: number; - data?: CreateOTCUploadPreUploadData; -} +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/spot.ts +File: src/types/request/otc.ts ================ +import { GateMultipartFile } from '../../lib/multipartUtil.js'; +⋮---- /**========================================================================================================================== - * SPOT + * OTC * ========================================================================================================================== */ ⋮---- -/** 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 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) } ⋮---- -export interface SpotOrderBook { - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; -} +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 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 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; } ⋮---- -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 -]; +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 */ ⋮---- -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 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) +} ⋮---- -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; +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 } ⋮---- -taker_fee: string; // For spot trading -maker_fee: string; // For spot trading +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 SpotAccount { - currency: string; - available: string; - locked: string; - update_id: number; - refresh_time: number; - last_update_time?: number; - trading_fee_rate?: string; +export interface CancelOTCOrderReq { + order_id: string; // Order ID } ⋮---- -export interface SpotAccountBook { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - code: string; - text: string; +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 } ⋮---- -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'; +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 } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +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 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; +export interface GetOTCFiatOrderDetailReq { + order_id: string; // Order ID } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +order_id: string; // Order ID ⋮---- -export interface SpotInsuranceHistory { - currency: string; - balance: string; - time: number; +export interface OTCBankIdReq { + bank_id: string; } ⋮---- -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 GetOTCBankSupplementChecklistReq { + bank_id: string; } ⋮---- -export interface GetSpotOpenOrdersResp { - currency_pair: string; - total: number; - orders: SpotOrder[]; +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 DeleteSpotBatchOrdersResp { - currency_pair: string; - id: string; - succeeded: boolean; - label: string; - message: string; - account: string; - text: string; +export interface SubmitOTCBankPersonalSupplementReq { + bank_id: string; + id_document_front: GateMultipartFile; + id_document_back: GateMultipartFile; + address_proof: GateMultipartFile; } ⋮---- -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; +export interface SubmitOTCBankEnterpriseSupplementReq { + bank_id: string; + certificate: GateMultipartFile; + share_holders: GateMultipartFile; + passport: GateMultipartFile; + share_holding_structure: GateMultipartFile; + uid?: string; + funds_statement?: GateMultipartFile; + additional?: GateMultipartFile; } ⋮---- -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; +export interface CreateOTCUploadPreUploadReq { + content_type: string; + scene: 'general' | 'bank' | 'assessment' | 'credit'; } ================ -File: src/types/request/futures.ts +File: src/types/request/spot.ts ================ /**========================================================================================================================== - * FUTURES + * SPOT * ========================================================================================================================== */ ⋮---- -export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; +/** Limit-order take-profit / stop-loss on create */ +export interface SpotOrderTPSL { + trigger_price: string; + order_price: string; +} ⋮---- -export interface GetFuturesOrderBookReq { - settle: FuturesSettle; - contract: 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 GetFuturesTradesReq { - settle: FuturesSettle; - contract: string; +export interface GetSpotTradesReq { + currency_pair: string; limit?: number; - offset?: number; last_id?: string; + reverse?: boolean; from?: number; to?: number; + page?: 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; +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 BatchFundingRatesReq { - settle: 'btc' | 'usdt' | 'usd1'; - contracts: string[]; -} -⋮---- -export interface GetLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; +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; } ⋮---- -export interface GetRiskLimitTiersReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; -} +/** + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. + */ ⋮---- -export interface GetRiskLimitTableReq { - settle: FuturesSettle; - table_id: string; +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -/** Change types for `GET /futures/{settle}/account_book`. */ -export type FuturesAccountBookType = - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset' - | 'dividend'; // v4.106.147: dividend payout -⋮---- -| 'dividend'; // v4.106.147: dividend payout -⋮---- -export interface GetFuturesAccountBookReq { - settle: FuturesSettle; - contract?: string; +export interface GetSpotOrdersReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; limit?: number; - offset?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; from?: number; to?: number; - type?: FuturesAccountBookType; -} -⋮---- -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; + side?: 'buy' | 'sell'; } ⋮---- -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; - /** BBO price type for the take-profit leg */ - tpsl_tp_bbo_type?: string; - /** BBO price type for the stop-loss leg */ - tpsl_sl_bbo_type?: string; - pos_margin_mode?: 'isolated' | 'cross'; +export interface CancelSpotBatchOrdersReq { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -/** BBO price type for the take-profit leg */ +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + xGateExptime?: number; +} ⋮---- -/** BBO price type for the stop-loss leg */ +export interface GetSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; +} ⋮---- -export interface GetFuturesOrdersReq { - settle: FuturesSettle; - contract?: string; - status: string; +export interface GetSpotTradingHistoryReq { + currency_pair?: string; limit?: number; - offset?: number; - last_id?: string; + page?: number; + order_id?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; } ⋮---- -export interface DeleteAllFuturesOrdersReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - side?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; +export interface UpdateSpotBatchOrdersReq { + order_id?: string; + currency_pair?: string; + amount?: string; + price?: string; + amend_text?: string; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; } ⋮---- -export interface GetFuturesOrdersByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; +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 UpdateFuturesOrderReq { +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; - settle: FuturesSettle; order_id: string; - size?: number; + 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; } ⋮---- -export interface GetFuturesTradingHistoryReq { - settle: FuturesSettle; - contract?: string; - order?: number; +/** GET /spot/pov_orders */ +export interface GetSpotPovOrdersReq { + status: 'open' | 'finished'; + currency_pair?: string; + side?: 'buy' | 'sell'; + page?: 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'; +/** 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; } ⋮---- -export interface GetFuturesPositionHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; +/** DELETE /spot/pov_orders */ +export interface CancelSpotPovOrdersReq { + currency_pair?: string; } + +================ +File: src/types/request/tradfi.ts +================ +/** TradFi API request types */ ⋮---- -export interface GetFuturesLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; +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; - 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; +export interface TradFiCreateTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; } ⋮---- -/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ +export interface TradFiGetTransactionsParams { + begin_time?: number; + end_time?: number; + type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; + page?: number; + page_size?: number; +} ⋮---- -price: string; // Required: Order price. Set to 0 to use market price +export interface TradFiCreateOrderReq { + price: string; + price_type: 'trigger' | 'market'; + side: 1 | 2; + symbol: string; + volume: string; + price_tp?: string; + price_sl?: string; + leverage?: number; +} ⋮---- -price: string; // Required: Price value for price trigger -rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +export interface TradFiModifyOrderReq { + price: string; + price_tp?: string | null; + price_sl?: string | null; +} ⋮---- -export interface GetFuturesAutoOrdersReq { - settle: FuturesSettle; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; +export interface TradFiModifyPositionReq { + price_tp?: string | null; + price_sl?: string | null; } ⋮---- -/** - * 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 +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/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'; } ⋮---- -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 +/** @deprecated */ ⋮---- -// 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; +/** 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; } ⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint request -export interface GetFuturesInsuranceReq { - settle: FuturesSettle; - limit?: 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 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 +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; } ⋮---- -/** Same semantics as `size` (decimal contract size) */ -⋮---- -/** When fully closing in single-position mode, set true */ +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ ⋮---- -price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price -auto_size?: string; // Not required in single position mode +export interface FixedTermLadderApr { + apr: string; + left: string; + right: string; +} ⋮---- -/** 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'; +export interface FixedTermProductInfo { + pre_redeem: number; + reinvest: number; + redeem_account: number; + min_vip: number; + max_vip: number; } ⋮---- -/** 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 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 TerminateTrailOrderReq { - settle: 'btc' | 'usdt'; +export interface FixedTermCouponInfo { id?: number; - text?: string; + 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 BatchTerminateTrailOrdersReq { - settle: 'btc' | 'usdt'; - contract?: string; - related_position?: 1 | 2; +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 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 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 GetTrailOrderDetailReq { - settle: 'btc' | 'usdt'; - id: 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 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 GetEarnFixedTermProductsResponse { + code: number; + message: string; + data: { + list: FixedTermProduct[]; + total: number; + }; + timestamp: number; } ⋮---- -export interface GetTrailOrderChangeLogReq { - settle: 'btc' | 'usdt'; - id: number; - page_num?: number; - page_size?: number; +export interface GetEarnFixedTermProductsByAssetResponse { + code: number; + message: string; + data: { + list: FixedTermProductSimple[]; + }; + timestamp: 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 CreateEarnFixedTermLendResponse { + code?: number; + message?: string; + data?: { + order_id?: number; + }; + timestamp?: number; } ⋮---- -export interface StopChaseOrderReq { - settle: FuturesSettle; - id?: string; - text?: string; +export interface GetEarnFixedTermLendsResponse { + code: number; + message: string; + data: { + list: FixedTermLendOrder[]; + total: number; + }; + timestamp: number; } ⋮---- -export interface StopAllChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - pos_margin_mode?: 'isolated' | 'cross' | string; +export interface CreateEarnFixedTermPreRedeemResponse { + code?: number; + message?: string; + data?: Record; + timestamp?: number; } ⋮---- -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; +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; } ⋮---- -/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ -⋮---- -export interface GetChaseOrderDetailReq { - settle: FuturesSettle; - id: string; +export interface GetEarnFixedTermHistoryResponse { + code?: number; + message?: string; + data?: { + list?: FixedTermHistoryRecord[]; + total?: number; + }; + timestamp?: number; } ================ -File: src/types/response/futures.ts +File: src/types/response/unified.ts ================ -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ -⋮---- -import type { FuturesAccountBookType } from '../request/futures.js'; -⋮---- -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 +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 } ⋮---- -is_internal?: boolean; // Deprecated -⋮---- -export interface FuturesCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; -} +mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin ⋮---- -export interface PremiumIndexKLine { - t: number; - c: string; - h: string; - l: string; - o: string; -} +locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin ⋮---- -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; -} +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) ⋮---- -quanto_base_rate?: string; // Deprecated +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 ⋮---- -export interface BatchFundingRatesResponse { - contract?: string; - data?: { t: number; r: string }[]; -} +is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all ⋮---- -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; -} +use_funding?: boolean; // Whether Earn funds are used as margin ⋮---- -export interface IndexConstituents { - index: string; - constituents: { - exchange: string; - symbols: string[]; - }[]; +export interface UnifiedLoan { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; } ⋮---- -export interface LiquidationHistoryRecord { - time: number; - contract: string; - size: number; - order_size: number; - order_price: string; - fill_price: string; - left: 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 RiskLimitTier { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; // First-tier maintenance margin rate requirement - leverage_max: string; - contract: string; +export interface UnifiedInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; } ⋮---- -maintenance_rate: string; // First-tier maintenance margin rate requirement +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 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; +export interface UnifiedCurrencyDiscountTiers { 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; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + leverage: 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; - /** v4.106.147: includes `dividend` (dividend payout) */ - type: FuturesAccountBookType; - text: string; - contract?: string; - trade_id: string; - id: string; +export interface UserCurrencyLeverageConfig { + current_leverage: string; + min_leverage: string; + max_leverage: string; + debit: string; + available_margin: string; + borrowable: string; + except_leverage_borrowable: string; } ⋮---- -/** v4.106.147: includes `dividend` (dividend payout) */ -⋮---- -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; +export interface UnifiedLoanCurrency { + name: string; + prec: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + loan_status: string; } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +export interface UnifiedHistoryLendingRate { + currency: string; + tier: string; + tier_up_rate: string; + rates: { + time: number; + rate: string; + }[]; +} ⋮---- -/** Read-only; order notional in settle currency (API response only; omit from order requests). */ +export interface MarginTier { + tier: string; + margin_rate: string; + lower_limit: string; + upper_limit: string; +} ⋮---- -/** Read-only; traded value (API response only; omit from order requests). */ +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; + }[]; + }[]; +} ⋮---- -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 +export interface UnifiedCollateralCurrenciesResp { + is_success: boolean; +} ⋮---- -/** 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 UnifiedQuickRepayDebtItem { + currency?: string; + debt_amount?: string; + estimated_usd?: string; + borrowed?: string; + neg_balance?: 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 +export interface UnifiedQuickRepayAvailableItem { + currency?: string; + available?: string; + estimated_usd?: string; } ⋮---- -leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode +export interface QuickEstimatedRepayment { + debt_currencies?: UnifiedQuickRepayDebtItem[]; + available_currencies?: UnifiedQuickRepayAvailableItem[]; +} ⋮---- -leverage_max?: string; // Max leverage based on current position size -maintenance_rate?: string; // Tiered maintenance margin rate calculation +export interface QuickRepayRepaidInfo { + currency: string; + repaid: string; + left: string; +} ⋮---- -liq_price?: string; // Estimated liquidation price for reference only -liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management +export interface QuickRepayUsedInfo { + currency: string; + used: string; +} ⋮---- -initial_margin?: string; // Expanded scope description -maintenance_margin?: string; // Expanded scope description +export interface QuickRepaymentResp { + order_id: string; + repaid_infos: QuickRepayRepaidInfo[]; + used_infos: QuickRepayUsedInfo[]; +} ⋮---- -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 +/** GET/POST /unified/delta_neutral — v4.106.97 */ +export interface DeltaNeutralEnabled { + enabled: boolean; +} ⋮---- -cross_leverage_limit?: string; // Simplified description +/** POST /unified/leverage/user_setting failed currency entry */ +export interface LeverageFailedCurrency { + currency: string; + reason: string; +} + +================ +File: src/types/websockets/client.ts +================ +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; ⋮---- -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 +/** + * Event args for subscribing/unsubscribing + */ ⋮---- -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 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; + + /** Use the Gate TestNet WebSocket hosts. */ + 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; } ⋮---- -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; -} +/** Your API key */ ⋮---- -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; +/** Your API secret */ +⋮---- +/** Use the Gate TestNet WebSocket hosts. */ +⋮---- +/** 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; } -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; + +================ +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); + } } -⋮---- -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; + +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); + } } -⋮---- -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; + +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); } -⋮---- -/** 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; + +try { + ws.subscribe( + { + topic: 'futures.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.perpFuturesUSDTV4, + ); +} catch (error) { + console.error('Futures subscription failed:', error); } -⋮---- -export interface FuturesADLRiskStates { - settle: string; - states: Record; + +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); } -⋮---- -/** GET /futures/{settle}/get_leverage/{contract} — API field name is `Lever` */ -export interface FuturesContractLeverageInfo { - Lever: string; + +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); } -⋮---- -/** 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; + +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); } -⋮---- -/** - * 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 + +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); + } } -⋮---- -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; + +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); + } } -⋮---- -/** 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; + +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); + } } -⋮---- -/** - * 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; - }; + +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(); + } } -⋮---- -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; + +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(); + } } -⋮---- -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; + +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); + } } -⋮---- -/** 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; + +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; + } } -⋮---- -export interface TrailChangeLog { - updated_at?: number; - amount?: string; - is_gte?: boolean; - activation_price?: string; - price_type?: number; - price_offset?: string; - is_create?: boolean; + +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); } -⋮---- -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; + +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); } -⋮---- -export interface CreateChaseOrderResp { - id?: string; + +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); } -⋮---- -export interface StopChaseOrderResp { - order?: ChaseOrder; + +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(); + } } -⋮---- -export interface StopAllChaseOrdersResp { - orders?: ChaseOrder[]; + +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` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | + +For WebSocket TestNet, set `useTestnet: true`. + +```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, + useTestnet: true, +}); +``` + +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(); + }); } -⋮---- -export interface GetChaseOrdersResp { - orders?: ChaseOrder[]; + +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(); + }); } -⋮---- -export interface GetChaseOrderDetailResp { - order?: ChaseOrder; + +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(); + }); } -================ -File: README.md -================ -# Node.js & JavaScript SDK for Gate.com (Gate.io) REST APIs, WebSockets & WebSocket API +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. -

- - - - SDK Logo - - -

+### Use custom order IDs -[![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) +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. -[1]: https://www.npmjs.com/package/gateio-api +### Apply product metadata -Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST APIs and WebSockets: +Before placing an order: -- 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 +- 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. -## Table of Contents +Refresh metadata regularly and when Gate rejects an order for a precision or size rule. -- [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) +### Confirm final state -## Installation +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. -`npm install --save gateio-api` +After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. -## Examples +### Scope credentials and network access -Refer to the [examples](./examples) folder for implementation demos, including: +- 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. -- **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 +### Shut down connections -## Issues & Discussion +Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. -- 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) +## FAQ - +### Does `gateio-api` work with plain JavaScript? -## Related Projects +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. -Check out our JavaScript/TypeScript/Node.js SDKs & Projects: +### Which client should I use? -- 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) - +Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. -## Documentation +### Do public Gate API calls need credentials? -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. +No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. -### API Documentation Links +### Why did a REST API call return an object when another returned an array? -- [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) +Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. -## Structure +### Why does `getSpotTicker()` return an array for one pair? -This project uses typescript. Resources are stored in 2 key structures: +That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. -- [src](./src) - the whole connector written in typescript -- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! +### 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. -# Usage +### Why does Gate use `BTC_USDT`? -Create API credentials on Gate.com's website: +Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. -- [Gate.com API Key Management](https://www.gate.com/myaccount/api_key_manage) +### What do `account` and `settle` change? -## REST API +`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. -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. +### What is the `text` order field? -To use any of Gate.com's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the `RestClient`: +`text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. -```javascript -const { RestClient } = require('gateio-api'); +### Why am I not receiving WebSocket updates? -const API_KEY = 'xxx'; -const PRIVATE_KEY = 'yyy'; +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. -const client = new RestClient({ - apiKey: API_KEY, - apiSecret: PRIVATE_KEY, -}); +### Which `WS_KEY_MAP` value should I use? -// Spot Trading Example -client - .getSpotTicker() - .then((result) => { - console.log('all spot tickers result: ', result); - }) - .catch((err) => { - console.error('spot ticker error: ', err); - }); +Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. -client - .getSpotOrders({ - currency_pair: 'BTC_USDT', - status: 'open', - }) - .then((result) => { - console.log('getSpotOrders result: ', result); - }) - .catch((err) => { - console.error('getSpotOrders error: ', err); - }); +### Why do private Futures topics use my Gate user ID? -// CrossEx Trading Example - Trade across multiple exchanges -client - .getCrossExSymbols() - .then((result) => { - console.log('CrossEx symbols: ', result); - }) - .catch((err) => { - console.error('CrossEx error: ', err); - }); +It is part of the payload required by those channels. Retrieve it with `getAccountDetail()` instead of hardcoding it. -// 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); - }); +### What is the difference between a stream and the WebSocket API? -// 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); - }); -``` +Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. -TestNet REST for spot and futures is `baseUrlKey: 'testnet'` (`https://api-testnet.gateapi.io/api/v4`). `baseUrlKey: 'futuresTestnet'` is that same host, kept so older configs keep working. WebSocket TestNet is `useTestnet: true` on `WebsocketClient`. +### Does a successful WebSocket API response mean the order filled? -See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. +No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. -## WebSockets +### 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? -All WebSocket functionality is supported via the unified `WebsocketClient`. This client handles all Gate.com WebSocket streams with automatic connection management and reconnection. +No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. -Key WebSocket features: +### Can I use Gate US or Gate EU with the SDK? -- 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 +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. -### WebSocket Data Streams +### Can REST API and WebSocket traffic use the same proxy? -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). +Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. -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. +### Does a proxy change signing or account eligibility? -Data events are emitted from the WebsocketClient via the `update` event, see example below: +No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. -```javascript -const { WebsocketClient } = require('gateio-api'); +### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? -const API_KEY = 'xxx'; -const PRIVATE_KEY = 'yyy'; +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. -const wsConfig = { - apiKey: API_KEY, - apiSecret: PRIVATE_KEY, +## Next steps - /* - The following parameters are optional: - */ +- 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). - // Livenet is used by default, use this to enable testnet: - // useTestnet: true +================ +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'; +} - // how long to wait (in ms) before deciding the connection should be terminated & reconnected - // pongTimeout: 1000, +================ +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'; +} - // how often to check (in ms) that WS connection is still alive - // pingInterval: 10000, +================ +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; +} - // how long to wait before attempting to reconnect (in ms) after connection is closed - // reconnectTimeout: 500, +================ +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; +} - // config options sent to RestClient (used for time sync). See RestClient docs. - // restOptions: { }, +================ +File: src/index.ts +================ +// Request Types +⋮---- +// Response Types +⋮---- +// Websockets Types +⋮---- +// Shared Types - // config for axios used for HTTP requests. E.g for proxy support - // requestOptions: { } -}; +================ +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; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; + }; +} +⋮---- +/** v4.106.158: was `list` */ +⋮---- +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; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; + }; +} +⋮---- +/** v4.106.158: was `list` */ +⋮---- +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; +} -const ws = new WebsocketClient(wsConfig); +================ +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; +} +⋮---- +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout +⋮---- +| 'dividend'; // v4.106.147: dividend payout +⋮---- +export interface GetFuturesAccountBookReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: FuturesAccountBookType; +} +⋮---- +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; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; + pos_margin_mode?: 'isolated' | 'cross'; +} +⋮---- +/** BBO price type for the take-profit leg */ +⋮---- +/** BBO price type for the stop-loss leg */ +⋮---- +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/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 +⋮---- +/** v4.106.147: includes `dividend` (dividend payout) */ +export type FuturesAccountBookRecordType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; +⋮---- +export interface FuturesAccountBookRecord { + time: number; + change: string; + balance: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookRecordType; + text: string; + contract?: string; + trade_id: string; + id: string; +} +⋮---- +/** v4.106.147: includes `dividend` (dividend payout) */ +⋮---- +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; +} +⋮---- /** - * 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'); - + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ +⋮---- /** - * 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); - } + * @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; } - -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 @@ -20200,20 +19623,575 @@ createStockTransaction( ): Promise>> ⋮---- /** - * Query supported stock exchanges - * - * @returns Promise with exchange list - */ -getStockExchanges(): 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: 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); + }); +``` + +WebSocket TestNet: set `useTestnet: true` on `WebsocketClient`. + +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'); + /** - * 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>> + * 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: package.json