This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter). ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter - Files are sorted by Git change count (files with more changes are at the bottom) ================================================================ Directory Structure ================================================================ examples/ futures/ getBalances.ts getOrders.ts getTickers.ts submitLimitOrder.ts submitMarketOrder.ts testnet.ts spot/ getBalances.ts getCandles.ts getOrders.ts getTickers.ts submitLimitOrder.ts submitMarketOrder.ts futures-balance-trade.ts README.md ws-api-client.ts ws-private-perp-futures-wsapi.ts ws-private-perp-futures.ts ws-private-spot-wsapi.ts ws-private-spot.ts ws-public.ts src/ lib/ websocket/ websocket-util.ts WsStore.ts WsStore.types.ts BaseRestClient.ts BaseWSClient.ts logger.ts misc-util.ts requestUtils.ts webCryptoAPI.ts types/ request/ account.ts collateralLoan.ts delivery.ts earn.ts earnuni.ts flashswap.ts futures.ts margin.ts marginuni.ts multicollateralLoan.ts options.ts rebate.ts spot.ts subaccount.ts unified.ts wallet.ts withdrawal.ts response/ account.ts collateralloan.ts delivery.ts earn.ts earnuni.ts flashswap.ts futures.ts margin.ts marginuni.ts multicollateralLoan.ts options.ts rebate.ts spot.ts subaccount.ts unified.ts wallet.ts withdrawal.ts websockets/ client.ts events.ts requests.ts wsAPI.ts shared.ts index.ts RestClient.ts WebsocketAPIClient.ts WebsocketClient.ts .eslintrc.cjs .gitignore .nvmrc .prettierrc jest.config.ts LICENSE.md package.json postBuild.sh README.md tea.yaml tsconfig.cjs.json tsconfig.esm.json tsconfig.json tsconfig.linting.json ================================================================ Files ================================================================ ================ File: examples/futures/getBalances.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getFuturesBalances() ⋮---- // Fetch the futures account balance for USDT settlement ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get futures balances ================ File: examples/futures/getOrders.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key or use environment variables secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret or use environment variables ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getFuturesOrders() ⋮---- // Fetch open futures orders with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency status: 'open', // Specify the status of the orders to fetch ⋮---- console.log('openOrders: ', openOrders); // Log the response to the console ⋮---- // Fetch finished futures orders with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency status: 'finished', // Specify the status of the orders to fetch ⋮---- console.log('finishedOrders: ', finishedOrders); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get futures orders ================ File: examples/futures/getTickers.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getFuturesTicker() ⋮---- // Fetch all futures tickers with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency ⋮---- console.log('allTickers: ', allTickers); // Log the response to the console ⋮---- // Fetch a specific futures ticker with USDT settlement ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract ⋮---- console.log('ticker: ', ticker); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get futures tickers ================ File: examples/futures/submitLimitOrder.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitFuturesOrder() ⋮---- // Submit a limit order for futures trading ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract size: 10, // Order size: positive for long, negative for short price: '45000', // Limit price for the order tif: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to submit a futures order ================ File: examples/futures/submitMarketOrder.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitFuturesOrder() ⋮---- // Submit a market order for futures trading ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract size: 20, // Order size: positive for long, negative for short price: '0', // Market order, so price is set to '0' tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to submit a futures order ================ File: examples/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/spot/getBalances.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotBalances() ⋮---- // Fetch the spot account balances ⋮---- console.log('Response: ', balances); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get spot balances ================ File: examples/spot/getCandles.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotCandles() ⋮---- // Fetch the spot account balances ⋮---- console.log('Response: ', balances); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get spot balances ================ File: examples/spot/getOrders.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotOrders() ⋮---- // Fetch open spot orders for the BTC_USDT currency pair ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair status: 'open', // Specify the status of the orders to fetch ⋮---- console.log('openOrders: ', openOrders); // Log the response to the console ⋮---- // Fetch finished spot orders for the BTC_USDT currency pair ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair status: 'finished', // Specify the status of the orders to fetch ⋮---- console.log('finishedOrders: ', finishedOrders); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get spot orders ================ File: examples/spot/getTickers.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function getSpotTicker() ⋮---- // Fetch the ticker for a specific currency pair (BTC_USDT) ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair ⋮---- console.log('Response: ', ticker); // Log the response to the console ⋮---- // Fetch all tickers ⋮---- console.log('Response: ', allTickers); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to get spot tickers ================ File: examples/spot/submitLimitOrder.ts ================ import { RestClient } from '../../src'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitSpotOrder() ⋮---- // Submit a limit order for spot trading ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair side: 'buy', // Specify the order side: 'buy' or 'sell' type: 'limit', // Specify the order type: 'limit' amount: '0.001', // Specify the amount to buy price: '45000', // Specify the limit price time_in_force: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to submit a spot order ================ File: examples/spot/submitMarketOrder.ts ================ import { RestClient } from '../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- async function submitSpotOrder() ⋮---- // Submit a market order for spot trading ⋮---- currency_pair: 'BTC_USDT', // Specify the currency pair side: 'buy', // Specify the order side: 'buy' or 'sell' type: 'market', // Specify the order type: 'market' amount: '10', // Specify the amount to buy time_in_force: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error(`Error in execution: `, e); // Log any errors that occur ⋮---- // Execute the function to submit a spot order ================ File: examples/futures-balance-trade.ts ================ /** * This example demonstrates a simple commented workflow of: * - initialising the RestClient and WebsocketClient for Gate.io exchange * - connecting to an account’s private websockets (to receive updates asynchronously) * - checking if connection is successful * - fetching available futures balance * - placing an order using 50% of the available balance **/ ⋮---- // Import the RestClient and WebsocketClient from the published version of this SDK, installed via NPM (npm install gateio-api) import { RestClient, WebsocketClient } from 'gateio-api'; ⋮---- // Define the account object with API key and secret ⋮---- // Replace 'yourApiHere' with your actual API key or use environment variables ⋮---- // Replace 'yourSecretHere' with your actual API secret or use environment variables ⋮---- // Initialize the RestClient with the API credentials ⋮---- // initialise websocket client - if you want only public data, you can initialise the client without the apiKey and apiSecret, just WebsocketClient() ⋮---- // Data received ⋮---- async function subscribePrivateWs() ⋮---- // Enter your user ID here ⋮---- //sub to balances updates ⋮---- //sub to trades updates ⋮---- /** * Either send one topic (with params) at a time */ // client.subscribe({ // topic: 'futures.usertrades', // payload: [myUserID, '!all'], // }, 'perpFuturesUSDTV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: */ ⋮---- async function main() ⋮---- // Get futures account balance via REST ⋮---- // total usdt balance ⋮---- // available usdt balance ⋮---- // submit market order with 50% of the balance ⋮---- // Submit a market order with 50% of the balance ⋮---- settle: 'usdt', // Specify the settlement currency contract: 'BTC_USDT', // Specify the contract size: orderAmount, // Order size: positive for long, negative for short, in USDT price: '0', // Market order, so price is set to '0' tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- // for more detailed ws connection, you can use a lot more listeners like below: ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ================ File: examples/README.md ================ # Examples These samples can be executed using `ts-node` or `tsx`: ``` ts-node ./examples/ws-public.ts ``` Most examples also have minimal typescript, so if you rename them to "js" they should execute fine with just node. TypeScript is recommended but completely optional: ``` node ./examples/spot/getTickers.js ``` ================ File: examples/ws-api-client.ts ================ import { WebsocketAPIClient, WS_KEY_MAP } from '../src/index.js'; // import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- async function start() ⋮---- /** * Optional: authenticate in advance. This will prepare and authenticate a connection. * Useful to save time for the first request but completely optional. It will also happen automatically when you make your first request. */ // console.log(new Date(), 'Authenticating in advance...'); // await client.getWSClient().connectWSAPI('spotV4'); // console.log(new Date(), 'Authenticating in advance...OK!'); ⋮---- /* ============ SPOT TRADING EXAMPLES ============ */ ⋮---- // SPOT ORDER PLACE - Submit a new spot order ⋮---- // SPOT ORDER CANCEL - Cancel a specific spot order ⋮---- // SPOT ORDER CANCEL BY IDS - Cancel orders by ID list ⋮---- // SPOT ORDER CANCEL BY CURRENCY PAIR - Cancel all orders for a currency pair ⋮---- // SPOT ORDER AMEND - Update an existing spot order ⋮---- // SPOT ORDER STATUS - Get status of a specific spot order ⋮---- // SPOT ORDER LIST - Get list of spot orders ⋮---- /* ============ FUTURES TRADING EXAMPLES ============ */ ⋮---- /** * Gate has different websocket groups depending on the futures product. * * This affects which connection your command is sent to, so make sure to pass one matching your request. Look at WS_KEY_MAP (or the examples below) for details on the available product groups. */ ⋮---- /** * Also optional, as for spot. Keep in mind the first parameter (wsKey) might vary depending on which WS URL is needed. */ ⋮---- // console.log(new Date(), 'Authenticating in advance...'); // await client.getWSClient().connectWSAPI(futuresConnectionGroup); // await client.getWSClient().connectWSAPI('perpFuturesUSDTV4'); // await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); // await client.getWSClient().connectWSAPI('deliveryFuturesUSDTV4'); // await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); // console.log(new Date(), 'Authenticating in advance...OK!'); ⋮---- // FUTURES ORDER PLACE - Submit a new futures order ⋮---- // FUTURES ORDER BATCH PLACE - Submit multiple futures orders ⋮---- // FUTURES ORDER CANCEL - Cancel a specific futures order ⋮---- // FUTURES ORDER CANCEL BY IDS - Cancel futures orders by ID list ⋮---- // FUTURES ORDER CANCEL ALL - Cancel all open futures orders ⋮---- // FUTURES ORDER AMEND - Update an existing futures order ⋮---- // FUTURES ORDER LIST - Get list of futures orders ⋮---- // FUTURES ORDER STATUS - Get status of a specific futures order ================ File: examples/ws-private-perp-futures-wsapi.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ ⋮---- import { LogParams, WebsocketClient } from '../src/index.js'; // import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('update', (data) => { // // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); // console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); // }); ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('response', (data) => { // console.info( // new Date(), // 'ws server reply ', // JSON.stringify(data, null, 2), // '\n', // ); // }); ⋮---- // Optional, listen to this event if you prefer the event-driven approach. // See below comments on event-driven vs promise-driven. // client.on('authenticated', (data) => { // console.error(new Date(), 'ws authenticated: ', data); // }); ⋮---- /** * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. * * You have two ways to handle responses on the WS API. You can either: * - event-driven: process async `response` and `update` events from the websocket client, OR * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). */ ⋮---- /** * To authenticate, send an empty request to "futures.login". The SDK will handle all the parameters. * * Optional - you can inject rich types to set the response type * const loginResult = await client.sendWSAPIRequest>('perpFuturesUSDTV4', 'futures.login'); */ ⋮---- /** * For other channels, the 3rd parameter should have any parameters for the request (the payload). * * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. * */ ⋮---- /** * Submit futures order */ ⋮---- size: 20, // positive for long, negative for short ⋮---- /** * Submit batch futures order */ ⋮---- size: 10, // positive for long, negative for short ⋮---- size: 10, // positive for long, negative for short ⋮---- /** * Cancel futures order */ ⋮---- /** * Cancel all futures orders */ ⋮---- /** * Update/Amend Futures order */ ⋮---- /** * Get orders list */ ⋮---- /** * Get order status */ ================ File: examples/ws-private-perp-futures.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { LogParams, WebsocketClient, WsTopicRequest } from '../src/index.js'; // import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // console.log('auth with: ', account); ⋮---- // Data received ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- // TODO: many private topics use your user ID ⋮---- /** * Either send one topic (with params) at a time */ // client.subscribe({ // topic: 'futures.usertrades', // payload: [myUserID, '!all'], // }, 'perpFuturesUSDTV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: */ ================ File: examples/ws-private-spot-wsapi.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ ⋮---- import { LogParams, WebsocketClient } from '../src/index.js'; // import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('update', (data) => { // // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); // console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); // }); ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" // See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach // client.on('response', (data) => { // console.info( // new Date(), // 'ws server reply ', // JSON.stringify(data, null, 2), // '\n', // ); // }); ⋮---- // Optional, listen to this event if you prefer the event-driven approach. // See below comments on event-driven vs promise-driven. // client.on('authenticated', (data) => { // console.error(new Date(), 'ws authenticated: ', data); // }); ⋮---- /** * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. * * You have two ways to handle responses on the WS API. You can either: * - event-driven: process async `response` and `update` events from the websocket client, OR * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). */ ⋮---- /** * No need to authenticate first - the SDK will automatically authenticate for you when you send your first request. * * Unless you want to prepare the connection before your first request, to speed up your first request. */ ⋮---- /** * For other channels, the 3rd parameter should have any parameters for the request (the payload that goes in req_param in the docs). * * See WsAPIRequestsTopicMap for a topic->parameter map. * * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. */ ⋮---- /** * Submit spot order */ ⋮---- /** * Cancel spot order */ ⋮---- /** * Batch cancel spot order */ ⋮---- /** * Amend/Update spot order */ ⋮---- /** * Get spot order status */ ⋮---- /** * If you don't want to use await (and prefer the async event emitter), make sure to still include a catch block. * * The response will come async via the event emitter in the WS Client. */ ⋮---- // client // .sendWSAPIRequest('spotV4', 'spot.order_status', { // order_id: '600995435390', // currency_pair: 'BTC_USDT', // }) // .catch((e) => { // console.error(`exception ws api call, get spot order status: `, e); // }); ================ File: examples/ws-private-spot.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { LogParams, WebsocketClient, WsTopicRequest } from '../src/index.js'; // import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // Define a custom logger object to handle logging at different levels ⋮---- // Trace level logging: used for detailed debugging information ⋮---- // Uncomment the line below to enable trace logging // console.log(new Date(), 'trace', ...params); ⋮---- // Info level logging: used for general informational messages ⋮---- // Error level logging: used for error messages ⋮---- async function start() ⋮---- // console.log('auth with: ', account); ⋮---- // Data received ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- // client.subscribe(topics, 'spotV4'); ⋮---- // This has the same effect as above, it's just a different way of messaging which topic this is for // const topicWithoutParamsAsObject: WsTopicRequest = { // topic: 'spot.balances', // }; ⋮---- /** * Either send one topic (with optional params) at a time */ // client.subscribe(topicWithoutParamsAsObject, 'spotV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: */ ⋮---- /** * You can also subscribe in separate function calls as you wish. * * Any duplicate requests should get filtered out (e.g. here we subscribed to "spot.balances" twice, but the WS client will filter this out) */ ================ File: examples/ws-public.ts ================ // eslint-disable-next-line @typescript-eslint/no-unused-vars import { WebsocketClient, WsTopicRequest } from '../src/index.js'; // import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- // const customLogger = { // // eslint-disable-next-line @typescript-eslint/no-unused-vars // trace: (...params: LogParams): void => { // console.log('trace', ...params); // }, // info: (...params: LogParams): void => { // console.log('info', ...params); // }, // error: (...params: LogParams): void => { // console.error('error', ...params); // }, // }; ⋮---- async function start() ⋮---- // Optional, inject a custom logger // const client = new WebsocketClient({}, customLogger); ⋮---- // Data received ⋮---- // Something happened, attempting to reconnect ⋮---- // Reconnect successful ⋮---- // Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- // const topicWithoutParamsAsString = 'spot.balances'; ⋮---- // This has the same effect as above, it's just a different way of messaging which topic this is for // const topicWithoutParamsAsObject: WsTopicRequest = { // topic: 'spot.balances', // }; ⋮---- /** * Either send one topic (with optional params) at a time */ // client.subscribe(tickersRequestWithParams, 'spotV4'); ⋮---- /** * Or send multiple topics in a batch (grouped by ws connection (WsKey)) */ ⋮---- // /** // * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: // */ // client.subscribe( // [tickersRequestWithParams, rawTradesRequestWithParams, topicWithoutParamsAsString], // 'spotV4', // ); ================ File: src/lib/websocket/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.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { DefaultLogger } from '../logger.js'; import { DeferredPromise, WSConnectedResult, WsConnectionStateEnum, WsStoredState, } from './WsStore.types.js'; ⋮---- /** * Simple comparison of two objects, only checks 1-level deep (nested objects won't match) */ export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean ⋮---- type DeferredPromiseRef = (typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF]; ⋮---- export class WsStore< WsKey extends string, ⋮---- constructor(logger: DefaultLogger) ⋮---- /** Get WS stored state for key, optionally create if missing */ get( key: WsKey, createIfMissing?: true, ): WsStoredState; ⋮---- get( key: WsKey, createIfMissing?: false, ): WsStoredState | undefined; ⋮---- get( key: WsKey, createIfMissing?: boolean, ): WsStoredState | undefined ⋮---- getKeys(): WsKey[] ⋮---- create(key: WsKey): WsStoredState | undefined ⋮---- delete(key: WsKey): void ⋮---- // TODO: should we allow this at all? Perhaps block this from happening... ⋮---- /* connection websocket */ ⋮---- hasExistingActiveConnection(key: WsKey): boolean ⋮---- getWs(key: WsKey): WebSocket | undefined ⋮---- setWs(key: WsKey, wsConnection: WebSocket): WebSocket ⋮---- /** * deferred promises */ ⋮---- getDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, ): DeferredPromise | undefined ⋮---- createDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, throwIfExists: boolean, ): DeferredPromise ⋮---- // console.log('existing promise'); ⋮---- // console.log('create promise'); ⋮---- // TODO: Once stable, use Promise.withResolvers in future ⋮---- resolveDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, value: unknown, removeAfter: boolean, ): void ⋮---- rejectDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, value: unknown, removeAfter: boolean, ): void ⋮---- removeDeferredPromise( wsKey: WsKey, promiseRef: string | DeferredPromiseRef, ): void ⋮---- // Just in case it's pending ⋮---- rejectAllDeferredPromises(wsKey: WsKey, reason: string): void ⋮---- // Skip reserved keys, such as the connection promise ⋮---- /** Get promise designed to track a connection attempt in progress. Resolves once connected. */ getConnectionInProgressPromise( wsKey: WsKey, ): DeferredPromise | undefined ⋮---- getAuthenticationInProgressPromise( wsKey: WsKey, ): DeferredPromise ⋮---- createAuthenticationInProgressPromise( wsKey: WsKey, throwIfExists: boolean, ): DeferredPromise ⋮---- getTopicsByKey(): Record> ⋮---- /** * Find matching "topic" request from the store * @param key * @param topic * @returns */ getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- // Check for duplicate topic. If already tracked, don't store this one ⋮---- deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- // Check if we're subscribed to a topic like this ================ File: src/lib/websocket/WsStore.types.ts ================ /* eslint-disable @typescript-eslint/no-explicit-any */ import WebSocket from 'isomorphic-ws'; ⋮---- export enum WsConnectionStateEnum { INITIAL = 0, CONNECTING = 1, CONNECTED = 2, CLOSING = 3, RECONNECTING = 4, // ERROR_RECONNECTING = 5, ERROR = 5, } ⋮---- // ERROR_RECONNECTING = 5, ⋮---- export interface DeferredPromise { resolve?: (value: TSuccess) => TSuccess; reject?: (value: TError) => TError; promise?: Promise; } ⋮---- export interface WSConnectedResult { wsKey: string; ws: WebSocket; } ⋮---- export interface WsStoredState { /** The currently active websocket connection */ ws?: WebSocket; /** The current lifecycle state of the connection (enum) */ connectionState?: WsConnectionStateEnum; connectionStateChangedAt?: Date; /** A timer that will send an upstream heartbeat (ping) when it expires */ activePingTimer?: ReturnType | undefined; /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ activePongTimer?: ReturnType | undefined; /** If a reconnection is in progress, this will have the timer for the delayed reconnect */ activeReconnectTimer?: ReturnType | undefined; /** * When a connection attempt is in progress (even for reconnect), a promise is stored here. * * This promise will resolve once connected (and will then get removed); */ // connectionInProgressPromise?: DeferredPromise | undefined; deferredPromiseStore: Record; /** * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) * * A "Set" and a deep-object-match are used to ensure we only subscribe to a * topic once (tracking a list of unique topics we're expected to be connected to) */ subscribedTopics: Set; /** Whether this connection has completed authentication (only applies to private connections) */ isAuthenticated?: boolean; /** * Whether this connection has completed authentication before for the Websocket API, so it k * nows to automatically reauth if reconnected */ didAuthWSAPI?: boolean; /** To reauthenticate on the WS API, which channel do we send to? */ WSAPIAuthChannel?: string; } ⋮---- /** The currently active websocket connection */ ⋮---- /** The current lifecycle state of the connection (enum) */ ⋮---- /** A timer that will send an upstream heartbeat (ping) when it expires */ ⋮---- /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ ⋮---- /** If a reconnection is in progress, this will have the timer for the delayed reconnect */ ⋮---- /** * When a connection attempt is in progress (even for reconnect), a promise is stored here. * * This promise will resolve once connected (and will then get removed); */ // connectionInProgressPromise?: DeferredPromise | undefined; ⋮---- /** * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) * * A "Set" and a deep-object-match are used to ensure we only subscribe to a * topic once (tracking a list of unique topics we're expected to be connected to) */ ⋮---- /** Whether this connection has completed authentication (only applies to private connections) */ ⋮---- /** * Whether this connection has completed authentication before for the Websocket API, so it k * nows to automatically reauth if reconnected */ ⋮---- /** To reauthenticate on the WS API, which channel do we send to? */ ================ File: src/lib/BaseRestClient.ts ================ import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; 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; }; ⋮---- /** * 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 ⋮---- // 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) ⋮---- protected deletePrivate( endpoint: string, params?: ParamsInQueryBodyOrHeader, ) ⋮---- protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- // protected patchPrivate(endpoint: string, params?: any) { protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- /** * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. */ private async _call( method: Method, endpoint: string, params?: ParamsInQueryBodyOrHeader, isPublicApi?: boolean, ): Promise ⋮---- // Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- // Build a request and handle signature process ⋮---- // Dispatch request ⋮---- // See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- // Throw API rejections by parsing the response code from the body ⋮---- /** * @private generic handler to parse request exceptions */ parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- // Something happened in setting up the request that triggered an error ⋮---- // request made but no response received ⋮---- // The request was made and the server responded with a status code // that falls out of the range of 2xx ⋮---- // console.error('err: ', response?.data); ⋮---- // Prevent credentials from leaking into error messages ⋮---- /** * @private sign request and set recv window */ private async signRequest< T extends ParamsInQueryBodyOrHeader | undefined = {}, >( data: T, endpoint: string, method: Method, signMethod: SignMethod, ): Promise> ⋮---- const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- // recvWindow: this.options.recvWindow, ⋮---- // It's possible to override the recv window on a per rquest level ⋮---- // console.log('sign params: ', { // requestBodyToHash, // paramsStr: toSign, // url: this.baseUrl, // urlPath: this.baseUrlPath, // }); ⋮---- private async signMessage( paramsStr: string, secret: string, method: 'hex' | 'base64', algorithm: SignAlgorithm, ): Promise ⋮---- private async prepareSignParams< TParams extends ParamsInQueryBodyOrHeader | undefined, >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: true, ): Promise>; ⋮---- private async prepareSignParams< TParams extends ParamsInQueryBodyOrHeader | undefined, >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: false | undefined, ): Promise>; ⋮---- private async prepareSignParams< TParams extends ParamsInQueryBodyOrHeader | undefined, >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: boolean, ) ⋮---- /** Returns an axios request object. Handles signing process automatically if this is a private API call */ private async buildRequest( method: Method, endpoint: string, url: string, params?: ParamsInQueryBodyOrHeader, isPublicApi?: boolean, ): Promise ================ File: src/lib/BaseWSClient.ts ================ import EventEmitter from 'events'; import WebSocket from 'isomorphic-ws'; ⋮---- import { WebsocketClientOptions, WSClientConfigurableOptions, } from '../types/websockets/client.js'; import { WsOperation } from '../types/websockets/requests.js'; import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; import { DefaultLogger } from './logger.js'; import { isMessageEvent, MessageEventLike } from './requestUtils.js'; import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; import { safeTerminateWs, WsTopicRequest, WsTopicRequestOrStringTopic, } from './websocket/websocket-util.js'; import { WsStore } from './websocket/WsStore.js'; import { WSConnectedResult, WsConnectionStateEnum, } from './websocket/WsStore.types.js'; ⋮---- interface WSClientEventMap { /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ open: (evt: { wsKey: WsKey; event: any; wsUrl: string; ws: WebSocket; }) => void /** Reconnecting a dropped connection */; reconnect: (evt: { wsKey: WsKey; event: any }) => void; /** Successfully reconnected a connection that dropped */ reconnected: (evt: { wsKey: WsKey; event: any; wsUrl: string; ws: WebSocket; }) => void; /** Connection closed */ close: (evt: { wsKey: WsKey; event: any }) => void; /** Received reply to websocket command (e.g. after subscribing to topics) */ response: (response: any & { wsKey: WsKey }) => void; /** Received data for topic */ update: (response: any & { wsKey: WsKey }) => void; /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ exception: (response: any & { wsKey: WsKey }) => void; error: (response: any & { wsKey: WsKey }) => void; /** Confirmation that a connection successfully authenticated */ authenticated: (event: { wsKey: WsKey; event: any }) => void; } ⋮---- /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ ⋮---- }) => void /** Reconnecting a dropped connection */; ⋮---- /** Successfully reconnected a connection that dropped */ ⋮---- /** Connection closed */ ⋮---- /** Received reply to websocket command (e.g. after subscribing to topics) */ ⋮---- /** Received data for topic */ ⋮---- /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ ⋮---- /** Confirmation that a connection successfully authenticated */ ⋮---- export interface EmittableEvent { eventType: 'response' | 'update' | 'exception' | 'authenticated'; event: TEvent; } ⋮---- // Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 export interface BaseWebsocketClient { on>( event: U, listener: WSClientEventMap[U], ): this; emit>( event: U, ...args: Parameters[U]> ): boolean; } ⋮---- on>( event: U, listener: WSClientEventMap[U], ): this; ⋮---- emit>( event: U, ...args: Parameters[U]> ): boolean; ⋮---- /** * Users can conveniently pass topics as strings or objects (object has topic name + optional params). * * This method normalises topics into objects (object has topic name + optional params). */ function getNormalisedTopicRequests( wsTopicRequests: WsTopicRequestOrStringTopic[], ): WsTopicRequest[] ⋮---- // passed as string, convert to object ⋮---- // already a normalised object, thanks to user ⋮---- /** * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" */ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export abstract class BaseWebsocketClient< ⋮---- /** * The WS connections supported by the client, each identified by a unique primary key */ ⋮---- /** * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected */ ⋮---- constructor( options?: WSClientConfigurableOptions, logger?: typeof DefaultLogger, ) ⋮---- // Some defaults: ⋮---- // Gate.io only has one connection (for both public & private). Auth works with every sub, not on connect, so this is turned off. ⋮---- // Gate.io requires auth to be added to every request, when subscribing to private topics. This is handled automatically. ⋮---- // Automatically re-auth WS API, if we were auth'd before and get reconnected ⋮---- // Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; ⋮---- protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; ⋮---- protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; ⋮---- protected abstract isWsPing(data: any): boolean; ⋮---- protected abstract isWsPong(data: any): boolean; ⋮---- protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; ⋮---- protected abstract isPrivateTopicRequest( request: WsTopicRequest, wsKey: TWSKey, ): boolean; ⋮---- protected abstract getPrivateWSKeys(): TWSKey[]; ⋮---- protected abstract getWsUrl(wsKey: TWSKey): string; ⋮---- protected abstract getMaxTopicsPerSubscribeEvent( wsKey: TWSKey, ): number | null; ⋮---- /** * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics */ protected abstract getWsOperationEventsForTopics( topics: WsTopicRequest[], wsKey: TWSKey, operation: WsOperation, ): Promise; ⋮---- /** * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ protected abstract resolveEmittableEvents( wsKey: TWSKey, event: MessageEventLike, ): EmittableEvent[]; ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ protected abstract connectAll(): Promise[]; ⋮---- protected isPrivateWsKey(wsKey: TWSKey): boolean ⋮---- /** Returns auto-incrementing request ID, used to track promise references for async requests */ protected getNewRequestId(): string ⋮---- protected abstract sendWSAPIRequest( wsKey: TWSKey, channel: string, params?: any, ): Promise; ⋮---- protected abstract sendWSAPIRequest( wsKey: TWSKey, channel: string, params: any, ): Promise; ⋮---- public getTimeOffsetMs() ⋮---- // TODO: not implemented public setTimeOffsetMs(newOffset: number) ⋮---- /** * Don't call directly! Use subscribe() instead! * * Subscribe to one or more topics on a WS connection (identified by WS Key). * * - Topics are automatically cached * - Connections are automatically opened, if not yet connected * - Authentication is automatically handled * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). * * @param wsRequests array of topics to subscribe to * @param wsKey ws key referring to the ws connection these topics should be subscribed on */ protected subscribeTopicsForWsKey( wsTopicRequests: WsTopicRequestOrStringTopic[], wsKey: TWSKey, ) ⋮---- // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect ⋮---- // Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. ⋮---- /** * Are we in the process of connection? Nothing to send yet. */ ⋮---- // We're connected. Check if auth is needed and if already authenticated ⋮---- /** * If not authenticated yet and auth is required, don't request topics yet. * * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. */ ⋮---- // Finally, request subscription to topics if the connection is healthy and ready ⋮---- protected unsubscribeTopicsForWsKey( wsTopicRequests: WsTopicRequestOrStringTopic[], wsKey: TWSKey, ) ⋮---- // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- // If not connected, don't need to do anything. // Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. ⋮---- // We're connected. Check if auth is needed and if already authenticated ⋮---- /** * If not authenticated yet and auth is required, don't need to do anything. * We don't subscribe to topics until auth is complete anyway. */ ⋮---- // Finally, request subscription to topics if the connection is healthy and ready ⋮---- /** * Splits topic requests into two groups, public & private topic requests */ private sortTopicRequestsIntoPublicPrivate( wsTopicRequests: WsTopicRequest[], wsKey: TWSKey, ): ⋮---- /** Get the WsStore that tracks websockets & topics */ public getWsStore(): WsStore> ⋮---- public close(wsKey: TWSKey, force?: boolean) ⋮---- public closeAll(force?: boolean) ⋮---- public isConnected(wsKey: TWSKey): boolean ⋮---- /** * Request connection to a specific websocket, instead of waiting for automatic connection. */ protected async connect( wsKey: TWSKey, ): Promise ⋮---- private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket ⋮---- private parseWsError(context: string, error: any, wsKey: TWSKey) ⋮---- /** Get a signature, build the auth request and send it */ private async sendAuthRequest(wsKey: TWSKey): Promise ⋮---- // console.log('ws auth req', request); ⋮---- private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) ⋮---- private ping(wsKey: TWSKey) ⋮---- private clearTimers(wsKey: TWSKey) ⋮---- // Send a ping at intervals private clearPingTimer(wsKey: TWSKey) ⋮---- // Expect a pong within a time limit private clearPongTimer(wsKey: TWSKey) ⋮---- // this.logger.trace(`Cleared pong timeout for "${wsKey}"`); ⋮---- // this.logger.trace(`No active pong timer for "${wsKey}"`); ⋮---- /** * Simply builds and sends subscribe events for a list of topics for a ws key * * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. */ private async requestSubscribeTopics( wsKey: TWSKey, topics: WsTopicRequest[], ) ⋮---- // Automatically splits requests into smaller batches, if needed ⋮---- `Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" ⋮---- // console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2)); ⋮---- // this.logger.trace(`Sending batch via message: "${wsMessage}"`); ⋮---- /** * Simply builds and sends unsubscribe events for a list of topics for a ws key * * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. */ private async requestUnsubscribeTopics( wsKey: TWSKey, wsTopicRequests: WsTopicRequest[], ) ⋮---- /** * Try sending a string event on a WS connection (identified by the WS Key) */ public tryWsSend( wsKey: TWSKey, wsMessage: string, throwExceptions?: boolean, ) ⋮---- private async onWsOpen( event: any, wsKey: TWSKey, url: string, ws: WebSocket, ) ⋮---- // Resolve & cleanup deferred "connection attempt in progress" promise ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // Remove before resolving, in case there's more requests queued ⋮---- // Some websockets require an auth packet to be sent after opening the connection ⋮---- // Reconnect to topics known before it connected ⋮---- // Request sub to public topics, if any ⋮---- // Request sub to private topics, if auth on connect isn't needed ⋮---- // If enabled, automatically reauth WS API if reconnected ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- /** * Handle subscription to private topics _after_ authentication successfully completes asynchronously. * * Only used for exchanges that require auth before sending private topic subscription requests */ private onWsAuthenticated( wsKey: TWSKey, event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, ) ⋮---- // Resolve & cleanup deferred "auth attempt in progress" promise ⋮---- // Remove before continuing, in case there's more requests queued ⋮---- private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) ⋮---- // any message can clear the pong timer - wouldn't get a message if the ws wasn't working ⋮---- // console.log(`raw event: `, { data, dataType, emittableEvents }); ⋮---- private onWsClose(event: unknown, wsKey: TWSKey) ⋮---- // unintentional close, attempt recovery ⋮---- // clean up any pending promises for this connection ⋮---- // intentional close - clean up // clean up any pending promises for this connection ⋮---- // clean up any pending promises for this connection ⋮---- // This was an intentional close, delete all state for this connection, as if it never existed: ⋮---- private getWs(wsKey: TWSKey) ⋮---- private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) ⋮---- /** * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) */ protected async assertIsConnected(wsKey: TWSKey): Promise ⋮---- // Already in progress? Await shared promise and retry ⋮---- // Start connection, it should automatically store/return a promise. ⋮---- /** * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) */ public async assertIsAuthenticated(wsKey: TWSKey): Promise ⋮---- // Already in progress? Await shared promise and retry ⋮---- // this.logger.trace('assertIsAuthenticated(): ok'); ⋮---- // Start authentication, it should automatically store/return a promise. ================ File: src/lib/logger.ts ================ export type LogParams = null | any; ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- // console.log(_params); ⋮---- export type DefaultLogger = typeof DefaultLogger; ================ File: src/lib/misc-util.ts ================ export function neverGuard(x: never, msg: string): Error ================ File: src/lib/requestUtils.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { GateBaseUrlKey } from '../types/shared.js'; ⋮---- export interface RestClientOptions { /** Your API key */ apiKey?: string; /** Your API secret */ apiSecret?: string; /** * Override the default/global max size of the request window (in ms) for signed api calls. * If you don't include a recv window when making an API call, this value will be used as default */ recvWindow?: number; /** Default: false. If true, we'll throw errors if any params are undefined */ strictParamValidation?: boolean; /** * Optionally override API protocol + domain * e.g baseUrl: 'https://api.gate.io' **/ baseUrl?: string; // manually override with one of the known base URLs in the library baseUrlKey?: GateBaseUrlKey; /** Default: true. whether to try and post-process request exceptions (and throw them). */ parseExceptions?: boolean; /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ keepAlive?: boolean; /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. * Only relevant if keepAlive is set to true. * Default: 1000 (defaults comes from https agent) */ keepAliveMsecs?: number; /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ customSignMessageFn?: (message: string, secret: string) => Promise; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** * Override the default/global max size of the request window (in ms) for signed api calls. * If you don't include a recv window when making an API call, this value will be used as default */ ⋮---- /** Default: false. If true, we'll throw errors if any params are undefined */ ⋮---- /** * Optionally override API protocol + domain * e.g baseUrl: 'https://api.gate.io' **/ ⋮---- // manually override with one of the known base URLs in the library ⋮---- /** Default: true. whether to try and post-process request exceptions (and throw them). */ ⋮---- /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ ⋮---- /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. * Only relevant if keepAlive is set to true. * Default: 1000 (defaults comes from https agent) */ ⋮---- /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ ⋮---- export function serializeParams | undefined = {}>( params: T, strict_validation: boolean | undefined, encodeValues: boolean, prefixWith: string, ): string ⋮---- // Only prefix if there's a value ⋮---- export function getRestBaseUrl(restClientOptions: RestClientOptions): string ⋮---- export interface MessageEventLike { target: WebSocket; type: 'message'; data: string; } ⋮---- export function isMessageEvent(msg: unknown): msg is MessageEventLike ================ File: src/lib/webCryptoAPI.ts ================ import { neverGuard } from './misc-util.js'; ⋮---- function bufferToB64(buffer: ArrayBuffer): string ⋮---- export type SignEncodeMethod = 'hex' | 'base64'; export type SignAlgorithm = 'SHA-256' | 'SHA-512'; ⋮---- /** * Similar to node crypto's `createHash()` function */ export async function hashMessage( message: string, method: SignEncodeMethod, algorithm: SignAlgorithm, ): Promise ⋮---- /** * Sign a message, with a secret, using the Web Crypto API */ export async function signMessage( message: string, secret: string, method: SignEncodeMethod, algorithm: SignAlgorithm, ): Promise ⋮---- export function checkWebCryptoAPISupported() ================ File: src/types/request/account.ts ================ /**========================================================================================================================== * ACCOUNT * ========================================================================================================================== */ ⋮---- export interface CreateStpGroupReq { name: string; id?: number; creator_id?: number; create_time?: number; } ================ File: src/types/request/collateralLoan.ts ================ /**========================================================================================================================== * COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface SubmitLoanOrderReq { collateral_amount: string; collateral_currency: string; borrow_amount: string; borrow_currency: string; } ⋮---- export interface GetLoanOrdersReq { page?: number; limit?: number; collateral_currency?: string; borrow_currency?: string; } ⋮---- export interface GetLoanRepaymentHistoryReq { source: 'repay' | 'liquidate'; borrow_currency?: string; collateral_currency?: string; page?: number; limit?: number; from?: number; to?: number; } ⋮---- export interface UpdateLoanCollateralReq { order_id: number; collateral_currency: string; collateral_amount: string; type: 'append' | 'redeem'; } ⋮---- export interface GetLoanCollateralRecordsReq { page?: number; limit?: number; from?: number; to?: number; borrow_currency?: string; collateral_currency?: string; } ================ File: src/types/request/delivery.ts ================ /**========================================================================================================================== * DELIVERY * ========================================================================================================================== */ ⋮---- export interface GetDeliveryOrderBookReq { settle: 'usdt'; contract: string; interval?: '0' | '0.1' | '0.01'; limit?: number; with_id?: boolean; } ⋮---- export interface GetDeliveryTradesReq { settle: 'usdt'; contract: string; limit?: number; last_id?: string; from?: number; to?: number; } ⋮---- export interface GetDeliveryCandlesReq { settle: 'usdt'; contract: string; from?: number; to?: number; limit?: number; interval?: | '10s' | '30s' | '1m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '8h' | '12h' | '1d' | '7d' | '1w' | '30d'; } ⋮---- export interface GetDeliveryBookReq { settle: 'usdt'; limit?: number; from?: number; to?: number; type?: | 'dnw' | 'pnl' | 'fee' | 'refr' | 'fund' | 'point_dnw' | 'point_fee' | 'point_refr' | 'bonus_offset'; } ⋮---- export interface SubmitDeliveryFuturesOrderReq { settle: 'usdt'; contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: string; text?: string; auto_size?: string; stp_act?: string; } ⋮---- export interface GetDeliveryOrdersReq { settle: 'usdt'; contract?: string; status: 'open' | 'finished'; limit?: number; offset?: number; last_id?: string; count_total?: 0 | 1; } ⋮---- export interface GetDeliveryTradingHistoryReq { settle: 'usdt'; contract?: string; order?: number; limit?: number; offset?: number; last_id?: string; count_total?: 0 | 1; } ⋮---- export interface GetDeliveryClosedPositionsReq { settle: 'usdt'; contract?: string; limit?: number; } ⋮---- export interface GetDeliveryLiquidationHistoryReq { settle: 'usdt'; contract?: string; limit?: number; at?: number; } ⋮---- export interface GetDeliverySettlementHistoryReq { settle: 'usdt'; contract?: string; limit?: number; at?: number; } export interface GetDeliveryAutoOrdersReq { settle: 'usdt'; status: 'open' | 'finished'; contract?: string; limit?: number; offset?: number; } ================ File: src/types/request/earn.ts ================ /**========================================================================================================================== * EARN * ========================================================================================================================== */ ⋮---- export interface GetStructuredProductListReq { status: string; type?: string; page?: number; limit?: number; } ⋮---- export interface GetStructuredProductOrdersReq { from?: number; to?: number; page?: number; limit?: number; } ================ File: src/types/request/earnuni.ts ================ /**========================================================================================================================== * EARN UNI * ========================================================================================================================== */ ⋮---- export interface SubmitLendOrRedeemReq { currency: string; amount: string; type: 'lend' | 'redeem'; min_rate?: string; } ⋮---- export interface GetLendingOrdersReq { currency?: string; page?: number; limit?: number; } ⋮---- export interface GetLendingRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; type?: 'lend' | 'redeem'; } ⋮---- export interface GetLendingInterestRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; } ================ File: src/types/request/flashswap.ts ================ /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== */ ⋮---- export interface SubmitFlashSwapOrderReq { preview_id: string; sell_currency: string; sell_amount: string; buy_currency: string; buy_amount: string; } ⋮---- export interface GetFlashSwapOrdersReq { status?: number; sell_currency?: string; buy_currency?: string; reverse?: boolean; limit?: number; page?: number; } ⋮---- export interface GetFlashSwapOrderReq { order_id: number; } ⋮---- export interface SubmitFlashSwapOrderPreviewReq { sell_currency: string; sell_amount?: string; buy_currency: string; buy_amount?: string; } ================ File: src/types/request/futures.ts ================ /**========================================================================================================================== * FUTURES * ========================================================================================================================== */ ⋮---- export interface GetFuturesOrderBookReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; interval?: string; limit?: number; with_id?: boolean; } ⋮---- export interface GetFuturesTradesReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; limit?: number; offset?: number; last_id?: string; from?: number; to?: number; } ⋮---- export interface GetFuturesCandlesReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; from?: number; to?: number; limit?: number; interval?: string; } ⋮---- export interface GetFuturesStatsReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; from?: number; interval?: string; limit?: number; } ⋮---- export interface GetFundingRatesReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; limit?: number; from?: number; to?: number; } ⋮---- export interface GetLiquidationHistoryReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; from?: number; to?: number; limit?: number; } ⋮---- export interface GetRiskLimitTiersReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; limit?: number; offset?: number; } ⋮---- export interface GetRiskLimitTableReq { settle: 'btc' | 'usdt' | 'usd'; table_id: string; } ⋮---- export interface GetFuturesAccountBookReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; offset?: number; from?: number; to?: number; type?: | 'dnw' | 'pnl' | 'fee' | 'refr' | 'fund' | 'point_dnw' | 'point_fee' | 'point_refr' | 'bonus_offset'; } ⋮---- export interface GetFuturesPositionsReq { settle: 'btc' | 'usdt' | 'usd'; holding?: boolean; limit?: number; 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 } ⋮---- 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: 'btc' | 'usdt' | 'usd'; contract: string; change: string; dual_side: 'dual_long' | 'dual_short'; } ⋮---- export interface UpdateDualModePositionLeverageReq { settle: 'btc' | 'usdt' | 'usd'; contract: string; leverage: string; cross_leverage_limit?: string; } ⋮---- export interface SubmitFuturesOrderReq { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: string; text?: string; auto_size?: string; stp_act?: string; } ⋮---- export interface GetFuturesOrdersReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; status: string; limit?: number; offset?: number; last_id?: string; } ⋮---- export interface DeleteAllFuturesOrdersReq { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; contract: string; side?: string; } ⋮---- export interface GetFuturesOrdersByTimeRangeReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface UpdateFuturesOrderReq { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; order_id: string; size?: number; price?: string; amend_text?: string; } ⋮---- export interface GetFuturesTradingHistoryReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; order?: number; limit?: number; offset?: number; last_id?: string; } ⋮---- export interface GetFuturesTradingHistoryByTimeRangeReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; from?: number; to?: number; limit?: number; offset?: number; role?: 'maker' | 'taker'; } ⋮---- export interface GetFuturesPositionHistoryReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; offset?: number; from?: number; to?: number; side?: 'long' | 'short'; pnl?: string; } ⋮---- export interface GetFuturesLiquidationHistoryReq { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; at?: number; } ⋮---- export interface SubmitFuturesTriggeredOrderReq { initial: { contract: string; size?: number; 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: 'btc' | 'usdt' | 'usd'; } ⋮---- 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: 'btc' | 'usdt' | 'usd'; 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: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- // v4.104.6: New GET /futures/{settle}/insurance endpoint request export interface GetFuturesInsuranceReq { settle: 'btc' | 'usdt' | 'usd'; limit?: number; } ⋮---- export interface UpdateFuturesPriceTriggeredOrderReq { settle: 'btc' | 'usdt' | 'usd'; order_id: string; contract?: string; size?: number; price?: string; 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 } ⋮---- price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price auto_size?: string; // Not required in single position mode ================ File: src/types/request/margin.ts ================ /**========================================================================================================================== * MARGIN * ========================================================================================================================== */ ⋮---- export interface GetMarginBalanceHistoryReq { currency?: string; currency_pair?: string; type?: string; from?: number; to?: number; page?: number; limit?: number; } ⋮---- export interface GetCrossMarginAccountHistoryReq { currency?: string; from?: number; to?: number; page?: number; limit?: number; type?: string; } ⋮---- export interface SubmitCrossMarginBorrowLoanReq { currency: string; amount: string; text?: string; } ⋮---- export interface GetCrossMarginBorrowHistoryReq { status: number; currency?: string; limit?: number; offset?: number; reverse?: boolean; } ⋮---- export interface GetCrossMarginRepaymentsReq { currency?: string; loan_id?: string; limit?: number; offset?: number; reverse?: boolean; } ⋮---- export interface GetCrossMarginInterestRecordsReq { currency?: string; page?: number; limit?: number; from?: number; to?: number; } ================ File: src/types/request/marginuni.ts ================ /**========================================================================================================================== * MARGIN UNI * ========================================================================================================================== */ ⋮---- export interface GetMarginUNILoansReq { currency_pair?: string; currency?: string; page?: number; limit?: number; } ⋮---- export interface GetMarginUNILoanRecordsReq { type?: 'borrow' | 'repay'; currency?: string; currency_pair?: string; page?: number; limit?: number; } ⋮---- export interface GetMarginUNIInterestRecordsReq { currency_pair?: string; currency?: string; page?: number; limit?: number; from?: number; to?: number; } ⋮---- export interface GetMarginUNIMaxBorrowReq { currency: string; currency_pair: string; } ================ File: src/types/request/multicollateralLoan.ts ================ /**========================================================================================================================== * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface SubmitMultiLoanOrderReq { order_id?: string; order_type?: string; fixed_type?: string; fixed_rate?: string; auto_renew?: boolean; auto_repay?: boolean; borrow_currency: string; borrow_amount: string; collateral_currencies?: { currency?: string; amount?: string; }[]; } export interface GetMultiLoanOrdersReq { page?: number; limit?: number; sort?: string; order_type?: string; } ⋮---- export interface RepayMultiLoanReq { order_id: number; repay_items: { currency?: string; amount?: string; repaid_all?: boolean; }[]; } ⋮---- export interface GetMultiLoanRepayRecordsReq { type: 'repay' | 'liquidate'; borrow_currency?: string; page?: number; limit?: number; from?: number; to?: number; } ⋮---- export interface UpdateMultiLoanReq { order_id: number; type: 'append' | 'redeem'; collaterals?: { currency?: string; amount?: string; }[]; } ⋮---- export interface GetMultiLoanAdjustmentRecordsReq { page?: number; limit?: number; from?: number; to?: number; collateral_currency?: string; } ================ File: src/types/request/options.ts ================ /**========================================================================================================================== * OPTIONS * ========================================================================================================================== */ export interface GetOptionsSettlementHistoryReq { underlying: string; limit?: number; offset?: number; from?: number; to?: number; } export interface GetOptionsMySettlementsReq { underlying: string; contract?: string; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface GetOptionsOrderBookReq { contract: string; interval?: '0' | '0.1' | '0.01'; limit?: number; with_id?: boolean; } ⋮---- export interface GetOptionsCandlesReq { contract: string; limit?: number; from?: number; to?: number; interval?: '1m' | '5m' | '15m' | '30m' | '1h'; } ⋮---- export interface GetOptionsUnderlyingCandlesReq { underlying: string; limit?: number; from?: number; to?: number; interval?: '1m' | '5m' | '15m' | '30m' | '1h'; } ⋮---- export interface GetOptionsTradesReq { contract?: string; type?: 'C' | 'P'; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface GetOptionsAccountChangeReq { limit?: number; offset?: number; from?: number; to?: number; type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; } ⋮---- export interface SubmitOptionsOrderReq { contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: 'gtc' | 'ioc' | 'poc'; text?: string; } ⋮---- export interface GetOptionsOrdersReq { contract?: string; underlying?: string; status: 'open' | 'finished'; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface GetOptionsPersonalHistoryReq { underlying: string; contract?: string; limit?: number; offset?: number; from?: number; to?: number; } ⋮---- export interface OptionsMMPSettingsReq { underlying: string; window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) } ⋮---- window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) ================ File: src/types/request/rebate.ts ================ export interface GetAgencyTransactionHistoryReq { currency_pair?: string; user_id?: number; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface GetAgencyCommissionHistoryReq { currency?: string; user_id?: number; from?: number; to?: number; limit?: number; offset?: number; } ⋮---- export interface GetPartnerSubordinateListReq { user_id?: number; limit?: number; offset?: number; } ⋮---- export interface GetBrokerCommissionHistoryReq { limit?: number; offset?: number; user_id?: number; from?: number; to?: number; } ⋮---- export interface GetBrokerTransactionHistoryReq { limit?: number; offset?: number; user_id?: number; from?: number; to?: number; } ⋮---- // Interfaces for request and response export interface PartnerTransactionReq { currency_pair?: string; user_id?: number; from?: number; to?: number; limit?: number; offset?: number; } ================ File: src/types/request/spot.ts ================ /**========================================================================================================================== * SPOT * ========================================================================================================================== */ ⋮---- 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; type?: string; code?: string; } ⋮---- 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; } ⋮---- 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?: string; take_profit?: string; post_only?: boolean; } ⋮---- 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'; } ================ File: src/types/request/subaccount.ts ================ export interface CreateSubAccountReq { login_name: string; remark?: string; password?: string; email?: string; } ⋮---- export interface CreateSubAccountApiKeyReq { user_id: number; mode?: number; // Mode: 1 - classic, 2 - portfolio account name?: string; // API key name perms?: { name?: | 'wallet' | 'spot' | 'futures' | 'delivery' | 'earn' | 'options' | 'account' | 'unified' | 'loan'; // Permission name read_only?: boolean; // Read only }[]; ip_whitelist?: string[]; // IP white list } ⋮---- mode?: number; // Mode: 1 - classic, 2 - portfolio account name?: string; // API key name ⋮---- | 'loan'; // Permission name read_only?: boolean; // Read only ⋮---- ip_whitelist?: string[]; // IP white list ⋮---- export type UpdateSubAccountApiKeyReq = { key: string; } & CreateSubAccountApiKeyReq; ================ File: src/types/request/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[]; } ================ File: src/types/request/wallet.ts ================ 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; chain?: string; limit?: string; page?: number; } ⋮---- 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'; } ================ File: src/types/request/withdrawal.ts ================ /**================================================================================================================================ * WITHDRAW * ========================================================================================================================== */ ⋮---- export interface SubmitWithdrawalReq { amount: string; currency: string; chain: string; withdraw_order_id?: string; address?: string; memo?: string; } ================ File: src/types/response/account.ts ================ /**========================================================================================================================== * ACCOUNT * ========================================================================================================================== */ ⋮---- export interface AccountDetail { user_id: number; ip_whitelist: string[]; currency_pairs: string[]; key: { mode: number; }; tier: number; copy_trading_role: number; } ⋮---- export interface AccountRateLimit { type: string; tier: string; ratio: string; main_ratio: string; updated_at: string; } ⋮---- export interface StpGroup { id: number; name: string; creator_id: number; create_time: number; } ⋮---- export interface StpGroupUser { user_id: number; stp_id: number; create_time: number; } ⋮---- export interface AccountMainKey { state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified name: string; currency_pairs: string[]; user_id: number; ip_whitelist: string[]; perms: { name: string; read_only: boolean; }[]; key: string; created_at: string; updated_at: string; last_access: string; } ⋮---- state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified ================ File: src/types/response/collateralloan.ts ================ /**========================================================================================================================== * COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface LoanOrder { order_id: number; collateral_currency: string; collateral_amount: string; borrow_currency: string; borrow_amount: string; repaid_amount: string; repaid_principal: string; repaid_interest: string; init_ltv: string; current_ltv: string; liquidate_ltv: string; status: string; borrow_time: number; left_repay_total: string; left_repay_principal: string; left_repay_interest: string; } ⋮---- export interface LoanRepaymentHistoryRecord { order_id: number; record_id: number; repaid_amount: string; borrow_currency: string; collateral_currency: string; init_ltv: string; borrow_time: number; repay_time: number; total_interest: string; before_left_principal: string; after_left_principal: string; before_left_collateral: string; after_left_collateral: string; } ⋮---- export interface LoanCollateralRecord { order_id: number; record_id: number; borrow_currency: string; borrow_amount: string; collateral_currency: string; before_collateral: string; after_collateral: string; before_ltv: string; after_ltv: string; operate_time: number; } ⋮---- export interface LoanCollateralRatio { collateral_currency: string; borrow_currency: string; init_ltv: string; alert_ltv: string; liquidate_ltv: string; min_borrow_amount: string; left_borrowable_amount: string; } ================ File: src/types/response/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; } ⋮---- 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; basis_rate: string; basis_value: string; lowest_ask: string; highest_bid: string; } ⋮---- export interface DeliveryAccount { 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; }; enable_tiered_mm: boolean; } ⋮---- 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/earn.ts ================ /**========================================================================================================================== * EARN * ========================================================================================================================== */ ⋮---- export interface DualInvestmentProduct { id: number; instrument_name: string; invest_currency: string; exercise_currency: string; exercise_price: number; delivery_time: number; min_copies: number; max_copies: number; per_value: string; apy_display: string; start_time: number; end_time: number; status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; } ⋮---- 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 interface StructuredProduct { id: number; type: string; name_en: string; investment_coin: string; investment_period: string; min_annual_rate: string; mid_annual_rate: string; max_annual_rate: string; watch_market: string; start_time: number; end_time: number; status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; } ⋮---- export interface StructuredProductOrder { id: number; pid: string; lock_coin: string; amount: string; status: 'SUCCESS' | 'FAILED' | 'DONE'; income: string; create_time: number; } ================ File: src/types/response/earnuni.ts ================ /**========================================================================================================================== * EARN UNI * ========================================================================================================================== */ ⋮---- export interface LendingCurrency { currency: string; min_lend_amount: string; max_lend_amount: string; max_rate: string; min_rate: string; } ⋮---- export interface LendingOrder { currency: string; current_amount: string; amount: string; lent_amount: string; frozen_amount: string; min_rate: string; interest_status: string; reinvest_left_amount: string; create_time: number; update_time: number; } ⋮---- export interface LendingRecord { currency: string; amount: string; last_wallet_amount: string; last_lent_amount: string; last_frozen_amount: string; type: 'lend' | 'redeem'; create_time: number; } ⋮---- export interface LendingInterestRecord { status: number; currency: string; actual_rate: string; interest: string; interest_status: string; create_time: number; } ================ File: src/types/response/flashswap.ts ================ /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== */ ⋮---- export interface FlashSwapCurrencyPair { currency_pair: string; sell_currency: string; buy_currency: string; sell_min_amount: string; sell_max_amount: string; buy_min_amount: string; buy_max_amount: string; } ⋮---- export interface FlashSwapOrder { id: number; create_time: number; user_id: number; sell_currency: string; sell_amount: string; buy_currency: string; buy_amount: string; price: string; status: number; } ⋮---- export interface SubmitFlashSwapOrderPreviewResp { preview_id: string; sell_currency: string; sell_amount: string; buy_currency: string; buy_amount: string; price: string; } ================ File: src/types/response/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; } ⋮---- 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; basis_rate: string; basis_value: string; lowest_ask: string; highest_bid: string; lowest_size: string; highest_size: string; } ⋮---- export interface FuturesStats { time: number; lsr_taker: number; lsr_account: number; long_liq_size: number; long_liq_amount: number; long_liq_usd: number; short_liq_size: number; short_liq_amount: number; short_liq_usd: number; open_interest: number; open_interest_usd: number; top_lsr_account: number; top_lsr_size: 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; leverage_max: string; contract: string; } ⋮---- export interface FuturesAccount { 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; cross_margin_balance: string; cross_mmr: string; cross_imr: string; isolated_position_margin: string; enable_new_dual_mode: boolean; margin_mode: number; 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; } ⋮---- export interface FuturesAccountBookRecord { time: number; change: string; balance: string; type: string; text: string; contract?: string; trade_id: string; id: string; } ⋮---- export interface FuturesOrder { id?: number; user?: number; create_time?: number; finish_time?: number; finish_as?: | 'filled' | 'cancelled' | 'liquidated' | 'ioc' | '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; } ⋮---- export interface FuturesPosition { user?: number; contract?: string; size?: number; leverage?: string; risk_limit?: string; leverage_max?: string; maintenance_rate?: string; value?: string; margin?: string; entry_price?: string; liq_price?: string; liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management mark_price?: string; initial_margin?: string; maintenance_margin?: string; unrealised_pnl?: string; realised_pnl?: string; pnl_pnl?: string; pnl_fund?: string; pnl_fee?: string; history_pnl?: string; 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; 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 } ⋮---- liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management ⋮---- settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support isolated_margin?: string; // v4.104.6: Add isolated_margin field ⋮---- 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; cross_leverage_limit: string; entry_price: string; fill_price: string; trade_size: number; position_size: number; } ⋮---- export interface DeleteFuturesBatchOrdersResp { user_id: number; id: string; succeeded: boolean; message: string; } ⋮---- export interface FuturesContract { name?: string; type?: 'inverse' | 'direct'; quanto_multiplier?: string; leverage_min?: string; leverage_max?: string; maintenance_rate?: string; mark_type?: 'internal' | 'index'; 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; funding_rate?: string; funding_interval?: number; funding_next_apply?: 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; enable_bonus?: boolean; enable_credit?: boolean; create_time?: number; funding_cap_ratio?: string; } ⋮---- 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; 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; } ⋮---- export interface FuturesDeliveryContract { name?: string; underlying?: string; cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; type?: 'inverse' | 'direct'; quanto_multiplier?: string; leverage_min?: string; leverage_max?: string; maintenance_rate?: string; mark_type?: 'internal' | 'index'; 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; 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; } ⋮---- export interface BatchAmendOrderResp { succeeded: boolean; label?: string; detail?: string; id: number; user: number; create_time: number; finish_time?: number; finish_as?: | 'filled' | 'cancelled' | 'liquidated' | 'ioc' | '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; } ⋮---- /** * @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; leverage_max: string; deduction: string; } ⋮---- // v4.104.6: New GET /futures/{settle}/insurance endpoint types export interface FuturesInsuranceHistory { t: number; b: 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; leverage: string; locked: boolean; risk?: string; mmr?: string; base: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; quote: { currency: string; available: string; locked: string; borrowed: string; interest: 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; } ⋮---- export interface MarginUNILoan { currency: string; currency_pair: string; amount: string; type: string; create_time: number; update_time: number; } ⋮---- 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; create_time: number; } ⋮---- export interface MarginUNIMaxBorrowable { currency: string; currency_pair: string; borrowable: string; } ================ File: src/types/response/multicollateralLoan.ts ================ /**========================================================================================================================== * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- export interface MultiLoanOrder { order_id: string; order_type: string; fixed_type: string; fixed_rate: string; expire_time: number; auto_renew: boolean; auto_repay: boolean; current_ltv: string; status: string; borrow_time: number; total_left_repay_usdt: string; total_left_collateral_usdt: string; borrow_currencies: { currency: string; index_price: string; left_repay_principal: string; left_repay_interest: string; left_repay_usdt: string; }[]; collateral_currencies: { currency: string; index_price: string; left_collateral: string; left_collateral_usdt: string; }[]; } ⋮---- export interface RepayMultiLoanResp { order_id: number; repaid_currencies: { succeeded: boolean; label?: string; message?: string; currency: string; repaid_principal: string; repaid_interest: string; }[]; } ⋮---- export interface MultiLoanRepayRecord { order_id: number; record_id: number; init_ltv: string; before_ltv: string; after_ltv: string; borrow_time: number; repay_time: number; borrow_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; collateral_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; repaid_currencies: { currency: string; index_price: string; repaid_amount: string; repaid_principal: string; repaid_interest: string; repaid_amount_usdt: string; }[]; total_interest_list: { currency: string; index_price: string; amount: string; amount_usdt: string; }[]; left_repay_interest_list: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; } ⋮---- export interface UpdateMultiLoanResp { order_id: number; collateral_currencies: { succeeded: boolean; label?: string; message?: string; currency: string; amount: string; }[]; } ⋮---- export interface MultiLoanAdjustmentRecord { order_id: number; record_id: number; before_ltv: string; after_ltv: string; operate_time: number; borrow_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; collateral_currencies: { currency: string; index_price: string; before_amount: string; before_amount_usdt: string; after_amount: string; after_amount_usdt: string; }[]; } ⋮---- export interface MultiLoanCurrencyQuota { currency: string; index_price: string; min_quota: string; left_quota: string; left_quote_usdt: string; } ⋮---- export interface MultiLoanSupportedCurrencies { loan_currencies: { currency: string; price: string; }[]; collateral_currencies: { currency: string; index_price: string; discount: string; }[]; } ⋮---- export interface MultiLoanRatio { init_ltv: string; alert_ltv: string; liquidate_ltv: string; } ⋮---- export interface MultiLoanFixedRate { currency: string; rate_7d: string; rate_30d: string; update_time: number; } ================ File: src/types/response/options.ts ================ /**========================================================================================================================== * OPTIONS * ========================================================================================================================== */ ⋮---- export interface OptionsContract { name: string; tag: string; create_time: number; expiration_time: number; is_call: boolean; strike_price: string; last_price: string; mark_price: string; orderbook_id: number; trade_id: number; trade_size: number; position_size: number; underlying: string; underlying_price: string; multiplier: string; order_price_round: string; mark_price_round: string; 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; order_size_min: number; order_size_max: number; orders_limit: number; } ⋮---- 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; delta: string; gamma: string; vega: string; theta: string; rho: string; } ⋮---- 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; } ⋮---- export interface OptionsAccount { user: number; total: string; short_enabled: boolean; unrealised_pnl: string; init_margin: string; maint_margin: string; order_margin: string; available: string; point: string; currency: string; } 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; 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; } ⋮---- 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; role: 'taker' | 'maker'; } ⋮---- export interface OptionsMMPSettings { underlying: string; window: number; frozen_period: number; qty_limit: string; delta_limit: string; trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered } ⋮---- trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered ================ File: src/types/response/rebate.ts ================ export interface AgencyTransactionHistoryRecord { transaction_time: number; user_id: number; group_name: string; fee: string; fee_asset: string; currency_pair: string; amount: string; amount_asset: string; source: string; } ⋮---- export interface AgencyCommissionHistoryRecord { commission_time: number; user_id: number; group_name: string; commission_amount: string; commission_asset: string; source: string; } ⋮---- export interface PartnerSubordinate { user_id: number; user_join_time: number; type: number; desc: string; } ⋮---- export interface BrokerCommissionHistoryRecord { commission_time: number; user_id: number; group_name: string; amount: string; fee: string; fee_asset: string; rebate_fee: string; source: string; currency_pair: string; sub_broker_info: { user_id: number; original_commission_rate: string; relative_commission_rate: string; commission_rate: string; }; } ⋮---- export interface BrokerTransactionHistoryRecord { transaction_time: number; user_id: number; group_name: string; fee: string; currency_pair: string; amount: string; fee_asset: string; source: string; sub_broker_info: { user_id: number; original_commission_rate: string; relative_commission_rate: string; commission_rate: string; }; } ⋮---- export interface PartnerCommission { commission_time: number; user_id: number; group_name: string; commission_amount: string; commission_asset: string; source: string; } ⋮---- export interface PartnerTransaction { transaction_time: number; user_id: number; group_name: string; fee: string; fee_asset: string; currency_pair: string; amount: string; amount_asset: string; source: string; } ================ File: src/types/response/spot.ts ================ /**========================================================================================================================== * SPOT * ========================================================================================================================== */ 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[]; } ⋮---- 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; } ⋮---- 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; maker_fee: string; 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 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' | '-'; finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; } ⋮---- 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' | '-'; finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- 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; } ================ File: src/types/response/subaccount.ts ================ export interface SubAccount { remark?: string; login_name: string; password?: string; email?: string; state: number; type: number; user_id: number; create_time: number; } ⋮---- export interface CreatedSubAccountAPIKey { user_id: string; mode?: number; name?: string; perms?: { name?: | 'wallet' | 'spot' | 'futures' | 'delivery' | 'earn' | 'options' | 'account' | 'unified' | 'loan'; read_only?: boolean; }[]; ip_whitelist?: string[]; key: string; state: number; created_at: number; updated_at: number; last_access: number; } ⋮---- export interface SubAccountAPIKey { user_id?: string; mode?: number; name?: string; perms?: { name?: | 'wallet' | 'spot' | 'futures' | 'delivery' | 'earn' | 'options' | 'account' | 'unified' | 'loan'; read_only?: boolean; }[]; ip_whitelist?: string[]; key?: string; state?: number; created_at?: number; updated_at?: number; last_access?: number; } ⋮---- export interface SubAccountMode { user_id: number; is_unified: boolean; mode: 'classic' | 'multi_currency' | 'portfolio'; } ================ File: src/types/response/unified.ts ================ export interface UnifiedAccountInfo { user_id: number; refresh_time: number; locked: boolean; balances: { [key: string]: { available: string; freeze: string; borrowed: string; negative_liab: string; futures_pos_liab: string; equity: string; total_freeze: string; total_liab: string; spot_in_use: string; funding: string; funding_version: string; cross_balance: string; iso_balance: string; im: string; mm: string; mmr: string; margin_balance: string; available_margin: string; imr?: string; enabled_collateral?: boolean; }; }; total: string; borrowed: 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; unified_account_total: string; unified_account_total_liab: string; unified_account_total_equity: string; leverage: string; spot_order_loss: string; spot_hedge: boolean; margin_mode?: string; total_balance?: string; cross_leverage?: string; portfolio_margin?: string; risk_level?: string; is_all_collateral?: boolean; borrow_amount?: string; cross_margin_leverage?: string; use_funding?: boolean; } ⋮---- 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; } ================ 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 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; } ⋮---- | '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 ⋮---- export interface CreateDepositAddressResp { currency: string; address: string; multichain_addresses: { chain: string; address: string; payment_id: string; payment_name: string; obtain_failed: number; }[]; } ⋮---- export interface SubAccountTransferRecord { currency: string; sub_account: string; direction: 'to' | 'from'; amount: string; uid: string; client_order_id: string; timest: string; source: string; sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- export interface WithdrawalStatus { currency: string; name: string; name_cn: string; deposit: string; withdraw_percent: string; withdraw_fix: string; withdraw_day_limit: string; withdraw_amount_mini: string; withdraw_day_limit_remain: string; withdraw_eachtime_limit: string; withdraw_fix_on_chains: { [key: string]: string }; withdraw_percent_on_chains: { [key: string]: string }; } ⋮---- export interface SubAccountMarginBalance { currency_pair: string; locked: boolean; risk: string; base: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; quote: { currency: string; available: string; locked: string; borrowed: string; interest: string; }; } ⋮---- export interface SubAccountFuturesBalancesResp { uid: string; available: { [key: string]: { total: string; unrealised_pnl: string; position_margin: string; order_margin: string; available: string; point: string; currency: string; in_dual_mode: boolean; enable_credit: boolean; position_initial_margin: string; maintenance_margin: string; bonus: string; enable_evolved_classic: boolean; cross_order_margin: string; cross_initial_margin: string; cross_maintenance_margin: string; cross_unrealised_pnl: string; cross_available: string; isolated_position_margin: string; history: { dnw: string; pnl: string; fee: string; refr: string; fund: string; point_dnw: string; point_fee: string; point_refr: string; bonus_dnw: string; bonus_offset: string; }; }; }; } ⋮---- export interface SubAccountCrossMarginBalancesResp { uid: string; available: { user_id: number; locked: boolean; balances: { [key: string]: { available: string; freeze: string; borrowed: string; interest: string; }; }; total: string; borrowed: string; borrowed_net: string; net: string; leverage: string; interest: string; risk: string; total_initial_margin: string; total_margin_balance: string; total_maintenance_margin: string; total_initial_margin_rate: string; total_maintenance_margin_rate: string; total_available_margin: string; }; } ⋮---- export interface SavedAddress { currency: string; chain: string; address: string; name: string; tag: string; verified: string; } ⋮---- export interface TradingFees { user_id: number; taker_fee: string; maker_fee: string; gt_discount: boolean; gt_taker_fee: string; gt_maker_fee: string; loan_fee: string; point_type: string; futures_taker_fee: string; futures_maker_fee: string; delivery_taker_fee: string; delivery_maker_fee: string; debit_fee: number; } ⋮---- export interface GetBalancesResp { total: { amount: string; currency: string; unrealised_pnl?: string; borrowed?: string; }; details: { [key: string]: { amount: string; currency: string; unrealised_pnl?: string; borrowed?: string; }; }; } ⋮---- export interface SmallBalanceRecord { currency: string; available_balance: string; estimated_as_btc: string; convertible_to_gt: string; } ⋮---- export interface SmallBalanceHistoryRecord { id: string; currency: string; amount: string; gt_amount: string; create_time: number; } ⋮---- export interface PushOrder { id: number; push_uid: number; receive_uid: number; currency: string; amount: string; create_time: number; status: | 'CREATING' | 'PENDING' | 'CANCELLING' | 'CANCELLED' | 'REFUSING' | 'REFUSED' | 'RECEIVING' | 'RECEIVED'; message: string; } ================ File: src/types/response/withdrawal.ts ================ export interface WithdrawalRecord { id: string; txid: string; block_number: string; withdraw_order_id: string; 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 (Only considered truly on-chain when block_number > 0) | '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; } ⋮---- | 'BCODE' // Deposit Code Operation | 'CANCEL' // Cancelled | 'CANCELPEND' // Withdrawal Cancellation Pending | 'DMOVE' // Pending Manual Review | 'DONE' // Completed (Only considered truly on-chain when block_number > 0) | 'EXTPEND' // Sent and Waiting for Confirmation | 'FAIL' // On-Chain Failure Pending Confirmation | 'FVERIFY' // Facial Verification in Progress | 'INVALID' // Invalid Transaction | 'LOCKED' // Wallet-Side Order Locked | 'MANUAL' // Pending Manual Review | 'PEND' // Processing | 'PROCES' // Processing | 'REJECT' // Rejected | 'REQUEST' // Request in Progress | 'REVIEW' // Under Review | 'SPLITPEND' // Split Pending | 'VERIFY'; // Verification in Progress ================ File: src/types/websockets/client.ts ================ /** * Event args for subscribing/unsubscribing */ ⋮---- // export type WsTopicSubscribePrivateArgsV2 = // | WsTopicSubscribePrivateInstIdArgsV2 // | WsTopicSubscribePrivateCoinArgsV2; ⋮---- // export type WsTopicSubscribeEventArgsV2 = // | WsTopicSubscribePublicArgsV2 // | WsTopicSubscribePrivateArgsV2; ⋮---- /** General configuration for the WebsocketClient */ export interface WSClientConfigurableOptions { /** Your API key */ apiKey?: string; /** Your API secret */ apiSecret?: string; useTestnet?: boolean; /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ recvWindow?: number; /** How often to check if the connection is alive */ pingInterval?: number; /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ pongTimeout?: number; /** Delay in milliseconds before respawning the connection */ reconnectTimeout?: number; requestOptions?: {}; wsUrl?: string; /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ customSignMessageFn?: (message: string, secret: string) => Promise; /** * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. */ reauthWSAPIOnReconnect?: boolean; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- /** How often to check if the connection is alive */ ⋮---- /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- /** Delay in milliseconds before respawning the connection */ ⋮---- /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ ⋮---- /** * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. */ ⋮---- /** * WS configuration that's always defined, regardless of user configuration * (usually comes from defaults if there's no user-provided values) */ export interface WebsocketClientOptions extends WSClientConfigurableOptions { pingInterval: number; pongTimeout: number; reconnectTimeout: number; recvWindow: number; authPrivateConnectionsOnConnect: boolean; authPrivateRequests: boolean; reauthWSAPIOnReconnect: boolean; } ================ File: src/types/websockets/events.ts ================ export interface WsDataEvent { data: TData; table: string; wsKey: TWSKey; } ================ File: src/types/websockets/requests.ts ================ import { CHANNEL_ID } from '../../lib/requestUtils.js'; import { WSAPITopic } from './wsAPI.js'; ⋮---- export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; ⋮---- export interface WsRequestAuthGate { method: 'api_key'; KEY: string; SIGN: string; } ⋮---- export interface WsRequestPing { time: number; channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; } ⋮---- export interface WsRequestOperationGate< TWSTopic extends string, TWSPayload = any, > { time: number; id?: number; channel: TWSTopic; auth?: WsRequestAuthGate; event?: WsOperation; payload?: TWSPayload; } ⋮---- export interface WSAPIRequest< TRequestParams = any, TWSChannel extends WSAPITopic = any, > { time: number; id?: number; channel: TWSChannel; event: 'api'; payload: { req_id: string; req_param?: TRequestParams | string; req_header: { 'X-Gate-Channel-Id': typeof CHANNEL_ID; }; api_key?: string; signature?: string; timestamp?: string; }; } ================ File: src/types/websockets/wsAPI.ts ================ import { WsKey } from '../../lib/websocket/websocket-util.js'; ⋮---- export type SpotWSAPITopic = | 'spot.login' | 'spot.order_place' | 'spot.order_cancel' | 'spot.order_cancel_ids' | 'spot.order_cancel_cp' | 'spot.order_amend' | 'spot.order_status' | 'spot.order_list'; ⋮---- export type FuturesWSAPITopic = | 'futures.login' | 'futures.order_place' | 'futures.order_batch_place' | 'futures.order_cancel' | 'futures.order_cancel_cp' | 'futures.order_amend' | 'futures.order_list' | 'futures.order_status' | 'futures.order_cancel_ids'; ⋮---- export interface WsAPIWsKeyTopicMap { spotV4: SpotWSAPITopic; perpFuturesUSDTV4: FuturesWSAPITopic; perpFuturesBTCV4: FuturesWSAPITopic; deliveryFuturesUSDTV4: FuturesWSAPITopic; deliveryFuturesBTCV4: FuturesWSAPITopic; // optionsV4: never; // announcementsV4: never; } ⋮---- // optionsV4: never; // announcementsV4: never; ⋮---- export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; ⋮---- // ==================================== // Spot WebSocket API Request Types // ==================================== ⋮---- export interface WSAPISpotOrderPlaceReq { text?: string; currency_pair: string; type?: 'limit' | 'market'; account?: 'spot' | 'margin' | 'unified' | 'cross_margin'; side: 'buy' | 'sell'; amount: string; price?: string; time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; iceberg?: string; auto_borrow?: boolean; auto_repay?: boolean; stp_act?: 'cn' | 'co' | 'cb'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- export interface WSAPISpotOrderCancelReq { order_id: string; currency_pair: string; account?: string; } ⋮---- export interface WSAPISpotOrderCancelIdsReq { currency_pair: string; id: string; account?: string; } ⋮---- export interface WSAPISpotOrderCancelCPReq { currency_pair: string; side?: 'buy' | 'sell'; account?: string; } ⋮---- export interface WSAPISpotOrderAmendReq { amount?: string; price?: string; amend_text?: string; order_id: string; currency_pair: string; account?: string; } ⋮---- export interface WSAPISpotOrderStatusReq { order_id: string; currency_pair: string; account?: string; } ⋮---- export interface WSAPISpotOrderListReq { currency_pair: string; status: 'open' | 'finished'; page?: number; limit?: number; account?: string; from?: number; to?: number; side?: 'buy' | 'sell'; } ⋮---- // ==================================== // Futures WebSocket API Request Types // ==================================== ⋮---- export interface WSAPIFuturesOrderPlaceReq { contract: string; size: number; iceberg?: number; price?: string; close?: boolean; reduce_only?: boolean; tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; text?: string; auto_size?: 'close_long' | 'close_short'; stp_act?: 'cn' | 'co' | 'cb'; } ⋮---- export interface WSAPIFuturesOrderCancelReq { order_id: string; } ⋮---- export interface WSAPIFuturesOrderCancelCPReq { contract: string; side?: 'bid' | 'ask'; } ⋮---- export interface WSAPIFuturesOrderAmendReq { order_id: string; price?: string; size?: number; amend_text?: string; } ⋮---- export interface WSAPIFuturesOrderListReq { contract: string; status: 'open' | 'finished'; limit?: number; offset?: number; last_id?: string; count_total?: number; } ⋮---- export interface WSAPIFuturesOrderStatusReq { order_id: string; } ⋮---- // ==================================== // Spot WebSocket API Response Types // ==================================== ⋮---- export interface WSAPISpotOrder { id: string; text: string; amend_text: string; create_time: string; update_time: string; create_time_ms: number; update_time_ms: number; status: string; currency_pair: string; type: string; account: string; side: string; amount: string; price: string; time_in_force: string; iceberg: string; left: string; fill_price?: string; filled_amount?: string; filled_total: string; avg_deal_price?: string; fee: string; fee_currency: string; point_fee: string; gt_fee: string; gt_maker_fee?: string; gt_taker_fee?: string; gt_discount?: boolean; rebated_fee: string; rebated_fee_currency: string; stp_id?: number; stp_act?: string; finish_as: string; } ⋮---- export interface WSAPISpotOrderCancelIdsRespItem { currency_pair: string; id: string; succeeded: boolean; } ⋮---- // ==================================== // Futures WebSocket API Response Types // ==================================== ⋮---- export interface WSAPIFuturesOrder { id: number; user: number; create_time: number; finish_time?: number; update_time?: number; finish_as?: string; status: string; contract: string; size: number; price: string; tif: string; left?: number; fill_price: string; text: string; tkfr: string; mkfr: string; stp_id?: number; stp_act?: string; amend_text?: string; } ⋮---- export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { succeeded: boolean; } ⋮---- export interface WSAPIFuturesOrderCancelIdsRespItem { id: string; user_id: number; succeeded?: boolean; message?: string; } ⋮---- // ==================================== // Request Parameter Mapping // ==================================== ⋮---- export interface WsAPITopicRequestParamMap { 'spot.login': undefined; 'futures.login': undefined; 'spot.order_place': WSAPISpotOrderPlaceReq; 'spot.order_cancel': WSAPISpotOrderCancelReq; 'spot.order_cancel_ids': WSAPISpotOrderCancelIdsReq[]; 'spot.order_cancel_cp': WSAPISpotOrderCancelCPReq; 'spot.order_amend': WSAPISpotOrderAmendReq; 'spot.order_status': WSAPISpotOrderStatusReq; 'spot.order_list': WSAPISpotOrderListReq; 'futures.order_place': WSAPIFuturesOrderPlaceReq; 'futures.order_batch_place': WSAPIFuturesOrderPlaceReq[]; 'futures.order_cancel': WSAPIFuturesOrderCancelReq; 'futures.order_cancel_ids': string[]; 'futures.order_cancel_cp': WSAPIFuturesOrderCancelCPReq; 'futures.order_amend': WSAPIFuturesOrderAmendReq; 'futures.order_list': WSAPIFuturesOrderListReq; 'futures.order_status': WSAPIFuturesOrderStatusReq; } ⋮---- export type WsAPITopicRequestParams = WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; ⋮---- // ==================================== // Response Headers and Base Response // ==================================== ⋮---- export interface WSAPIResponseHeader { /** String timestamp as ms */ response_time: string; /** Status of WS API call. "200" if successful, else exception is thrown */ status: '200' | string; channel: TChannel; event: 'api'; client_id: string; } ⋮---- /** String timestamp as ms */ ⋮---- /** Status of WS API call. "200" if successful, else exception is thrown */ ⋮---- export interface WSAPILoginResponse { api_key: string; uid: string; } ⋮---- export interface WSAPIOrderStatusResponse { left: string; update_time: string; amount: string; create_time: string; price: string; finish_as: string; time_in_force: string; currency_pair: string; type: string; account: string; side: string; amend_text: string; text: string; status: string; iceberg: string; avg_deal_price: string; filled_total: string; id: string; fill_price: string; update_time_ms: number; create_time_ms: number; } ⋮---- export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; ⋮---- export interface WSAPIResponse< TResponseData extends object = WSAPIResponseData | object, TChannel extends WSAPITopic = WSAPITopic, > { wsKey: WsKey; header: WSAPIResponseHeader; data: { result: TResponseData; }; /** Auto-generated */ request_id: string; } ⋮---- /** Auto-generated */ ⋮---- // ==================================== // Response Type Mapping // ==================================== ⋮---- export interface WsAPITopicResponseMap { 'spot.login': WSAPIResponse; 'futures.login': WSAPIResponse; 'spot.order_place': WSAPIResponse; 'spot.order_cancel': WSAPIResponse; 'spot.order_cancel_ids': WSAPIResponse< WSAPISpotOrderCancelIdsRespItem[], 'spot.order_cancel_ids' >; 'spot.order_cancel_cp': WSAPIResponse< WSAPISpotOrder[], 'spot.order_cancel_cp' >; 'spot.order_amend': WSAPIResponse; 'spot.order_status': WSAPIResponse; 'spot.order_list': WSAPIResponse; 'futures.order_place': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_place' >; 'futures.order_batch_place': WSAPIResponse< WSAPIFuturesOrderBatchPlaceRespItem[], 'futures.order_batch_place' >; 'futures.order_cancel': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_cancel' >; 'futures.order_cancel_ids': WSAPIResponse< WSAPIFuturesOrderCancelIdsRespItem[], 'futures.order_cancel_ids' >; 'futures.order_cancel_cp': WSAPIResponse< WSAPIFuturesOrder[], 'futures.order_cancel_cp' >; 'futures.order_amend': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_amend' >; 'futures.order_list': WSAPIResponse< WSAPIFuturesOrder[], 'futures.order_list' >; 'futures.order_status': WSAPIResponse< WSAPIFuturesOrder, 'futures.order_status' >; } ⋮---- // export interface WsAPIResponseMap { // 'spot.login': WSAPIResponse; // 'futures.login': WSAPIResponse; // string: object; // } ================ File: src/types/shared.ts ================ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' | 'futuresTestnet'; ⋮---- // interfaces ⋮---- export interface FromToPageLimit { from: number; to: number; page: number; limit: number; } ⋮---- // Used for spot and flash swap export interface CurrencyPair { id?: string; base?: string; base_name?: string; quote?: string; quote_name?: string; 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; } ================ File: src/index.ts ================ // Request Types ⋮---- // Response Types ⋮---- // Websockets Types ⋮---- // Shared Types ================ File: src/RestClient.ts ================ import { AxiosRequestConfig } from 'axios'; ⋮---- import { BaseRestClient, REST_CLIENT_TYPE_ENUM, RestClientType, } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { CreateStpGroupReq } from './types/request/account.js'; import { GetLoanCollateralRecordsReq, GetLoanOrdersReq, GetLoanRepaymentHistoryReq, SubmitLoanOrderReq, UpdateLoanCollateralReq, } from './types/request/collateralLoan.js'; import { GetDeliveryAutoOrdersReq, GetDeliveryBookReq, GetDeliveryCandlesReq, GetDeliveryClosedPositionsReq, GetDeliveryLiquidationHistoryReq, GetDeliveryOrderBookReq, GetDeliveryOrdersReq, GetDeliverySettlementHistoryReq, GetDeliveryTradesReq, GetDeliveryTradingHistoryReq, SubmitDeliveryFuturesOrderReq, } from './types/request/delivery.js'; import { GetStructuredProductListReq, GetStructuredProductOrdersReq, } from './types/request/earn.js'; import { GetLendingInterestRecordsReq, GetLendingOrdersReq, GetLendingRecordsReq, SubmitLendOrRedeemReq, } from './types/request/earnuni.js'; import { GetFlashSwapOrdersReq, SubmitFlashSwapOrderPreviewReq, SubmitFlashSwapOrderReq, } from './types/request/flashswap.js'; import { BatchAmendOrderReq, DeleteAllFuturesOrdersReq, GetFundingRatesReq, GetFuturesAccountBookReq, GetFuturesAutoOrdersReq, GetFuturesCandlesReq, GetFuturesInsuranceReq, GetFuturesLiquidationHistoryReq, GetFuturesOrderBookReq, GetFuturesOrdersByTimeRangeReq, GetFuturesOrdersReq, GetFuturesPositionCloseHistoryReq, GetFuturesPositionHistoryReq, GetFuturesPositionsReq, GetFuturesStatsReq, GetFuturesTradesReq, GetFuturesTradingHistoryByTimeRangeReq, GetFuturesTradingHistoryReq, GetLiquidationHistoryReq, GetRiskLimitTableReq, GetRiskLimitTiersReq, SubmitFuturesOrderReq, SubmitFuturesTriggeredOrderReq, UpdateDualModePositionLeverageReq, UpdateDualModePositionMarginReq, UpdateFuturesOrderReq, UpdateFuturesPriceTriggeredOrderReq, } from './types/request/futures.js'; import { GetCrossMarginAccountHistoryReq, GetCrossMarginBorrowHistoryReq, GetCrossMarginInterestRecordsReq, GetCrossMarginRepaymentsReq, GetMarginBalanceHistoryReq, SubmitCrossMarginBorrowLoanReq, } from './types/request/margin.js'; import { GetMarginUNIInterestRecordsReq, GetMarginUNILoanRecordsReq, GetMarginUNILoansReq, GetMarginUNIMaxBorrowReq, } from './types/request/marginuni.js'; import { GetMultiLoanAdjustmentRecordsReq, GetMultiLoanOrdersReq, GetMultiLoanRepayRecordsReq, RepayMultiLoanReq, SubmitMultiLoanOrderReq, UpdateMultiLoanReq, } from './types/request/multicollateralLoan.js'; import { GetOptionsAccountChangeReq, GetOptionsCandlesReq, GetOptionsMySettlementsReq, GetOptionsOrderBookReq, GetOptionsOrdersReq, GetOptionsPersonalHistoryReq, GetOptionsSettlementHistoryReq, GetOptionsTradesReq, GetOptionsUnderlyingCandlesReq, OptionsMMPSettingsReq, SubmitOptionsOrderReq, } from './types/request/options.js'; import { GetAgencyCommissionHistoryReq, GetAgencyTransactionHistoryReq, GetBrokerCommissionHistoryReq, GetBrokerTransactionHistoryReq, GetPartnerSubordinateListReq, PartnerTransactionReq, } from './types/request/rebate.js'; import { CancelSpotBatchOrdersReq, DeleteSpotOrderReq, GetSpotAccountBookReq, GetSpotAutoOrdersReq, GetSpotCandlesReq, GetSpotInsuranceHistoryReq, GetSpotOrderBookReq, GetSpotOrderReq, GetSpotOrdersReq, GetSpotTradesReq, GetSpotTradingHistoryReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, UpdateSpotBatchOrdersReq, UpdateSpotOrderReq, } from './types/request/spot.js'; import { CreateSubAccountApiKeyReq, CreateSubAccountReq, UpdateSubAccountApiKeyReq, } from './types/request/subaccount.js'; import { GetUnifiedHistoryLendingRateReq, GetUnifiedInterestRecordsReq, GetUnifiedLoanRecordsReq, GetUnifiedLoansReq, PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, SubmitUnifiedBorrowOrRepayReq, SubmitUnifiedLoanRepayReq, } from './types/request/unified.js'; import { GetMainSubTransfersReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, GetWithdrawalDepositRecordsReq, ListPushOrdersReq, SubmitMainSubTransferReq, SubmitSubToSubTransferReq, SubmitTransferReq, } from './types/request/wallet.js'; import { SubmitWithdrawalReq } from './types/request/withdrawal.js'; import { AccountDetail, AccountMainKey, AccountRateLimit, StpGroup, StpGroupUser, } from './types/response/account.js'; import { LoanCollateralRatio, LoanCollateralRecord, LoanOrder, LoanRepaymentHistoryRecord, } from './types/response/collateralloan.js'; import { DeliveryAccount, DeliveryBook, DeliveryCandle, DeliveryClosedPosition, DeliveryLiquidationHistoryRecord, DeliveryOrderBook, DeliverySettlementHistoryRecord, DeliveryTicker, DeliveryTrade, DeliveryTradingHistoryRecord, } from './types/response/delivery.js'; import { DualInvestmentOrder, DualInvestmentProduct, StructuredProduct, StructuredProductOrder, } from './types/response/earn.js'; import { LendingCurrency, LendingInterestRecord, LendingOrder, LendingRecord, } from './types/response/earnuni.js'; import { FlashSwapCurrencyPair, FlashSwapOrder, SubmitFlashSwapOrderPreviewResp, } from './types/response/flashswap.js'; import { BatchAmendOrderResp, DeleteFuturesBatchOrdersResp, FuturesAccount, FuturesAccountBookRecord, FuturesAutoDeleveragingHistoryRecord, FuturesCandle, FuturesContract, FuturesDeliveryContract, FuturesInsuranceHistory, FuturesLiquidationHistoryRecord, FuturesOrder, FuturesOrderBook, FuturesPosition, FuturesPositionHistoryRecord, FuturesPriceTriggeredOrder, FuturesStats, FuturesTicker, FuturesTrade, FuturesTradingHistoryRecord, IndexConstituents, LiquidationHistoryRecord, PremiumIndexKLine, RiskLimitTableTier, RiskLimitTier, } from './types/response/futures.js'; import { CrossMarginAccount, CrossMarginAccountHistoryRecord, CrossMarginCurrency, CrossMarginMorrowLoanRecord, MarginAccount, MarginBalanceHistoryRecord, MarginUserAccount, } from './types/response/margin.js'; import { LendingMarket, MarginUNIInterestRecord, MarginUNILoan, MarginUNILoanRecord, MarginUNIMaxBorrowable, } from './types/response/marginuni.js'; import { MultiLoanAdjustmentRecord, MultiLoanCurrencyQuota, MultiLoanFixedRate, MultiLoanOrder, MultiLoanRatio, MultiLoanRepayRecord, MultiLoanSupportedCurrencies, RepayMultiLoanResp, UpdateMultiLoanResp, } from './types/response/multicollateralLoan.js'; import { GetOptionsLiquidationResp, OptionsAccount, OptionsAccountChangeRecord, OptionsCandle, OptionsContract, OptionsMMPSettings, OptionsOrderBook, OptionsPositionsUnderlying, OptionsSettlementHistoryRecord, OptionsTicker, OptionsTrade, OptionsUnderlyingCandle, OptionsUserHistoryRecord, OptionsUserSettlement, SubmitOptionsOrderResp, } from './types/response/options.js'; import { AgencyCommissionHistoryRecord, AgencyTransactionHistoryRecord, BrokerCommissionHistoryRecord, BrokerTransactionHistoryRecord, PartnerCommission, PartnerSubordinate, PartnerTransaction, } from './types/response/rebate.js'; import { DeleteSpotBatchOrdersResp, GetSpotOpenOrdersResp, SpotAccount, SpotAccountBook, SpotCandle, SpotCurrency, SpotFeeRates, SpotHistoricTradeRecord, SpotInsuranceHistory, SpotOrder, SpotOrderBook, SpotPriceTriggeredOrder, SpotTicker, SpotTrade, SubmitSpotBatchOrdersResp, } from './types/response/spot.js'; import { CreatedSubAccountAPIKey, SubAccount, SubAccountAPIKey, SubAccountMode, } from './types/response/subaccount.js'; import { MarginTier, PortfolioMarginCalculation, UnifiedAccountInfo, UnifiedCurrencyDiscountTiers, UnifiedHistoryLendingRate, UnifiedInterestRecord, UnifiedLoan, UnifiedLoanCurrency, UnifiedLoanRecord, UnifiedRiskUnitDetails, UserCurrencyLeverageConfig, } from './types/response/unified.js'; import { CreateDepositAddressResp, CurrencyChain, DepositRecord, GetBalancesResp, PushOrder, SavedAddress, SmallBalanceHistoryRecord, SmallBalanceRecord, SubAccountCrossMarginBalancesResp, SubAccountFuturesBalancesResp, SubAccountMarginBalance, SubAccountTransferRecord, TradingFees, WithdrawalStatus, } from './types/response/wallet.js'; import { WithdrawalRecord } from './types/response/withdrawal.js'; import { CurrencyPair, FromToPageLimit } from './types/shared.js'; ⋮---- /** * Unified REST API client for all of Gate's REST APIs */ export class RestClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- /** * * Custom SDK functions * */ ⋮---- /** * This method is used to get the latency and time sync between the client and the server. * This is not official API endpoint and is only used for internal testing purposes. * Use this method to check the latency and time sync between the client and the server. * Final values might vary slightly, but it should be within few ms difference. * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. */ async fetchLatencySummary(): Promise ⋮---- // Adjust server time by adding estimated one-way latency ⋮---- // Calculate time difference between adjusted server time and local time ⋮---- /** * * Gate.io misc endpoints * */ ⋮---- getClientType(): RestClientType ⋮---- getSystemMaintenanceStatus(): Promise ⋮---- /**================================================================================================================================ * WITHDRAW * ========================================================================================================================== */ ⋮---- /** * Withdraw * * Withdrawals to Gate addresses do not incur transaction fees. * * @param params Withdrawal parameters * @returns Promise */ submitWithdrawal(params: SubmitWithdrawalReq): Promise ⋮---- /** * Transfer between spot main accounts * * Both parties cannot be sub-accounts. * * @param params Transfer parameters * @returns Promise<{ * id: number; * }> */ submitSpotMainAccountTransfer(params: { receive_uid: number; currency: string; amount: string; }): Promise< ⋮---- /** * Cancel withdrawal with specified ID * * @param params Parameters containing the withdrawal ID * @returns Promise */ cancelWithdrawal(params: { withdrawal_id: string; }): Promise ⋮---- /**========================================================================================================================== * WALLET * ========================================================================================================================== */ ⋮---- /** * List chains supported for specified currency * * @param params Parameters containing the currency name * @returns Promise */ getCurrencyChains(params: ⋮---- /** * Generate currency deposit address * * @param params Parameters containing the currency name * @returns Promise */ createDepositAddress(params: { currency: string; }): Promise ⋮---- /** * Retrieve withdrawal records * * Record time range cannot exceed 30 days * * @param params Parameters for filtering withdrawal records * @returns Promise */ getWithdrawalRecords( params?: GetWithdrawalDepositRecordsReq, ): Promise ⋮---- /** * Retrieve deposit records * * Record time range cannot exceed 30 days * * @param params Parameters for filtering deposit records * @returns Promise */ getDepositRecords( params?: GetWithdrawalDepositRecordsReq, ): Promise ⋮---- /** * Transfer between trading accounts * * Transfer between different accounts. Currently support transfers between the following: * - spot - margin * - spot - futures(perpetual) * - spot - delivery * - spot - cross margin * - spot - options * * @param params Transfer parameters * @returns Promise */ submitTransfer(params: SubmitTransferReq): Promise< ⋮---- /** * Transfer between main and sub accounts * * Support transferring with sub user's spot or futures account. Note that only main user's spot account is used no matter which sub user's account is operated. * * @param params Transfer parameters * @returns Promise */ submitMainSubTransfer(params: SubmitMainSubTransferReq): Promise ⋮---- /** * Retrieve transfer records between main and sub accounts * * Record time range cannot exceed 30 days * * Note: only records after 2020-04-10 can be retrieved * * @param params Parameters for filtering transfer records * @returns Promise */ getMainSubTransfers( params?: GetMainSubTransfersReq, ): Promise ⋮---- /** * Sub-account transfers to sub-account * * It is possible to perform balance transfers between two sub-accounts under the same main account. You can use either the API Key of the main account or the API Key of the sub-account to initiate the transfer. * * @param params Transfer parameters * @returns Promise */ submitSubToSubTransfer(params: SubmitSubToSubTransferReq): Promise ⋮---- /** * Query transfer status based on client_order_id or tx_id * * @param params Parameters for querying transfer status * @returns Promise<{ * tx_id: string; * status: 'PENDING' | 'SUCCESS' | 'FAIL' | 'PARTIAL_SUCCESS'; * }> */ getTransferStatus(params: { client_order_id?: string; tx_id?: string; }): Promise< ⋮---- /** * Retrieve withdrawal status * * @param params Parameters for retrieving withdrawal status * @returns Promise */ getWithdrawalStatus(params?: { currency?: string; }): Promise ⋮---- /** * Retrieve sub account balances * * @param params Parameters for retrieving sub account balances * @returns Promise<{ uid: string; available: { [key: string]: string }; }[]> */ getSubBalance(params?: { sub_uid?: string }): Promise< { uid: string; available: { [key: string]: string }; }[] > { return this.getPrivate('/wallet/sub_account_balances', params); ⋮---- /** * Query sub accounts' margin balances * * @param params Parameters for querying sub accounts' margin balances * @returns Promise */ getSubMarginBalances(params?: { sub_uid?: string; }): Promise< ⋮---- /** * Query sub accounts' futures account balances * * @param params Parameters for querying sub accounts' futures account balances * @returns Promise */ getSubFuturesBalances(params?: { sub_uid?: string; settle?: string; }): Promise ⋮---- /** * Query subaccount's cross_margin account info * * @param params Parameters for querying subaccount's cross_margin account info * @returns Promise */ getSubCrossMarginBalances(params?: { sub_uid?: string; }): Promise ⋮---- /** * Query saved addresses * * @param params Parameters for querying saved address * @returns Promise */ getSavedAddresses(params: GetSavedAddressReq): Promise ⋮---- /** * Retrieve personal trading fee * * @param params Parameters for retrieving personal trading fee * @returns Promise */ getTradingFees(params?: { currency_pair?: string; settle?: 'BTC' | 'USDT' | 'USD'; }): Promise ⋮---- /** * Retrieve user's total balances * * This endpoint returns an approximate sum of exchanged amount from all currencies to input currency for each account. * The exchange rate and account balance could have been cached for at most 1 minute. It is not recommended to use its result for any trading calculation. * * For trading calculation, use the corresponding account query endpoint for each account type. For example: * - GET /spot/accounts to query spot account balance * - GET /margin/accounts to query margin account balance * - GET /futures/{settle}/accounts to query futures account balance * * @param params Parameters for retrieving total balances * @returns Promise */ getBalances(params?: ⋮---- /** * List small balance * * @returns Promise */ getSmallBalances(): Promise ⋮---- /** * Convert small balance * * @param params Parameters for converting small balance * @returns Promise */ convertSmallBalance(params?: { currency?: string[]; is_all?: boolean; }): Promise ⋮---- /** * List small balance history * * @param params Parameters for listing small balance history * @returns Promise */ getSmallBalanceHistory( params?: GetSmallBalanceHistoryReq, ): Promise ⋮---- /** * List push orders * * @param params Parameters for listing push orders * @returns Promise */ getPushOrders(params?: ListPushOrdersReq): Promise ⋮---- /**========================================================================================================================== * SUBACCOUNT * ========================================================================================================================== */ ⋮---- /** * Create a new sub-account * * @param params Parameters for creating a new sub-account * @returns Promise */ createSubAccount(params: CreateSubAccountReq): Promise ⋮---- /** * List sub-accounts * * @param params Parameters for listing sub-accounts * @returns Promise */ ⋮---- getSubAccounts(params?: ⋮---- /** * Get the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ getSubAccount(params: ⋮---- /** * Create API Key of the sub-account * * @param params Parameters for creating API Key of the sub-account * @returns Promise */ createSubAccountApiKey( params: CreateSubAccountApiKeyReq, ): Promise ⋮---- /** * List all API Key of the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ getSubAccountApiKeys(params: { user_id: number; }): Promise ⋮---- /** * Update API key of the sub-account * * @param params Parameters for updating API key of the sub-account * @returns Promise */ updateSubAccountApiKey(params: UpdateSubAccountApiKeyReq): Promise ⋮---- /** * Delete API key of the sub-account * * @param params Parameters for deleting API key of the sub-account * @returns Promise */ deleteSubAccountApiKey(params: { user_id: number; key: string; }): Promise ⋮---- /** * Get the API Key of the sub-account * * @param params Parameters containing the sub-account user ID and API key * @returns Promise */ getSubAccountApiKey(params: { user_id: number; key: string; }): Promise ⋮---- /** * Lock the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ lockSubAccount(params: ⋮---- /** * Unlock the sub-account * * @param params Parameters containing the sub-account user ID * @returns Promise */ unlockSubAccount(params: ⋮---- /** * Get sub-account mode * * Unified account mode: * - classic: Classic account mode * - multi_currency: Multi-currency margin mode * - portfolio: Portfolio margin mode * * @returns Promise */ getSubAccountMode(): Promise ⋮---- /**========================================================================================================================== * UNIFIED * ========================================================================================================================== */ ⋮---- /** * Get unified account information * * The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account. * @param params Parameters for retrieving unified account information * @returns Promise */ getUnifiedAccountInfo(params?: { currency?: string; sub_uid?: string; }): Promise ⋮---- /** * Query about the maximum borrowing for the unified account * * @param params Parameters for querying the maximum borrowing for the unified account * @returns Promise<{ * currency: string; * amount: string; * }> */ getUnifiedMaxBorrow(params: ⋮---- /** * Query about the maximum transferable for the unified account * * @param params Parameters for querying the maximum transferable for the unified account * @returns Promise<{ * currency: string; * amount: string; * }> */ getUnifiedMaxTransferable(params: ⋮---- /** * Batch query maximum transferable amounts for unified accounts * * After withdrawing currency, the transferable amount will change. * * @param params Parameters containing currencies to query (up to 100 at once) * @returns Promise with array of currency and maximum transferable amount */ getUnifiedMaxTransferables(params: { currencies: string }): Promise< { currency: string; amount: string; }[] > { return this.getPrivate('/unified/transferables', params); ⋮---- getUnifiedBatchMaxBorrowable(params: ⋮---- /** * Borrow or repay * * When borrowing, it is essential to ensure that the borrowed amount is not below the minimum borrowing threshold for the specific cryptocurrency and does not exceed the maximum borrowing limit set by the platform and the user. * * The interest on the loan will be automatically deducted from the account at regular intervals. It is the user's responsibility to manage the repayment of the borrowed amount. * * For repayment, the option to repay the entire borrowed amount is available by setting the parameter repaid_all=true * * @param params Parameters for borrowing or repaying * @returns Promise */ submitUnifiedBorrowOrRepay( params: SubmitUnifiedBorrowOrRepayReq, ): Promise ⋮---- /** * List loans * * @param params Parameters for listing loans * @returns Promise */ getUnifiedLoans(params?: GetUnifiedLoansReq): Promise ⋮---- /** * Get loan records * * @param params Parameters for getting loan records * @returns Promise */ getUnifiedLoanRecords( params?: GetUnifiedLoanRecordsReq, ): Promise ⋮---- /** * List interest records * * @param params Parameters for listing interest records * @returns Promise */ getUnifiedInterestRecords( params?: GetUnifiedInterestRecordsReq, ): Promise ⋮---- /** * Retrieve user risk unit details, only valid in portfolio margin mode * * @returns Promise */ getUnifiedRiskUnitDetails(): Promise ⋮---- /** * Set mode of the unified account * * Switching between different account modes requires only passing the parameters corresponding to the target account mode. It also supports opening or closing configuration switches for the corresponding account mode when switching. * * @param params Parameters for setting the mode of the unified account * @returns Promise */ setUnifiedAccountMode(params: SetUnifiedAccountModeReq): Promise ⋮---- /** * Query mode of the unified account * * @returns Promise */ getUnifiedAccountMode(): Promise ⋮---- /** * Get unified estimate rate * * Due to fluctuations in lending depth, hourly interest rates may vary, and thus, I cannot provide exact rates. When a currency is not supported, the interest rate returned will be an empty string. * * @param params Parameters for querying estimate rates * @returns Promise<{ [key: string]: string }> */ getUnifiedEstimateRate(params: { currencies: string[]; }): Promise< ⋮---- /** * List currency discount tiers * * @returns Promise */ getUnifiedCurrencyDiscountTiers(): Promise ⋮---- /** * List loan margin tiers * * @returns Promise<{ * currency: string; * margin_tiers: MarginTier[]; * }[]> */ getLoanMarginTiers(): Promise< { currency: string; margin_tiers: MarginTier[]; }[] > { return this.get('/unified/loan_margin_tiers'); ⋮---- /** * Portfolio margin calculator * * Portfolio Margin Calculator When inputting a simulated position portfolio, each position includes the position name and quantity held, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. When inputting simulated orders, each order includes the market identifier, order price, and order quantity, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. Market orders are not included. * * @param params Parameters for portfolio margin calculator * @returns Promise */ portfolioMarginCalculate( params: PortfolioMarginCalculatorReq, ): Promise ⋮---- /** * Query user currency leverage configuration * * Get the maximum and minimum leverage multiples that users can set for a currency type * * @param params Parameters containing the currency * @returns Promise */ getUserCurrencyLeverageConfig(params: { currency: string; }): Promise ⋮---- /** * Get the user's currency leverage * * If currency is not passed, query all currencies. * * @param params Optional parameters containing the currency * @returns Promise */ getUserCurrencyLeverageSettings(params?: { currency?: string }): Promise< { currency: string; leverage: string; }[] > { return this.getPrivate('/unified/leverage/user_currency_setting', params); ⋮---- /** * Set the currency leverage ratio * * @param params Parameters for setting currency leverage ratio * @returns Promise Returns nothing on success (204 No Content) */ updateUserCurrencyLeverage(params: { currency: string; leverage: string; }): Promise ⋮---- /** * List loan currencies supported by unified account * * @param params Optional parameters for filtering * @returns Promise with array of loan currencies */ getUnifiedLoanCurrencies(params?: { currency?: string; }): Promise ⋮---- /** * Get historical lending rates * * @param params Parameters for retrieving historical lending rates * @returns Promise */ getHistoricalLendingRates( params: GetUnifiedHistoryLendingRateReq, ): Promise ⋮---- submitUnifiedLoanRepay(params: SubmitUnifiedLoanRepayReq): Promise ⋮---- /**========================================================================================================================== * SPOT * ========================================================================================================================== */ ⋮---- /** * List all currencies' details * * Currency has two forms: * - Only currency name, e.g., BTC, USDT * - _, e.g., HT_ETH * * The latter one occurs when one currency has multiple chains. Currency detail contains a chain field whatever the form is. To retrieve all chains of one currency, you can use all the details which have the name of the currency or name starting with _. * * @returns Promise */ getSpotCurrencies(): Promise ⋮---- /** * Get details of a specific currency * * @param params Parameters for retrieving details of a specific currency * @returns Promise */ getSpotCurrency(params: ⋮---- /** * List all currency pairs supported * * @returns Promise */ getSpotCurrencyPairs(): Promise ⋮---- /** * Get details of a specific currency pair * * @param params Parameters for retrieving details of a specific currency pair * @returns Promise */ getSpotCurrencyPair(params: { currency_pair: string; }): Promise ⋮---- /** * Retrieve ticker information * * Return only related data if currency_pair is specified; otherwise return all of them. * * @param params Parameters for retrieving ticker information * @returns Promise */ getSpotTicker(params?: { currency_pair?: string; timezone?: 'utc0' | 'utc8' | 'all'; }): Promise ⋮---- /** * Retrieve order book * * Order book will be sorted by price from high to low on bids; low to high on asks. * * @param params Parameters for retrieving order book * @returns Promise */ getSpotOrderBook(params: GetSpotOrderBookReq): Promise ⋮---- /** * Retrieve market trades * * You can use from and to to query by time range, or use last_id by scrolling page. The default behavior is by time range. * Scrolling query using last_id is not recommended any more. If last_id is specified, time range query parameters will be ignored. * * @param params Parameters for retrieving market trades * @returns Promise */ getSpotTrades(params: GetSpotTradesReq): Promise ⋮---- /** * Market Candles * * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving market Candles * @returns Promise */ getSpotCandles(params: GetSpotCandlesReq): Promise ⋮---- /** * Query user trading fee rates * * This API is deprecated in favour of new fee retrieving API /wallet/fee. * * @param params Parameters for querying user trading fee rates * @returns Promise */ getSpotFeeRates(params?: ⋮---- /** * Query a batch of user trading fee rates * * @param params Parameters for querying a batch of user trading fee rates */ getSpotBatchFeeRates(params: { currency_pairs: string; }): Promise> ⋮---- /** * List spot accounts * * @param params Parameters for listing spot accounts * @returns Promise */ getSpotAccounts(params?: ⋮---- /** * Query account book * * Record time range cannot exceed 30 days. * * @param params Parameters for querying account book * @returns Promise */ getSpotAccountBook( params?: GetSpotAccountBookReq, ): Promise ⋮---- /** * Create a batch of orders * * Batch orders requirements: * - custom order field text is required * - At most 4 currency pairs, maximum 10 orders each, are allowed in one request * - No mixture of spot orders and margin orders, i.e. account must be identical for all orders * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating a batch of orders * @returns Promise */ submitSpotBatchOrders( body: SpotOrder[], params?: { xGateExptime?: number; }, ): Promise ⋮---- /** * List all open orders * * List open orders in all currency pairs. * Note that pagination parameters affect record number in each currency pair's open order list. No pagination is applied to the number of currency pairs returned. All currency pairs with open orders will be returned. * Spot, portfolio, and margin orders are returned by default. To list cross margin orders, account must be set to cross_margin. * * @param params Parameters for listing all open orders * @returns Promise */ getSpotOpenOrders(params?: { page?: number; limit?: number; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; }): Promise ⋮---- /** * Close position when cross-currency is disabled * * Currently, only cross-margin accounts are supported to close position when cross currencies are disabled. Maximum buy quantity = (unpaid principal and interest - currency balance - the amount of the currency in the order book) / 0.998 * * @param params Parameters for closing position when cross-currency is disabled * @returns Promise */ submitSpotClosePosCrossDisabled( params: SubmitSpotClosePosCrossDisabledReq, ): Promise ⋮---- /** * Create an order * * You can place orders with spot, portfolio, margin or cross margin account through setting the account field. It defaults to spot, which means spot account is used to place orders. If the user is using unified account, it defaults to the unified account. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating an order * @returns Promise */ submitSpotOrder(params: SubmitSpotOrderReq): Promise ⋮---- /** * List orders * * Spot, portfolio and margin orders are returned by default. If cross margin orders are needed, account must be set to cross_margin. * * @param params Parameters for listing orders * @returns Promise */ getSpotOrders(params: GetSpotOrdersReq): Promise ⋮---- /** * Cancel all open orders in specified currency pair * * If account is not set, all open orders, including spot, portfolio, margin and cross margin ones, will be cancelled. * You can set account to cancel only orders within the specified account. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling all open orders in specified currency pair * @returns Promise */ cancelSpotOpenOrders(params: { currency_pair: string; side?: 'buy' | 'sell'; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; xGateExptime?: number; }): Promise ⋮---- /** * Cancel a batch of orders with an ID list * * Multiple currency pairs can be specified, but maximum 20 orders are allowed per request. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a batch of orders * @returns Promise */ batchCancelSpotOrders( body: CancelSpotBatchOrdersReq[], params?: { xGateExptime?: number; }, ): Promise ⋮---- /** * Get a single order * * Spot, portfolio and margin orders are queried by default. If cross margin orders are needed or portfolio margin account are used, account must be set to cross_margin. * * @param params Parameters for getting a single order * @returns Promise */ getSpotOrder(params: GetSpotOrderReq): Promise ⋮---- /** * Amend an order * * By default, the orders of spot, portfolio and margin account are updated. If you need to modify orders of the cross-margin account, you must specify account as cross_margin. For portfolio margin account, only cross_margin account is supported. * * Currently, only supports modification of price or amount fields. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for amending an order * @returns Promise */ updateSpotOrder(params: UpdateSpotOrderReq): Promise ⋮---- /** * Cancel a single order * * Spot, portfolio and margin orders are cancelled by default. If trying to cancel cross margin orders or portfolio margin account are used, account must be set to cross_margin. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a single order * @returns Promise */ cancelSpotOrder(params: DeleteSpotOrderReq): Promise ⋮---- /** * List personal trading history * * Spot, portfolio and margin trades are queried by default. If cross margin trades are needed, account must be set to cross_margin. * * You can also set from and/or to to query by time range. If you don't specify from and/or to parameters, only the last 7 days of data will be returned. The range of from and to is not allowed to exceed 30 days. Time range parameters are handled as order finish time. * * @param params Parameters for listing personal trading history * @returns Promise */ getSpotTradingHistory( params?: GetSpotTradingHistoryReq, ): Promise ⋮---- /** * Get server current time * * @returns Promise<{ * server_time: number; * }> */ getServerTime(): Promise< ⋮---- /** * Countdown cancel orders * * When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown. * * @param params Parameters for setting countdown cancel orders * @returns Promise<{ * triggerTime: number; * }> */ submitSpotCountdownOrders(params: { timeout: number; currency_pair?: string; }): Promise< ⋮---- /** * Batch modification of orders * * Default modification of orders for spot, portfolio, and margin accounts. To modify orders for a cross margin account, the account parameter must be specified as cross_margin. For portfolio margin accounts, the account parameter can only be specified as cross_margin. Currently, only modifications to price or quantity (choose one) are supported. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for batch modification of orders * @returns Promise */ batchUpdateSpotOrders( body: UpdateSpotBatchOrdersReq[], params?: { xGateExptime?: number; }, ): Promise ⋮---- /** * Query spot insurance fund historical data * * @param params Parameters for querying spot insurance fund history * @returns Promise<{ * currency: string; * balance: string; * time: number; * }[]> */ getSpotInsuranceHistory( params: GetSpotInsuranceHistoryReq, ): Promise ⋮---- /** * Create a price-triggered order * * @param params Parameters for creating a price-triggered order * @returns Promise<{ * id: number; * }> */ submitSpotPriceTriggerOrder(params: SpotPriceTriggeredOrder): Promise< ⋮---- /** * Retrieve running auto order list * * @param params Parameters for retrieving running auto order list * @returns Promise */ getSpotAutoOrders( params: GetSpotAutoOrdersReq, ): Promise ⋮---- /** * Cancel all open orders * * @param params Parameters for cancelling all open orders * @returns Promise */ cancelAllOpenSpotOrders(params?: { market?: string; account?: 'normal' | 'margin' | 'cross_margin'; }): Promise ⋮---- /** * Get a price-triggered order * * @param params Parameters for getting a price-triggered order * @returns Promise */ getPriceTriggeredOrder(params: { order_id: string; }): Promise ⋮---- /** * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order * @returns Promise */ cancelSpotTriggeredOrder(params: { order_id: string; }): Promise ⋮---- /** * Set collateral currency * * @param params Parameters for setting collateral currency * @returns Promise<{ * is_success: boolean; * }> */ setCollateralCurrency(params: { collateral_type: 0 | 1; enable_list?: string[]; disable_list?: string[]; }): Promise< ⋮---- /**========================================================================================================================== * MARGIN * ========================================================================================================================== */ ⋮---- /** * Margin account list * * @param params Parameters for listing margin accounts * @returns Promise */ getMarginAccounts(params?: { currency_pair?: string; }): Promise ⋮---- /** * List margin account balance change history * * Only transferals from and to margin account are provided for now. Time range allows 30 days at most. * * @param params Parameters for listing margin account balance change history * @returns Promise */ getMarginBalanceHistory( params?: GetMarginBalanceHistoryReq, ): Promise ⋮---- /** * Funding account list * * @param params Parameters for listing funding accounts * @returns Promise<{ * currency: string; * available: string; * locked: string; * lent: string; * total_lent: string; * }[]> */ getFundingAccounts(params?: { currency?: string }): Promise< { currency: string; available: string; locked: string; lent: string; total_lent: string; }[] > { return this.getPrivate('/margin/funding_accounts', params); ⋮---- /** * Update user's auto repayment setting * * @param params Parameters for updating auto repayment setting * @returns Promise<{ status: 'on' | 'off' }> */ updateAutoRepaymentSetting(params: { status: 'on' | 'off'; }): Promise< ⋮---- /** * Retrieve user auto repayment setting * * @returns Promise<{ status: 'on' | 'off' }> */ getAutoRepaymentSetting(): Promise< ⋮---- /** * Get the max transferable amount for a specific margin currency * * @param params Parameters for retrieving the max transferable amount * @returns Promise<{ * currency: string; * currency_pair?: string; * amount: string; * }> */ getMarginTransferableAmount(params: { currency: string; currency_pair?: string; }): Promise< ⋮---- /** * @deprecated as of 2025-02-10 * Currencies supported by cross margin * * @returns Promise */ getCrossMarginCurrencies(): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve detail of one single currency supported by cross margin * * @param params Parameters containing the currency name * @returns Promise */ getCrossMarginCurrency(params: { currency: string; }): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve cross margin account * * @returns Promise */ getCrossMarginAccount(): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve cross margin account change history * * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving cross margin account change history * @returns Promise */ getCrossMarginAccountHistory( params?: GetCrossMarginAccountHistoryReq, ): Promise ⋮---- /** * * @deprecated as of 2025-02-10 * Create a cross margin borrow loan * * Borrow amount cannot be less than currency minimum borrow amount. * * @param params Parameters for creating a cross margin borrow loan * @returns Promise * */ submitCrossMarginBorrowLoan( params: SubmitCrossMarginBorrowLoanReq, ): Promise ⋮---- /** * * List cross margin borrow history * * Sort by creation time in descending order by default. Set reverse=false to return ascending results. * * @param params Parameters for listing cross margin borrow history * @returns Promise */ getCrossMarginBorrowHistory( params: GetCrossMarginBorrowHistoryReq, ): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve single borrow loan detail * * @param params Parameters containing the borrow loan ID * @returns Promise */ getCrossMarginBorrowLoan(params: { loan_id: string; }): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Cross margin repayments * * When the liquidity of the currency is insufficient and the transaction risk is high, the currency will be disabled, and funds cannot be transferred. When the available balance of cross-margin is insufficient, the balance of the spot account can be used for repayment. Please ensure that the balance of the spot account is sufficient, and system uses cross-margin account for repayment first. * * @param params Parameters for cross margin repayments * @returns Promise */ submitCrossMarginRepayment(params: { currency: string; amount: string; }): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Retrieve cross margin repayments * * Sort by creation time in descending order by default. Set reverse=false to return ascending results. * * @param params Parameters for retrieving cross margin repayments * @returns Promise */ getCrossMarginRepayments( params?: GetCrossMarginRepaymentsReq, ): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Interest records for the cross margin account * * @param params Parameters for retrieving interest records * @returns Promise */ getCrossMarginInterestRecords( params?: GetCrossMarginInterestRecordsReq, ): Promise ⋮---- /** * @deprecated as of 2025-02-10 * Get the max transferable amount for a specific cross margin currency * * @param params Parameters for retrieving the max transferable amount * @returns Promise<{ * currency: string; * amount: string; * }> */ getCrossMarginTransferableAmount(params: ⋮---- /** * @deprecated as of 2025-02-10 * Estimated interest rates * * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. * * @param params Parameters for retrieving estimated interest rates * @returns Promise */ getEstimatedInterestRates(params: ⋮---- /** * @deprecated as of 2025-02-10 * Get the max borrowable amount for a specific cross margin currency * * @param params Parameters for retrieving the max borrowable amount * @returns Promise<{ * currency: string; * amount: string; * }> */ getCrossMarginBorrowableAmount(params: ⋮---- /** * Check the user's own leverage lending gradient in the current market * * @param params Parameters containing currency pair to query * @returns Promise with array of market gradient information */ getMarginUserLoanTiers(params: { currency_pair: string }): Promise< { tier_amount: string; mmr: string; leverage: string; }[] > { return this.getPrivate('/margin/user/loan_margin_tiers', params); ⋮---- /** * Query the current market leverage lending gradient * * @param params Parameters containing currency pair to query * @returns Promise with array of market gradient information */ getMarginPublicLoanTiers(params: { currency_pair: string }): Promise< { tier_amount: string; mmr: string; leverage: string; }[] > { return this.get('/margin/loan_margin_tiers', params); ⋮---- /** * Set the user market leverage multiple * * @param params Parameters containing currency pair and leverage value * @returns Promise - Returns nothing on success (204 No Content) */ setMarginUserLeverage(params: { currency_pair: string; leverage: string; }): Promise ⋮---- /** * Query the user's leverage account list * * Supports querying risk rate per position account and margin rate per position account * * @param params Optional parameters for filtering by currency pair * @returns Promise with array of margin account details */ getMarginUserAccounts(params?: { currency_pair?: string; }): Promise ⋮---- /**========================================================================================================================== * MARGIN UNI * ========================================================================================================================== */ /** * List lending markets * * @returns Promise */ getLendingMarkets(): Promise ⋮---- /** * Get detail of lending market * * @param params Parameters containing the currency pair * @returns Promise<{ * currency_pair: string; * base_min_borrow_amount: string; * quote_min_borrow_amount: string; * leverage: string; * }> */ getLendingMarket(params: ⋮---- /** * Estimate interest rate * * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. * * @param params Parameters for retrieving estimated interest rates * @returns Promise */ getEstimatedInterestRate(params: ⋮---- /** * Borrow or repay * * @param params Parameters for borrowing or repaying * @returns Promise */ submitMarginUNIBorrowOrRepay(params: { currency: string; type: 'borrow' | 'repay'; amount: string; currency_pair: string; repaid_all?: boolean; }): Promise ⋮---- /** * List loans * * @param params Parameters for listing loans * @returns Promise */ getMarginUNILoans(params?: GetMarginUNILoansReq): Promise ⋮---- /** * Get loan records * * @param params Parameters for retrieving loan records * @returns Promise */ getMarginUNILoanRecords( params?: GetMarginUNILoanRecordsReq, ): Promise ⋮---- /** * List interest records * * @param params Parameters for listing interest records * @returns Promise */ getMarginUNIInterestRecords( params?: GetMarginUNIInterestRecordsReq, ): Promise ⋮---- /** * Get maximum borrowable * * @param params Parameters for retrieving the maximum borrowable amount * @returns Promise */ getMarginUNIMaxBorrow( params: GetMarginUNIMaxBorrowReq, ): Promise /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== */ ⋮---- /** * List All Supported Currency Pairs In Flash Swap * * @param params Parameters for retrieving data of the specified currency * @returns Promise */ getFlashSwapCurrencyPairs(params?: { currency?: string; page?: number; limit?: number; }): Promise ⋮---- /** * Create a flash swap order * * Initiate a flash swap preview in advance because order creation requires a preview result. * * @param params Parameters for creating a flash swap order * @returns Promise */ submitFlashSwapOrder( params: SubmitFlashSwapOrderReq, ): Promise ⋮---- /** * List all flash swap orders * * @param params Parameters for listing flash swap orders * @returns Promise */ getFlashSwapOrders( params?: GetFlashSwapOrdersReq, ): Promise ⋮---- /** * Get a single flash swap order's detail * * @param params Parameters containing the flash swap order ID * @returns Promise */ getFlashSwapOrder(params: ⋮---- /** * Initiate a flash swap order preview * * @param params Parameters for initiating a flash swap order preview * @returns Promise */ submitFlashSwapOrderPreview( params: SubmitFlashSwapOrderPreviewReq, ): Promise ⋮---- /**========================================================================================================================== * FUTURES * ========================================================================================================================== */ ⋮---- /** * List all futures contracts * * @param params Parameters for listing futures contracts * @returns Promise */ getFuturesContracts(params: { settle: 'btc' | 'usdt' | 'usd'; limit?: number; offset?: number; }): Promise ⋮---- /** * Get a single contract * * @param params Parameters for retrieving a single contract * @returns Promise */ getFuturesContract(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise ⋮---- /** * Futures order book * * Bids will be sorted by price from high to low, while asks sorted reversely. * * @param params Parameters for retrieving the futures order book * @returns Promise */ getFuturesOrderBook( params: GetFuturesOrderBookReq, ): Promise ⋮---- /** * Futures trading history * * @param params Parameters for retrieving futures trading history * @returns Promise */ getFuturesTrades(params: GetFuturesTradesReq): Promise ⋮---- /** * Get futures Candles * * Return specified contract Candles. If prefix contract with mark_, the contract's mark price Candles are returned; if prefix with index_, index price Candles will be returned. * * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving futures Candles * @returns Promise */ getFuturesCandles(params: GetFuturesCandlesReq): Promise ⋮---- /** * Premium Index K-Line * * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving premium index K-Line * @returns Promise */ getPremiumIndexKLines( params: GetFuturesCandlesReq, ): Promise ⋮---- /** * List futures tickers * * @param params Parameters for listing futures tickers * @returns Promise */ getFuturesTickers(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; }): Promise ⋮---- /** * Funding rate history * * @param params Parameters for retrieving funding rate history * @returns Promise<{ * t: number; * r: string; * }[]> */ getFundingRates(params: GetFundingRatesReq): Promise< { t: number; r: string; }[] > { const { settle, ...query } = params; return this.get(`/futures/$ ⋮---- /** * Futures insurance balance history * * @param params Parameters for retrieving futures insurance balance history * @returns Promise<{ * t: number; * b: string; * }[]> */ getFuturesInsuranceBalanceHistory(params: { settle: 'btc' | 'usdt' | 'usd'; limit?: number; }): Promise< { t: number; b: string; }[] > { const { settle, ...query } = params; return this.get(`/futures/$ ⋮---- /** * Futures stats * * @param params Parameters for retrieving futures stats * @returns Promise */ getFuturesStats(params: GetFuturesStatsReq): Promise ⋮---- /** * Get index constituents * * @param params Parameters for retrieving index constituents * @returns Promise */ getIndexConstituents(params: { settle: 'btc' | 'usdt' | 'usd'; index: string; }): Promise ⋮---- /** * Retrieve liquidation history * * Interval between from and to cannot exceed 3600. Some private fields will not be returned in public endpoints. Refer to field description for detail. * * @param params Parameters for retrieving liquidation history * @returns Promise */ getLiquidationHistory( params: GetLiquidationHistoryReq, ): Promise ⋮---- /** * List risk limit tiers * * When the 'contract' parameter is not passed, the default is to query the risk limits for the top 100 markets. * 'Limit' and 'offset' correspond to pagination queries at the market level, not to the length of the returned array. * This only takes effect when the 'contract' parameter is empty. * * @param params Parameters for listing risk limit tiers * @returns Promise */ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise ⋮---- /** * Query futures account * * @param params Parameters for querying futures account * @returns Promise */ getFuturesAccount(params: { settle: 'btc' | 'usdt' | 'usd'; }): Promise ⋮---- /** * Query account book * * If the contract field is provided, it can only filter records that include this field after 2023-10-30. * * @param params Parameters for querying account book * @returns Promise */ getFuturesAccountBook( params: GetFuturesAccountBookReq, ): Promise ⋮---- /** * List all positions of a user * * @param params Parameters for listing all positions of a user * @returns Promise */ getFuturesPositions( params: GetFuturesPositionsReq, ): Promise ⋮---- /** * Get single position * * @param params Parameters for retrieving a single position * @returns Promise */ getFuturesPosition(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise ⋮---- /** * Update position margin * * @param params Parameters for updating position margin * @returns Promise */ updateFuturesMargin(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; change: string; }): Promise ⋮---- /** * Update position leverage * * @param params Parameters for updating position leverage * @returns Promise */ updateFuturesLeverage(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; leverage: string; cross_leverage_limit?: string; }): Promise ⋮---- /** * Update position by store mode * * @param params Parameters for updating position by store mode * @returns Promise */ updateFuturesPositionMode(params: { settle: 'btc' | 'usdt'; mode: 'ISOLATED' | 'CROSS'; contract: string; }): Promise ⋮---- /** * Update position risk limit * * @param params Parameters for updating position risk limit * @returns Promise */ updatePositionRiskLimit(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; risk_limit: string; }): Promise ⋮---- /** * Enable or disable dual mode * * Before setting dual mode, make sure all positions are closed and no orders are open. * * @param params Parameters for enabling or disabling dual mode * @returns Promise */ updateFuturesDualMode(params: { settle: 'btc' | 'usdt' | 'usd'; dual_mode: boolean; }): Promise ⋮---- /** * Retrieve position detail in dual mode * * @param params Parameters for retrieving position detail in dual mode * @returns Promise */ getDualModePosition(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise ⋮---- /** * Update position margin in dual mode * * @param params Parameters for updating position margin in dual mode * @returns Promise */ updateDualModePositionMargin( params: UpdateDualModePositionMarginReq, ): Promise ⋮---- /** * Update position leverage in dual mode * * @param params Parameters for updating position leverage in dual mode * @returns Promise */ updateDualModePositionLeverage( params: UpdateDualModePositionLeverageReq, ): Promise ⋮---- /** * Update position risk limit in dual mode * * @param params Parameters for updating position risk limit in dual mode * @returns Promise */ updateDualModePositionRiskLimit(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; risk_limit: string; }): Promise ⋮---- /** * Create a futures order * * Creating futures orders requires size, which is the number of contracts instead of currency amount. You can use quanto_multiplier in the contract detail response to know how much currency 1 size contract represents. * Zero-filled order cannot be retrieved 10 minutes after order cancellation. You will get a 404 not found for such orders. * Set reduce_only to true to keep the position from changing side when reducing position size. * In single position mode, to close a position, you need to set size to 0 and close to true. * In dual position mode, to close one side position, you need to set auto_size side, reduce_only to true, and size to 0. * Set stp_act to decide the strategy of self-trade prevention. For detailed usage, refer to the stp_act parameter in the request body. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating a futures order * @returns Promise */ submitFuturesOrder(params: SubmitFuturesOrderReq): Promise ⋮---- /** * List futures orders * * Zero-fill order cannot be retrieved for 10 minutes after cancellation. * Historical orders, by default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/orders_timerange. * * @param params Parameters for listing futures orders * @returns Promise */ getFuturesOrders(params: GetFuturesOrdersReq): Promise ⋮---- /** * Cancel all open orders matched * * Zero-filled order cannot be retrieved 10 minutes after order cancellation. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling all open orders matched * @returns Promise */ cancelAllFuturesOrders( params: DeleteAllFuturesOrdersReq, ): Promise ⋮---- /** * List Futures Orders By Time Range * * @param params Parameters for listing futures orders by time range * @returns Promise */ getFuturesOrdersByTimeRange( params: GetFuturesOrdersByTimeRangeReq, ): Promise ⋮---- /** * Create a batch of futures orders * * Up to 10 orders per request. * If any of the order's parameters are missing or in the wrong format, all of them will not be executed, and a http status 400 error will be returned directly. * If the parameters are checked and passed, all are executed. Even if there is a business logic error in the middle (such as insufficient funds), it will not affect other execution orders. * The returned result is in array format, and the order corresponds to the orders in the request body. * In the returned result, the succeeded field of type bool indicates whether the execution was successful or not. * If the execution is successful, the normal order content is included; if the execution fails, the label field is included to indicate the cause of the error. * In the rate limiting, each order is counted individually. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for creating a batch of futures orders * @returns Promise */ submitFuturesBatchOrders(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; orders: SubmitFuturesOrderReq[]; }): Promise ⋮---- /** * Get a single order * * Zero-fill order cannot be retrieved for 10 minutes after cancellation. * Historical orders, by default, only data within the past 6 months is supported. * * @param params Parameters for retrieving a single order * @returns Promise */ getFuturesOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise ⋮---- /** * Cancel a single order * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a single order * @returns Promise */ cancelFuturesOrder(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise ⋮---- /** * Amend an order * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for amending an order * @returns Promise */ updateFuturesOrder(params: UpdateFuturesOrderReq): Promise ⋮---- /** * List personal trading history * * By default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/my_trades_timerange. * * @param params Parameters for listing personal trading history * @returns Promise */ getFuturesTradingHistory( params: GetFuturesTradingHistoryReq, ): Promise ⋮---- /** * List personal trading history * * This endpoint is for data longer than 6 months. * * @param params Parameters for listing personal trading history * @returns Promise */ getFuturesTradingHistoryByTimeRange( params: GetFuturesTradingHistoryByTimeRangeReq, ): Promise ⋮---- /** * List position close history * * @param params Parameters for listing position close history * @returns Promise */ getFuturesPositionHistory( params: GetFuturesPositionHistoryReq, ): Promise ⋮---- /** * List liquidation history * * @param params Parameters for listing liquidation history * @returns Promise */ getFuturesLiquidationHistory( params: GetFuturesLiquidationHistoryReq, ): Promise ⋮---- /** * List Auto-Deleveraging History * * @param params Parameters for listing auto-deleveraging history * @returns Promise */ getFuturesAutoDeleveragingHistory( params: GetFuturesLiquidationHistoryReq, ): Promise ⋮---- /** * Countdown cancel orders * * When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown. * For example, call this endpoint at 30s intervals, each countdown timeout is set to 30s. If this endpoint is not called again within 30 seconds, all pending orders on the specified market will be automatically cancelled, if no market is specified, all market pending orders will be cancelled. * If the timeout is set to 0 within 30 seconds, the countdown timer will expire and the cancel function will be cancelled. * * @param params Parameters for setting countdown cancel orders * @returns Promise<{ triggerTime: number }> */ setFuturesOrderCancelCountdown(params: { settle: 'btc' | 'usdt' | 'usd'; timeout: number; contract?: string; }): Promise< ⋮---- /** * Query user trading fee rates * * @param params Parameters for querying user trading fee rates * @returns Promise */ getFuturesUserTradingFees(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; }): Promise ⋮---- /** * Cancel a batch of orders with an ID list * * Multiple distinct order ID list can be specified. Each request can cancel a maximum of 20 records. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Parameters for cancelling a batch of orders with an ID list * @returns Promise */ batchCancelFuturesOrders(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; orderIds: string[]; }): Promise ⋮---- /** * Batch modify orders with specified IDs * * You can specify multiple different order IDs. You can only modify up to 10 orders in one request. * * NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header. * * @param params Array of BatchAmendOrderReq objects * @param settle Settlement currency (e.g., 'btc', 'usdt', 'usd') * @returns Promise */ batchUpdateFuturesOrders(params: { xGateExptime?: number; settle: 'btc' | 'usdt' | 'usd'; orders: BatchAmendOrderReq[]; }): Promise ⋮---- /** * Query risk limit table by table_id * * @param params Parameters for querying risk limit table * @returns Promise */ getRiskLimitTable( params: GetRiskLimitTableReq, ): Promise ⋮---- /** * Create a price-triggered order * * @param params Parameters for creating a price-triggered order * @returns Promise<{ id: number }> */ submitFuturesPriceTriggeredOrder( params: SubmitFuturesTriggeredOrderReq, ): Promise< ⋮---- /** * List all auto orders * * @param params Parameters for listing all auto orders * @returns Promise */ getFuturesAutoOrders( params: GetFuturesAutoOrdersReq, ): Promise ⋮---- /** * Cancel all open orders * * @param params Parameters for cancelling all open orders * @returns Promise */ cancelAllOpenFuturesOrders(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise ⋮---- /** * Get a price-triggered order * * @param params Parameters for retrieving a price-triggered order * @returns Promise */ getFuturesPriceTriggeredOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise ⋮---- /** * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order * @returns Promise */ cancelFuturesPriceTriggeredOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise ⋮---- /** * Update a single price-triggered order * * @param params Parameters for updating a price-triggered order * @returns Promise<{ id: number }> */ updateFuturesPriceTriggeredOrder( params: UpdateFuturesPriceTriggeredOrderReq, ): Promise< ⋮---- getFuturesPositionCloseHistory( params: GetFuturesPositionCloseHistoryReq, ): Promise ⋮---- getFuturesInsuranceHistory( params: GetFuturesInsuranceReq, ): Promise ⋮---- /**========================================================================================================================== * DELIVERY * ========================================================================================================================== */ ⋮---- /** * List all futures contracts * * @param params Parameters for listing all futures contracts * @returns Promise */ getAllDeliveryContracts(params: { settle: 'usdt'; }): Promise ⋮---- /** * Get a single contract * * @param params Parameters for retrieving a single contract * @returns Promise */ getDeliveryContract(params: { settle: 'usdt'; contract: string; }): Promise ⋮---- /** * Futures order book * * Bids will be sorted by price from high to low, while asks sorted reversely * * @param params Parameters for retrieving the futures order book * @returns Promise */ getDeliveryOrderBook( params: GetDeliveryOrderBookReq, ): Promise ⋮---- /** * Futures trading history * * @param params Parameters for retrieving the futures trading history * @returns Promise */ getDeliveryTrades(params: GetDeliveryTradesReq): Promise ⋮---- /** * Get futures Candles * * Return specified contract Candles. If prefix contract with mark_, the contract's mark price Candles are returned; if prefix with index_, index price Candles will be returned. * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving futures Candles * @returns Promise */ getDeliveryCandles(params: GetDeliveryCandlesReq): Promise ⋮---- /** * List futures tickers * * @param params Parameters for listing futures tickers * @returns Promise */ getDeliveryTickers(params: { settle: 'usdt'; contract?: string; }): Promise ⋮---- /** * Futures insurance balance history * * @param params Parameters for retrieving the futures insurance balance history * @returns Promise<{ * t: number; * b: string; * }[]> */ getDeliveryInsuranceBalanceHistory(params: { settle: 'usdt'; limit?: number; }): Promise< { t: number; b: string; }[] > { const { settle, ...query } = params; return this.get(`/delivery/$ ⋮---- /** * Query futures account * * @param params Parameters for querying futures account * @returns Promise */ getDeliveryAccount(params: ⋮---- /** * Query account book * * @param params Parameters for querying account book * @returns Promise */ getDeliveryBook(params: GetDeliveryBookReq): Promise ⋮---- /** * List all positions of a user * * @param params Parameters for listing all positions of a user * @returns Promise */ getDeliveryPositions(params: ⋮---- /** * Get single position * * @param params Parameters for retrieving a single position * @returns Promise */ getDeliveryPosition(params: { settle: 'usdt'; contract: string; }): Promise ⋮---- /** * Update position margin * * @param params Parameters for updating position margin * @returns Promise */ updateDeliveryMargin(params: { settle: 'usdt'; contract: string; change: string; }): Promise ⋮---- /** * Update position leverage * * @param params Parameters for updating position leverage * @returns Promise */ updateDeliveryLeverage(params: { settle: 'usdt'; contract: string; leverage: string; }): Promise ⋮---- /** * Update position risk limit * * @param params Parameters for updating position risk limit * @returns Promise */ updateDeliveryRiskLimit(params: { settle: 'usdt'; contract: string; risk_limit: string; }): Promise ⋮---- /** * Create a futures order * * Zero-filled order cannot be retrieved 10 minutes after order cancellation * * @param params Parameters for creating a futures order * @returns Promise */ submitDeliveryOrder( params: SubmitDeliveryFuturesOrderReq, ): Promise ⋮---- /** * List futures orders * * Zero-fill order cannot be retrieved 10 minutes after order cancellation. * * @param params Parameters for listing futures orders * @returns Promise */ getDeliveryOrders(params: GetDeliveryOrdersReq): Promise ⋮---- /** * Cancel all open orders matched * * Zero-filled order cannot be retrieved 10 minutes after order cancellation * * @param params Parameters for cancelling all open orders matched * @returns Promise */ cancelAllDeliveryOrders(params: { settle: 'usdt'; contract: string; side?: 'ask' | 'bid'; }): Promise ⋮---- /** * Get a single order * * Zero-filled order cannot be retrieved 10 minutes after order cancellation * * @param params Parameters for retrieving a single order * @returns Promise */ getDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /** * Cancel a single order * * @param params Parameters for cancelling a single order * @returns Promise */ cancelDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /** * List personal trading history * * @param params Parameters for listing personal trading history * @returns Promise */ getDeliveryTradingHistory( params: GetDeliveryTradingHistoryReq, ): Promise ⋮---- /** * List position close history * * @param params Parameters for listing position close history * @returns Promise */ getDeliveryClosedPositions( params: GetDeliveryClosedPositionsReq, ): Promise ⋮---- /** * List liquidation history * * @param params Parameters for listing liquidation history * @returns Promise */ getDeliveryLiquidationHistory( params: GetDeliveryLiquidationHistoryReq, ): Promise ⋮---- /** * List settlement history * * @param params Parameters for listing settlement history * @returns Promise */ getDeliverySettlementHistory( params: GetDeliverySettlementHistoryReq, ): Promise ⋮---- /** * Create a price-triggered order * * @param params Parameters for creating a price-triggered order * @returns Promise<{ id: number }> */ submitDeliveryTriggeredOrder( params: SubmitFuturesTriggeredOrderReq, ): Promise< ⋮---- /** * List all auto orders * * @param params Parameters for listing all auto orders * @returns Promise */ getDeliveryAutoOrders( params: GetDeliveryAutoOrdersReq, ): Promise ⋮---- /** * Cancel all open orders * * @param params Parameters for cancelling all open orders * @returns Promise */ cancelAllOpenDeliveryOrders(params: { settle: 'usdt'; contract: string; }): Promise ⋮---- /** * Get a price-triggered order * * @param params Parameters for retrieving a price-triggered order * @returns Promise */ getDeliveryTriggeredOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /** * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order * @returns Promise */ cancelTriggeredDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise ⋮---- /**========================================================================================================================== * OPTIONS * ========================================================================================================================== */ ⋮---- /** * List all underlyings * * @returns Promise<{ name: string; index_price: string }[]> */ getOptionsUnderlyings(): Promise< ⋮---- /** * List all expiration times * * @param params Parameters for listing expiration times * @returns Promise */ getOptionsExpirationTimes(params: ⋮---- /** * List all the contracts with specified underlying and expiration time * * @param params Parameters for listing contracts * @returns Promise */ getOptionsContracts(params: { underlying: string; expiration?: number; }): Promise ⋮---- /** * Query specified contract detail * * @param params Parameters for querying specified contract detail * @returns Promise */ getOptionsContract(params: ⋮---- /** * List settlement history * * @param params Parameters for listing settlement history * @returns Promise */ getOptionsSettlementHistory( params: GetOptionsSettlementHistoryReq, ): Promise ⋮---- /** * Get specified contract's settlement * * @param params Parameters for retrieving specified contract's settlement * @returns Promise */ getOptionsContractSettlement(params: { contract: string; underlying: string; at: number; }): Promise ⋮---- /** * List my options settlements * * @param params Parameters for listing my options settlements * @returns Promise */ getOptionsMySettlements( params: GetOptionsMySettlementsReq, ): Promise ⋮---- /** * Options order book * * Bids will be sorted by price from high to low, while asks sorted reversely * * @param params Parameters for retrieving options order book * @returns Promise */ getOptionsOrderBook( params: GetOptionsOrderBookReq, ): Promise ⋮---- /** * List tickers of options contracts * * @param params Parameters for listing tickers of options contracts * @returns Promise */ getOptionsTickers(params: ⋮---- /** * Get underlying ticker * * @param params Parameters for retrieving underlying ticker * @returns Promise<{ * trade_put: number; * trade_call: number; * index_price: string; * }> */ getOptionsUnderlyingTicker(params: ⋮---- /** * Get options Candles * * @param params Parameters for retrieving options Candles * @returns Promise */ getOptionsCandles(params: GetOptionsCandlesReq): Promise ⋮---- /** * Mark price Candles of an underlying * * @param params Parameters for retrieving mark price Candles of an underlying * @returns Promise */ getOptionsUnderlyingCandles( params: GetOptionsUnderlyingCandlesReq, ): Promise ⋮---- /** * Options trade history * * @param params Parameters for retrieving options trade history * @returns Promise */ getOptionsTrades(params: GetOptionsTradesReq): Promise ⋮---- /** * List options account * * @returns Promise */ getOptionsAccount(): Promise ⋮---- /** * List account changing history * * @param params Parameters for listing account changing history * @returns Promise */ getOptionsAccountChange( params?: GetOptionsAccountChangeReq, ): Promise ⋮---- /** * List user's positions of specified underlying * * @param params Parameters for listing user's positions of specified underlying * @returns Promise */ getOptionsPositionsUnderlying(params: { underlying?: string; }): Promise ⋮---- /** * Get specified contract position * * @param params Parameters for retrieving specified contract position * @returns Promise */ getOptionsPositionContract(params: { contract: string; }): Promise ⋮---- /** * List user's liquidation history of specified underlying * * @param params Parameters for listing user's liquidation history of specified underlying * @returns Promise */ getOptionsLiquidation(params: { underlying: string; contract?: string; }): Promise ⋮---- /** * Create an options order * * @param params Parameters for creating an options order * @returns Promise */ submitOptionsOrder( params: SubmitOptionsOrderReq, ): Promise ⋮---- /** * List options orders * * @param params Parameters for listing options orders * @returns Promise */ getOptionsOrders( params: GetOptionsOrdersReq, ): Promise ⋮---- /** * Cancel all open orders matched * * @param params Parameters for canceling all open orders matched * @returns Promise */ cancelAllOpenOptionsOrders(params: { contract?: string; underlying?: string; side?: 'ask' | 'bid'; }): Promise ⋮---- /** * Get a single order * * @param params Parameters for retrieving a single order * @returns Promise */ getOptionsOrder(params: { order_id: number; }): Promise ⋮---- /** * Cancel a single order * * @param params Parameters for canceling a single order * @returns Promise */ cancelOptionsOrder(params: { order_id: number; }): Promise ⋮---- /** * Countdown cancel orders for options * * Option order heartbeat detection. When the timeout set by the user is reached, * if there is no cancel or new countdown set, related pending orders will be * automatically cancelled. This endpoint can be called repeatedly to set a new * countdown or cancel the countdown. * * @param params Parameters for setting countdown cancel orders * @returns Promise<{ * triggerTime: number; * }> */ submitOptionsCountdownCancel(params: { timeout: number; contract?: string; underlying?: string; }): Promise< ⋮---- /** * List personal trading history * * @param params Parameters for listing personal trading history * @returns Promise */ getOptionsPersonalHistory( params: GetOptionsPersonalHistoryReq, ): Promise ⋮---- /** * Set MMP (Market Maker Protection) settings * * @param params Parameters for setting MMP settings * @returns Promise */ setOptionsMMPSettings( params: OptionsMMPSettingsReq, ): Promise ⋮---- /** * Query MMP (Market Maker Protection) settings * * @param params Parameters for querying MMP settings * @returns Promise */ getOptionsMMPSettings(params?: { underlying?: string; }): Promise ⋮---- /** * Reset MMP (Market Maker Protection) settings * * @param params Parameters for resetting MMP settings * @returns Promise */ resetOptionsMMPSettings(params: { underlying: string; }): Promise ⋮---- /**========================================================================================================================== * EARN UNI * ========================================================================================================================== */ ⋮---- /** * List currencies for lending * * @returns Promise */ getLendingCurrencies(): Promise ⋮---- /** * Get currency detail for lending * * @param params Parameters for retrieving currency detail for lending * @returns Promise */ getLendingCurrency(params: ⋮---- /** * Lend or redeem * * @param params Parameters for lending or redeeming * @returns Promise */ submitLendOrRedeemOrder(params: SubmitLendOrRedeemReq): Promise ⋮---- /** * List user's lending orders * * @param params Parameters for listing user's lending orders * @returns Promise */ getLendingOrders(params?: GetLendingOrdersReq): Promise ⋮---- /** * Amend lending order * * Currently only supports amending the minimum interest rate (hour) * * @param params Parameters for amending lending order * @returns Promise */ updateLendingOrder(params: { currency?: string; min_rate?: string; }): Promise ⋮---- /** * List records of lending * * @param params Parameters for listing records of lending * @returns Promise */ getLendingRecords(params?: GetLendingRecordsReq): Promise ⋮---- /** * Get the user's total interest income of specified currency * * @param params Parameters for retrieving the user's total interest income of specified currency * @returns Promise<{ * currency: string; * interest: string; * }> */ getLendingTotalInterest(params: ⋮---- /** * List interest records * * @param params Parameters for listing interest records * @returns Promise */ getLendingInterestRecords( params?: GetLendingInterestRecordsReq, ): Promise ⋮---- /** * Set interest reinvestment toggle * @deprecated as of v4.99.0, 23-06-2025 * * @param params Parameters for setting interest reinvestment toggle * @returns Promise */ updateInterestReinvestment(params: { currency: string; status: boolean; }): Promise ⋮---- /** * Query currency interest compounding status * * @param params Parameters for querying currency interest compounding status * @returns Promise<{ * currency: string; * interest_status: string; * }> */ getLendingInterestStatus(params: ⋮---- /** * UniLoan currency annualized trend chart * * Get the annualized interest rate trend chart data for a specific currency * * @param params Parameters for retrieving the annualized trend chart * @returns Promise<{ time: number; value: string }[]> */ getLendingAnnualizedTrendChart(params: { from: number; to: number; asset: string; }): Promise< ⋮---- getLendingEstimatedRates(): Promise< { currency: string; est_rate: string }[] > { return this.getPrivate('/earn/uni/rate'); ⋮---- /**========================================================================================================================== * COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- /** * Place order * * @param params Parameters for placing an order * @returns Promise<{ order_id: number }> */ submitLoanOrder(params: SubmitLoanOrderReq): Promise< ⋮---- /** * List Orders * * @param params Parameters for listing orders * @returns Promise */ getLoanOrders(params?: GetLoanOrdersReq): Promise ⋮---- /** * Get a single order * * @param params Parameters for retrieving a single order * @returns Promise */ getLoanOrder(params: ⋮---- /** * Repayment * * @param params Parameters for repayment * @returns Promise<{ * repaid_principal: string; * repaid_interest: string; * }> */ submitLoanRepay(params: { order_id: number; repay_amount: string; repaid_all: boolean; }): Promise< ⋮---- /** * Repayment history * * @param params Parameters for retrieving repayment history * @returns Promise */ getLoanRepaymentHistory( params: GetLoanRepaymentHistoryReq, ): Promise ⋮---- /** * Increase or redeem collateral * * @param params Parameters for increasing or redeeming collateral * @returns Promise */ updateLoanCollateral(params: UpdateLoanCollateralReq): Promise ⋮---- /** * Query collateral adjustment records * * @param params Parameters for querying collateral adjustment records * @returns Promise */ getLoanCollateralRecords( params?: GetLoanCollateralRecordsReq, ): Promise ⋮---- /** * Query the total borrowing and collateral amount for the user * * @returns Promise<{ * borrow_amount: string; * collateral_amount: string; * }> */ getLoanTotalAmount(): Promise< ⋮---- /** * Query user's collateralization ratio * * @param params Parameters for querying user's collateralization ratio * @returns Promise */ getLoanCollateralizationRatio(params: { collateral_currency: string; borrow_currency: string; }): Promise ⋮---- /** * Query supported borrowing and collateral currencies * * @param params Parameters for querying supported borrowing and collateral currencies * @returns Promise<{ * loan_currency: string; * collateral_currency: string[]; * }[]> */ getLoanSupportedCurrencies(params?: { loan_currency?: string }): Promise< { loan_currency: string; collateral_currency: string[]; }[] > { return this.get('/loan/collateral/currencies', params); ⋮---- /**========================================================================================================================== * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- /** * Create Multi-Collateral Order * * @param params Parameters for creating a multi-collateral order * @returns Promise<{ order_id: number }> */ submitMultiLoanOrder( params: SubmitMultiLoanOrderReq, ): Promise< ⋮---- /** * List Multi-Collateral Orders * * @param params Parameters for listing multi-collateral orders * @returns Promise */ getMultiLoanOrders( params?: GetMultiLoanOrdersReq, ): Promise ⋮---- /** * Get Multi-Collateral Order Detail * * @param params Parameters for retrieving a multi-collateral order detail * @returns Promise */ getMultiLoanOrder(params: ⋮---- /** * Repay Multi-Collateral Loan * * @param params Parameters for repaying a multi-collateral loan * @returns Promise */ repayMultiLoan(params: RepayMultiLoanReq): Promise ⋮---- /** * List Multi-Collateral Repay Records * * @param params Parameters for listing multi-collateral repay records * @returns Promise */ getMultiLoanRepayRecords( params: GetMultiLoanRepayRecordsReq, ): Promise ⋮---- /** * Operate Multi-Collateral * * @param params Parameters for operating multi-collateral * @returns Promise */ updateMultiLoan(params: UpdateMultiLoanReq): Promise ⋮---- /** * Query collateral adjustment records * * @param params Parameters for querying collateral adjustment records * @returns Promise */ getMultiLoanAdjustmentRecords( params?: GetMultiLoanAdjustmentRecordsReq, ): Promise ⋮---- /** * List User Currency Quota * * @param params Parameters for listing user currency quota * @returns Promise */ getMultiLoanCurrencyQuota(params: { type: 'collateral' | 'borrow'; currency: string; }): Promise ⋮---- /** * Query supported borrowing and collateral currencies in Multi-Collateral * * @returns Promise */ getMultiLoanSupportedCurrencies(): Promise ⋮---- /** * Get Multi-Collateral ratio * * @returns Promise */ getMultiLoanRatio(): Promise ⋮---- /** * Query fixed interest rates for the currency for 7 days and 30 days * * @returns Promise */ getMultiLoanFixedRates(): Promise ⋮---- /** * Query the current interest rate of currencies * * Query the current interest rate of currencies in the last hour. * The current interest rate is updated every hour. * * @param params Parameters containing currencies to query and optional VIP level * @returns Promise */ getMultiLoanCurrentRates(params: { currencies: string[]; vip_level?: string; }): Promise< { currency: string; current_rate: string; }[] > { return this.get('/loan/multi_collateral/current_rate', params); ⋮---- /**========================================================================================================================== * EARN * ========================================================================================================================== */ ⋮---- /** * ETH swap (formerly ETH2 swap) * @param params Parameters for ETH swap (1 - ETH to GTETH, 2 - GTETH to ETH) * @returns Promise */ submitEth2Swap(params: ⋮---- /** * Get GTETH historical rate of return data (formerly ETH2) * * @returns Promise> */ getEth2RateHistory(): Promise< { date_time: number; date: string; rate: string }[] > { return this.getPrivate('/earn/staking/eth2/rate_records'); ⋮---- /** * Dual Investment product list * * @returns Promise */ getDualInvestmentProducts(params?: { plan_id?: string; }): Promise ⋮---- /** * Dual Investment order list * * @returns Promise */ getDualInvestmentOrders( params?: FromToPageLimit, ): Promise ⋮---- /** * Place Dual Investment order * * @param params Parameters for placing a dual investment order * @returns Promise */ submitDualInvestmentOrder(params: { plan_id: string; copies: string; is_max: number; amount: string; }): Promise ⋮---- /** * Structured Product List * * @param params Parameters for listing structured products * @returns Promise */ getStructuredProducts( params: GetStructuredProductListReq, ): Promise ⋮---- /** * Structured Product Order List * * @param params Parameters for listing structured product orders * @returns Promise */ getStructuredProductOrders( params?: GetStructuredProductOrdersReq, ): Promise ⋮---- /** * Place Structured Product Order * * @param params Parameters for placing a structured product order * @returns Promise */ submitStructuredProductOrder(params: { pid?: string; amount?: string; }): Promise ⋮---- /** * List staking coins * * @param params Parameters for listing staking coins * @returns Promise */ getStakingCoins(params?: { coin?: string; cointype?: string; }): Promise ⋮---- /** * On-chain Token Swap for Earned Coins * * @param params Parameters for staking swap * @returns Promise */ submitStakingSwap(params: { coin: string; side: '0' | '1'; // 0 - Stake, 1 - Redeem amount: string; pid?: number; }): Promise ⋮---- side: '0' | '1'; // 0 - Stake, 1 - Redeem ⋮---- /**========================================================================================================================== * ACCOUNT * ========================================================================================================================== */ ⋮---- /** * Get account detail * * @returns Promise */ getAccountDetail(): Promise ⋮---- /** * Get user transaction rate limit information * * @returns Promise */ getAccountRateLimit(): Promise ⋮---- /** * Create STP Group * * @param params Parameters for creating an STP group * @returns Promise */ createStpGroup(params: CreateStpGroupReq): Promise ⋮---- /** * List STP Groups * * @param params Parameters for listing STP groups * @returns Promise */ getStpGroups(params?: ⋮---- /** * List users of the STP group * * @param params Parameters for listing users of the STP group * @returns Promise */ getStpGroupUsers(params: ⋮---- /** * Add users to the STP group * * @param params Parameters for adding users to the STP group * @returns Promise */ addUsersToStpGroup(params: { stp_id: number; body: number[]; }): Promise ⋮---- /** * Delete the user in the STP group * * @param params Parameters for deleting users from the STP group * @returns Promise */ deleteUserFromStpGroup(params: { stp_id: number; user_id: number; }): Promise ⋮---- /** * Set GT deduction * * Enable or disable GT deduction for the current account. * * @param params Parameters for setting GT deduction * @returns Promise */ setGTDeduction(params: ⋮---- /** * Query GT deduction configuration * * Query the current GT deduction configuration for the account. * * @returns Promise<{ enabled: boolean }> */ getGTDeduction(): Promise< ⋮---- /** * Query all main account API key information * * @returns Promise */ getAccountMainKeys(): Promise ⋮---- /**========================================================================================================================== * REBATES * ========================================================================================================================== */ ⋮---- /** * The agency obtains the transaction history of the recommended user. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving transaction history * @returns Promise */ getAgencyTransactionHistory( params: GetAgencyTransactionHistoryReq, ): Promise< ⋮---- /** * The agency obtains the commission history of the recommended user. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving commission history * @returns Promise */ getAgencyCommissionHistory( params: GetAgencyCommissionHistoryReq, ): Promise< ⋮---- /** * Partner obtains transaction records of recommended users * * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving transaction records * @returns Promise */ getPartnerTransactionHistory(params?: PartnerTransactionReq): Promise< ⋮---- /** * Partner obtains commission records of recommended users * * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving commission records * @returns Promise */ getPartnerCommissionHistory(params?: PartnerTransactionReq): Promise< ⋮---- /** * Partner subordinate list * * Including sub-agents, direct customers, indirect customers * * @param params Parameters for retrieving partner subordinate list * @returns Promise<{ * total: number; * list: { * user_id: number; * user_join_time: number; * type: number; * desc: string; * }[]; * }> */ getPartnerSubordinateList(params?: GetPartnerSubordinateListReq): Promise< ⋮---- /** * The broker obtains the user's commission rebate records. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving commission rebate records * @returns Promise */ getBrokerCommissionHistory( params: GetBrokerCommissionHistoryReq, ): Promise< ⋮---- /** * The broker obtains the user's trading history. * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving trading history * @returns Promise */ getBrokerTransactionHistory( params: GetBrokerTransactionHistoryReq, ): Promise< ⋮---- /** * User retrieves rebate information. */ getUserRebateInfo(): Promise< ⋮---- /** * Query user-subordinate relationship * * Checks whether specified users are in the system and their relationship status */ getUserSubordinateRelationships(params: { user_id_list: string; // Comma-separated list of user IDs (max 100) }): Promise< ⋮---- user_id_list: string; // Comma-separated list of user IDs (max 100) ================ File: src/WebsocketAPIClient.ts ================ import { DefaultLogger } from './lib/logger.js'; import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; import { WSClientConfigurableOptions } from './types/websockets/client.js'; import { WSAPIFuturesOrder, WSAPIFuturesOrderAmendReq, WSAPIFuturesOrderBatchPlaceRespItem, WSAPIFuturesOrderCancelCPReq, WSAPIFuturesOrderCancelIdsRespItem, WSAPIFuturesOrderCancelReq, WSAPIFuturesOrderListReq, WSAPIFuturesOrderPlaceReq, WSAPIFuturesOrderStatusReq, WSAPIResponse, WSAPISpotOrder, WSAPISpotOrderAmendReq, WSAPISpotOrderCancelCPReq, WSAPISpotOrderCancelIdsReq, WSAPISpotOrderCancelIdsRespItem, WSAPISpotOrderCancelReq, WSAPISpotOrderListReq, WSAPISpotOrderPlaceReq, WSAPISpotOrderStatusReq, WSAPIWsKey, } from './types/websockets/wsAPI.js'; import { WebsocketClient } from './WebsocketClient.js'; ⋮---- /** * Configurable options specific to only the REST-like WebsocketAPIClient */ export interface WSAPIClientConfigurableOptions { /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ attachEventListeners: boolean; } ⋮---- /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ ⋮---- /** * This is a minimal Websocket API wrapper around the WebsocketClient. * * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should * be used to transmit that message. This is only useful if you wish to use an alternative wss * domain that is supported by the SDK. * * Note: To use testnet, don't set the wsKey - use `testnet: true` in * the constructor instead. * * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some * may find the below methods slightly more intuitive. * * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 */ export class WebsocketAPIClient ⋮---- constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, ) ⋮---- public getWSClient(): WebsocketClient ⋮---- public setTimeOffsetMs(newOffset: number): void ⋮---- /* * * SPOT - Trading requests * */ ⋮---- /** * Submit a spot order */ submitNewSpotOrder( params: WSAPISpotOrderPlaceReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel a spot order */ cancelSpotOrder( params: WSAPISpotOrderCancelReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel all spot orders with the given id list */ cancelSpotOrderById( params: WSAPISpotOrderCancelIdsReq[], wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel a spot order for a given symbol */ cancelSpotOrderForSymbol( params: WSAPISpotOrderCancelCPReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Update a spot order */ updateSpotOrder( params: WSAPISpotOrderAmendReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get the status of a spot order */ getSpotOrderStatus( params: WSAPISpotOrderStatusReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get all spot orders */ getSpotOrders( params: WSAPISpotOrderListReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /* * * Futures - Trading requests * */ ⋮---- /** * Submit a futures order. * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ submitNewFuturesOrder( params: WSAPIFuturesOrderPlaceReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Submit a batch of futures orders * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ submitNewFuturesBatchOrder( params: WSAPIFuturesOrderPlaceReq[], wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel a futures order * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ cancelFuturesOrder( params: WSAPIFuturesOrderCancelReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel futures orders by id list * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ cancelFuturesOrderById( params: string[], wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Cancel all open futures orders * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ cancelFuturesAllOpenOrders( params: WSAPIFuturesOrderCancelCPReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Update a futures order * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ updateFuturesOrder( params: WSAPIFuturesOrderAmendReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get all futures orders * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ getFuturesOrders( params: WSAPIFuturesOrderListReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * Get futures order status * * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ getFuturesOrderStatus( params: WSAPIFuturesOrderStatusReq, wsKey?: WSAPIWsKey, ): Promise> ⋮---- /** * * * * * * * * Private methods for handling some of the convenience/automation provided by the WS API Client * * * * * * * */ ⋮---- private setupDefaultEventListeners() ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- // Blind JSON.stringify can fail on circular references ⋮---- // JSON.stringify({ ...data, target: 'WebSocket' }), ================ File: src/WebsocketClient.ts ================ import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; import { neverGuard } from './lib/misc-util.js'; import { CHANNEL_ID, MessageEventLike } from './lib/requestUtils.js'; import { SignAlgorithm, SignEncodeMethod, signMessage, } from './lib/webCryptoAPI.js'; import { getPrivateFuturesTopics, getPrivateOptionsTopics, getPrivateSpotTopics, getPromiseRefForWSAPIRequest, WS_BASE_URL_MAP, WS_KEY_MAP, WsKey, WsMarket, WsTopicRequest, } from './lib/websocket/websocket-util.js'; import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; import { WSAPIRequest, WsOperation, WsRequestOperationGate, WsRequestPing, } from './types/websockets/requests.js'; import { WsAPITopicRequestParamMap, WsAPITopicResponseMap, WSAPIWsKey, WsAPIWsKeyTopicMap, } from './types/websockets/wsAPI.js'; ⋮---- export interface WSAPIRequestFlags { /** If true, will skip auth requirement for WS API connection */ authIsOptional?: boolean | undefined; } ⋮---- /** If true, will skip auth requirement for WS API connection */ ⋮---- /** * WS topics are always a string for gate. Some exchanges use complex objects */ export type WsTopic = string; ⋮---- export class WebsocketClient extends BaseWebsocketClient ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. * * Returns array of promises that individually resolve when each connection is successfully opened. */ public connectAll(): Promise[] ⋮---- /** * Ensures the WS API connection is active and ready. * * You do not need to call this, but if you call this before making any WS API requests, * it can accelerate the first request (by preparing the connection in advance). */ public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise ⋮---- /** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- /** * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters). * Objects should be formatted as {topic: string, params: object}. * * - Subscriptions are automatically routed to the correct websocket connection. * - Authentication/connection is automatic. * - Resubscribe after network issues is automatic. * * Call `unsubscribe(topics)` to remove topics */ public subscribe( requests: | (WsTopicRequest | WsTopic) | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) ⋮---- /** * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. * * - Requests are automatically routed to the correct websocket connection. * - These topics will be removed from the topic cache, so they won't be subscribed to again. */ public unsubscribe( requests: | (WsTopicRequest | WsTopic) | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) ⋮---- /** * WS API Methods - similar to the REST API, but via WebSockets */ ⋮---- /** * Send a Websocket API event on a connection. Returns a promise that resolves on reply. * * Returned promise is rejected if an exception is detected in the reply OR the connection disconnects for any reason (even if automatic reconnect will happen). * * After a fresh connection, you should always send a login request first. * * If you authenticated once and you're reconnected later (e.g. connection temporarily lost), the SDK will by default automatically: * - Detect you were authenticated to the WS API before * - Try to re-authenticate (up to 5 times, in case something (bad timestamp) goes wrong) * - If it succeeds, it will emit the 'authenticated' event. * - If it fails and gives up, it will emit an 'exception' event (type: 'wsapi.auth', reason: detailed text). * * You can turn off the automatic re-auth WS API logic using `reauthWSAPIOnReconnect: false` in the WSClient config. * * @param wsKey - The connection this event is for (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4") * @param channel - The channel this event is for (e.g. "spot.login" to authenticate) * @param params - Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs. * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response */ ⋮---- // This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call) async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse extends | WsAPITopicResponseMap[TWSChannel] | object = WsAPITopicResponseMap[TWSChannel], >( wsKey: TWSKey, channel: TWSChannel, params?: TWSParams extends void | never ? undefined : TWSParams, requestFlags?: WSAPIRequestFlags, ): Promise; ⋮---- async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse = object, >( wsKey: TWSKey, channel: TWSChannel, params: TWSParams & { signRequest?: boolean }, requestFlags?: WSAPIRequestFlags, ): Promise ⋮---- // Some commands don't require authentication. ⋮---- // this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- // this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- // id: timeInSeconds, ⋮---- /** * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated * can introduce a small delay before the actual request is sent, if not connected before that request is * made. This can lead to a curious race condition, where the request timestamp is before * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. * * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, * it offsets that timestamp by the delay. */ ⋮---- // Sign request ⋮---- // Store deferred promise ⋮---- // Enrich returned promise with request context for easier debugging ⋮---- // throw e; ⋮---- // Send event ⋮---- // Return deferred promise, so caller can await this call ⋮---- /** * * Internal methods - not intended for public use * */ ⋮---- protected getWsUrl(wsKey: WsKey): string ⋮---- protected sendPingEvent(wsKey: WsKey) ⋮---- protected sendPongEvent(wsKey: WsKey) ⋮---- // Send a protocol layer pong ⋮---- // NOT IN USE for gate.io, pings for gate are protocol layer pings // eslint-disable-next-line @typescript-eslint/no-unused-vars protected isWsPing(_msg: any): boolean ⋮---- protected isWsPong(msg: any): boolean ⋮---- /** * Parse incoming events into categories, before emitting to the user */ protected resolveEmittableEvents( wsKey: WsKey, event: MessageEventLike, ): EmittableEvent[] ⋮---- // WS API Exception ⋮---- // WS API Success ⋮---- // Most events use "event: 'update'" for topic updates // The legacy "futures.order_book" topic uses "all" for this field // 'futures.obu' is used for the orderbook v2 event. Oddly in a different structure than the other topics. ⋮---- // These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- // Request/reply pattern for authentication success ⋮---- /** * Determines if a topic is for a private channel, using a hardcoded list of strings */ protected isPrivateTopicRequest( request: WsTopicRequest, wsKey: WsKey, ): boolean ⋮---- // No private announcements channels ⋮---- /** * Not in use for gate.io */ ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket ⋮---- /** * Not in use for gate.io */ protected getPrivateWSKeys(): WsKey[] ⋮---- protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** Force subscription requests to be sent in smaller batches, if a number is returned */ // eslint-disable-next-line @typescript-eslint/no-unused-vars protected getMaxTopicsPerSubscribeEvent(_wsKey: WsKey): number | null ⋮---- /** * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) */ protected async getWsOperationEventsForTopics( topics: WsTopicRequest[], wsKey: WsKey, operation: WsOperation, ): Promise ⋮---- // console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); // console.trace(); ⋮---- // Events that are ready to send (usually stringified JSON) ⋮---- /** * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ private async getWsRequestEvents( market: WsMarket, operation: WsOperation, requests: WsTopicRequest[], wsKey: WsKey, ): Promise[]> ⋮---- // If private topic request, build auth part for request ⋮---- // No key or secret, push event as failed ⋮---- private async signMessage( paramsStr: string, secret: string, method: 'hex' | 'base64', algorithm: SignAlgorithm, ): Promise ⋮---- protected async getWsAuthRequestEvent(wsKey: WsKey): Promise ⋮---- // id: timeInSeconds, ⋮---- /** * * @param requestEvent * @returns A signed updated WS API request object, ready to be sent */ private async signWSAPIRequest( requestEvent: WSAPIRequest, ): Promise> ================ File: .eslintrc.cjs ================ // 'no-unused-vars': ['warn'], ================ File: .gitignore ================ !.gitkeep .DS_STORE *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json pids *.pid *.seed *.pid.lock node_modules/ .npm .eslintcache .node_repl_history *.tgz .yarn-integrity .env .env.test .cache bundleReport.html .history/ dist coverage localtest.sh repomix.sh ws-private-spot-wsapi-performance.ts ws-private-perp-futures-wsapi-readonly.ts privatetest.ts privaterepotracker restClientRegex.ts testfile.ts ================ File: .nvmrc ================ v22.17.0 ================ File: .prettierrc ================ { "tabWidth": 2, "singleQuote": true, "trailingComma": "all" } ================ File: jest.config.ts ================ /** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */ ⋮---- import type { Config } from 'jest'; ⋮---- // All imported modules in your tests should be mocked automatically // automock: false, ⋮---- // Stop running tests after `n` failures // bail: 0, bail: false, // enable to stop test when an error occur, ⋮---- // The directory where Jest should store its cached dependency information // cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- // Automatically clear mock calls, instances, contexts and results before every test ⋮---- // Indicates whether the coverage information should be collected while executing the test ⋮---- // An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- // The directory where Jest should output its coverage files ⋮---- // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // Indicates which provider should be used to instrument code for coverage ⋮---- // A list of reporter names that Jest uses when writing coverage reports // coverageReporters: [ // "json", // "text", // "lcov", // "clover" // ], ⋮---- // An object that configures minimum threshold enforcement for coverage results // coverageThreshold: undefined, ⋮---- // A path to a custom dependency extractor // dependencyExtractor: undefined, ⋮---- // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, ⋮---- // The default configuration for fake timers // fakeTimers: { // "enableGlobally": false // }, ⋮---- // Force coverage collection from ignored files using an array of glob patterns // forceCoverageMatch: [], ⋮---- // A path to a module which exports an async function that is triggered once before all test suites // globalSetup: undefined, ⋮---- // A path to a module which exports an async function that is triggered once after all test suites // globalTeardown: undefined, ⋮---- // A set of global variables that need to be available in all test environments // globals: {}, ⋮---- // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. // maxWorkers: "50%", ⋮---- // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ // "node_modules" // ], ⋮---- // An array of file extensions your modules use ⋮---- // modulePaths: ['src'], ⋮---- // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module // moduleNameMapper: {}, ⋮---- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], ⋮---- // Activates notifications for test results // notify: false, ⋮---- // An enum that specifies notification mode. Requires { notify: true } // notifyMode: "failure-change", ⋮---- // A preset that is used as a base for Jest's configuration // preset: undefined, ⋮---- // Run tests from one or more projects // projects: undefined, ⋮---- // Use this configuration option to add custom reporters to Jest // reporters: undefined, ⋮---- // Automatically reset mock state before every test // resetMocks: false, ⋮---- // Reset the module registry before running each individual test // resetModules: false, ⋮---- // A path to a custom resolver // resolver: undefined, ⋮---- // Automatically restore mock state and implementation before every test // restoreMocks: false, ⋮---- // The root directory that Jest should scan for tests and modules within // rootDir: undefined, ⋮---- // A list of paths to directories that Jest should use to search for files in // roots: [ // "" // ], ⋮---- // Allows you to use a custom runner instead of Jest's default test runner // runner: "jest-runner", ⋮---- // The paths to modules that run some code to configure or set up the testing environment before each test // setupFiles: [], ⋮---- // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], ⋮---- // The number of seconds after which a test is considered as slow and reported as such in the results. // slowTestThreshold: 5, ⋮---- // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], ⋮---- // The test environment that will be used for testing // testEnvironment: "jest-environment-node", ⋮---- // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, ⋮---- // Adds a location field to test results // testLocationInResults: false, ⋮---- // The glob patterns Jest uses to detect test files ⋮---- // "**/__tests__/**/*.[jt]s?(x)", ⋮---- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped // testPathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // The regexp pattern or array of patterns that Jest uses to detect test files // testRegex: [], ⋮---- // This option allows the use of a custom results processor // testResultsProcessor: undefined, ⋮---- // This option allows use of a custom test runner // testRunner: "jest-circus/runner", ⋮---- // A map from regular expressions to paths to transformers // transform: undefined, ⋮---- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ // "/node_modules/", // "\\.pnp\\.[^\\/]+$" // ], ⋮---- // Prevents import esm module error from v1 axios release, issue #5026 ⋮---- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them // unmockedModulePathPatterns: undefined, ⋮---- // Indicates whether each individual test should be reported during the run // verbose: undefined, verbose: true, // report individual test ⋮---- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode // watchPathIgnorePatterns: [], ⋮---- // Whether to use watchman for file crawling // watchman: true, ================ File: LICENSE.md ================ Copyright 2022 Tiago Siebler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================ File: package.json ================ { "name": "gateio-api", "version": "1.3.1", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", "build": "rm -fr dist/* && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", "test": "jest --passWithNoTests", "lint": "eslint src" }, "main": "dist/cjs/index.js", "module": "dist/mjs/index.js", "types": "dist/mjs/index.d.ts", "exports": { ".": { "import": "./dist/mjs/index.js", "require": "./dist/cjs/index.js", "types": "./dist/mjs/index.d.ts" } }, "type": "module", "files": [ "dist/*", "llms.txt" ], "author": "Tiago Siebler (https://github.com/tiagosiebler)", "contributors": [ "Jerko J (https://github.com/JJ-Cro)" ], "dependencies": { "axios": "^1.12.2", "isomorphic-ws": "^4.0.1", "ws": "^8.18.3" }, "devDependencies": { "@types/jest": "^29.5.12", "@types/node": "^22.10.2", "@types/ws": "^8.5.10", "@typescript-eslint/eslint-plugin": "^8.18.0", "@typescript-eslint/parser": "^8.18.0", "eslint": "^8.29.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.1.3", "eslint-plugin-require-extensions": "^0.1.3", "eslint-plugin-simple-import-sort": "^12.1.1", "jest": "^29.7.0", "ts-jest": "^29.1.2", "ts-node": "^10.9.2", "typescript": "^5.7.3" }, "keywords": [ "Gate", "Gate.io", "Gate.com", "Gate api", "Gate.io api", "Gate.com api", "Gate nodejs", "Gate javascript", "Gate javascript websocket api", "Gate typescript", "Gate js", "Gate ts", "Gate api node", "Gate sdk javascript", "algo trading", "api", "websocket", "rest", "rest api", "ccxt", "trading bots", "nodejs", "node", "trading", "cryptocurrency", "bitcoin", "best" ], "funding": { "type": "individual", "url": "https://github.com/sponsors/tiagosiebler" }, "license": "MIT", "repository": { "type": "git", "url": "https://github.com/tiagosiebler/gateio-api" }, "bugs": { "url": "https://github.com/tiagosiebler/gateio-api/issues" }, "homepage": "https://github.com/tiagosiebler/gateio-api#readme" } ================ File: postBuild.sh ================ #!/bin/bash # # Add package.json files to cjs/mjs subtrees # cat >dist/cjs/package.json <dist/mjs/package.json < 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/tiagosiebler/gateio-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/gateio-api/actions/workflows/e2etest.yml) [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/gateio-api)][1] [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) [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 & Announcements APIs. - Unified RestClient for all Gate.com trading products. - Strongly typed on most requests and responses. - 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. - WebSocket API for Gate.com Spot, Margin, Perpetual Futures & Delivery Futures. - 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). ## 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) - [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/tiagosiebler/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 my related JavaScript/TypeScript/Node.js projects: - Try my REST API & WebSocket SDKs: - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/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) - [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, and Options. 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, }); 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', // Specify the currency pair status: 'open', // Specify the status of the orders to fetch }) .then((result) => { console.log('getSpotOrders result: ', result); }) .catch((err) => { console.error('getSpotOrders error: ', err); }); ``` See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets All WebSocket functionality is supported via the unified `WebsocketClient`. This client handles all Gate.com WebSocket streams with automatic connection management and reconnection. Key WebSocket features: - Event driven messaging - Smart WebSocket persistence with automatic reconnection - Heartbeat mechanisms to detect disconnections - Automatic resubscription after reconnection - Support for all Gate.com trading products (Spot, Margin, Futures, Options) - WebSocket API support for real-time trading operations ### WebSocket Data Streams All available WebSockets can be used via a shared `WebsocketClient`. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see [WS_KEY_MAP](src/lib/websocket/websocket-util.ts) for a list of supported values). Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the [examples](./examples/) folder on GitHub. Data events are emitted from the WebsocketClient via the `update` event, see example below: ```javascript const { WebsocketClient } = require('gateio-api'); const API_KEY = 'xxx'; const PRIVATE_KEY = 'yyy'; const wsConfig = { apiKey: API_KEY, apiSecret: PRIVATE_KEY, /* The following parameters are optional: */ // Livenet is used by default, use this to enable testnet: // useTestnet: true // how long to wait (in ms) before deciding the connection should be terminated & reconnected // pongTimeout: 1000, // how often to check (in ms) that WS connection is still alive // pingInterval: 10000, // how long to wait before attempting to reconnect (in ms) after connection is closed // reconnectTimeout: 500, // config options sent to RestClient (used for time sync). See RestClient docs. // restOptions: { }, // config for axios used for HTTP requests. E.g for proxy support // requestOptions: { } }; const ws = new WebsocketClient(wsConfig); /** * Subscribing to data: **/ const userOrders = { topic: 'spot.orders', payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], }; const userTrades = { topic: 'spot.usertrades', payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], }; const userPriceOrders = { topic: 'spot.priceorders', payload: ['!all'], }; // subscribe to multiple topics at once ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4'); // and/or subscribe to individual topics on demand ws.subscribe( { topic: 'spot.priceorders', payload: ['!all'], }, 'spotV4', ); // Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above) ws.subscribe('spot.balances', 'spotV4'); /** * Handling events: **/ // Listen to events coming from websockets. This is the primary data source ws.on('update', (data) => { console.log('data', data); }); // Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) ws.on('open', ({ wsKey, event }) => { console.log('connection open for websocket with ID: ' + wsKey); }); // Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic) ws.on('response', (response) => { console.log('response', response); }); // Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected. ws.on('close', () => { console.log('connection closed'); }); // Optional: listen to internal exceptions. Useful for debugging if something weird happens ws.on('exception', (data) => { console.error('exception: ', data); }); // Optional: Listen to raw error events. ws.on('error', (err) => { console.error('ERR', err); }); ``` See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail. ### Websocket API Gate.com supports sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. The WebSocket API is available through two approaches, depending on individual preference: #### Event Driven API The WebSocket API is available in the [WebsocketClient](./src/WebsocketClient.ts) via the `sendWSAPIRequest(wsKey, channel, params)` method. Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. - event-driven: - send requests via `client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API exception for channel', channel, e))`, fire and forget, don't use await - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` - promise-driven: - send requests via `const result = await client.sendWSAPIRequest(wsKey, channel, params)`, which returns a promise - await each call - use try/catch blocks to handle promise rejections #### REST-like API The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the RestClient). It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. ```javascript const { WebsocketAPIClient } = require('gateio-api'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; async function start() { // Make an instance of the WS API Client const wsClient = new WebsocketAPIClient({ apiKey: API_KEY, apiSecret: API_SECRET, // Automatically re-auth WS API, if we were auth'd before and get reconnected reauthWSAPIOnReconnect: true, }); try { // Connection will authenticate automatically before first request // Make WebSocket API calls, very similar to a REST API: /* ============ SPOT TRADING EXAMPLES ============ */ // Submit a new spot order const newOrder = await wsClient.submitNewSpotOrder({ text: 't-my-custom-id', currency_pair: 'BTC_USDT', type: 'limit', account: 'spot', side: 'buy', amount: '1', price: '10000', }); console.log('Order result:', newOrder.data); // Cancel a spot order const cancelOrder = await wsClient.cancelSpotOrder({ order_id: '1700664330', currency_pair: 'BTC_USDT', account: 'spot', }); console.log('Cancel result:', cancelOrder.data); // Get spot order status const orderStatus = await wsClient.getSpotOrderStatus({ order_id: '1700664330', currency_pair: 'BTC_USDT', account: 'spot', }); console.log('Order status:', orderStatus.data); /* ============ FUTURES TRADING EXAMPLES ============ */ // Submit a new futures order const newFuturesOrder = await wsClient.submitNewFuturesOrder({ contract: 'BTC_USDT', size: 10, price: '31503.28', tif: 'gtc', text: 't-my-custom-id', }); console.log('Futures order result:', newFuturesOrder.data); // Cancel a futures order const cancelFuturesOrder = await wsClient.cancelFuturesOrder({ order_id: '74046514', }); console.log('Cancel futures order result:', cancelFuturesOrder.data); // Get futures order status const futuresOrderStatus = await wsClient.getFuturesOrderStatus({ order_id: '74046543', }); console.log('Futures order status:', futuresOrderStatus.data); } catch (e) { console.error('WS API Error:', e); } } start(); ``` For more detailed examples using any approach, refer to the [examples](./examples/) folder (e.g. [ws-api-client.ts](./examples/ws-api-client.ts)). --- ## Customise Logging Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired. ```javascript const { WebsocketClient, DefaultLogger } = require('gateio-api'); // Disable all logging on the silly level DefaultLogger.silly = () => {}; const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger); ``` ## 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/tiagosiebler/gateio-api/image)](https://github.com/tiagosiebler/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` ### 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=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) ================ File: tea.yaml ================ --- version: 1.0.0 codeOwners: - '0xeb1a7BF44a801e33a339705A266Afc0Cba3D6D54' quorum: 1 ================ File: tsconfig.cjs.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "outDir": "dist/cjs", "target": "esnext" }, "include": ["src/**/*.*"] } ================ File: tsconfig.esm.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "module": "esnext", "outDir": "dist/mjs", "target": "esnext" }, "include": ["src/**/*.*"] } ================ File: tsconfig.json ================ { "compilerOptions": { "allowSyntheticDefaultImports": true, "baseUrl": ".", "noEmitOnError": true, "declaration": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": false, "inlineSourceMap": false, "lib": ["esnext"], "listEmittedFiles": false, "listFiles": false, "moduleResolution": "node", "noFallthroughCasesInSwitch": true, "noImplicitAny": true, "noUnusedParameters": true, "pretty": true, "removeComments": false, "resolveJsonModule": true, "skipLibCheck": false, "sourceMap": true, "strict": true, "strictNullChecks": true, "types": ["node", "jest"], "module": "commonjs", "outDir": "dist/cjs", "target": "esnext" }, "compileOnSave": true, "exclude": ["node_modules", "dist"], "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] } ================ File: tsconfig.linting.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "outDir": "dist/cjs", "target": "esnext", "rootDir": "../", "allowJs": true }, "include": [ "src/**/*.*", "test/**/*.*", "examples/**/*.*", ".eslintrc.cjs", "jest.config.ts" ] } ================================================================ End of Codebase ================================================================