### Execute WebSocket Public Example with ts-node Source: https://github.com/tiagosiebler/gateio-api/blob/master/examples/README.md Run the public WebSocket example using ts-node. Ensure ts-node is installed. ```bash ts-node ./examples/ws-public.ts ``` -------------------------------- ### Execute Spot Get Tickers Example with Node.js Source: https://github.com/tiagosiebler/gateio-api/blob/master/examples/README.md Run the spot tickers example using Node.js. Rename the file to .js if needed. TypeScript is optional. ```bash node ./examples/spot/getTickers.js ``` -------------------------------- ### Initialize RestClient and Get Spot Orders Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt This example demonstrates fetching both open and finished spot orders for a specified currency pair. Ensure your API credentials are set up correctly. ```typescript 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 const account = { 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 const client = new RestClient(account); async function getSpotOrders() { try { // Fetch open spot orders for the BTC_USDT currency pair const openOrders = await client.spot.getOrders({ 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 const finishedOrders = await client.spot.getOrders({ 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 } catch (e) { console.error('Error in execution: ', e); // Log any errors that occur } } // Execute the function to get spot orders getSpotOrders(); ``` -------------------------------- ### Initialize RestClient and Get Spot Tickers Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt This example shows how to retrieve ticker information for a specific currency pair and for all available pairs. Ensure API credentials are configured. ```typescript 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 const account = { 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 const client = new RestClient(account); async function getSpotTicker() { try { // Fetch the ticker for a specific currency pair (BTC_USDT) const ticker = await client.spot.getTickers({ currency_pair: 'BTC_USDT', // Specify the currency pair }); console.log('Response: ', ticker); // Log the response to the console // Fetch all tickers const allTickers = await client.spot.getAllTickers(); console.log('Response: ', allTickers); // Log the response to the console } catch (e) { console.error('Error in execution: ', e); // Log any errors that occur } } // Execute the function to get spot tickers getSpotTicker(); ``` -------------------------------- ### Install gateio-api SDK Source: https://context7.com/tiagosiebler/gateio-api/llms.txt Install the SDK using npm. This is the first step before using any of the SDK's functionalities. ```bash npm install gateio-api ``` -------------------------------- ### Make a GET Request Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Helper method for making GET requests. GET requests only support parameters in the query string. ```typescript protected get(endpoint: string, params?: object) ``` -------------------------------- ### Get Dual Project Recommend Source: https://github.com/tiagosiebler/gateio-api/blob/master/docs/endpointFunctionList.md Retrieves recommended dual investment projects. ```APIDOC ## GET /earn/dual/project-recommend ### Description Retrieves recommended dual investment projects. ### Method GET ### Endpoint /earn/dual/project-recommend ``` -------------------------------- ### Get Currency Chains Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Lists all supported blockchain chains for a given currency. ```APIDOC ## GET /api/v4/wallet/currency_chains ### Description Lists chains supported for a specified currency. ### Method GET ### Endpoint /api/v4/wallet/currency_chains ### Parameters #### Query Parameters - **currency** (string) - Required - The currency for which to list chains. ### Response #### Success Response (200) - **chain** (string) - The name of the blockchain chain. - **deposit_with_address** (boolean) - Whether deposit is supported with an address. - **withdraw_with_address** (boolean) - Whether withdrawal is supported with an address. #### Response Example ```json [ { "chain": "USDT_ERC20", "deposit_with_address": true, "withdraw_with_address": true }, { "chain": "USDT_TRC20", "deposit_with_address": true, "withdraw_with_address": true } ] ``` ``` -------------------------------- ### Get Futures Contract Size Multiplier Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Example demonstrating how to get the futures contract size multiplier (quanto_multiplier) and convert between notional value and order size in contracts. ```typescript /** * Example: Get futures contract size (quanto_multiplier) and convert between * notional (e.g. USDT) and order size in contracts. * * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. */ ``` -------------------------------- ### Initialize RestClient and Get Spot Balances Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Demonstrates how to initialize the RestClient with API credentials and fetch spot account balances. Ensure your API key and secret are correctly set as environment variables or replaced directly. ```typescript 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 const account = { 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 const client = new RestClient(account); async function getSpotBalances() { try { // Fetch the spot account balances const balances = await client.spot.getBalances(); console.log('Response: ', balances); // Log the response to the console } catch (e) { console.error('Error in execution: ', e); // Log any errors that occur } } // Execute the function to get spot balances getSpotBalances(); ``` -------------------------------- ### Get Futures Tickers (TypeScript) Source: https://context7.com/tiagosiebler/gateio-api/llms.txt Fetches real-time ticker data for perpetual futures contracts. This is a public endpoint. Examples show fetching a single contract's ticker and all USDT-settled tickers. ```typescript import { RestClient } from 'gateio-api'; const client = new RestClient({}); async function main() { try { // Single contract ticker const btcTicker = await client.getFuturesTickers({ settle: 'usdt', contract: 'BTC_USDT', }); console.log('BTC_USDT futures ticker:', btcTicker); // All USDT-settled tickers const allTickers = await client.getFuturesTickers({ settle: 'usdt' }); console.log(`Total futures tickers: ${allTickers.length}`); } catch (e) { console.error('Error fetching futures tickers:', e); } } main(); ``` -------------------------------- ### Event-driven WebSocket Client Setup Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Sets up a WebSocket client with event listeners for 'response' and 'authenticated' events. This demonstrates the event-driven approach for handling WebSocket communication. ```javascript client.on('response', (data) => { console.info( new Date(), 'ws server reply ', JSON.stringify(data, null, 2), '\n', ); }); client.on('authenticated', (data) => { console.error(new Date(), 'ws authenticated: ', data); }); ``` -------------------------------- ### RestClient Initialization and Spot Trading Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Demonstrates how to initialize the RestClient and perform a Spot trading operation to get all spot tickers. ```APIDOC ## RestClient Initialization and Spot Trading ### Description Initialize the `RestClient` with your API key and private key, then use it to fetch all spot tickers. ### Method `new RestClient(config)` `client.getSpotTicker()` ### Parameters #### RestClient Initialization - **apiKey** (string) - Your Gate.io API key. - **apiSecret** (string) - Your Gate.io private key. #### getSpotTicker Parameters None ### Request Example ```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); }); ``` ### Response #### Success Response (200) - **result** (object) - An object containing spot ticker information. ``` -------------------------------- ### Make a Private GET Request Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Helper method for making private GET requests. GET requests only support parameters in the query string. ```typescript protected getPrivate(endpoint: string, params?: object) ``` -------------------------------- ### WebsocketClient - connectAll / Pre-connect Source: https://context7.com/tiagosiebler/gateio-api/llms.txt Shows how to eagerly establish all available WebSocket connections in advance using `connectAll()`, ensuring that subsequent subscriptions or API calls have no connection overhead. ```APIDOC ## WebsocketClient — connectAll / Pre-connect Eagerly opens all available WebSocket connections in advance so the first subscription or WS API call incurs no connection overhead. ### Usage ```typescript import { WebsocketClient } from 'gateio-api'; const client = new WebsocketClient({ apiKey: process.env.API_KEY!, apiSecret: process.env.API_SECRET!, }); async function main() { // Pre-connect all WebSocket endpoints const connections = client.connectAll(); await Promise.all(connections); console.log('All WebSocket connections established'); // Now subscriptions and WS API calls will be instant client.subscribe('spot.balances', 'spotV4'); client.on('update', (data) => console.log('Data:', JSON.stringify(data))); } main(); ``` ``` -------------------------------- ### Get P2P Merchant Ad Detail Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get the details of a P2P merchant ad. ```APIDOC ## GET /api/v4/p2p/merchant/ads/{ad_id} ### Description Get the details of a P2P merchant ad. ### Method GET ### Endpoint /api/v4/p2p/merchant/ads/{ad_id} ### Parameters #### Path Parameters - **ad_id** (string) - Required - The ID of the ad. ### Response #### Success Response (200) - **ad_id** (string) - The ID of the ad. - **currency** (string) - The currency of the ad. - **type** (string) - The type of the ad (BUY/SELL). - **price** (string) - The price set in the ad. - **status** (string) - The status of the ad. ### Response Example ```json { "ad_id": "AD789", "currency": "USDT", "type": "BUY", "price": "1.01", "status": "ACTIVE" } ``` ``` -------------------------------- ### Get P2P Merchant User Info Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get P2P merchant account information. ```APIDOC ## GET /api/v4/p2p/merchant/user_info ### Description Get P2P merchant account information. ### Method GET ### Endpoint /api/v4/p2p/merchant/user_info ### Response #### Success Response (200) - **user_id** (string) - The user ID of the merchant. - **nickname** (string) - The nickname of the merchant. - **level** (string) - The merchant level. ### Response Example ```json { "user_id": "12345", "nickname": "MerchantA", "level": "Gold" } ``` ``` -------------------------------- ### WebsocketClient Initialization and Subscription Source: https://github.com/tiagosiebler/gateio-api/blob/master/README.md Demonstrates how to initialize the WebsocketClient with configuration options and subscribe to multiple WebSocket topics. ```APIDOC ## WebsocketClient Initialization and Subscription ### Description Initialize the `WebsocketClient` with API credentials and configuration. Subscribe to various data streams using topic objects or strings. The client manages connections automatically. ### Method `new WebsocketClient(wsConfig)` `ws.subscribe(topics, version)` ### Parameters #### `wsConfig` Object - **apiKey** (string) - Required - Your Gate.io API key. - **apiSecret** (string) - Required - Your Gate.io API secret. - **useTestnet** (boolean) - Optional - Set to `true` to use the testnet environment. - **pongTimeout** (number) - Optional - Timeout in milliseconds before terminating a connection. - **pingInterval** (number) - Optional - Interval in milliseconds to check connection health. - **reconnectTimeout** (number) - Optional - Timeout in milliseconds before attempting to reconnect. - **restOptions** (object) - Optional - Configuration options for the RestClient. - **requestOptions** (object) - Optional - Configuration for axios used for HTTP requests. #### `topics` Parameter for `subscribe` - Can be an array of topic objects or a single topic object/string. - Topic object structure: `{ topic: string, payload: string[] }` - Example topic strings: `'spot.balances'` #### `version` Parameter for `subscribe` - (string) - The API version to use, e.g., `'spotV4'`. ### Request Example ```javascript const { WebsocketClient } = require('gateio-api'); const wsConfig = { apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', useTestnet: false, pongTimeout: 1000, pingInterval: 10000, reconnectTimeout: 500 }; const ws = new WebsocketClient(wsConfig); const userOrders = { topic: 'spot.orders', payload: ['BTC_USDT', 'ETH_USDT'] }; const userTrades = { topic: 'spot.usertrades', payload: ['BTC_USDT', 'ETH_USDT'] }; // Subscribe to multiple topics ws.subscribe([userOrders, userTrades], 'spotV4'); // Subscribe to a single topic ws.subscribe('spot.balances', 'spotV4'); ``` ### Response No direct response for subscription, but events are emitted. ``` -------------------------------- ### WebsocketClient Initialization and Subscription Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Demonstrates how to initialize the WebsocketClient with API credentials and subscribe to multiple data streams. ```APIDOC ## WebsocketClient Initialization and Subscription ### Description Initialize the `WebsocketClient` with your API key and secret. You can configure optional parameters like `useTestnet`, `pongTimeout`, `pingInterval`, and `reconnectTimeout`. This example shows how to subscribe to several topics at once using a configuration object. ### Method `new WebsocketClient(wsConfig)` `ws.subscribe(topics, apiVersion)` ### Parameters #### `wsConfig` Object - **apiKey** (string) - Your Gate.io API key. - **apiSecret** (string) - Your Gate.io API secret. - **useTestnet** (boolean, optional) - Set to `true` to use the testnet. - **pongTimeout** (number, optional) - Timeout in milliseconds before terminating a connection. - **pingInterval** (number, optional) - Interval in milliseconds to check connection health. - **reconnectTimeout** (number, optional) - Timeout in milliseconds before attempting to reconnect. #### `ws.subscribe` Parameters - **topics** (Array | Object | string) - A single topic object, an array of topic objects, or a string representing a topic. - **topic** (string) - The topic to subscribe to (e.g., 'spot.orders'). - **payload** (Array) - An array of symbols or '!all' for the topic. - **apiVersion** (string) - The API version to use (e.g., 'spotV4'). ### Request Example ```javascript const { WebsocketClient } = require('gateio-api'); const API_KEY = 'YOUR_API_KEY'; const PRIVATE_KEY = 'YOUR_PRIVATE_KEY'; const wsConfig = { apiKey: API_KEY, apiSecret: PRIVATE_KEY, // useTestnet: true, // pongTimeout: 1000, // pingInterval: 10000, // reconnectTimeout: 500 }; const ws = new WebsocketClient(wsConfig); const userOrders = { topic: 'spot.orders', payload: ['BTC_USDT', 'ETH_USDT'] }; const userTrades = { topic: 'spot.usertrades', payload: ['BTC_USDT', 'ETH_USDT'] }; // Subscribe to multiple topics ws.subscribe([userOrders, userTrades], 'spotV4'); // Subscribe to a single topic ws.subscribe({ topic: 'spot.priceorders', payload: ['!all'] }, 'spotV4'); // Subscribe to a topic without payload ws.subscribe('spot.balances', 'spotV4'); ``` ### Response #### Success Response - **response** (Object) - A response object confirming the subscription or other WebSocket API interactions. #### Response Example ```json { "event": "subscribe", "result": true, "channel": "spot.orders", "id": 12345 } ``` ``` -------------------------------- ### Get Spot Order Status Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get the status of a spot order. This is a placeholder comment indicating the functionality. ```plaintext /** * Get spot order status */ ``` -------------------------------- ### createEarnFixedTermLend Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Subscribes to a fixed-term earn product. This action initiates an investment into a selected earn product. ```APIDOC ## POST /api/v4/earn/lend ### Description Subscribes to a fixed-term earn product. ### Method POST ### Endpoint /api/v4/earn/lend ### Parameters #### Request Body - **params** (object) - Required - Parameters for subscribing to a fixed-term earn product. - **product_id** (string) - Required - The ID of the earn product. - **amount** (string) - Required - The amount to subscribe. - **currency** (string) - Required - The currency of the investment. ### Response #### Success Response (200) - **CreateEarnFixedTermLendResponse** (object) - Response confirming the subscription to the earn product. ``` -------------------------------- ### Get P2P Merchant Payment Method List Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get the list of payment methods available for P2P merchants. ```APIDOC ## GET /api/v4/p2p/merchant/payment_methods ### Description Get the list of payment methods available for P2P merchants. ### Method GET ### Endpoint /api/v4/p2p/merchant/payment_methods ### Parameters #### Query Parameters - **type** (string) - Optional - Filter by payment method type (e.g., "bank_transfer"). ### Response #### Success Response (200) - **list** (array) - Array of payment methods. - **id** (string) - The ID of the payment method. - **type** (string) - The type of the payment method. - **name** (string) - The name of the payment method. ### Response Example ```json { "list": [ { "id": "PM123", "type": "bank_transfer", "name": "Bank Transfer" } ] } ``` ``` -------------------------------- ### Get OTC User Default Bank Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get user's default bank account information for order placement. This is useful for retrieving default payment details. ```APIDOC ## GET /api/v4/otc/user_bank ### Description Get user's default bank account information for order placement. ### Method GET ### Endpoint /api/v4/otc/user_bank ### Response #### Success Response (200) - **bank_name** (string) - The name of the bank. - **account_number** (string) - The bank account number. - **account_holder** (string) - The name of the account holder. ### Response Example ```json { "bank_name": "Example Bank", "account_number": "1234567890", "account_holder": "John Doe" } ``` ``` -------------------------------- ### Initialize RestClient and Get Spot Candles Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Shows how to initialize the RestClient and fetch historical candlestick data for a trading pair. API credentials should be configured before execution. ```typescript 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 const account = { 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 const client = new RestClient(account); async function getSpotCandles() { try { // Fetch the spot account balances const balances = await client.spot.getCandles({ currency_pair: 'BTC_USDT', }); console.log('Response: ', balances); // Log the response to the console } catch (e) { console.error('Error in execution: ', e); // Log any errors that occur } } // Execute the function to get spot balances getSpotCandles(); ``` -------------------------------- ### getMaximumBorrowable Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get the maximum borrowable amount. ```APIDOC ## GET /margin/maximum_borrowable ### Description Get the maximum borrowable amount. ### Method GET ### Endpoint /margin/maximum_borrowable ### Parameters #### Query Parameters - **params** (object) - Required - Parameters for retrieving the maximum borrowable amount. ``` -------------------------------- ### getDualProjectRecommend Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves a list of recommended dual-currency projects. This helps users discover suitable investment opportunities. ```APIDOC ## GET /api/v4/dual/recommend ### Description Retrieves a list of recommended dual-currency projects. ### Method GET ### Endpoint /api/v4/dual/recommend ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering recommendations. - **currency** (string) - Optional - Filter by currency. - **limit** (string) - Optional - Limit the number of results. - **offset** (string) - Optional - Offset for pagination. ### Response #### Success Response (200) - **DualProjectRecommend[]** (array) - An array of recommended dual-currency projects. ``` -------------------------------- ### WebSocket Client Configuration Options Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Constructor for the BaseWebsocketClient. It accepts optional configuration options and a logger instance. Default configurations for Gate.io are mentioned, including automatic re-authentication and handling of private topics. ```typescript constructor( options?: WSClientConfigurableOptions, logger?: typeof DefaultLogger, ) ⋮---- ``` -------------------------------- ### getLendingMarket Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Get detail of a lending market. ```APIDOC ## GET /lending/market ### Description Get detail of a lending market. ### Method GET ### Endpoint /lending/market ### Parameters #### Query Parameters - **params** (object) - Required - Parameters containing the currency pair - **currency_pair** (string) - Required - The currency pair. ``` -------------------------------- ### Get Sub-Account Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves details for a specific sub-account. ```APIDOC ## GET /subaccount/{user_id} ### Description Retrieves details for a specific sub-account. ### Method GET ### Endpoint /subaccount/{user_id} ### Parameters #### Path Parameters - **user_id** (number) - Required - The user ID of the sub-account. ### Response #### Success Response (200) - **uid** (number) - Sub-account user ID. - **name** (string) - Sub-account name. - **role** (string) - Sub-account role. - **total_amount** (string) - Total amount of assets in the sub-account. - **created_time** (string) - Timestamp of sub-account creation. ### Response Example ```json { "uid": 12345, "name": "sub1", "role": "admin", "total_amount": "1000.50", "created_time": "1678886400" } ``` ``` -------------------------------- ### Initialize and Use RestClient for Gate.io APIs Source: https://github.com/tiagosiebler/gateio-api/blob/master/README.md Import and initialize the RestClient with your API keys to access various trading products like Spot, CrossEx, Alpha, and OTC. Handles all REST API operations across different markets. ```javascript const { RestClient } = require('gateio-api'); const API_KEY = 'xxx'; const PRIVATE_KEY = 'yyy'; const client = new RestClient({ apiKey: API_KEY, apiSecret: PRIVATE_KEY, }); ``` ```javascript // Spot Trading Example client .getSpotTicker() .then((result) => { console.log('all spot tickers result: ', result); }) .catch((err) => { console.error('spot ticker error: ', err); }); client .getSpotOrders({ currency_pair: 'BTC_USDT', status: 'open', }) .then((result) => { console.log('getSpotOrders result: ', result); }) .catch((err) => { console.error('getSpotOrders error: ', err); }); ``` ```javascript // CrossEx Trading Example - Trade across multiple exchanges client .getCrossExSymbols() .then((result) => { console.log('CrossEx symbols: ', result); }) .catch((err) => { console.error('CrossEx error: ', err); }); ``` ```javascript // Alpha Trading Example - Trade meme tokens and new listings client .getAlphaCurrencies() .then((result) => { console.log('Alpha currencies: ', result); }) .catch((err) => { console.error('Alpha error: ', err); }); ``` ```javascript // OTC Trading Example - Fiat and stablecoin trading client .createOTCQuote({ side: 'BUY', pay_coin: 'USDT', get_coin: 'USD', pay_amount: '1000', create_quote_token: '1', }) .then((result) => { console.log('OTC quote: ', result); }) .catch((err) => { console.error('OTC error: ', err); }); ``` -------------------------------- ### Get Dual Project Recommend Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves recommended dual investment projects. Allows filtering by mode, coin, type, and exclusion of history projects. ```APIDOC ## GET /earn/dual/project-recommend ### Description Retrieves recommended dual investment projects. ### Method GET ### Endpoint /earn/dual/project-recommend ### Parameters #### Query Parameters - **mode** (string) - Optional - Filter by mode. - **coin** (string) - Optional - Filter by coin. - **type** (string) - Optional - Filter by type. - **history_pids** (string) - Optional - Comma-separated project IDs to exclude. ``` -------------------------------- ### Get Futures Positions Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves current futures positions. ```APIDOC ## GET /api/v4/futures/positions ### Description Retrieves current futures positions. ### Method GET ### Endpoint /api/v4/futures/positions ### Parameters #### Query Parameters - **settle** (string) - Required - The settlement currency (btc, usdt, usd). - **holding** (boolean) - Optional - Filter by holding positions (true/false). - **limit** (number) - Optional - The maximum number of records to return. Default is 100. - **offset** (number) - Optional - The offset for pagination. Default is 0. - **position_side** (string) - Optional - Filter by position side (e.g., 'long', 'short'). - **hedge_mode** (boolean) - Optional - Enable hedge mode. ``` -------------------------------- ### Initialize and Configure WebsocketClient Source: https://github.com/tiagosiebler/gateio-api/blob/master/README.md Configure and initialize the WebsocketClient with API keys and optional settings like testnet usage, timeouts, and intervals. This client manages WebSocket connections automatically. ```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); ``` -------------------------------- ### Get Sub Account Balances Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves the balances of a sub-account. ```APIDOC ## GET /wallet/sub_account_balances ### Description Retrieves the balances of a sub-account. ### Method GET ### Endpoint /wallet/sub_account_balances ### Parameters #### Query Parameters - **sub_uid** (string) - Optional - The UID of the sub-account - **page** (number) - Optional - Page number - **limit** (number) - Optional - Maximum number of records to return ### Response #### Success Response (200) - **balances** (array) - List of sub-account balances ``` -------------------------------- ### Get Sub Account Source: https://github.com/tiagosiebler/gateio-api/blob/master/docs/endpointFunctionList.md Retrieves information about a specific sub-account. ```APIDOC ## GET /sub_accounts/{user_id} ### Description Retrieves information about a specific sub-account. ### Method GET ### Endpoint /sub_accounts/{user_id} ``` -------------------------------- ### Subscribe to Spot Balances (Object Topic) Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Subscribe to the 'spot.balances' topic using a WsTopicRequest object. This format allows for additional parameters if needed for other topics. ```typescript // const topicWithoutParamsAsObject: WsTopicRequest = { // topic: 'spot.balances', // }; ``` -------------------------------- ### Subscribe to Spot Balances (String Topic) Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Subscribe to the 'spot.balances' topic using a simple string. This is a basic way to receive account balance updates. ```typescript // const topicWithoutParamsAsString = 'spot.balances'; ``` -------------------------------- ### Get Spot Ticker Source: https://github.com/tiagosiebler/gateio-api/blob/master/README.md Retrieves all spot market tickers. ```APIDOC ## Get Spot Ticker ### Description Retrieves all spot market tickers. ### Method GET ### Endpoint /spot/tickers ### Parameters None ### Response #### Success Response (200) - **currency_pair** (string) - The trading pair. - **last** (string) - The last traded price. - **lowest_ask** (string) - The lowest ask price. - **highest_bid** (string) - The highest bid price. - **change_percentage** (string) - The percentage change in price. - **base_volume** (string) - The base currency volume. - **quote_volume** (string) - The quote currency volume. - **high_buy_price** (string) - The highest buy price. - **low_sell_price** (string) - The lowest sell price. - **is_freeze** (string) - Indicates if trading is frozen. - **seq** (integer) - Sequence number. ### Request Example ```javascript client .getSpotTicker() .then((result) => { console.log('all spot tickers result: ', result); }) .catch((err) => { console.error('spot ticker error: ', err); }); ``` ``` -------------------------------- ### Get TradFi Assets Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves the user's TradFi assets. ```APIDOC ## GET /api/v4/tradfi/assets ### Description Retrieves the user's TradFi assets. ### Method GET ### Endpoint /api/v4/tradfi/assets ``` -------------------------------- ### Get Dual Project Recommend Parameters Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Parameters for retrieving dual investment project recommendations. Supports filtering by mode, coin, type, and excluding specific project IDs. ```typescript export interface GetDualProjectRecommendReq { mode?: string; coin?: string; type?: string; /** Comma-separated project IDs to exclude */ history_pids?: string; } ``` -------------------------------- ### REST Client Constructor Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Initializes the REST client with options for API connectivity and network configuration. ```typescript constructor( restClientOptions: RestClientOptions = {}, networkOptions: AxiosRequestConfig = {}, ) ``` -------------------------------- ### Get Options Underlyings Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Lists all available underlyings for options contracts. ```APIDOC ## GET /api/v4/options/underlyings ### Description List all underlyings for options contracts. ### Method GET ### Endpoint /api/v4/options/underlyings ### Response #### Success Response (200) - **Array<{ name: string; index_price: string }>** - An array of underlyings with their index prices ``` -------------------------------- ### Get Server Time Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves the current server time from Gate.io. ```APIDOC ## GET /api/v4/time ### Description Retrieves the current server time from Gate.io. ### Method GET ### Endpoint /api/v4/time ### Response #### Success Response (200) - **server_time** (integer) - Current server time in Unix timestamp format. ### Response Example ```json { "server_time": 1678886400 } ``` ``` -------------------------------- ### RestClient Initialization Source: https://github.com/tiagosiebler/gateio-api/blob/master/README.md Initialize the RestClient with your API key and secret. ```APIDOC ## RestClient Initialization ### Description Initialize the RestClient with your API key and secret. ### Method Constructor ### Parameters - **apiKey** (string) - Required - Your Gate.io API key. - **apiSecret** (string) - Required - Your Gate.io API secret. ### Request Example ```javascript const { RestClient } = require('gateio-api'); const API_KEY = 'YOUR_API_KEY'; const PRIVATE_KEY = 'YOUR_PRIVATE_KEY'; const client = new RestClient({ apiKey: API_KEY, apiSecret: PRIVATE_KEY, }); ``` ``` -------------------------------- ### Get Sub-Accounts Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves a list of all sub-accounts associated with the main account. ```APIDOC ## GET /subaccounts ### Description Retrieves a list of all sub-accounts. ### Method GET ### Endpoint /subaccounts ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of sub-accounts to return. - **offset** (integer) - Optional - The starting point for the query. ### Response #### Success Response (200) - **total** (integer) - Total number of sub-accounts. - **list** (array) - Array of sub-account objects. - **uid** (integer) - Sub-account user ID. - **name** (string) - Sub-account name. - **role** (string) - Sub-account role. - **total_amount** (string) - Total amount of assets in the sub-account. - **created_time** (string) - Timestamp of sub-account creation. ### Response Example ```json { "total": 2, "list": [ { "uid": 12345, "name": "sub1", "role": "admin", "total_amount": "1000.50", "created_time": "1678886400" } ] } ``` ``` -------------------------------- ### Initialize RestClient for Limit Order Submission Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt This snippet shows the initialization of the RestClient, which is the first step before submitting a limit order. The actual order submission logic would follow. ```typescript 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 const account = { 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 const client = new RestClient(account); ``` -------------------------------- ### Get Client Type Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves the type of the current REST client. ```typescript getClientType(): RestClientType ``` -------------------------------- ### Dual Project Recommend Interface Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Represents a recommended Dual Investment project with its key details. ```APIDOC ## GET /earn/dual/project-recommend item ### Description Retrieves details for a recommended Dual Investment project, including investment parameters and potential returns. ### Response #### Success Response (200) - **id** (number) - Unique identifier for the project. - **category** (number) - Category of the project. - **type** (string) - Type of the Dual Investment product. - **invest_currency** (string) - The currency for investment. - **exercise_currency** (string) - The currency for exercising the option. - **apy_display** (string) - Display value for Annual Percentage Yield (APY). - **exercise_price** (string) - The exercise price. - **delivery_timest** (number) - Timestamp for delivery. - **min_amount** (string) - Minimum investment amount. - **max_amount** (string) - Maximum investment amount. - **min_copies** (number) - Minimum number of copies. - **max_copies** (number) - Maximum number of copies. - **invest_days** (number) - Number of investment days. - **invest_hours** (string) - Investment duration in hours. ``` -------------------------------- ### Get Futures Liquidation History Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves the historical futures liquidations. ```APIDOC ## GET /api/v4/futures/liquidation_history ### Description Retrieves the historical futures liquidations. ### Method GET ### Endpoint /api/v4/futures/liquidation_history ### Parameters #### Query Parameters - **settle** (string) - Required - The settlement currency (btc, usdt, usd). - **contract** (string) - Optional - The futures contract identifier. - **limit** (number) - Optional - The maximum number of records to return. Default is 100. - **at** (number) - Optional - The timestamp for liquidation history. ``` -------------------------------- ### WsStore Constructor Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Initializes the WsStore with a logger instance for tracking events and errors. ```typescript constructor(logger: DefaultLogger) ``` -------------------------------- ### Create Earn Fixed-Term Lend Parameters Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Parameters for creating a fixed-term earn lending order. Includes product ID, amount, and optional settings for year rate, reinvestment, redemption, and financial rate. ```typescript export interface CreateEarnFixedTermLendReq { product_id: number; amount: string; year_rate?: string; reinvest_status?: number; // 0 off, 1 on redeem_account_type?: number; // 1 spot financial_rate_id?: number; // interest boost coupon id, 0 = none sub_business?: number; } ``` -------------------------------- ### Get Futures Position History Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves the historical futures positions. ```APIDOC ## GET /api/v4/futures/position_history ### Description Retrieves the historical futures positions. ### Method GET ### Endpoint /api/v4/futures/position_history ### Parameters #### Query Parameters - **settle** (string) - Required - The settlement currency (btc, usdt, usd). - **contract** (string) - Optional - The futures contract identifier. - **limit** (number) - Optional - The maximum number of records to return. Default is 100. - **offset** (number) - Optional - The offset for pagination. Default is 0. - **from** (number) - Optional - The start timestamp (in milliseconds). - **to** (number) - Optional - The end timestamp (in milliseconds). - **side** (string) - Optional - The side of the position ('long' or 'short'). - **pnl** (string) - Optional - Filter by PNL amount. ``` -------------------------------- ### ESLint Configuration Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt ESLint configuration file. This example shows a commented-out rule for 'no-unused-vars'. ```javascript // 'no-unused-vars': ['warn'], ``` -------------------------------- ### Get Futures Orders Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves futures orders based on status. ```APIDOC ## GET /api/v4/futures/orders ### Description Retrieves futures orders based on status. ### Method GET ### Endpoint /api/v4/futures/orders ### Parameters #### Query Parameters - **settle** (string) - Required - The settlement currency (btc, usdt, usd). - **contract** (string) - Optional - The futures contract identifier. - **status** (string) - Required - The status of the orders (e.g., 'open', 'closed'). - **limit** (number) - Optional - The maximum number of records to return. Default is 100. - **offset** (number) - Optional - The offset for pagination. Default is 0. - **last_id** (string) - Optional - The ID of the last record. ``` -------------------------------- ### Use Gate.io WebSocket API as REST-like Client Source: https://github.com/tiagosiebler/gateio-api/blob/master/README.md Demonstrates how to use the WebsocketAPIClient for making various trading orders and status requests. Ensure API keys are set up for authentication. The client automatically handles WebSocket connection management and re-authentication. ```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(); ``` -------------------------------- ### Get Liquidation History Source: https://github.com/tiagosiebler/gateio-api/blob/master/llms.txt Retrieves liquidation history for futures contracts. ```APIDOC ## GET /api/v4/futures/liquidation_history ### Description Retrieves liquidation history for futures contracts. ### Method GET ### Endpoint /api/v4/futures/liquidation_history ### Parameters #### Query Parameters - **settle** (string) - Required - The settlement currency (btc, usdt, usd). - **contract** (string) - Optional - The futures contract identifier. - **from** (number) - Optional - The start timestamp (in milliseconds). - **to** (number) - Optional - The end timestamp (in milliseconds). - **limit** (number) - Optional - The maximum number of records to return. Default is 100. ```